blob: 111713b541c90440feaced7e6fbb2e33b70c7743 [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
Max Kazantsev8aacef62017-10-04 06:53:22 +000082static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
83 cl::Hidden, cl::init(false));
84
Sanjoy Das7a18a232016-08-14 01:04:36 +000085static const char *ClonedLoopTag = "irce.loop.clone";
86
Sanjoy Dasa1837a32015-01-16 01:03:22 +000087#define DEBUG_TYPE "irce"
88
89namespace {
90
91/// An inductive range check is conditional branch in a loop with
92///
93/// 1. a very cold successor (i.e. the branch jumps to that successor very
94/// rarely)
95///
96/// and
97///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000098/// 2. a condition that is provably true for some contiguous range of values
99/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000100///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000101class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000102 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000103 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000104 // Range check of the form "0 <= I".
105 RANGE_CHECK_LOWER = 1,
106
107 // Range check of the form "I < L" where L is known positive.
108 RANGE_CHECK_UPPER = 2,
109
110 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
111 // conditions.
112 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
113
114 // Unrecognized range check condition.
115 RANGE_CHECK_UNKNOWN = (unsigned)-1
116 };
117
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000118 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000119
Sanjoy Dasee77a482016-05-26 01:50:18 +0000120 const SCEV *Offset = nullptr;
121 const SCEV *Scale = nullptr;
122 Value *Length = nullptr;
123 Use *CheckUse = nullptr;
124 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000125
Sanjoy Das337d46b2015-03-24 19:29:18 +0000126 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
127 ScalarEvolution &SE, Value *&Index,
128 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000129
Sanjoy Dasa0992682016-05-26 00:09:02 +0000130 static void
131 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
132 SmallVectorImpl<InductiveRangeCheck> &Checks,
133 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000134
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000135public:
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)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000152 OS << "\n CheckUse: ";
153 getCheckUse()->getUser()->print(OS);
154 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 }
156
Davide Italianod1279df2016-08-18 15:55:49 +0000157 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000158 void dump() {
159 print(dbgs());
160 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000161
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000162 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000163
Sanjoy Das351db052015-01-22 09:32:02 +0000164 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
165 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
166
167 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000168 const SCEV *Begin;
169 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000170
171 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000172 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000173 assert(Begin->getType() == End->getType() && "ill-typed range!");
174 }
175
176 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000177 const SCEV *getBegin() const { return Begin; }
178 const SCEV *getEnd() const { return End; }
Max Kazantsev25d86552017-10-11 06:53:07 +0000179 bool isEmpty() const { return Begin == End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000180 };
181
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000182 /// This is the value the condition of the branch needs to evaluate to for the
183 /// branch to take the hot successor (see (1) above).
184 bool getPassingDirection() { return true; }
185
Sanjoy Das95c476d2015-02-21 22:20:22 +0000186 /// Computes a range for the induction variable (IndVar) in which the range
187 /// check is redundant and can be constant-folded away. The induction
188 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000189 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000190 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191
Sanjoy Dasa0992682016-05-26 00:09:02 +0000192 /// Parse out a set of inductive range checks from \p BI and append them to \p
193 /// Checks.
194 ///
195 /// NB! There may be conditions feeding into \p BI that aren't inductive range
196 /// checks, and hence don't end up in \p Checks.
197 static void
198 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
199 BranchProbabilityInfo &BPI,
200 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000201};
202
203class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000204public:
205 static char ID;
206 InductiveRangeCheckElimination() : LoopPass(ID) {
207 initializeInductiveRangeCheckEliminationPass(
208 *PassRegistry::getPassRegistry());
209 }
210
211 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000212 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000213 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000214 }
215
216 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
217};
218
219char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000220}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000221
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000222INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
223 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000224INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000225INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000226INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
227 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000228
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000229StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000230 InductiveRangeCheck::RangeCheckKind RCK) {
231 switch (RCK) {
232 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
233 return "RANGE_CHECK_UNKNOWN";
234
235 case InductiveRangeCheck::RANGE_CHECK_UPPER:
236 return "RANGE_CHECK_UPPER";
237
238 case InductiveRangeCheck::RANGE_CHECK_LOWER:
239 return "RANGE_CHECK_LOWER";
240
241 case InductiveRangeCheck::RANGE_CHECK_BOTH:
242 return "RANGE_CHECK_BOTH";
243 }
244
245 llvm_unreachable("unknown range check type!");
246}
247
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000248/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000249/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000250/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000251/// range checked, and set `Length` to the upper limit `Index` is being range
252/// checked with if (and only if) the range check type is stronger or equal to
253/// RANGE_CHECK_UPPER.
254///
255InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000256InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
257 ScalarEvolution &SE, Value *&Index,
258 Value *&Length) {
259
260 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
261 const SCEV *S = SE.getSCEV(V);
262 if (isa<SCEVCouldNotCompute>(S))
263 return false;
264
265 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
266 SE.isKnownNonNegative(S);
267 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000268
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000269 using namespace llvm::PatternMatch;
270
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000271 ICmpInst::Predicate Pred = ICI->getPredicate();
272 Value *LHS = ICI->getOperand(0);
273 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000274
275 switch (Pred) {
276 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000277 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000278
279 case ICmpInst::ICMP_SLE:
280 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000281 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000282 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000283 if (match(RHS, m_ConstantInt<0>())) {
284 Index = LHS;
285 return RANGE_CHECK_LOWER;
286 }
287 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000288
289 case ICmpInst::ICMP_SLT:
290 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000291 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000292 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000293 if (match(RHS, m_ConstantInt<-1>())) {
294 Index = LHS;
295 return RANGE_CHECK_LOWER;
296 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000297
Sanjoy Das337d46b2015-03-24 19:29:18 +0000298 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000299 Index = RHS;
300 Length = LHS;
301 return RANGE_CHECK_UPPER;
302 }
303 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000304
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000305 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000307 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000308 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000309 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000310 Index = RHS;
311 Length = LHS;
312 return RANGE_CHECK_BOTH;
313 }
314 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000315 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000316
317 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000318}
319
Sanjoy Dasa0992682016-05-26 00:09:02 +0000320void InductiveRangeCheck::extractRangeChecksFromCond(
321 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
322 SmallVectorImpl<InductiveRangeCheck> &Checks,
323 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000324 using namespace llvm::PatternMatch;
325
Sanjoy Das8fe88922016-05-26 00:08:24 +0000326 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000327 if (!Visited.insert(Condition).second)
328 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000329
Sanjoy Dasa0992682016-05-26 00:09:02 +0000330 if (match(Condition, m_And(m_Value(), m_Value()))) {
331 SmallVector<InductiveRangeCheck, 8> SubChecks;
332 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
333 SubChecks, Visited);
334 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
335 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000336
Sanjoy Dasa0992682016-05-26 00:09:02 +0000337 if (SubChecks.size() == 2) {
338 // Handle a special case where we know how to merge two checks separately
339 // checking the upper and lower bounds into a full range check.
340 const auto &RChkA = SubChecks[0];
341 const auto &RChkB = SubChecks[1];
342 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
343 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000344
Sanjoy Dasa0992682016-05-26 00:09:02 +0000345 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
346 // But if one of them is a RANGE_CHECK_LOWER and the other is a
347 // RANGE_CHECK_UPPER (only possibility if they're different) then
348 // together they form a RANGE_CHECK_BOTH.
349 SubChecks[0].Kind =
350 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
351 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
352 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000353
Sanjoy Dasa0992682016-05-26 00:09:02 +0000354 // We updated one of the checks in place, now erase the other.
355 SubChecks.pop_back();
356 }
357 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358
Sanjoy Dasa0992682016-05-26 00:09:02 +0000359 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
360 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000361 }
362
Sanjoy Dasa0992682016-05-26 00:09:02 +0000363 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
364 if (!ICI)
365 return;
366
367 Value *Length = nullptr, *Index;
368 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
369 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
370 return;
371
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000372 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000373 bool IsAffineIndex =
374 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
375
376 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000377 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000378
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000379 InductiveRangeCheck IRC;
380 IRC.Length = Length;
381 IRC.Offset = IndexAddRec->getStart();
382 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000383 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000384 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000385 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000386}
387
Sanjoy Dasa0992682016-05-26 00:09:02 +0000388void InductiveRangeCheck::extractRangeChecksFromBranch(
389 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
390 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000391
392 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000393 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000394
395 BranchProbability LikelyTaken(15, 16);
396
Sanjoy Dasbb969792016-07-22 00:40:56 +0000397 if (!SkipProfitabilityChecks &&
398 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000399 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000400
Sanjoy Dasa0992682016-05-26 00:09:02 +0000401 SmallPtrSet<Value *, 8> Visited;
402 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
403 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000404}
405
Anna Thomas65ca8e92016-12-13 21:05:21 +0000406// Add metadata to the loop L to disable loop optimizations. Callers need to
407// confirm that optimizing loop L is not beneficial.
408static void DisableAllLoopOptsOnLoop(Loop &L) {
409 // We do not care about any existing loopID related metadata for L, since we
410 // are setting all loop metadata to false.
411 LLVMContext &Context = L.getHeader()->getContext();
412 // Reserve first location for self reference to the LoopID metadata node.
413 MDNode *Dummy = MDNode::get(Context, {});
414 MDNode *DisableUnroll = MDNode::get(
415 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
416 Metadata *FalseVal =
417 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
418 MDNode *DisableVectorize = MDNode::get(
419 Context,
420 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
421 MDNode *DisableLICMVersioning = MDNode::get(
422 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
423 MDNode *DisableDistribution= MDNode::get(
424 Context,
425 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
426 MDNode *NewLoopID =
427 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
428 DisableLICMVersioning, DisableDistribution});
429 // Set operand 0 to refer to the loop id itself.
430 NewLoopID->replaceOperandWith(0, NewLoopID);
431 L.setLoopID(NewLoopID);
432}
433
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000434namespace {
435
Sanjoy Dase75ed922015-02-26 08:19:31 +0000436// Keeps track of the structure of a loop. This is similar to llvm::Loop,
437// except that it is more lightweight and can track the state of a loop through
438// changing and potentially invalid IR. This structure also formalizes the
439// kinds of loops we can deal with -- ones that have a single latch that is also
440// an exiting block *and* have a canonical induction variable.
441struct LoopStructure {
442 const char *Tag;
443
444 BasicBlock *Header;
445 BasicBlock *Latch;
446
447 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
448 // successor is `LatchExit', the exit block of the loop.
449 BranchInst *LatchBr;
450 BasicBlock *LatchExit;
451 unsigned LatchBrExitIdx;
452
Sanjoy Dasec892132017-02-07 23:59:07 +0000453 // The loop represented by this instance of LoopStructure is semantically
454 // equivalent to:
455 //
456 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000457 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000458 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000459 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000460 // ... body ...
461
Max Kazantseva22742b2017-08-31 05:58:15 +0000462 Value *IndVarBase;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000463 Value *IndVarStart;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000464 Value *IndVarStep;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000465 Value *LoopExitAt;
466 bool IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000467 bool IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000468
469 LoopStructure()
470 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
Max Kazantseva22742b2017-08-31 05:58:15 +0000471 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarBase(nullptr),
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000472 IndVarStart(nullptr), IndVarStep(nullptr), LoopExitAt(nullptr),
Serguei Katkov675e3042017-09-21 04:50:41 +0000473 IndVarIncreasing(false), IsSignedPredicate(true) {}
Sanjoy Dase75ed922015-02-26 08:19:31 +0000474
475 template <typename M> LoopStructure map(M Map) const {
476 LoopStructure Result;
477 Result.Tag = Tag;
478 Result.Header = cast<BasicBlock>(Map(Header));
479 Result.Latch = cast<BasicBlock>(Map(Latch));
480 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
481 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
482 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000483 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000484 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000485 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000486 Result.LoopExitAt = Map(LoopExitAt);
487 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000488 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000489 return Result;
490 }
491
Sanjoy Dase91665d2015-02-26 08:56:04 +0000492 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
493 BranchProbabilityInfo &BPI,
494 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000495 const char *&);
496};
497
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000498/// This class is used to constrain loops to run within a given iteration space.
499/// The algorithm this class implements is given a Loop and a range [Begin,
500/// End). The algorithm then tries to break out a "main loop" out of the loop
501/// it is given in a way that the "main loop" runs with the induction variable
502/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
503/// loops to run any remaining iterations. The pre loop runs any iterations in
504/// which the induction variable is < Begin, and the post loop runs any
505/// iterations in which the induction variable is >= End.
506///
507class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000508 // The representation of a clone of the original loop we started out with.
509 struct ClonedLoop {
510 // The cloned blocks
511 std::vector<BasicBlock *> Blocks;
512
513 // `Map` maps values in the clonee into values in the cloned version
514 ValueToValueMapTy Map;
515
516 // An instance of `LoopStructure` for the cloned loop
517 LoopStructure Structure;
518 };
519
520 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
521 // more details on what these fields mean.
522 struct RewrittenRangeInfo {
523 BasicBlock *PseudoExit;
524 BasicBlock *ExitSelector;
525 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000526 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000527
Sanjoy Dase75ed922015-02-26 08:19:31 +0000528 RewrittenRangeInfo()
529 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000530 };
531
532 // Calculated subranges we restrict the iteration space of the main loop to.
533 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000534 // these fields are computed. `LowLimit` is None if there is no restriction
535 // on low end of the restricted iteration space of the main loop. `HighLimit`
536 // is None if there is no restriction on high end of the restricted iteration
537 // space of the main loop.
538
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000539 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000540 Optional<const SCEV *> LowLimit;
541 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000542 };
543
544 // A utility function that does a `replaceUsesOfWith' on the incoming block
545 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
546 // incoming block list with `ReplaceBy'.
547 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
548 BasicBlock *ReplaceBy);
549
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550 // Compute a safe set of limits for the main loop to run in -- effectively the
551 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000552 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000553 //
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000554 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000555
556 // Clone `OriginalLoop' and return the result in CLResult. The IR after
557 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
558 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
559 // but there is no such edge.
560 //
561 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
562
Sanjoy Das21434472016-08-14 01:04:46 +0000563 // Create the appropriate loop structure needed to describe a cloned copy of
564 // `Original`. The clone is described by `VM`.
565 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
566 ValueToValueMapTy &VM);
567
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000568 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
569 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
570 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
571 // `OriginalHeaderCount'.
572 //
573 // If there are iterations left to execute, control is made to jump to
574 // `ContinuationBlock', otherwise they take the normal loop exit. The
575 // returned `RewrittenRangeInfo' object is populated as follows:
576 //
577 // .PseudoExit is a basic block that unconditionally branches to
578 // `ContinuationBlock'.
579 //
580 // .ExitSelector is a basic block that decides, on exit from the loop,
581 // whether to branch to the "true" exit or to `PseudoExit'.
582 //
583 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
584 // for each PHINode in the loop header on taking the pseudo exit.
585 //
586 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
587 // preheader because it is made to branch to the loop header only
588 // conditionally.
589 //
590 RewrittenRangeInfo
591 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
592 Value *ExitLoopAt,
593 BasicBlock *ContinuationBlock) const;
594
595 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
596 // function creates a new preheader for `LS' and returns it.
597 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000598 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
599 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000600
601 // `ContinuationBlockAndPreheader' was the continuation block for some call to
602 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
603 // This function rewrites the PHI nodes in `LS.Header' to start with the
604 // correct value.
605 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000606 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
608
609 // Even though we do not preserve any passes at this time, we at least need to
610 // keep the parent loop structure consistent. The `LPPassManager' seems to
611 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000612 // blocks denoted by BBs to this loops parent loop if required.
613 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000614
615 // Some global state.
616 Function &F;
617 LLVMContext &Ctx;
618 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000619 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000620 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000621 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000622
623 // Information about the original loop we started out with.
624 Loop &OriginalLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000625 const SCEV *LatchTakenCount;
626 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000627
628 // The preheader of the main loop. This may or may not be different from
629 // `OriginalPreheader'.
630 BasicBlock *MainLoopPreheader;
631
632 // The range we need to run the main loop in.
633 InductiveRangeCheck::Range Range;
634
635 // The structure of the main loop (see comment at the beginning of this class
636 // for a definition)
637 LoopStructure MainLoopStructure;
638
639public:
Sanjoy Das21434472016-08-14 01:04:46 +0000640 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
641 const LoopStructure &LS, ScalarEvolution &SE,
642 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000643 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das35459f02016-08-14 01:04:50 +0000644 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L),
Sanjoy Das21434472016-08-14 01:04:46 +0000645 LatchTakenCount(nullptr), OriginalPreheader(nullptr),
646 MainLoopPreheader(nullptr), Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647
648 // Entry point for the algorithm. Returns true on success.
649 bool run();
650};
651
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000652}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000653
654void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
655 BasicBlock *ReplaceBy) {
656 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
657 if (PN->getIncomingBlock(i) == Block)
658 PN->setIncomingBlock(i, ReplaceBy);
659}
660
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000661static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
662 APInt Max = Signed ?
663 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
664 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
665 return SE.getSignedRange(S).contains(Max) &&
666 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000667}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000668
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000669static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
670 bool Signed) {
671 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
672 assert(SE.isKnownNonNegative(S2) &&
673 "We expected the 2nd arg to be non-negative!");
674 const SCEV *Max = SE.getConstant(
675 Signed ? APInt::getSignedMaxValue(
676 cast<IntegerType>(S1->getType())->getBitWidth())
677 : APInt::getMaxValue(
678 cast<IntegerType>(S1->getType())->getBitWidth()));
679 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
680 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
681 S1, CapForS1);
682}
683
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000684static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
685 APInt Min = Signed ?
686 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
687 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
688 return SE.getSignedRange(S).contains(Min) &&
689 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000690}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000691
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000692static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
693 bool Signed) {
694 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
695 assert(SE.isKnownNonPositive(S2) &&
696 "We expected the 2nd arg to be non-positive!");
697 const SCEV *Max = SE.getConstant(
698 Signed ? APInt::getSignedMinValue(
699 cast<IntegerType>(S1->getType())->getBitWidth())
700 : APInt::getMinValue(
701 cast<IntegerType>(S1->getType())->getBitWidth()));
702 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
703 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
704 S1, CapForS1);
705}
706
Sanjoy Dase75ed922015-02-26 08:19:31 +0000707Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000708LoopStructure::parseLoopStructure(ScalarEvolution &SE,
709 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000710 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000711 if (!L.isLoopSimplifyForm()) {
712 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000713 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000714 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000715
716 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000717 assert(Latch && "Simplified loops only have one latch!");
718
Sanjoy Das7a18a232016-08-14 01:04:36 +0000719 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
720 FailureReason = "loop has already been cloned";
721 return None;
722 }
723
Sanjoy Dase75ed922015-02-26 08:19:31 +0000724 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000725 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000726 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000727 }
728
Sanjoy Dase75ed922015-02-26 08:19:31 +0000729 BasicBlock *Header = L.getHeader();
730 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000731 if (!Preheader) {
732 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000733 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000734 }
735
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000736 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000737 if (!LatchBr || LatchBr->isUnconditional()) {
738 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000739 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000740 }
741
Sanjoy Dase75ed922015-02-26 08:19:31 +0000742 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000743
Sanjoy Dase91665d2015-02-26 08:56:04 +0000744 BranchProbability ExitProbability =
745 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
746
Sanjoy Dasbb969792016-07-22 00:40:56 +0000747 if (!SkipProfitabilityChecks &&
748 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000749 FailureReason = "short running loop, not profitable";
750 return None;
751 }
752
Sanjoy Dase75ed922015-02-26 08:19:31 +0000753 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
754 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
755 FailureReason = "latch terminator branch not conditional on integral icmp";
756 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000757 }
758
Sanjoy Dase75ed922015-02-26 08:19:31 +0000759 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
760 if (isa<SCEVCouldNotCompute>(LatchCount)) {
761 FailureReason = "could not compute latch count";
762 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000763 }
764
Sanjoy Dase75ed922015-02-26 08:19:31 +0000765 ICmpInst::Predicate Pred = ICI->getPredicate();
766 Value *LeftValue = ICI->getOperand(0);
767 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
768 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
769
770 Value *RightValue = ICI->getOperand(1);
771 const SCEV *RightSCEV = SE.getSCEV(RightValue);
772
773 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
774 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
775 if (isa<SCEVAddRecExpr>(RightSCEV)) {
776 std::swap(LeftSCEV, RightSCEV);
777 std::swap(LeftValue, RightValue);
778 Pred = ICmpInst::getSwappedPredicate(Pred);
779 } else {
780 FailureReason = "no add recurrences in the icmp";
781 return None;
782 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000783 }
784
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000785 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
786 if (AR->getNoWrapFlags(SCEV::FlagNSW))
787 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000788
789 IntegerType *Ty = cast<IntegerType>(AR->getType());
790 IntegerType *WideTy =
791 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
792
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000793 const SCEVAddRecExpr *ExtendAfterOp =
794 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
795 if (ExtendAfterOp) {
796 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
797 const SCEV *ExtendedStep =
798 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
799
800 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
801 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
802
803 if (NoSignedWrap)
804 return true;
805 }
806
807 // We may have proved this when computing the sign extension above.
808 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
809 };
810
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000811 // Here we check whether the suggested AddRec is an induction variable that
812 // can be handled (i.e. with known constant step), and if yes, calculate its
813 // step and identify whether it is increasing or decreasing.
814 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
815 ConstantInt *&StepCI) {
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000816 if (!AR->isAffine())
817 return false;
818
Sanjoy Dase75ed922015-02-26 08:19:31 +0000819 // Currently we only work with induction variables that have been proved to
820 // not wrap. This restriction can potentially be lifted in the future.
821
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000822 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000823 return false;
824
825 if (const SCEVConstant *StepExpr =
826 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000827 StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000828 assert(!StepCI->isZero() && "Zero step?");
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000829 IsIncreasing = !StepCI->isNegative();
830 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000831 }
832
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000833 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000834 };
835
Serguei Katkov675e3042017-09-21 04:50:41 +0000836 // `ICI` is interpreted as taking the backedge if the *next* value of the
837 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000838
Max Kazantseva22742b2017-08-31 05:58:15 +0000839 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000840 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000841 bool IsSignedPredicate = true;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000842 ConstantInt *StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +0000843 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000844 FailureReason = "LHS in icmp not induction variable";
845 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000846 }
847
Serguei Katkov675e3042017-09-21 04:50:41 +0000848 const SCEV *StartNext = IndVarBase->getStart();
849 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
850 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000851 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000852
Sanjoy Dase75ed922015-02-26 08:19:31 +0000853 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000855 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000856 if (StepCI->isOne()) {
857 // Try to turn eq/ne predicates to those we can work with.
858 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
859 // while (++i != len) { while (++i < len) {
860 // ... ---> ...
861 // } }
862 // If both parts are known non-negative, it is profitable to use
863 // unsigned comparison in increasing loop. This allows us to make the
864 // comparison check against "RightSCEV + 1" more optimistic.
865 if (SE.isKnownNonNegative(IndVarStart) &&
866 SE.isKnownNonNegative(RightSCEV))
867 Pred = ICmpInst::ICMP_ULT;
868 else
869 Pred = ICmpInst::ICMP_SLT;
870 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
871 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
872 // while (true) { while (true) {
873 // if (++i == len) ---> if (++i > len - 1)
874 // break; break;
875 // ... ...
876 // } }
877 // TODO: Insert ICMP_UGT if both are non-negative?
878 Pred = ICmpInst::ICMP_SGT;
879 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
880 DecreasedRightValueByOne = true;
881 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000882 }
883
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000884 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
885 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000886 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000887 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000888
889 if (!FoundExpectedPred) {
890 FailureReason = "expected icmp slt semantically, found something else";
891 return None;
892 }
893
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000894 IsSignedPredicate =
895 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000896
897 // FIXME: We temporarily disable unsigned latch conditions by default
898 // because of found problems with intersecting signed and unsigned ranges.
899 // We are going to turn it on once the problems are fixed.
900 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
901 FailureReason = "unsigned latch conditions are explicitly prohibited";
902 return None;
903 }
904
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000905 // The predicate that we need to check that the induction variable lies
906 // within bounds.
907 ICmpInst::Predicate BoundPred =
908 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
909
Sanjoy Dase75ed922015-02-26 08:19:31 +0000910 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000911 const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
912 SE.getOne(Step->getType()));
913 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000914 // TODO: this restriction is easily removable -- we just have to
915 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000916 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000917 return None;
918 }
919
Sanjoy Dasec892132017-02-07 23:59:07 +0000920 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000921 &L, BoundPred, IndVarStart,
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000922 SE.getAddExpr(RightSCEV, Step))) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000923 FailureReason = "Induction variable start not bounded by upper limit";
924 return None;
925 }
926
Max Kazantsev2c627a92017-07-18 04:53:48 +0000927 // We need to increase the right value unless we have already decreased
928 // it virtually when we replaced EQ with SGT.
929 if (!DecreasedRightValueByOne) {
930 IRBuilder<> B(Preheader->getTerminator());
931 RightValue = B.CreateAdd(RightValue, One);
932 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000933 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000934 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000935 FailureReason = "Induction variable start not bounded by upper limit";
936 return None;
937 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000938 assert(!DecreasedRightValueByOne &&
939 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000940 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000941 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000942 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000943 if (StepCI->isMinusOne()) {
944 // Try to turn eq/ne predicates to those we can work with.
945 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
946 // while (--i != len) { while (--i > len) {
947 // ... ---> ...
948 // } }
949 // We intentionally don't turn the predicate into UGT even if we know
950 // that both operands are non-negative, because it will only pessimize
951 // our check against "RightSCEV - 1".
952 Pred = ICmpInst::ICMP_SGT;
953 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
954 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
955 // while (true) { while (true) {
956 // if (--i == len) ---> if (--i < len + 1)
957 // break; break;
958 // ... ...
959 // } }
960 // TODO: Insert ICMP_ULT if both are non-negative?
961 Pred = ICmpInst::ICMP_SLT;
962 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
963 IncreasedRightValueByOne = true;
964 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000965 }
966
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000967 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
968 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
969
Sanjoy Dase75ed922015-02-26 08:19:31 +0000970 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000971 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000972
973 if (!FoundExpectedPred) {
974 FailureReason = "expected icmp sgt semantically, found something else";
975 return None;
976 }
977
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000978 IsSignedPredicate =
979 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000980
981 // FIXME: We temporarily disable unsigned latch conditions by default
982 // because of found problems with intersecting signed and unsigned ranges.
983 // We are going to turn it on once the problems are fixed.
984 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
985 FailureReason = "unsigned latch conditions are explicitly prohibited";
986 return None;
987 }
988
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000989 // The predicate that we need to check that the induction variable lies
990 // within bounds.
991 ICmpInst::Predicate BoundPred =
992 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
993
Sanjoy Dase75ed922015-02-26 08:19:31 +0000994 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000995 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
996 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000997 // TODO: this restriction is easily removable -- we just have to
998 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000999 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +00001000 return None;
1001 }
1002
Sanjoy Dasec892132017-02-07 23:59:07 +00001003 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001004 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +00001005 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1006 FailureReason = "Induction variable start not bounded by lower limit";
1007 return None;
1008 }
1009
Max Kazantsev2c627a92017-07-18 04:53:48 +00001010 // We need to decrease the right value unless we have already increased
1011 // it virtually when we replaced EQ with SLT.
1012 if (!IncreasedRightValueByOne) {
1013 IRBuilder<> B(Preheader->getTerminator());
1014 RightValue = B.CreateSub(RightValue, One);
1015 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001016 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001017 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +00001018 FailureReason = "Induction variable start not bounded by lower limit";
1019 return None;
1020 }
Max Kazantsev2c627a92017-07-18 04:53:48 +00001021 assert(!IncreasedRightValueByOne &&
1022 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001023 }
1024 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001025 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1026
Sanjoy Dase75ed922015-02-26 08:19:31 +00001027 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001028 ScalarEvolution::LoopInvariant &&
1029 "loop variant exit count doesn't make sense!");
1030
Sanjoy Dase75ed922015-02-26 08:19:31 +00001031 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001032 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1033 Value *IndVarStartV =
1034 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001035 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001036 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001037
Sanjoy Dase75ed922015-02-26 08:19:31 +00001038 LoopStructure Result;
1039
1040 Result.Tag = "main";
1041 Result.Header = Header;
1042 Result.Latch = Latch;
1043 Result.LatchBr = LatchBr;
1044 Result.LatchExit = LatchExit;
1045 Result.LatchBrExitIdx = LatchBrExitIdx;
1046 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001047 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001048 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001049 Result.IndVarIncreasing = IsIncreasing;
1050 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001051 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001052
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001053 FailureReason = nullptr;
1054
Sanjoy Dase75ed922015-02-26 08:19:31 +00001055 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001056}
1057
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001058Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001059LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001060 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1061
Sanjoy Das351db052015-01-22 09:32:02 +00001062 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001063 return None;
1064
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001065 LoopConstrainer::SubRanges Result;
1066
1067 // I think we can be more aggressive here and make this nuw / nsw if the
1068 // addition that feeds into the icmp for the latch's terminating branch is nuw
1069 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001070 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1071 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001072
Sanjoy Dase75ed922015-02-26 08:19:31 +00001073 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001074
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001075 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1076 // [Smallest, GreatestSeen] is the range of values the induction variable
1077 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001078
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001079 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001080
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001081 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001082 if (Increasing) {
1083 Smallest = Start;
1084 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001085 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1086 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001087 } else {
1088 // These two computations may sign-overflow. Here is why that is okay:
1089 //
1090 // We know that the induction variable does not sign-overflow on any
1091 // iteration except the last one, and it starts at `Start` and ends at
1092 // `End`, decrementing by one every time.
1093 //
1094 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1095 // induction variable is decreasing we know that that the smallest value
1096 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1097 //
1098 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1099 // that case, `Clamp` will always return `Smallest` and
1100 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1101 // will be an empty range. Returning an empty range is always safe.
1102 //
1103
Max Kazantsev6c466a32017-06-28 04:57:45 +00001104 Smallest = SE.getAddExpr(End, One);
1105 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001106 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001107 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001108
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001109 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev0aaf8c12017-08-18 22:50:29 +00001110 bool MaybeNegativeValues = IsSignedPredicate || !SE.isKnownNonNegative(S);
1111 return MaybeNegativeValues
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001112 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1113 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001114 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001115
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001116 // In some cases we can prove that we don't need a pre or post loop.
1117 ICmpInst::Predicate PredLE =
1118 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1119 ICmpInst::Predicate PredLT =
1120 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001121
1122 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001123 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001124 if (!ProvablyNoPreloop)
1125 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001126
1127 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001128 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001129 if (!ProvablyNoPostLoop)
1130 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001131
1132 return Result;
1133}
1134
1135void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1136 const char *Tag) const {
1137 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1138 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1139 Result.Blocks.push_back(Clone);
1140 Result.Map[BB] = Clone;
1141 }
1142
1143 auto GetClonedValue = [&Result](Value *V) {
1144 assert(V && "null values not in domain!");
1145 auto It = Result.Map.find(V);
1146 if (It == Result.Map.end())
1147 return V;
1148 return static_cast<Value *>(It->second);
1149 };
1150
Sanjoy Das7a18a232016-08-14 01:04:36 +00001151 auto *ClonedLatch =
1152 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1153 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1154 MDNode::get(Ctx, {}));
1155
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001156 Result.Structure = MainLoopStructure.map(GetClonedValue);
1157 Result.Structure.Tag = Tag;
1158
1159 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1160 BasicBlock *ClonedBB = Result.Blocks[i];
1161 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1162
1163 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1164
1165 for (Instruction &I : *ClonedBB)
1166 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001167 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168
1169 // Exit blocks will now have one more predecessor and their PHI nodes need
1170 // to be edited to reflect that. No phi nodes need to be introduced because
1171 // the loop is in LCSSA.
1172
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001173 for (auto *SBB : successors(OriginalBB)) {
1174 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001175 continue; // not an exit block
1176
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001177 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001178 auto *PN = dyn_cast<PHINode>(&I);
1179 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001180 break;
1181
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001182 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1183 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1184 }
1185 }
1186 }
1187}
1188
1189LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001190 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001191 BasicBlock *ContinuationBlock) const {
1192
1193 // We start with a loop with a single latch:
1194 //
1195 // +--------------------+
1196 // | |
1197 // | preheader |
1198 // | |
1199 // +--------+-----------+
1200 // | ----------------\
1201 // | / |
1202 // +--------v----v------+ |
1203 // | | |
1204 // | header | |
1205 // | | |
1206 // +--------------------+ |
1207 // |
1208 // ..... |
1209 // |
1210 // +--------------------+ |
1211 // | | |
1212 // | latch >----------/
1213 // | |
1214 // +-------v------------+
1215 // |
1216 // |
1217 // | +--------------------+
1218 // | | |
1219 // +---> original exit |
1220 // | |
1221 // +--------------------+
1222 //
1223 // We change the control flow to look like
1224 //
1225 //
1226 // +--------------------+
1227 // | |
1228 // | preheader >-------------------------+
1229 // | | |
1230 // +--------v-----------+ |
1231 // | /-------------+ |
1232 // | / | |
1233 // +--------v--v--------+ | |
1234 // | | | |
1235 // | header | | +--------+ |
1236 // | | | | | |
1237 // +--------------------+ | | +-----v-----v-----------+
1238 // | | | |
1239 // | | | .pseudo.exit |
1240 // | | | |
1241 // | | +-----------v-----------+
1242 // | | |
1243 // ..... | | |
1244 // | | +--------v-------------+
1245 // +--------------------+ | | | |
1246 // | | | | | ContinuationBlock |
1247 // | latch >------+ | | |
1248 // | | | +----------------------+
1249 // +---------v----------+ |
1250 // | |
1251 // | |
1252 // | +---------------^-----+
1253 // | | |
1254 // +-----> .exit.selector |
1255 // | |
1256 // +----------v----------+
1257 // |
1258 // +--------------------+ |
1259 // | | |
1260 // | original exit <----+
1261 // | |
1262 // +--------------------+
1263 //
1264
1265 RewrittenRangeInfo RRI;
1266
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001267 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001268 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001269 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001270 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001271 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001272
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001273 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001274 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001275 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276
1277 IRBuilder<> B(PreheaderJump);
1278
1279 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001280 Value *EnterLoopCond = nullptr;
1281 if (Increasing)
1282 EnterLoopCond = IsSignedPredicate
1283 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1284 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1285 else
1286 EnterLoopCond = IsSignedPredicate
1287 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1288 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001289
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001290 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1291 PreheaderJump->eraseFromParent();
1292
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001293 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001294 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001295 Value *TakeBackedgeLoopCond = nullptr;
1296 if (Increasing)
1297 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001298 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1299 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001300 else
1301 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001302 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1303 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001304 Value *CondForBranch = LS.LatchBrExitIdx == 1
1305 ? TakeBackedgeLoopCond
1306 : B.CreateNot(TakeBackedgeLoopCond);
1307
1308 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001309
1310 B.SetInsertPoint(RRI.ExitSelector);
1311
1312 // IterationsLeft - are there any more iterations left, given the original
1313 // upper bound on the induction variable? If not, we branch to the "real"
1314 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001315 Value *IterationsLeft = nullptr;
1316 if (Increasing)
1317 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001318 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1319 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001320 else
1321 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001322 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1323 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1325
1326 BranchInst *BranchToContinuation =
1327 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1328
1329 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1330 // each of the PHI nodes in the loop header. This feeds into the initial
1331 // value of the same PHI nodes if/when we continue execution.
1332 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001333 auto *PN = dyn_cast<PHINode>(&I);
1334 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001335 break;
1336
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001337 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1338 BranchToContinuation);
1339
1340 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
Serguei Katkov675e3042017-09-21 04:50:41 +00001341 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1342 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001343 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1344 }
1345
Max Kazantseva22742b2017-08-31 05:58:15 +00001346 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001347 BranchToContinuation);
1348 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001349 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001350
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001351 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1352 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1353 for (Instruction &I : *LS.LatchExit) {
1354 if (PHINode *PN = dyn_cast<PHINode>(&I))
1355 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1356 else
1357 break;
1358 }
1359
1360 return RRI;
1361}
1362
1363void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001364 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001365 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1366
1367 unsigned PHIIndex = 0;
1368 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001369 auto *PN = dyn_cast<PHINode>(&I);
1370 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001371 break;
1372
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001373 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1374 if (PN->getIncomingBlock(i) == ContinuationBlock)
1375 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1376 }
1377
Sanjoy Dase75ed922015-02-26 08:19:31 +00001378 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001379}
1380
Sanjoy Dase75ed922015-02-26 08:19:31 +00001381BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1382 BasicBlock *OldPreheader,
1383 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001384
1385 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1386 BranchInst::Create(LS.Header, Preheader);
1387
1388 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001389 auto *PN = dyn_cast<PHINode>(&I);
1390 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001391 break;
1392
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001393 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1394 replacePHIBlock(PN, OldPreheader, Preheader);
1395 }
1396
1397 return Preheader;
1398}
1399
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001400void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001401 Loop *ParentLoop = OriginalLoop.getParentLoop();
1402 if (!ParentLoop)
1403 return;
1404
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001405 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001406 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001407}
1408
Sanjoy Das21434472016-08-14 01:04:46 +00001409Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1410 ValueToValueMapTy &VM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001411 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001412 if (Parent)
1413 Parent->addChildLoop(&New);
1414 else
1415 LI.addTopLevelLoop(&New);
1416 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001417
1418 // Add all of the blocks in Original to the new loop.
1419 for (auto *BB : Original->blocks())
1420 if (LI.getLoopFor(BB) == Original)
1421 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1422
1423 // Add all of the subloops to the new loop.
1424 for (Loop *SubLoop : *Original)
1425 createClonedLoopStructure(SubLoop, &New, VM);
1426
1427 return &New;
1428}
1429
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001430bool LoopConstrainer::run() {
1431 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001432 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1433 Preheader = OriginalLoop.getLoopPreheader();
1434 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1435 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001436
1437 OriginalPreheader = Preheader;
1438 MainLoopPreheader = Preheader;
1439
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001440 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1441 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001442 if (!MaybeSR.hasValue()) {
1443 DEBUG(dbgs() << "irce: could not compute subranges\n");
1444 return false;
1445 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001446
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001447 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001448 bool Increasing = MainLoopStructure.IndVarIncreasing;
1449 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001450 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001451
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001452 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001453 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001454
1455 // It would have been better to make `PreLoop' and `PostLoop'
1456 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1457 // constructor.
1458 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001459 bool NeedsPreLoop =
1460 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1461 bool NeedsPostLoop =
1462 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1463
1464 Value *ExitPreLoopAt = nullptr;
1465 Value *ExitMainLoopAt = nullptr;
1466 const SCEVConstant *MinusOneS =
1467 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1468
1469 if (NeedsPreLoop) {
1470 const SCEV *ExitPreLoopAtSCEV = nullptr;
1471
1472 if (Increasing)
1473 ExitPreLoopAtSCEV = *SR.LowLimit;
1474 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001475 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001476 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1477 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1478 << "\n");
1479 return false;
1480 }
1481 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1482 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001483
Sanjoy Dase75ed922015-02-26 08:19:31 +00001484 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1485 ExitPreLoopAt->setName("exit.preloop.at");
1486 }
1487
1488 if (NeedsPostLoop) {
1489 const SCEV *ExitMainLoopAtSCEV = nullptr;
1490
1491 if (Increasing)
1492 ExitMainLoopAtSCEV = *SR.HighLimit;
1493 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001494 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001495 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1496 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1497 << "\n");
1498 return false;
1499 }
1500 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1501 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001502
Sanjoy Dase75ed922015-02-26 08:19:31 +00001503 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1504 ExitMainLoopAt->setName("exit.mainloop.at");
1505 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001506
1507 // We clone these ahead of time so that we don't have to deal with changing
1508 // and temporarily invalid IR as we transform the loops.
1509 if (NeedsPreLoop)
1510 cloneLoop(PreLoop, "preloop");
1511 if (NeedsPostLoop)
1512 cloneLoop(PostLoop, "postloop");
1513
1514 RewrittenRangeInfo PreLoopRRI;
1515
1516 if (NeedsPreLoop) {
1517 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1518 PreLoop.Structure.Header);
1519
1520 MainLoopPreheader =
1521 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001522 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1523 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001524 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1525 PreLoopRRI);
1526 }
1527
1528 BasicBlock *PostLoopPreheader = nullptr;
1529 RewrittenRangeInfo PostLoopRRI;
1530
1531 if (NeedsPostLoop) {
1532 PostLoopPreheader =
1533 createPreheader(PostLoop.Structure, Preheader, "postloop");
1534 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001535 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001536 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1537 PostLoopRRI);
1538 }
1539
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001540 BasicBlock *NewMainLoopPreheader =
1541 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1542 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1543 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1544 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001545
1546 // Some of the above may be nullptr, filter them out before passing to
1547 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001548 auto NewBlocksEnd =
1549 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001550
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001551 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001552
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001553 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001554
Anna Thomas72180322017-06-06 14:54:01 +00001555 // We need to first add all the pre and post loop blocks into the loop
1556 // structures (as part of createClonedLoopStructure), and then update the
1557 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1558 // LI when LoopSimplifyForm is generated.
1559 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001560 if (!PreLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001561 PreL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001562 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001563 }
1564
1565 if (!PostLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001566 PostL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001567 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001568 }
1569
Anna Thomas72180322017-06-06 14:54:01 +00001570 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1571 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1572 formLCSSARecursively(*L, DT, &LI, &SE);
1573 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1574 // Pre/post loops are slow paths, we do not need to perform any loop
1575 // optimizations on them.
1576 if (!IsOriginalLoop)
1577 DisableAllLoopOptsOnLoop(*L);
1578 };
1579 if (PreL)
1580 CanonicalizeLoop(PreL, false);
1581 if (PostL)
1582 CanonicalizeLoop(PostL, false);
1583 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001584
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001585 return true;
1586}
1587
Sanjoy Das95c476d2015-02-21 22:20:22 +00001588/// Computes and returns a range of values for the induction variable (IndVar)
1589/// in which the range check can be safely elided. If it cannot compute such a
1590/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001591Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001592InductiveRangeCheck::computeSafeIterationSpace(
1593 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001594 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1595 // variable, that may or may not exist as a real llvm::Value in the loop) and
1596 // this inductive range check is a range check on the "C + D * I" ("C" is
1597 // getOffset() and "D" is getScale()). We rewrite the value being range
1598 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001599 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001600 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001601 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001602 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1603 //
1604 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1605 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001606 //
1607 // Proof:
1608 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001609 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1610 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1611 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1612 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001613 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001614 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1615 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001616
Sanjoy Das95c476d2015-02-21 22:20:22 +00001617 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1618 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001619
Sanjoy Das95c476d2015-02-21 22:20:22 +00001620 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001621 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001622
Sanjoy Das95c476d2015-02-21 22:20:22 +00001623 const SCEV *A = IndVar->getStart();
1624 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1625 if (!B)
1626 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001627 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001628
1629 const SCEV *C = getOffset();
1630 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1631 if (D != B)
1632 return None;
1633
Max Kazantsev95054702017-08-04 07:41:24 +00001634 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001635
1636 const SCEV *M = SE.getMinusSCEV(C, A);
Sanjoy Das95c476d2015-02-21 22:20:22 +00001637 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001638 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001639
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001640 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1641 // We can potentially do much better here.
1642 if (Value *V = getLength()) {
1643 UpperLimit = SE.getSCEV(V);
1644 } else {
1645 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1646 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1647 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1648 }
1649
1650 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001651 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001652}
1653
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001654static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001655IntersectRange(ScalarEvolution &SE,
1656 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001657 const InductiveRangeCheck::Range &R2) {
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001658 if (R2.isEmpty())
Max Kazantsev25d86552017-10-11 06:53:07 +00001659 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001660 if (!R1.hasValue())
1661 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001662 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001663 // We never return empty ranges from this function, and R1 is supposed to be
1664 // a result of intersection. Thus, R1 is never empty.
1665 assert(!R1Value.isEmpty() && "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001666
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001667 // TODO: we could widen the smaller range and have this work; but for now we
1668 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001669 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001670 return None;
1671
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001672 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1673 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1674
Max Kazantsev25d86552017-10-11 06:53:07 +00001675 // If the resulting range is empty, just return None.
1676 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1677 if (Ret.isEmpty())
1678 return None;
1679 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001680}
1681
1682bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001683 if (skipLoop(L))
1684 return false;
1685
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001686 if (L->getBlocks().size() >= LoopSizeCutoff) {
1687 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1688 return false;
1689 }
1690
1691 BasicBlock *Preheader = L->getLoopPreheader();
1692 if (!Preheader) {
1693 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1694 return false;
1695 }
1696
1697 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001698 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001699 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001700 BranchProbabilityInfo &BPI =
1701 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001702
1703 for (auto BBI : L->getBlocks())
1704 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001705 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1706 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001707
1708 if (RangeChecks.empty())
1709 return false;
1710
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001711 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1712 OS << "irce: looking at loop "; L->print(OS);
1713 OS << "irce: loop has " << RangeChecks.size()
1714 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001715 for (InductiveRangeCheck &IRC : RangeChecks)
1716 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001717 };
1718
1719 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1720
1721 if (PrintRangeChecks)
1722 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001723
Sanjoy Dase75ed922015-02-26 08:19:31 +00001724 const char *FailureReason = nullptr;
1725 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001726 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001727 if (!MaybeLoopStructure.hasValue()) {
1728 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1729 << "\n";);
1730 return false;
1731 }
1732 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001733 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001734 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001735
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001736 Optional<InductiveRangeCheck::Range> SafeIterRange;
1737 Instruction *ExprInsertPt = Preheader->getTerminator();
1738
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001739 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001740
1741 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001742 for (InductiveRangeCheck &IRC : RangeChecks) {
1743 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001744 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001745 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001746 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001747 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev25d86552017-10-11 06:53:07 +00001748 assert(!MaybeSafeIterRange.getValue().isEmpty() &&
1749 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001750 RangeChecksToEliminate.push_back(IRC);
1751 SafeIterRange = MaybeSafeIterRange.getValue();
1752 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001753 }
1754 }
1755
1756 if (!SafeIterRange.hasValue())
1757 return false;
1758
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001759 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001760 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1761 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001762 bool Changed = LC.run();
1763
1764 if (Changed) {
1765 auto PrintConstrainedLoopInfo = [L]() {
1766 dbgs() << "irce: in function ";
1767 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1768 dbgs() << "constrained ";
1769 L->print(dbgs());
1770 };
1771
1772 DEBUG(PrintConstrainedLoopInfo());
1773
1774 if (PrintChangedLoops)
1775 PrintConstrainedLoopInfo();
1776
1777 // Optimize away the now-redundant range checks.
1778
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001779 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1780 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001781 ? ConstantInt::getTrue(Context)
1782 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001783 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001784 }
1785 }
1786
1787 return Changed;
1788}
1789
1790Pass *llvm::createInductiveRangeCheckEliminationPass() {
1791 return new InductiveRangeCheckElimination;
1792}