blob: ec6d17d15441ebfd8cfc0ddfb8e98836a1465850 [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/LoopInfo.h"
47#include "llvm/Analysis/LoopPass.h"
48#include "llvm/Analysis/ScalarEvolution.h"
49#include "llvm/Analysis/ScalarEvolutionExpander.h"
50#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000051#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000054#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/PatternMatch.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000059#include "llvm/Transforms/Scalar.h"
60#include "llvm/Transforms/Utils/BasicBlockUtils.h"
61#include "llvm/Transforms/Utils/Cloning.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000062#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000063#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064
65using namespace llvm;
66
Benjamin Kramer970eac42015-02-06 17:51:54 +000067static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
68 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000069
Benjamin Kramer970eac42015-02-06 17:51:54 +000070static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
71 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000072
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000073static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
74 cl::init(false));
75
Sanjoy Dase91665d2015-02-26 08:56:04 +000076static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
77 cl::Hidden, cl::init(10));
78
Sanjoy Dasbb969792016-07-22 00:40:56 +000079static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
80 cl::Hidden, cl::init(false));
81
Sanjoy Das7a18a232016-08-14 01:04:36 +000082static const char *ClonedLoopTag = "irce.loop.clone";
83
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084#define DEBUG_TYPE "irce"
85
86namespace {
87
88/// An inductive range check is conditional branch in a loop with
89///
90/// 1. a very cold successor (i.e. the branch jumps to that successor very
91/// rarely)
92///
93/// and
94///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000095/// 2. a condition that is provably true for some contiguous range of values
96/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000097///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000099 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000100 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000101 // Range check of the form "0 <= I".
102 RANGE_CHECK_LOWER = 1,
103
104 // Range check of the form "I < L" where L is known positive.
105 RANGE_CHECK_UPPER = 2,
106
107 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
108 // conditions.
109 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
110
111 // Unrecognized range check condition.
112 RANGE_CHECK_UNKNOWN = (unsigned)-1
113 };
114
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000115 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000116
Sanjoy Dasee77a482016-05-26 01:50:18 +0000117 const SCEV *Offset = nullptr;
118 const SCEV *Scale = nullptr;
119 Value *Length = nullptr;
120 Use *CheckUse = nullptr;
121 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122
Sanjoy Das337d46b2015-03-24 19:29:18 +0000123 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
124 ScalarEvolution &SE, Value *&Index,
125 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000126
Sanjoy Dasa0992682016-05-26 00:09:02 +0000127 static void
128 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
129 SmallVectorImpl<InductiveRangeCheck> &Checks,
130 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132public:
133 const SCEV *getOffset() const { return Offset; }
134 const SCEV *getScale() const { return Scale; }
135 Value *getLength() const { return Length; }
136
137 void print(raw_ostream &OS) const {
138 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000139 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000140 OS << " Offset: ";
141 Offset->print(OS);
142 OS << " Scale: ";
143 Scale->print(OS);
144 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000145 if (Length)
146 Length->print(OS);
147 else
148 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000149 OS << "\n CheckUse: ";
150 getCheckUse()->getUser()->print(OS);
151 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000152 }
153
Davide Italianod1279df2016-08-18 15:55:49 +0000154 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 void dump() {
156 print(dbgs());
157 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000158
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000159 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000160
Sanjoy Das351db052015-01-22 09:32:02 +0000161 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
162 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
163
164 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000165 const SCEV *Begin;
166 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000167
168 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000169 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000170 assert(Begin->getType() == End->getType() && "ill-typed range!");
171 }
172
173 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000174 const SCEV *getBegin() const { return Begin; }
175 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000176 };
177
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000178 /// This is the value the condition of the branch needs to evaluate to for the
179 /// branch to take the hot successor (see (1) above).
180 bool getPassingDirection() { return true; }
181
Sanjoy Das95c476d2015-02-21 22:20:22 +0000182 /// Computes a range for the induction variable (IndVar) in which the range
183 /// check is redundant and can be constant-folded away. The induction
184 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000185 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000186 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000187
Sanjoy Dasa0992682016-05-26 00:09:02 +0000188 /// Parse out a set of inductive range checks from \p BI and append them to \p
189 /// Checks.
190 ///
191 /// NB! There may be conditions feeding into \p BI that aren't inductive range
192 /// checks, and hence don't end up in \p Checks.
193 static void
194 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
195 BranchProbabilityInfo &BPI,
196 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000197};
198
199class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000200public:
201 static char ID;
202 InductiveRangeCheckElimination() : LoopPass(ID) {
203 initializeInductiveRangeCheckEliminationPass(
204 *PassRegistry::getPassRegistry());
205 }
206
207 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000208 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000209 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000210 }
211
212 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
213};
214
215char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000216}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000217
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000218INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
219 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000220INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000221INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000222INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
223 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000224
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000225StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000226 InductiveRangeCheck::RangeCheckKind RCK) {
227 switch (RCK) {
228 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
229 return "RANGE_CHECK_UNKNOWN";
230
231 case InductiveRangeCheck::RANGE_CHECK_UPPER:
232 return "RANGE_CHECK_UPPER";
233
234 case InductiveRangeCheck::RANGE_CHECK_LOWER:
235 return "RANGE_CHECK_LOWER";
236
237 case InductiveRangeCheck::RANGE_CHECK_BOTH:
238 return "RANGE_CHECK_BOTH";
239 }
240
241 llvm_unreachable("unknown range check type!");
242}
243
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000244/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000245/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000246/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000247/// range checked, and set `Length` to the upper limit `Index` is being range
248/// checked with if (and only if) the range check type is stronger or equal to
249/// RANGE_CHECK_UPPER.
250///
251InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000252InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
253 ScalarEvolution &SE, Value *&Index,
254 Value *&Length) {
255
256 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
257 const SCEV *S = SE.getSCEV(V);
258 if (isa<SCEVCouldNotCompute>(S))
259 return false;
260
261 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
262 SE.isKnownNonNegative(S);
263 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000264
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000265 using namespace llvm::PatternMatch;
266
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000267 ICmpInst::Predicate Pred = ICI->getPredicate();
268 Value *LHS = ICI->getOperand(0);
269 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000270
271 switch (Pred) {
272 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000273 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000274
275 case ICmpInst::ICMP_SLE:
276 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000277 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000278 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000279 if (match(RHS, m_ConstantInt<0>())) {
280 Index = LHS;
281 return RANGE_CHECK_LOWER;
282 }
283 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000284
285 case ICmpInst::ICMP_SLT:
286 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000287 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000288 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000289 if (match(RHS, m_ConstantInt<-1>())) {
290 Index = LHS;
291 return RANGE_CHECK_LOWER;
292 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000293
Sanjoy Das337d46b2015-03-24 19:29:18 +0000294 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295 Index = RHS;
296 Length = LHS;
297 return RANGE_CHECK_UPPER;
298 }
299 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000300
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000302 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000303 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000304 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000305 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306 Index = RHS;
307 Length = LHS;
308 return RANGE_CHECK_BOTH;
309 }
310 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000311 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000312
313 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000314}
315
Sanjoy Dasa0992682016-05-26 00:09:02 +0000316void InductiveRangeCheck::extractRangeChecksFromCond(
317 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
318 SmallVectorImpl<InductiveRangeCheck> &Checks,
319 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320 using namespace llvm::PatternMatch;
321
Sanjoy Das8fe88922016-05-26 00:08:24 +0000322 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000323 if (!Visited.insert(Condition).second)
324 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000325
Sanjoy Dasa0992682016-05-26 00:09:02 +0000326 if (match(Condition, m_And(m_Value(), m_Value()))) {
327 SmallVector<InductiveRangeCheck, 8> SubChecks;
328 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
329 SubChecks, Visited);
330 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
331 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000332
Sanjoy Dasa0992682016-05-26 00:09:02 +0000333 if (SubChecks.size() == 2) {
334 // Handle a special case where we know how to merge two checks separately
335 // checking the upper and lower bounds into a full range check.
336 const auto &RChkA = SubChecks[0];
337 const auto &RChkB = SubChecks[1];
338 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
339 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000340
Sanjoy Dasa0992682016-05-26 00:09:02 +0000341 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
342 // But if one of them is a RANGE_CHECK_LOWER and the other is a
343 // RANGE_CHECK_UPPER (only possibility if they're different) then
344 // together they form a RANGE_CHECK_BOTH.
345 SubChecks[0].Kind =
346 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
347 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
348 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000349
Sanjoy Dasa0992682016-05-26 00:09:02 +0000350 // We updated one of the checks in place, now erase the other.
351 SubChecks.pop_back();
352 }
353 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354
Sanjoy Dasa0992682016-05-26 00:09:02 +0000355 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
356 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357 }
358
Sanjoy Dasa0992682016-05-26 00:09:02 +0000359 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
360 if (!ICI)
361 return;
362
363 Value *Length = nullptr, *Index;
364 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
365 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
366 return;
367
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000368 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000369 bool IsAffineIndex =
370 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
371
372 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000373 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000375 InductiveRangeCheck IRC;
376 IRC.Length = Length;
377 IRC.Offset = IndexAddRec->getStart();
378 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000379 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000380 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000381 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000382}
383
Sanjoy Dasa0992682016-05-26 00:09:02 +0000384void InductiveRangeCheck::extractRangeChecksFromBranch(
385 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
386 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000387
388 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000389 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000390
391 BranchProbability LikelyTaken(15, 16);
392
Sanjoy Dasbb969792016-07-22 00:40:56 +0000393 if (!SkipProfitabilityChecks &&
394 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000396
Sanjoy Dasa0992682016-05-26 00:09:02 +0000397 SmallPtrSet<Value *, 8> Visited;
398 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
399 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000400}
401
Anna Thomas65ca8e92016-12-13 21:05:21 +0000402// Add metadata to the loop L to disable loop optimizations. Callers need to
403// confirm that optimizing loop L is not beneficial.
404static void DisableAllLoopOptsOnLoop(Loop &L) {
405 // We do not care about any existing loopID related metadata for L, since we
406 // are setting all loop metadata to false.
407 LLVMContext &Context = L.getHeader()->getContext();
408 // Reserve first location for self reference to the LoopID metadata node.
409 MDNode *Dummy = MDNode::get(Context, {});
410 MDNode *DisableUnroll = MDNode::get(
411 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
412 Metadata *FalseVal =
413 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
414 MDNode *DisableVectorize = MDNode::get(
415 Context,
416 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
417 MDNode *DisableLICMVersioning = MDNode::get(
418 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
419 MDNode *DisableDistribution= MDNode::get(
420 Context,
421 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
422 MDNode *NewLoopID =
423 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
424 DisableLICMVersioning, DisableDistribution});
425 // Set operand 0 to refer to the loop id itself.
426 NewLoopID->replaceOperandWith(0, NewLoopID);
427 L.setLoopID(NewLoopID);
428}
429
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000430namespace {
431
Sanjoy Dase75ed922015-02-26 08:19:31 +0000432// Keeps track of the structure of a loop. This is similar to llvm::Loop,
433// except that it is more lightweight and can track the state of a loop through
434// changing and potentially invalid IR. This structure also formalizes the
435// kinds of loops we can deal with -- ones that have a single latch that is also
436// an exiting block *and* have a canonical induction variable.
437struct LoopStructure {
438 const char *Tag;
439
440 BasicBlock *Header;
441 BasicBlock *Latch;
442
443 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
444 // successor is `LatchExit', the exit block of the loop.
445 BranchInst *LatchBr;
446 BasicBlock *LatchExit;
447 unsigned LatchBrExitIdx;
448
Sanjoy Dasec892132017-02-07 23:59:07 +0000449 // The loop represented by this instance of LoopStructure is semantically
450 // equivalent to:
451 //
452 // intN_ty inc = IndVarIncreasing ? 1 : -1;
453 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
454 //
455 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarNext)
456 // ... body ...
457
Sanjoy Dase75ed922015-02-26 08:19:31 +0000458 Value *IndVarNext;
459 Value *IndVarStart;
460 Value *LoopExitAt;
461 bool IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000462 bool IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000463
464 LoopStructure()
465 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
466 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000467 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false),
468 IsSignedPredicate(true) {}
Sanjoy Dase75ed922015-02-26 08:19:31 +0000469
470 template <typename M> LoopStructure map(M Map) const {
471 LoopStructure Result;
472 Result.Tag = Tag;
473 Result.Header = cast<BasicBlock>(Map(Header));
474 Result.Latch = cast<BasicBlock>(Map(Latch));
475 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
476 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
477 Result.LatchBrExitIdx = LatchBrExitIdx;
478 Result.IndVarNext = Map(IndVarNext);
479 Result.IndVarStart = Map(IndVarStart);
480 Result.LoopExitAt = Map(LoopExitAt);
481 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000482 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000483 return Result;
484 }
485
Sanjoy Dase91665d2015-02-26 08:56:04 +0000486 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
487 BranchProbabilityInfo &BPI,
488 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000489 const char *&);
490};
491
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000492/// This class is used to constrain loops to run within a given iteration space.
493/// The algorithm this class implements is given a Loop and a range [Begin,
494/// End). The algorithm then tries to break out a "main loop" out of the loop
495/// it is given in a way that the "main loop" runs with the induction variable
496/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
497/// loops to run any remaining iterations. The pre loop runs any iterations in
498/// which the induction variable is < Begin, and the post loop runs any
499/// iterations in which the induction variable is >= End.
500///
501class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000502 // The representation of a clone of the original loop we started out with.
503 struct ClonedLoop {
504 // The cloned blocks
505 std::vector<BasicBlock *> Blocks;
506
507 // `Map` maps values in the clonee into values in the cloned version
508 ValueToValueMapTy Map;
509
510 // An instance of `LoopStructure` for the cloned loop
511 LoopStructure Structure;
512 };
513
514 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
515 // more details on what these fields mean.
516 struct RewrittenRangeInfo {
517 BasicBlock *PseudoExit;
518 BasicBlock *ExitSelector;
519 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000520 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000521
Sanjoy Dase75ed922015-02-26 08:19:31 +0000522 RewrittenRangeInfo()
523 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000524 };
525
526 // Calculated subranges we restrict the iteration space of the main loop to.
527 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000528 // these fields are computed. `LowLimit` is None if there is no restriction
529 // on low end of the restricted iteration space of the main loop. `HighLimit`
530 // is None if there is no restriction on high end of the restricted iteration
531 // space of the main loop.
532
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000533 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000534 Optional<const SCEV *> LowLimit;
535 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000536 };
537
538 // A utility function that does a `replaceUsesOfWith' on the incoming block
539 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
540 // incoming block list with `ReplaceBy'.
541 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
542 BasicBlock *ReplaceBy);
543
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000544 // Compute a safe set of limits for the main loop to run in -- effectively the
545 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000546 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000547 //
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000548 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000549
550 // Clone `OriginalLoop' and return the result in CLResult. The IR after
551 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
552 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
553 // but there is no such edge.
554 //
555 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
556
Sanjoy Das21434472016-08-14 01:04:46 +0000557 // Create the appropriate loop structure needed to describe a cloned copy of
558 // `Original`. The clone is described by `VM`.
559 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
560 ValueToValueMapTy &VM);
561
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
563 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
564 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
565 // `OriginalHeaderCount'.
566 //
567 // If there are iterations left to execute, control is made to jump to
568 // `ContinuationBlock', otherwise they take the normal loop exit. The
569 // returned `RewrittenRangeInfo' object is populated as follows:
570 //
571 // .PseudoExit is a basic block that unconditionally branches to
572 // `ContinuationBlock'.
573 //
574 // .ExitSelector is a basic block that decides, on exit from the loop,
575 // whether to branch to the "true" exit or to `PseudoExit'.
576 //
577 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
578 // for each PHINode in the loop header on taking the pseudo exit.
579 //
580 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
581 // preheader because it is made to branch to the loop header only
582 // conditionally.
583 //
584 RewrittenRangeInfo
585 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
586 Value *ExitLoopAt,
587 BasicBlock *ContinuationBlock) const;
588
589 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
590 // function creates a new preheader for `LS' and returns it.
591 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000592 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
593 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000594
595 // `ContinuationBlockAndPreheader' was the continuation block for some call to
596 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
597 // This function rewrites the PHI nodes in `LS.Header' to start with the
598 // correct value.
599 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000600 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000601 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
602
603 // Even though we do not preserve any passes at this time, we at least need to
604 // keep the parent loop structure consistent. The `LPPassManager' seems to
605 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000606 // blocks denoted by BBs to this loops parent loop if required.
607 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000608
609 // Some global state.
610 Function &F;
611 LLVMContext &Ctx;
612 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000613 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000614 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000615 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000616
617 // Information about the original loop we started out with.
618 Loop &OriginalLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000619 const SCEV *LatchTakenCount;
620 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621
622 // The preheader of the main loop. This may or may not be different from
623 // `OriginalPreheader'.
624 BasicBlock *MainLoopPreheader;
625
626 // The range we need to run the main loop in.
627 InductiveRangeCheck::Range Range;
628
629 // The structure of the main loop (see comment at the beginning of this class
630 // for a definition)
631 LoopStructure MainLoopStructure;
632
633public:
Sanjoy Das21434472016-08-14 01:04:46 +0000634 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
635 const LoopStructure &LS, ScalarEvolution &SE,
636 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000637 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das35459f02016-08-14 01:04:50 +0000638 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L),
Sanjoy Das21434472016-08-14 01:04:46 +0000639 LatchTakenCount(nullptr), OriginalPreheader(nullptr),
640 MainLoopPreheader(nullptr), Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641
642 // Entry point for the algorithm. Returns true on success.
643 bool run();
644};
645
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000646}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647
648void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
649 BasicBlock *ReplaceBy) {
650 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
651 if (PN->getIncomingBlock(i) == Block)
652 PN->setIncomingBlock(i, ReplaceBy);
653}
654
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000655static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
656 APInt Max = Signed ?
657 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
658 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
659 return SE.getSignedRange(S).contains(Max) &&
660 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000661}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000662
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000663static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
664 APInt Min = Signed ?
665 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
666 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
667 return SE.getSignedRange(S).contains(Min) &&
668 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000669}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000670
Sanjoy Dase75ed922015-02-26 08:19:31 +0000671Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000672LoopStructure::parseLoopStructure(ScalarEvolution &SE,
673 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000674 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000675 if (!L.isLoopSimplifyForm()) {
676 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000677 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000678 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000679
680 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000681 assert(Latch && "Simplified loops only have one latch!");
682
Sanjoy Das7a18a232016-08-14 01:04:36 +0000683 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
684 FailureReason = "loop has already been cloned";
685 return None;
686 }
687
Sanjoy Dase75ed922015-02-26 08:19:31 +0000688 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000689 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000690 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000691 }
692
Sanjoy Dase75ed922015-02-26 08:19:31 +0000693 BasicBlock *Header = L.getHeader();
694 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000695 if (!Preheader) {
696 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000697 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000698 }
699
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000700 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000701 if (!LatchBr || LatchBr->isUnconditional()) {
702 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000703 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000704 }
705
Sanjoy Dase75ed922015-02-26 08:19:31 +0000706 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000707
Sanjoy Dase91665d2015-02-26 08:56:04 +0000708 BranchProbability ExitProbability =
709 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
710
Sanjoy Dasbb969792016-07-22 00:40:56 +0000711 if (!SkipProfitabilityChecks &&
712 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000713 FailureReason = "short running loop, not profitable";
714 return None;
715 }
716
Sanjoy Dase75ed922015-02-26 08:19:31 +0000717 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
718 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
719 FailureReason = "latch terminator branch not conditional on integral icmp";
720 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000721 }
722
Sanjoy Dase75ed922015-02-26 08:19:31 +0000723 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
724 if (isa<SCEVCouldNotCompute>(LatchCount)) {
725 FailureReason = "could not compute latch count";
726 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000727 }
728
Sanjoy Dase75ed922015-02-26 08:19:31 +0000729 ICmpInst::Predicate Pred = ICI->getPredicate();
730 Value *LeftValue = ICI->getOperand(0);
731 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
732 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
733
734 Value *RightValue = ICI->getOperand(1);
735 const SCEV *RightSCEV = SE.getSCEV(RightValue);
736
737 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
738 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
739 if (isa<SCEVAddRecExpr>(RightSCEV)) {
740 std::swap(LeftSCEV, RightSCEV);
741 std::swap(LeftValue, RightValue);
742 Pred = ICmpInst::getSwappedPredicate(Pred);
743 } else {
744 FailureReason = "no add recurrences in the icmp";
745 return None;
746 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000747 }
748
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000749 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
750 if (AR->getNoWrapFlags(SCEV::FlagNSW))
751 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000752
753 IntegerType *Ty = cast<IntegerType>(AR->getType());
754 IntegerType *WideTy =
755 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
756
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000757 const SCEVAddRecExpr *ExtendAfterOp =
758 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
759 if (ExtendAfterOp) {
760 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
761 const SCEV *ExtendedStep =
762 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
763
764 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
765 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
766
767 if (NoSignedWrap)
768 return true;
769 }
770
771 // We may have proved this when computing the sign extension above.
772 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
773 };
774
775 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
776 if (!AR->isAffine())
777 return false;
778
Sanjoy Dase75ed922015-02-26 08:19:31 +0000779 // Currently we only work with induction variables that have been proved to
780 // not wrap. This restriction can potentially be lifted in the future.
781
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000782 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000783 return false;
784
785 if (const SCEVConstant *StepExpr =
786 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
787 ConstantInt *StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000788 assert(!StepCI->isZero() && "Zero step?");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000789 if (StepCI->isOne() || StepCI->isMinusOne()) {
790 IsIncreasing = StepCI->isOne();
791 return true;
792 }
793 }
794
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000795 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000796 };
797
798 // `ICI` is interpreted as taking the backedge if the *next* value of the
799 // induction variable satisfies some constraint.
800
801 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
802 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000803 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000804 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
805 FailureReason = "LHS in icmp not induction variable";
806 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000807 }
808
Sanjoy Dasec892132017-02-07 23:59:07 +0000809 const SCEV *StartNext = IndVarNext->getStart();
810 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
811 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
812
Sanjoy Dase75ed922015-02-26 08:19:31 +0000813 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000814 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000815 bool DecreasedRightValueByOne = false;
816 // Try to turn eq/ne predicates to those we can work with.
817 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
818 // while (++i != len) { while (++i < len) {
819 // ... ---> ...
820 // } }
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000821 // If both parts are known non-negative, it is profitable to use unsigned
822 // comparison in increasing loop. This allows us to make the comparison
823 // check against "RightSCEV + 1" more optimistic.
824 if (SE.isKnownNonNegative(IndVarStart) &&
825 SE.isKnownNonNegative(RightSCEV))
826 Pred = ICmpInst::ICMP_ULT;
827 else
828 Pred = ICmpInst::ICMP_SLT;
Max Kazantsev2c627a92017-07-18 04:53:48 +0000829 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000830 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000831 // while (true) { while (true) {
832 // if (++i == len) ---> if (++i > len - 1)
833 // break; break;
834 // ... ...
835 // } }
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000836 // TODO: Insert ICMP_UGT if both are non-negative?
Max Kazantsev2c627a92017-07-18 04:53:48 +0000837 Pred = ICmpInst::ICMP_SGT;
838 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
839 DecreasedRightValueByOne = true;
840 }
841
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000842 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
843 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000844 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000845 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000846
847 if (!FoundExpectedPred) {
848 FailureReason = "expected icmp slt semantically, found something else";
849 return None;
850 }
851
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000852 IsSignedPredicate =
853 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
854 // The predicate that we need to check that the induction variable lies
855 // within bounds.
856 ICmpInst::Predicate BoundPred =
857 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
858
Sanjoy Dase75ed922015-02-26 08:19:31 +0000859 if (LatchBrExitIdx == 0) {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000860 if (CanBeMax(SE, RightSCEV, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000861 // TODO: this restriction is easily removable -- we just have to
862 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000863 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000864 return None;
865 }
866
Sanjoy Dasec892132017-02-07 23:59:07 +0000867 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000868 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +0000869 SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType())))) {
870 FailureReason = "Induction variable start not bounded by upper limit";
871 return None;
872 }
873
Max Kazantsev2c627a92017-07-18 04:53:48 +0000874 // We need to increase the right value unless we have already decreased
875 // it virtually when we replaced EQ with SGT.
876 if (!DecreasedRightValueByOne) {
877 IRBuilder<> B(Preheader->getTerminator());
878 RightValue = B.CreateAdd(RightValue, One);
879 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000880 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000881 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000882 FailureReason = "Induction variable start not bounded by upper limit";
883 return None;
884 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000885 assert(!DecreasedRightValueByOne &&
886 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000887 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000888 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000889 bool IncreasedRightValueByOne = false;
890 // Try to turn eq/ne predicates to those we can work with.
891 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
892 // while (--i != len) { while (--i > len) {
893 // ... ---> ...
894 // } }
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000895 // We intentionally don't turn the predicate into UGT even if we know that
896 // both operands are non-negative, because it will only pessimize our
897 // check against "RightSCEV - 1".
Max Kazantsev2c627a92017-07-18 04:53:48 +0000898 Pred = ICmpInst::ICMP_SGT;
899 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000900 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000901 // while (true) { while (true) {
902 // if (--i == len) ---> if (--i < len + 1)
903 // break; break;
904 // ... ...
905 // } }
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000906 // TODO: Insert ICMP_ULT if both are non-negative?
Max Kazantsev2c627a92017-07-18 04:53:48 +0000907 Pred = ICmpInst::ICMP_SLT;
908 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
909 IncreasedRightValueByOne = true;
910 }
911
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000912 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
913 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
914
Sanjoy Dase75ed922015-02-26 08:19:31 +0000915 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000916 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000917
918 if (!FoundExpectedPred) {
919 FailureReason = "expected icmp sgt semantically, found something else";
920 return None;
921 }
922
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000923 IsSignedPredicate =
924 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
925 // The predicate that we need to check that the induction variable lies
926 // within bounds.
927 ICmpInst::Predicate BoundPred =
928 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
929
Sanjoy Dase75ed922015-02-26 08:19:31 +0000930 if (LatchBrExitIdx == 0) {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000931 if (CanBeMin(SE, RightSCEV, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000932 // TODO: this restriction is easily removable -- we just have to
933 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000934 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000935 return None;
936 }
937
Sanjoy Dasec892132017-02-07 23:59:07 +0000938 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000939 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +0000940 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
941 FailureReason = "Induction variable start not bounded by lower limit";
942 return None;
943 }
944
Max Kazantsev2c627a92017-07-18 04:53:48 +0000945 // We need to decrease the right value unless we have already increased
946 // it virtually when we replaced EQ with SLT.
947 if (!IncreasedRightValueByOne) {
948 IRBuilder<> B(Preheader->getTerminator());
949 RightValue = B.CreateSub(RightValue, One);
950 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000951 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000952 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000953 FailureReason = "Induction variable start not bounded by lower limit";
954 return None;
955 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000956 assert(!IncreasedRightValueByOne &&
957 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000958 }
959 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000960 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
961
Sanjoy Dase75ed922015-02-26 08:19:31 +0000962 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000963 ScalarEvolution::LoopInvariant &&
964 "loop variant exit count doesn't make sense!");
965
Sanjoy Dase75ed922015-02-26 08:19:31 +0000966 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 const DataLayout &DL = Preheader->getModule()->getDataLayout();
968 Value *IndVarStartV =
969 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000970 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000971 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000972
Sanjoy Dase75ed922015-02-26 08:19:31 +0000973 LoopStructure Result;
974
975 Result.Tag = "main";
976 Result.Header = Header;
977 Result.Latch = Latch;
978 Result.LatchBr = LatchBr;
979 Result.LatchExit = LatchExit;
980 Result.LatchBrExitIdx = LatchBrExitIdx;
981 Result.IndVarStart = IndVarStartV;
982 Result.IndVarNext = LeftValue;
983 Result.IndVarIncreasing = IsIncreasing;
984 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000985 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000986
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000987 FailureReason = nullptr;
988
Sanjoy Dase75ed922015-02-26 08:19:31 +0000989 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000990}
991
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000992Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000993LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000994 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
995
Sanjoy Das351db052015-01-22 09:32:02 +0000996 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000997 return None;
998
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000999 LoopConstrainer::SubRanges Result;
1000
1001 // I think we can be more aggressive here and make this nuw / nsw if the
1002 // addition that feeds into the icmp for the latch's terminating branch is nuw
1003 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001004 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1005 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001006
Sanjoy Dase75ed922015-02-26 08:19:31 +00001007 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001008
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001009 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1010 // [Smallest, GreatestSeen] is the range of values the induction variable
1011 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001012
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001013 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001014
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001015 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001016 if (Increasing) {
1017 Smallest = Start;
1018 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001019 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1020 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001021 } else {
1022 // These two computations may sign-overflow. Here is why that is okay:
1023 //
1024 // We know that the induction variable does not sign-overflow on any
1025 // iteration except the last one, and it starts at `Start` and ends at
1026 // `End`, decrementing by one every time.
1027 //
1028 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1029 // induction variable is decreasing we know that that the smallest value
1030 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1031 //
1032 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1033 // that case, `Clamp` will always return `Smallest` and
1034 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1035 // will be an empty range. Returning an empty range is always safe.
1036 //
1037
Max Kazantsev6c466a32017-06-28 04:57:45 +00001038 Smallest = SE.getAddExpr(End, One);
1039 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001040 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001041 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001042
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001043 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
1044 return IsSignedPredicate
1045 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1046 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001047 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001048
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001049 // In some cases we can prove that we don't need a pre or post loop.
1050 ICmpInst::Predicate PredLE =
1051 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1052 ICmpInst::Predicate PredLT =
1053 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001054
1055 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001056 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001057 if (!ProvablyNoPreloop)
1058 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001059
1060 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001061 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001062 if (!ProvablyNoPostLoop)
1063 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001064
1065 return Result;
1066}
1067
1068void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1069 const char *Tag) const {
1070 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1071 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1072 Result.Blocks.push_back(Clone);
1073 Result.Map[BB] = Clone;
1074 }
1075
1076 auto GetClonedValue = [&Result](Value *V) {
1077 assert(V && "null values not in domain!");
1078 auto It = Result.Map.find(V);
1079 if (It == Result.Map.end())
1080 return V;
1081 return static_cast<Value *>(It->second);
1082 };
1083
Sanjoy Das7a18a232016-08-14 01:04:36 +00001084 auto *ClonedLatch =
1085 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1086 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1087 MDNode::get(Ctx, {}));
1088
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001089 Result.Structure = MainLoopStructure.map(GetClonedValue);
1090 Result.Structure.Tag = Tag;
1091
1092 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1093 BasicBlock *ClonedBB = Result.Blocks[i];
1094 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1095
1096 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1097
1098 for (Instruction &I : *ClonedBB)
1099 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001100 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001101
1102 // Exit blocks will now have one more predecessor and their PHI nodes need
1103 // to be edited to reflect that. No phi nodes need to be introduced because
1104 // the loop is in LCSSA.
1105
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001106 for (auto *SBB : successors(OriginalBB)) {
1107 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001108 continue; // not an exit block
1109
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001110 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001111 auto *PN = dyn_cast<PHINode>(&I);
1112 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001113 break;
1114
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001115 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1116 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1117 }
1118 }
1119 }
1120}
1121
1122LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001123 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001124 BasicBlock *ContinuationBlock) const {
1125
1126 // We start with a loop with a single latch:
1127 //
1128 // +--------------------+
1129 // | |
1130 // | preheader |
1131 // | |
1132 // +--------+-----------+
1133 // | ----------------\
1134 // | / |
1135 // +--------v----v------+ |
1136 // | | |
1137 // | header | |
1138 // | | |
1139 // +--------------------+ |
1140 // |
1141 // ..... |
1142 // |
1143 // +--------------------+ |
1144 // | | |
1145 // | latch >----------/
1146 // | |
1147 // +-------v------------+
1148 // |
1149 // |
1150 // | +--------------------+
1151 // | | |
1152 // +---> original exit |
1153 // | |
1154 // +--------------------+
1155 //
1156 // We change the control flow to look like
1157 //
1158 //
1159 // +--------------------+
1160 // | |
1161 // | preheader >-------------------------+
1162 // | | |
1163 // +--------v-----------+ |
1164 // | /-------------+ |
1165 // | / | |
1166 // +--------v--v--------+ | |
1167 // | | | |
1168 // | header | | +--------+ |
1169 // | | | | | |
1170 // +--------------------+ | | +-----v-----v-----------+
1171 // | | | |
1172 // | | | .pseudo.exit |
1173 // | | | |
1174 // | | +-----------v-----------+
1175 // | | |
1176 // ..... | | |
1177 // | | +--------v-------------+
1178 // +--------------------+ | | | |
1179 // | | | | | ContinuationBlock |
1180 // | latch >------+ | | |
1181 // | | | +----------------------+
1182 // +---------v----------+ |
1183 // | |
1184 // | |
1185 // | +---------------^-----+
1186 // | | |
1187 // +-----> .exit.selector |
1188 // | |
1189 // +----------v----------+
1190 // |
1191 // +--------------------+ |
1192 // | | |
1193 // | original exit <----+
1194 // | |
1195 // +--------------------+
1196 //
1197
1198 RewrittenRangeInfo RRI;
1199
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001200 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001201 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001202 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001203 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001204 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001205
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001206 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001207 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001208 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001209
1210 IRBuilder<> B(PreheaderJump);
1211
1212 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001213 Value *EnterLoopCond = nullptr;
1214 if (Increasing)
1215 EnterLoopCond = IsSignedPredicate
1216 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1217 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1218 else
1219 EnterLoopCond = IsSignedPredicate
1220 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1221 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001222
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001223 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1224 PreheaderJump->eraseFromParent();
1225
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001226 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001227 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001228 Value *TakeBackedgeLoopCond = nullptr;
1229 if (Increasing)
1230 TakeBackedgeLoopCond = IsSignedPredicate
1231 ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1232 : B.CreateICmpULT(LS.IndVarNext, ExitSubloopAt);
1233 else
1234 TakeBackedgeLoopCond = IsSignedPredicate
1235 ? B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt)
1236 : B.CreateICmpUGT(LS.IndVarNext, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001237 Value *CondForBranch = LS.LatchBrExitIdx == 1
1238 ? TakeBackedgeLoopCond
1239 : B.CreateNot(TakeBackedgeLoopCond);
1240
1241 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001242
1243 B.SetInsertPoint(RRI.ExitSelector);
1244
1245 // IterationsLeft - are there any more iterations left, given the original
1246 // upper bound on the induction variable? If not, we branch to the "real"
1247 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001248 Value *IterationsLeft = nullptr;
1249 if (Increasing)
1250 IterationsLeft = IsSignedPredicate
1251 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1252 : B.CreateICmpULT(LS.IndVarNext, LS.LoopExitAt);
1253 else
1254 IterationsLeft = IsSignedPredicate
1255 ? B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt)
1256 : B.CreateICmpUGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001257 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1258
1259 BranchInst *BranchToContinuation =
1260 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1261
1262 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1263 // each of the PHI nodes in the loop header. This feeds into the initial
1264 // value of the same PHI nodes if/when we continue execution.
1265 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001266 auto *PN = dyn_cast<PHINode>(&I);
1267 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001268 break;
1269
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001270 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1271 BranchToContinuation);
1272
1273 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1274 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1275 RRI.ExitSelector);
1276 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1277 }
1278
Sanjoy Dase75ed922015-02-26 08:19:31 +00001279 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1280 BranchToContinuation);
1281 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1282 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1283
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001284 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1285 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1286 for (Instruction &I : *LS.LatchExit) {
1287 if (PHINode *PN = dyn_cast<PHINode>(&I))
1288 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1289 else
1290 break;
1291 }
1292
1293 return RRI;
1294}
1295
1296void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001297 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001298 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1299
1300 unsigned PHIIndex = 0;
1301 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001302 auto *PN = dyn_cast<PHINode>(&I);
1303 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001304 break;
1305
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001306 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1307 if (PN->getIncomingBlock(i) == ContinuationBlock)
1308 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1309 }
1310
Sanjoy Dase75ed922015-02-26 08:19:31 +00001311 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001312}
1313
Sanjoy Dase75ed922015-02-26 08:19:31 +00001314BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1315 BasicBlock *OldPreheader,
1316 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001317
1318 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1319 BranchInst::Create(LS.Header, Preheader);
1320
1321 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001322 auto *PN = dyn_cast<PHINode>(&I);
1323 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324 break;
1325
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001326 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1327 replacePHIBlock(PN, OldPreheader, Preheader);
1328 }
1329
1330 return Preheader;
1331}
1332
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001333void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001334 Loop *ParentLoop = OriginalLoop.getParentLoop();
1335 if (!ParentLoop)
1336 return;
1337
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001338 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001339 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340}
1341
Sanjoy Das21434472016-08-14 01:04:46 +00001342Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1343 ValueToValueMapTy &VM) {
Chandler Carruth29c22d22017-05-25 03:01:31 +00001344 Loop &New = *new Loop();
1345 if (Parent)
1346 Parent->addChildLoop(&New);
1347 else
1348 LI.addTopLevelLoop(&New);
1349 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001350
1351 // Add all of the blocks in Original to the new loop.
1352 for (auto *BB : Original->blocks())
1353 if (LI.getLoopFor(BB) == Original)
1354 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1355
1356 // Add all of the subloops to the new loop.
1357 for (Loop *SubLoop : *Original)
1358 createClonedLoopStructure(SubLoop, &New, VM);
1359
1360 return &New;
1361}
1362
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363bool LoopConstrainer::run() {
1364 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001365 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1366 Preheader = OriginalLoop.getLoopPreheader();
1367 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1368 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001369
1370 OriginalPreheader = Preheader;
1371 MainLoopPreheader = Preheader;
1372
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001373 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1374 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001375 if (!MaybeSR.hasValue()) {
1376 DEBUG(dbgs() << "irce: could not compute subranges\n");
1377 return false;
1378 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001379
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001380 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001381 bool Increasing = MainLoopStructure.IndVarIncreasing;
1382 IntegerType *IVTy =
1383 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1384
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001385 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001386 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001387
1388 // It would have been better to make `PreLoop' and `PostLoop'
1389 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1390 // constructor.
1391 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001392 bool NeedsPreLoop =
1393 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1394 bool NeedsPostLoop =
1395 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1396
1397 Value *ExitPreLoopAt = nullptr;
1398 Value *ExitMainLoopAt = nullptr;
1399 const SCEVConstant *MinusOneS =
1400 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1401
1402 if (NeedsPreLoop) {
1403 const SCEV *ExitPreLoopAtSCEV = nullptr;
1404
1405 if (Increasing)
1406 ExitPreLoopAtSCEV = *SR.LowLimit;
1407 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001408 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001409 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1410 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1411 << "\n");
1412 return false;
1413 }
1414 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1415 }
1416
1417 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1418 ExitPreLoopAt->setName("exit.preloop.at");
1419 }
1420
1421 if (NeedsPostLoop) {
1422 const SCEV *ExitMainLoopAtSCEV = nullptr;
1423
1424 if (Increasing)
1425 ExitMainLoopAtSCEV = *SR.HighLimit;
1426 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001427 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001428 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1429 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1430 << "\n");
1431 return false;
1432 }
1433 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1434 }
1435
1436 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1437 ExitMainLoopAt->setName("exit.mainloop.at");
1438 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001439
1440 // We clone these ahead of time so that we don't have to deal with changing
1441 // and temporarily invalid IR as we transform the loops.
1442 if (NeedsPreLoop)
1443 cloneLoop(PreLoop, "preloop");
1444 if (NeedsPostLoop)
1445 cloneLoop(PostLoop, "postloop");
1446
1447 RewrittenRangeInfo PreLoopRRI;
1448
1449 if (NeedsPreLoop) {
1450 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1451 PreLoop.Structure.Header);
1452
1453 MainLoopPreheader =
1454 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001455 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1456 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001457 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1458 PreLoopRRI);
1459 }
1460
1461 BasicBlock *PostLoopPreheader = nullptr;
1462 RewrittenRangeInfo PostLoopRRI;
1463
1464 if (NeedsPostLoop) {
1465 PostLoopPreheader =
1466 createPreheader(PostLoop.Structure, Preheader, "postloop");
1467 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001468 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001469 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1470 PostLoopRRI);
1471 }
1472
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001473 BasicBlock *NewMainLoopPreheader =
1474 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1475 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1476 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1477 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001478
1479 // Some of the above may be nullptr, filter them out before passing to
1480 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001481 auto NewBlocksEnd =
1482 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001483
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001484 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001485
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001486 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001487
Anna Thomas72180322017-06-06 14:54:01 +00001488 // We need to first add all the pre and post loop blocks into the loop
1489 // structures (as part of createClonedLoopStructure), and then update the
1490 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1491 // LI when LoopSimplifyForm is generated.
1492 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001493 if (!PreLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001494 PreL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001495 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001496 }
1497
1498 if (!PostLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001499 PostL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001500 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001501 }
1502
Anna Thomas72180322017-06-06 14:54:01 +00001503 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1504 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1505 formLCSSARecursively(*L, DT, &LI, &SE);
1506 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1507 // Pre/post loops are slow paths, we do not need to perform any loop
1508 // optimizations on them.
1509 if (!IsOriginalLoop)
1510 DisableAllLoopOptsOnLoop(*L);
1511 };
1512 if (PreL)
1513 CanonicalizeLoop(PreL, false);
1514 if (PostL)
1515 CanonicalizeLoop(PostL, false);
1516 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001517
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001518 return true;
1519}
1520
Sanjoy Das95c476d2015-02-21 22:20:22 +00001521/// Computes and returns a range of values for the induction variable (IndVar)
1522/// in which the range check can be safely elided. If it cannot compute such a
1523/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001524Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001525InductiveRangeCheck::computeSafeIterationSpace(
1526 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001527 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1528 // variable, that may or may not exist as a real llvm::Value in the loop) and
1529 // this inductive range check is a range check on the "C + D * I" ("C" is
1530 // getOffset() and "D" is getScale()). We rewrite the value being range
1531 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1532 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1533 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001534 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001535 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001536 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001537 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1538 //
1539 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1540 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001541 //
1542 // Proof:
1543 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001544 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1545 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1546 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1547 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001548 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001549 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1550 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001551
Sanjoy Das95c476d2015-02-21 22:20:22 +00001552 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1553 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001554
Sanjoy Das95c476d2015-02-21 22:20:22 +00001555 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001556 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001557
Sanjoy Das95c476d2015-02-21 22:20:22 +00001558 const SCEV *A = IndVar->getStart();
1559 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1560 if (!B)
1561 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001562 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001563
1564 const SCEV *C = getOffset();
1565 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1566 if (D != B)
1567 return None;
1568
1569 ConstantInt *ConstD = D->getValue();
1570 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1571 return None;
1572
1573 const SCEV *M = SE.getMinusSCEV(C, A);
1574
1575 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001576 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001577
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001578 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1579 // We can potentially do much better here.
1580 if (Value *V = getLength()) {
1581 UpperLimit = SE.getSCEV(V);
1582 } else {
1583 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1584 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1585 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1586 }
1587
1588 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001589 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001590}
1591
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001592static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001593IntersectRange(ScalarEvolution &SE,
1594 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001595 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001596 if (!R1.hasValue())
1597 return R2;
1598 auto &R1Value = R1.getValue();
1599
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001600 // TODO: we could widen the smaller range and have this work; but for now we
1601 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001602 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001603 return None;
1604
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001605 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1606 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1607
1608 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001609}
1610
1611bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001612 if (skipLoop(L))
1613 return false;
1614
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001615 if (L->getBlocks().size() >= LoopSizeCutoff) {
1616 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1617 return false;
1618 }
1619
1620 BasicBlock *Preheader = L->getLoopPreheader();
1621 if (!Preheader) {
1622 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1623 return false;
1624 }
1625
1626 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001627 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001628 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001629 BranchProbabilityInfo &BPI =
1630 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001631
1632 for (auto BBI : L->getBlocks())
1633 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001634 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1635 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001636
1637 if (RangeChecks.empty())
1638 return false;
1639
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001640 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1641 OS << "irce: looking at loop "; L->print(OS);
1642 OS << "irce: loop has " << RangeChecks.size()
1643 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001644 for (InductiveRangeCheck &IRC : RangeChecks)
1645 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001646 };
1647
1648 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1649
1650 if (PrintRangeChecks)
1651 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001652
Sanjoy Dase75ed922015-02-26 08:19:31 +00001653 const char *FailureReason = nullptr;
1654 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001655 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001656 if (!MaybeLoopStructure.hasValue()) {
1657 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1658 << "\n";);
1659 return false;
1660 }
1661 LoopStructure LS = MaybeLoopStructure.getValue();
1662 bool Increasing = LS.IndVarIncreasing;
1663 const SCEV *MinusOne =
1664 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1665 const SCEVAddRecExpr *IndVar =
1666 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1667
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001668 Optional<InductiveRangeCheck::Range> SafeIterRange;
1669 Instruction *ExprInsertPt = Preheader->getTerminator();
1670
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001671 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001672
1673 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001674 for (InductiveRangeCheck &IRC : RangeChecks) {
1675 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001676 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001677 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001678 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001679 if (MaybeSafeIterRange.hasValue()) {
1680 RangeChecksToEliminate.push_back(IRC);
1681 SafeIterRange = MaybeSafeIterRange.getValue();
1682 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001683 }
1684 }
1685
1686 if (!SafeIterRange.hasValue())
1687 return false;
1688
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001689 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001690 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1691 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001692 bool Changed = LC.run();
1693
1694 if (Changed) {
1695 auto PrintConstrainedLoopInfo = [L]() {
1696 dbgs() << "irce: in function ";
1697 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1698 dbgs() << "constrained ";
1699 L->print(dbgs());
1700 };
1701
1702 DEBUG(PrintConstrainedLoopInfo());
1703
1704 if (PrintChangedLoops)
1705 PrintConstrainedLoopInfo();
1706
1707 // Optimize away the now-redundant range checks.
1708
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001709 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1710 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001711 ? ConstantInt::getTrue(Context)
1712 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001713 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001714 }
1715 }
1716
1717 return Changed;
1718}
1719
1720Pass *llvm::createInductiveRangeCheckEliminationPass() {
1721 return new InductiveRangeCheckElimination;
1722}