blob: 04d23a5333de6d31d766069f468464826f2c878a [file] [log] [blame]
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
Sanjoy Dasa1837a32015-01-16 01:03:22 +00002//
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//===----------------------------------------------------------------------===//
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00009//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000010// The InductiveRangeCheckElimination pass splits a loop's iteration space into
11// three disjoint ranges. It does that in a way such that the loop running in
12// the middle loop provably does not need range checks. As an example, it will
13// convert
14//
15// len = < known positive >
16// for (i = 0; i < n; i++) {
17// if (0 <= i && i < len) {
18// do_something();
19// } else {
20// throw_out_of_bounds();
21// }
22// }
23//
24// to
25//
26// len = < known positive >
27// limit = smin(n, len)
28// // no first segment
29// for (i = 0; i < limit; i++) {
30// if (0 <= i && i < len) { // this check is fully redundant
31// do_something();
32// } else {
33// throw_out_of_bounds();
34// }
35// }
36// for (i = limit; i < n; i++) {
37// if (0 <= i && i < len) {
38// do_something();
39// } else {
40// throw_out_of_bounds();
41// }
42// }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000043//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000044//===----------------------------------------------------------------------===//
45
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000046#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/None.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000049#include "llvm/ADT/Optional.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/ADT/StringRef.h"
53#include "llvm/ADT/Twine.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000054#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/Analysis/LoopInfo.h"
56#include "llvm/Analysis/LoopPass.h"
57#include "llvm/Analysis/ScalarEvolution.h"
58#include "llvm/Analysis/ScalarEvolutionExpander.h"
59#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000060#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DerivedTypes.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064#include "llvm/IR/Dominators.h"
65#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000066#include "llvm/IR/IRBuilder.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000067#include "llvm/IR/InstrTypes.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000068#include "llvm/IR/Instructions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000069#include "llvm/IR/Metadata.h"
70#include "llvm/IR/Module.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000071#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000072#include "llvm/IR/Type.h"
73#include "llvm/IR/Use.h"
74#include "llvm/IR/User.h"
75#include "llvm/IR/Value.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000076#include "llvm/Pass.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000077#include "llvm/Support/BranchProbability.h"
78#include "llvm/Support/Casting.h"
79#include "llvm/Support/CommandLine.h"
80#include "llvm/Support/Compiler.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000082#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000083#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084#include "llvm/Transforms/Scalar.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000085#include "llvm/Transforms/Utils/Cloning.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000086#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000087#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000088#include "llvm/Transforms/Utils/ValueMapper.h"
89#include <algorithm>
90#include <cassert>
91#include <iterator>
92#include <limits>
93#include <utility>
94#include <vector>
Sanjoy Dasa1837a32015-01-16 01:03:22 +000095
96using namespace llvm;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000097using namespace llvm::PatternMatch;
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098
Benjamin Kramer970eac42015-02-06 17:51:54 +000099static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
100 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000101
Benjamin Kramer970eac42015-02-06 17:51:54 +0000102static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
103 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000104
Sanjoy Das9c1bfae2015-03-17 01:40:22 +0000105static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
106 cl::init(false));
107
Sanjoy Dase91665d2015-02-26 08:56:04 +0000108static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
109 cl::Hidden, cl::init(10));
110
Sanjoy Dasbb969792016-07-22 00:40:56 +0000111static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
112 cl::Hidden, cl::init(false));
113
Max Kazantsev8aacef62017-10-04 06:53:22 +0000114static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
115 cl::Hidden, cl::init(false));
116
Sanjoy Das7a18a232016-08-14 01:04:36 +0000117static const char *ClonedLoopTag = "irce.loop.clone";
118
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000119#define DEBUG_TYPE "irce"
120
121namespace {
122
123/// An inductive range check is conditional branch in a loop with
124///
125/// 1. a very cold successor (i.e. the branch jumps to that successor very
126/// rarely)
127///
128/// and
129///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000130/// 2. a condition that is provably true for some contiguous range of values
131/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000133class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000134 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000135 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000136 // Range check of the form "0 <= I".
137 RANGE_CHECK_LOWER = 1,
138
139 // Range check of the form "I < L" where L is known positive.
140 RANGE_CHECK_UPPER = 2,
141
142 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
143 // conditions.
144 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
145
146 // Unrecognized range check condition.
147 RANGE_CHECK_UNKNOWN = (unsigned)-1
148 };
149
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000150 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000151
Sanjoy Dasee77a482016-05-26 01:50:18 +0000152 const SCEV *Offset = nullptr;
153 const SCEV *Scale = nullptr;
154 Value *Length = nullptr;
155 Use *CheckUse = nullptr;
156 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000157
Sanjoy Das337d46b2015-03-24 19:29:18 +0000158 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
159 ScalarEvolution &SE, Value *&Index,
160 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000161
Sanjoy Dasa0992682016-05-26 00:09:02 +0000162 static void
163 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
164 SmallVectorImpl<InductiveRangeCheck> &Checks,
165 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000166
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000167public:
168 const SCEV *getOffset() const { return Offset; }
169 const SCEV *getScale() const { return Scale; }
170 Value *getLength() const { return Length; }
171
172 void print(raw_ostream &OS) const {
173 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000174 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000175 OS << " Offset: ";
176 Offset->print(OS);
177 OS << " Scale: ";
178 Scale->print(OS);
179 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000180 if (Length)
181 Length->print(OS);
182 else
183 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000184 OS << "\n CheckUse: ";
185 getCheckUse()->getUser()->print(OS);
186 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000187 }
188
Davide Italianod1279df2016-08-18 15:55:49 +0000189 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000190 void dump() {
191 print(dbgs());
192 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000193
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000194 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000195
Sanjoy Das351db052015-01-22 09:32:02 +0000196 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
197 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
198
199 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000200 const SCEV *Begin;
201 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000202
203 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000204 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000205 assert(Begin->getType() == End->getType() && "ill-typed range!");
206 }
207
208 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000209 const SCEV *getBegin() const { return Begin; }
210 const SCEV *getEnd() const { return End; }
Max Kazantsev25d86552017-10-11 06:53:07 +0000211 bool isEmpty() const { return Begin == End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000212 };
213
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000214 /// This is the value the condition of the branch needs to evaluate to for the
215 /// branch to take the hot successor (see (1) above).
216 bool getPassingDirection() { return true; }
217
Sanjoy Das95c476d2015-02-21 22:20:22 +0000218 /// Computes a range for the induction variable (IndVar) in which the range
219 /// check is redundant and can be constant-folded away. The induction
220 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000221 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000222 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223
Sanjoy Dasa0992682016-05-26 00:09:02 +0000224 /// Parse out a set of inductive range checks from \p BI and append them to \p
225 /// Checks.
226 ///
227 /// NB! There may be conditions feeding into \p BI that aren't inductive range
228 /// checks, and hence don't end up in \p Checks.
229 static void
230 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
231 BranchProbabilityInfo &BPI,
232 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000233};
234
235class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000236public:
237 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000238
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000239 InductiveRangeCheckElimination() : LoopPass(ID) {
240 initializeInductiveRangeCheckEliminationPass(
241 *PassRegistry::getPassRegistry());
242 }
243
244 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000245 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000246 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000247 }
248
249 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
250};
251
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000252} // end anonymous namespace
253
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000254char InductiveRangeCheckElimination::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000255
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000256INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
257 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000258INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000259INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000260INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
261 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000262
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000263StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000264 InductiveRangeCheck::RangeCheckKind RCK) {
265 switch (RCK) {
266 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
267 return "RANGE_CHECK_UNKNOWN";
268
269 case InductiveRangeCheck::RANGE_CHECK_UPPER:
270 return "RANGE_CHECK_UPPER";
271
272 case InductiveRangeCheck::RANGE_CHECK_LOWER:
273 return "RANGE_CHECK_LOWER";
274
275 case InductiveRangeCheck::RANGE_CHECK_BOTH:
276 return "RANGE_CHECK_BOTH";
277 }
278
279 llvm_unreachable("unknown range check type!");
280}
281
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000282/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000283/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000284/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000285/// range checked, and set `Length` to the upper limit `Index` is being range
286/// checked with if (and only if) the range check type is stronger or equal to
287/// RANGE_CHECK_UPPER.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000288InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000289InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
290 ScalarEvolution &SE, Value *&Index,
291 Value *&Length) {
Sanjoy Das337d46b2015-03-24 19:29:18 +0000292 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
293 const SCEV *S = SE.getSCEV(V);
294 if (isa<SCEVCouldNotCompute>(S))
295 return false;
296
297 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
298 SE.isKnownNonNegative(S);
299 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000300
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000301 ICmpInst::Predicate Pred = ICI->getPredicate();
302 Value *LHS = ICI->getOperand(0);
303 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000304
305 switch (Pred) {
306 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000307 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000308
309 case ICmpInst::ICMP_SLE:
310 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000311 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000312 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000313 if (match(RHS, m_ConstantInt<0>())) {
314 Index = LHS;
315 return RANGE_CHECK_LOWER;
316 }
317 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000318
319 case ICmpInst::ICMP_SLT:
320 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000321 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000322 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000323 if (match(RHS, m_ConstantInt<-1>())) {
324 Index = LHS;
325 return RANGE_CHECK_LOWER;
326 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000327
Sanjoy Das337d46b2015-03-24 19:29:18 +0000328 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000329 Index = RHS;
330 Length = LHS;
331 return RANGE_CHECK_UPPER;
332 }
333 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000334
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000335 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000336 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000337 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000338 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000339 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000340 Index = RHS;
341 Length = LHS;
342 return RANGE_CHECK_BOTH;
343 }
344 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000345 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000346
347 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000348}
349
Sanjoy Dasa0992682016-05-26 00:09:02 +0000350void InductiveRangeCheck::extractRangeChecksFromCond(
351 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
352 SmallVectorImpl<InductiveRangeCheck> &Checks,
353 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000354 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000355 if (!Visited.insert(Condition).second)
356 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000357
Sanjoy Dasa0992682016-05-26 00:09:02 +0000358 if (match(Condition, m_And(m_Value(), m_Value()))) {
359 SmallVector<InductiveRangeCheck, 8> SubChecks;
360 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
361 SubChecks, Visited);
362 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
363 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000364
Sanjoy Dasa0992682016-05-26 00:09:02 +0000365 if (SubChecks.size() == 2) {
366 // Handle a special case where we know how to merge two checks separately
367 // checking the upper and lower bounds into a full range check.
368 const auto &RChkA = SubChecks[0];
369 const auto &RChkB = SubChecks[1];
370 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
371 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000372 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
373 // But if one of them is a RANGE_CHECK_LOWER and the other is a
374 // RANGE_CHECK_UPPER (only possibility if they're different) then
375 // together they form a RANGE_CHECK_BOTH.
376 SubChecks[0].Kind =
377 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
378 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
379 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000380
Sanjoy Dasa0992682016-05-26 00:09:02 +0000381 // We updated one of the checks in place, now erase the other.
382 SubChecks.pop_back();
383 }
384 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000385
Sanjoy Dasa0992682016-05-26 00:09:02 +0000386 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
387 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000388 }
389
Sanjoy Dasa0992682016-05-26 00:09:02 +0000390 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
391 if (!ICI)
392 return;
393
394 Value *Length = nullptr, *Index;
395 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
396 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
397 return;
398
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000399 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000400 bool IsAffineIndex =
401 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
402
403 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000404 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000405
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000406 InductiveRangeCheck IRC;
407 IRC.Length = Length;
408 IRC.Offset = IndexAddRec->getStart();
409 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000410 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000411 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000412 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000413}
414
Sanjoy Dasa0992682016-05-26 00:09:02 +0000415void InductiveRangeCheck::extractRangeChecksFromBranch(
416 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
417 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000418 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000419 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000420
421 BranchProbability LikelyTaken(15, 16);
422
Sanjoy Dasbb969792016-07-22 00:40:56 +0000423 if (!SkipProfitabilityChecks &&
424 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000425 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000426
Sanjoy Dasa0992682016-05-26 00:09:02 +0000427 SmallPtrSet<Value *, 8> Visited;
428 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
429 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000430}
431
Anna Thomas65ca8e92016-12-13 21:05:21 +0000432// Add metadata to the loop L to disable loop optimizations. Callers need to
433// confirm that optimizing loop L is not beneficial.
434static void DisableAllLoopOptsOnLoop(Loop &L) {
435 // We do not care about any existing loopID related metadata for L, since we
436 // are setting all loop metadata to false.
437 LLVMContext &Context = L.getHeader()->getContext();
438 // Reserve first location for self reference to the LoopID metadata node.
439 MDNode *Dummy = MDNode::get(Context, {});
440 MDNode *DisableUnroll = MDNode::get(
441 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
442 Metadata *FalseVal =
443 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
444 MDNode *DisableVectorize = MDNode::get(
445 Context,
446 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
447 MDNode *DisableLICMVersioning = MDNode::get(
448 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
449 MDNode *DisableDistribution= MDNode::get(
450 Context,
451 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
452 MDNode *NewLoopID =
453 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
454 DisableLICMVersioning, DisableDistribution});
455 // Set operand 0 to refer to the loop id itself.
456 NewLoopID->replaceOperandWith(0, NewLoopID);
457 L.setLoopID(NewLoopID);
458}
459
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000460namespace {
461
Sanjoy Dase75ed922015-02-26 08:19:31 +0000462// Keeps track of the structure of a loop. This is similar to llvm::Loop,
463// except that it is more lightweight and can track the state of a loop through
464// changing and potentially invalid IR. This structure also formalizes the
465// kinds of loops we can deal with -- ones that have a single latch that is also
466// an exiting block *and* have a canonical induction variable.
467struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000468 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000469
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000470 BasicBlock *Header = nullptr;
471 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000472
473 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
474 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000475 BranchInst *LatchBr = nullptr;
476 BasicBlock *LatchExit = nullptr;
477 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000478
Sanjoy Dasec892132017-02-07 23:59:07 +0000479 // The loop represented by this instance of LoopStructure is semantically
480 // equivalent to:
481 //
482 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000483 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000484 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000485 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000486 // ... body ...
487
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000488 Value *IndVarBase = nullptr;
489 Value *IndVarStart = nullptr;
490 Value *IndVarStep = nullptr;
491 Value *LoopExitAt = nullptr;
492 bool IndVarIncreasing = false;
493 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000494
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000495 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000496
497 template <typename M> LoopStructure map(M Map) const {
498 LoopStructure Result;
499 Result.Tag = Tag;
500 Result.Header = cast<BasicBlock>(Map(Header));
501 Result.Latch = cast<BasicBlock>(Map(Latch));
502 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
503 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
504 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000505 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000506 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000507 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000508 Result.LoopExitAt = Map(LoopExitAt);
509 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000510 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000511 return Result;
512 }
513
Sanjoy Dase91665d2015-02-26 08:56:04 +0000514 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
515 BranchProbabilityInfo &BPI,
516 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000517 const char *&);
518};
519
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000520/// This class is used to constrain loops to run within a given iteration space.
521/// The algorithm this class implements is given a Loop and a range [Begin,
522/// End). The algorithm then tries to break out a "main loop" out of the loop
523/// it is given in a way that the "main loop" runs with the induction variable
524/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
525/// loops to run any remaining iterations. The pre loop runs any iterations in
526/// which the induction variable is < Begin, and the post loop runs any
527/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000528class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000529 // The representation of a clone of the original loop we started out with.
530 struct ClonedLoop {
531 // The cloned blocks
532 std::vector<BasicBlock *> Blocks;
533
534 // `Map` maps values in the clonee into values in the cloned version
535 ValueToValueMapTy Map;
536
537 // An instance of `LoopStructure` for the cloned loop
538 LoopStructure Structure;
539 };
540
541 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
542 // more details on what these fields mean.
543 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000544 BasicBlock *PseudoExit = nullptr;
545 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000546 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000547 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000548
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000549 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550 };
551
552 // Calculated subranges we restrict the iteration space of the main loop to.
553 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000554 // these fields are computed. `LowLimit` is None if there is no restriction
555 // on low end of the restricted iteration space of the main loop. `HighLimit`
556 // is None if there is no restriction on high end of the restricted iteration
557 // space of the main loop.
558
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000559 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000560 Optional<const SCEV *> LowLimit;
561 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562 };
563
564 // A utility function that does a `replaceUsesOfWith' on the incoming block
565 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
566 // incoming block list with `ReplaceBy'.
567 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
568 BasicBlock *ReplaceBy);
569
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000570 // Compute a safe set of limits for the main loop to run in -- effectively the
571 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000572 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000573 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000574
575 // Clone `OriginalLoop' and return the result in CLResult. The IR after
576 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
577 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
578 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000579 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
580
Sanjoy Das21434472016-08-14 01:04:46 +0000581 // Create the appropriate loop structure needed to describe a cloned copy of
582 // `Original`. The clone is described by `VM`.
583 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
584 ValueToValueMapTy &VM);
585
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000586 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
587 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
588 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
589 // `OriginalHeaderCount'.
590 //
591 // If there are iterations left to execute, control is made to jump to
592 // `ContinuationBlock', otherwise they take the normal loop exit. The
593 // returned `RewrittenRangeInfo' object is populated as follows:
594 //
595 // .PseudoExit is a basic block that unconditionally branches to
596 // `ContinuationBlock'.
597 //
598 // .ExitSelector is a basic block that decides, on exit from the loop,
599 // whether to branch to the "true" exit or to `PseudoExit'.
600 //
601 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
602 // for each PHINode in the loop header on taking the pseudo exit.
603 //
604 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
605 // preheader because it is made to branch to the loop header only
606 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607 RewrittenRangeInfo
608 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
609 Value *ExitLoopAt,
610 BasicBlock *ContinuationBlock) const;
611
612 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
613 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000614 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
615 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000616
617 // `ContinuationBlockAndPreheader' was the continuation block for some call to
618 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
619 // This function rewrites the PHI nodes in `LS.Header' to start with the
620 // correct value.
621 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000622 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000623 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
624
625 // Even though we do not preserve any passes at this time, we at least need to
626 // keep the parent loop structure consistent. The `LPPassManager' seems to
627 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000628 // blocks denoted by BBs to this loops parent loop if required.
629 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000630
631 // Some global state.
632 Function &F;
633 LLVMContext &Ctx;
634 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000635 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000636 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000637 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000638
639 // Information about the original loop we started out with.
640 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000641
642 const SCEV *LatchTakenCount = nullptr;
643 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000644
645 // The preheader of the main loop. This may or may not be different from
646 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000647 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000648
649 // The range we need to run the main loop in.
650 InductiveRangeCheck::Range Range;
651
652 // The structure of the main loop (see comment at the beginning of this class
653 // for a definition)
654 LoopStructure MainLoopStructure;
655
656public:
Sanjoy Das21434472016-08-14 01:04:46 +0000657 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
658 const LoopStructure &LS, ScalarEvolution &SE,
659 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000660 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000661 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R),
662 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000663
664 // Entry point for the algorithm. Returns true on success.
665 bool run();
666};
667
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000668} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000669
670void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
671 BasicBlock *ReplaceBy) {
672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
673 if (PN->getIncomingBlock(i) == Block)
674 PN->setIncomingBlock(i, ReplaceBy);
675}
676
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000677static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
678 APInt Max = Signed ?
679 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
680 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
681 return SE.getSignedRange(S).contains(Max) &&
682 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000683}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000684
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000685static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
686 bool Signed) {
687 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
688 assert(SE.isKnownNonNegative(S2) &&
689 "We expected the 2nd arg to be non-negative!");
690 const SCEV *Max = SE.getConstant(
691 Signed ? APInt::getSignedMaxValue(
692 cast<IntegerType>(S1->getType())->getBitWidth())
693 : APInt::getMaxValue(
694 cast<IntegerType>(S1->getType())->getBitWidth()));
695 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
696 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
697 S1, CapForS1);
698}
699
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000700static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
701 APInt Min = Signed ?
702 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
703 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
704 return SE.getSignedRange(S).contains(Min) &&
705 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000706}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000707
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000708static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
709 bool Signed) {
710 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
711 assert(SE.isKnownNonPositive(S2) &&
712 "We expected the 2nd arg to be non-positive!");
713 const SCEV *Max = SE.getConstant(
714 Signed ? APInt::getSignedMinValue(
715 cast<IntegerType>(S1->getType())->getBitWidth())
716 : APInt::getMinValue(
717 cast<IntegerType>(S1->getType())->getBitWidth()));
718 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
719 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
720 S1, CapForS1);
721}
722
Sanjoy Dase75ed922015-02-26 08:19:31 +0000723Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000724LoopStructure::parseLoopStructure(ScalarEvolution &SE,
725 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000726 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000727 if (!L.isLoopSimplifyForm()) {
728 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000729 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000730 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000731
732 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000733 assert(Latch && "Simplified loops only have one latch!");
734
Sanjoy Das7a18a232016-08-14 01:04:36 +0000735 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
736 FailureReason = "loop has already been cloned";
737 return None;
738 }
739
Sanjoy Dase75ed922015-02-26 08:19:31 +0000740 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000741 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000742 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000743 }
744
Sanjoy Dase75ed922015-02-26 08:19:31 +0000745 BasicBlock *Header = L.getHeader();
746 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000747 if (!Preheader) {
748 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000749 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000750 }
751
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000752 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000753 if (!LatchBr || LatchBr->isUnconditional()) {
754 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000755 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000756 }
757
Sanjoy Dase75ed922015-02-26 08:19:31 +0000758 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000759
Sanjoy Dase91665d2015-02-26 08:56:04 +0000760 BranchProbability ExitProbability =
761 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
762
Sanjoy Dasbb969792016-07-22 00:40:56 +0000763 if (!SkipProfitabilityChecks &&
764 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000765 FailureReason = "short running loop, not profitable";
766 return None;
767 }
768
Sanjoy Dase75ed922015-02-26 08:19:31 +0000769 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
770 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
771 FailureReason = "latch terminator branch not conditional on integral icmp";
772 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000773 }
774
Sanjoy Dase75ed922015-02-26 08:19:31 +0000775 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
776 if (isa<SCEVCouldNotCompute>(LatchCount)) {
777 FailureReason = "could not compute latch count";
778 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000779 }
780
Sanjoy Dase75ed922015-02-26 08:19:31 +0000781 ICmpInst::Predicate Pred = ICI->getPredicate();
782 Value *LeftValue = ICI->getOperand(0);
783 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
784 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
785
786 Value *RightValue = ICI->getOperand(1);
787 const SCEV *RightSCEV = SE.getSCEV(RightValue);
788
789 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
790 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
791 if (isa<SCEVAddRecExpr>(RightSCEV)) {
792 std::swap(LeftSCEV, RightSCEV);
793 std::swap(LeftValue, RightValue);
794 Pred = ICmpInst::getSwappedPredicate(Pred);
795 } else {
796 FailureReason = "no add recurrences in the icmp";
797 return None;
798 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000799 }
800
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000801 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
802 if (AR->getNoWrapFlags(SCEV::FlagNSW))
803 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000804
805 IntegerType *Ty = cast<IntegerType>(AR->getType());
806 IntegerType *WideTy =
807 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
808
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000809 const SCEVAddRecExpr *ExtendAfterOp =
810 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
811 if (ExtendAfterOp) {
812 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
813 const SCEV *ExtendedStep =
814 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
815
816 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
817 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
818
819 if (NoSignedWrap)
820 return true;
821 }
822
823 // We may have proved this when computing the sign extension above.
824 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
825 };
826
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000827 // Here we check whether the suggested AddRec is an induction variable that
828 // can be handled (i.e. with known constant step), and if yes, calculate its
829 // step and identify whether it is increasing or decreasing.
830 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
831 ConstantInt *&StepCI) {
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000832 if (!AR->isAffine())
833 return false;
834
Sanjoy Dase75ed922015-02-26 08:19:31 +0000835 // Currently we only work with induction variables that have been proved to
836 // not wrap. This restriction can potentially be lifted in the future.
837
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000838 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000839 return false;
840
841 if (const SCEVConstant *StepExpr =
842 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000843 StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000844 assert(!StepCI->isZero() && "Zero step?");
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000845 IsIncreasing = !StepCI->isNegative();
846 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000847 }
848
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000849 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000850 };
851
Serguei Katkov675e3042017-09-21 04:50:41 +0000852 // `ICI` is interpreted as taking the backedge if the *next* value of the
853 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854
Max Kazantseva22742b2017-08-31 05:58:15 +0000855 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000856 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000857 bool IsSignedPredicate = true;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000858 ConstantInt *StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +0000859 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000860 FailureReason = "LHS in icmp not induction variable";
861 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000862 }
863
Serguei Katkov675e3042017-09-21 04:50:41 +0000864 const SCEV *StartNext = IndVarBase->getStart();
865 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
866 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000867 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000868
Sanjoy Dase75ed922015-02-26 08:19:31 +0000869 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000870 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000871 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000872 if (StepCI->isOne()) {
873 // Try to turn eq/ne predicates to those we can work with.
874 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
875 // while (++i != len) { while (++i < len) {
876 // ... ---> ...
877 // } }
878 // If both parts are known non-negative, it is profitable to use
879 // unsigned comparison in increasing loop. This allows us to make the
880 // comparison check against "RightSCEV + 1" more optimistic.
881 if (SE.isKnownNonNegative(IndVarStart) &&
882 SE.isKnownNonNegative(RightSCEV))
883 Pred = ICmpInst::ICMP_ULT;
884 else
885 Pred = ICmpInst::ICMP_SLT;
886 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
887 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
888 // while (true) { while (true) {
889 // if (++i == len) ---> if (++i > len - 1)
890 // break; break;
891 // ... ...
892 // } }
893 // TODO: Insert ICMP_UGT if both are non-negative?
894 Pred = ICmpInst::ICMP_SGT;
895 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
896 DecreasedRightValueByOne = true;
897 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000898 }
899
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000900 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
901 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000902 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000903 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000904
905 if (!FoundExpectedPred) {
906 FailureReason = "expected icmp slt semantically, found something else";
907 return None;
908 }
909
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000910 IsSignedPredicate =
911 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000912
913 // FIXME: We temporarily disable unsigned latch conditions by default
914 // because of found problems with intersecting signed and unsigned ranges.
915 // We are going to turn it on once the problems are fixed.
916 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
917 FailureReason = "unsigned latch conditions are explicitly prohibited";
918 return None;
919 }
920
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000921 // The predicate that we need to check that the induction variable lies
922 // within bounds.
923 ICmpInst::Predicate BoundPred =
924 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
925
Sanjoy Dase75ed922015-02-26 08:19:31 +0000926 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000927 const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
928 SE.getOne(Step->getType()));
929 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000930 // TODO: this restriction is easily removable -- we just have to
931 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000932 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000933 return None;
934 }
935
Sanjoy Dasec892132017-02-07 23:59:07 +0000936 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000937 &L, BoundPred, IndVarStart,
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000938 SE.getAddExpr(RightSCEV, Step))) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000939 FailureReason = "Induction variable start not bounded by upper limit";
940 return None;
941 }
942
Max Kazantsev2c627a92017-07-18 04:53:48 +0000943 // We need to increase the right value unless we have already decreased
944 // it virtually when we replaced EQ with SGT.
945 if (!DecreasedRightValueByOne) {
946 IRBuilder<> B(Preheader->getTerminator());
947 RightValue = B.CreateAdd(RightValue, One);
948 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000949 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000950 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000951 FailureReason = "Induction variable start not bounded by upper limit";
952 return None;
953 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000954 assert(!DecreasedRightValueByOne &&
955 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000956 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000957 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000958 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000959 if (StepCI->isMinusOne()) {
960 // Try to turn eq/ne predicates to those we can work with.
961 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
962 // while (--i != len) { while (--i > len) {
963 // ... ---> ...
964 // } }
965 // We intentionally don't turn the predicate into UGT even if we know
966 // that both operands are non-negative, because it will only pessimize
967 // our check against "RightSCEV - 1".
968 Pred = ICmpInst::ICMP_SGT;
969 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
970 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
971 // while (true) { while (true) {
972 // if (--i == len) ---> if (--i < len + 1)
973 // break; break;
974 // ... ...
975 // } }
976 // TODO: Insert ICMP_ULT if both are non-negative?
977 Pred = ICmpInst::ICMP_SLT;
978 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
979 IncreasedRightValueByOne = true;
980 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000981 }
982
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000983 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
984 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
985
Sanjoy Dase75ed922015-02-26 08:19:31 +0000986 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000987 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000988
989 if (!FoundExpectedPred) {
990 FailureReason = "expected icmp sgt semantically, found something else";
991 return None;
992 }
993
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000994 IsSignedPredicate =
995 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000996
997 // FIXME: We temporarily disable unsigned latch conditions by default
998 // because of found problems with intersecting signed and unsigned ranges.
999 // We are going to turn it on once the problems are fixed.
1000 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
1001 FailureReason = "unsigned latch conditions are explicitly prohibited";
1002 return None;
1003 }
1004
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001005 // The predicate that we need to check that the induction variable lies
1006 // within bounds.
1007 ICmpInst::Predicate BoundPred =
1008 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
1009
Sanjoy Dase75ed922015-02-26 08:19:31 +00001010 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001011 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
1012 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001013 // TODO: this restriction is easily removable -- we just have to
1014 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001015 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +00001016 return None;
1017 }
1018
Sanjoy Dasec892132017-02-07 23:59:07 +00001019 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001020 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +00001021 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1022 FailureReason = "Induction variable start not bounded by lower limit";
1023 return None;
1024 }
1025
Max Kazantsev2c627a92017-07-18 04:53:48 +00001026 // We need to decrease the right value unless we have already increased
1027 // it virtually when we replaced EQ with SLT.
1028 if (!IncreasedRightValueByOne) {
1029 IRBuilder<> B(Preheader->getTerminator());
1030 RightValue = B.CreateSub(RightValue, One);
1031 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001032 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001033 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +00001034 FailureReason = "Induction variable start not bounded by lower limit";
1035 return None;
1036 }
Max Kazantsev2c627a92017-07-18 04:53:48 +00001037 assert(!IncreasedRightValueByOne &&
1038 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001039 }
1040 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001041 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1042
Sanjoy Dase75ed922015-02-26 08:19:31 +00001043 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001044 ScalarEvolution::LoopInvariant &&
1045 "loop variant exit count doesn't make sense!");
1046
Sanjoy Dase75ed922015-02-26 08:19:31 +00001047 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001048 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1049 Value *IndVarStartV =
1050 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001051 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001052 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001053
Sanjoy Dase75ed922015-02-26 08:19:31 +00001054 LoopStructure Result;
1055
1056 Result.Tag = "main";
1057 Result.Header = Header;
1058 Result.Latch = Latch;
1059 Result.LatchBr = LatchBr;
1060 Result.LatchExit = LatchExit;
1061 Result.LatchBrExitIdx = LatchBrExitIdx;
1062 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001063 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001064 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001065 Result.IndVarIncreasing = IsIncreasing;
1066 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001067 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001068
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001069 FailureReason = nullptr;
1070
Sanjoy Dase75ed922015-02-26 08:19:31 +00001071 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001072}
1073
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001074Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001075LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001076 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1077
Sanjoy Das351db052015-01-22 09:32:02 +00001078 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001079 return None;
1080
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001081 LoopConstrainer::SubRanges Result;
1082
1083 // I think we can be more aggressive here and make this nuw / nsw if the
1084 // addition that feeds into the icmp for the latch's terminating branch is nuw
1085 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001086 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1087 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001088
Sanjoy Dase75ed922015-02-26 08:19:31 +00001089 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001090
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001091 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1092 // [Smallest, GreatestSeen] is the range of values the induction variable
1093 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001094
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001095 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001096
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001097 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001098 if (Increasing) {
1099 Smallest = Start;
1100 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001101 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1102 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001103 } else {
1104 // These two computations may sign-overflow. Here is why that is okay:
1105 //
1106 // We know that the induction variable does not sign-overflow on any
1107 // iteration except the last one, and it starts at `Start` and ends at
1108 // `End`, decrementing by one every time.
1109 //
1110 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1111 // induction variable is decreasing we know that that the smallest value
1112 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1113 //
1114 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1115 // that case, `Clamp` will always return `Smallest` and
1116 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1117 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001118
Max Kazantsev6c466a32017-06-28 04:57:45 +00001119 Smallest = SE.getAddExpr(End, One);
1120 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001121 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001122 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001123
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001124 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev0aaf8c12017-08-18 22:50:29 +00001125 bool MaybeNegativeValues = IsSignedPredicate || !SE.isKnownNonNegative(S);
1126 return MaybeNegativeValues
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001127 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1128 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001129 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001130
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001131 // In some cases we can prove that we don't need a pre or post loop.
1132 ICmpInst::Predicate PredLE =
1133 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1134 ICmpInst::Predicate PredLT =
1135 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001136
1137 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001138 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001139 if (!ProvablyNoPreloop)
1140 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001141
1142 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001143 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001144 if (!ProvablyNoPostLoop)
1145 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001146
1147 return Result;
1148}
1149
1150void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1151 const char *Tag) const {
1152 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1153 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1154 Result.Blocks.push_back(Clone);
1155 Result.Map[BB] = Clone;
1156 }
1157
1158 auto GetClonedValue = [&Result](Value *V) {
1159 assert(V && "null values not in domain!");
1160 auto It = Result.Map.find(V);
1161 if (It == Result.Map.end())
1162 return V;
1163 return static_cast<Value *>(It->second);
1164 };
1165
Sanjoy Das7a18a232016-08-14 01:04:36 +00001166 auto *ClonedLatch =
1167 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1168 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1169 MDNode::get(Ctx, {}));
1170
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001171 Result.Structure = MainLoopStructure.map(GetClonedValue);
1172 Result.Structure.Tag = Tag;
1173
1174 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1175 BasicBlock *ClonedBB = Result.Blocks[i];
1176 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1177
1178 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1179
1180 for (Instruction &I : *ClonedBB)
1181 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001182 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001183
1184 // Exit blocks will now have one more predecessor and their PHI nodes need
1185 // to be edited to reflect that. No phi nodes need to be introduced because
1186 // the loop is in LCSSA.
1187
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001188 for (auto *SBB : successors(OriginalBB)) {
1189 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001190 continue; // not an exit block
1191
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001192 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001193 auto *PN = dyn_cast<PHINode>(&I);
1194 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001195 break;
1196
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001197 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1198 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1199 }
1200 }
1201 }
1202}
1203
1204LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001205 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001206 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001207 // We start with a loop with a single latch:
1208 //
1209 // +--------------------+
1210 // | |
1211 // | preheader |
1212 // | |
1213 // +--------+-----------+
1214 // | ----------------\
1215 // | / |
1216 // +--------v----v------+ |
1217 // | | |
1218 // | header | |
1219 // | | |
1220 // +--------------------+ |
1221 // |
1222 // ..... |
1223 // |
1224 // +--------------------+ |
1225 // | | |
1226 // | latch >----------/
1227 // | |
1228 // +-------v------------+
1229 // |
1230 // |
1231 // | +--------------------+
1232 // | | |
1233 // +---> original exit |
1234 // | |
1235 // +--------------------+
1236 //
1237 // We change the control flow to look like
1238 //
1239 //
1240 // +--------------------+
1241 // | |
1242 // | preheader >-------------------------+
1243 // | | |
1244 // +--------v-----------+ |
1245 // | /-------------+ |
1246 // | / | |
1247 // +--------v--v--------+ | |
1248 // | | | |
1249 // | header | | +--------+ |
1250 // | | | | | |
1251 // +--------------------+ | | +-----v-----v-----------+
1252 // | | | |
1253 // | | | .pseudo.exit |
1254 // | | | |
1255 // | | +-----------v-----------+
1256 // | | |
1257 // ..... | | |
1258 // | | +--------v-------------+
1259 // +--------------------+ | | | |
1260 // | | | | | ContinuationBlock |
1261 // | latch >------+ | | |
1262 // | | | +----------------------+
1263 // +---------v----------+ |
1264 // | |
1265 // | |
1266 // | +---------------^-----+
1267 // | | |
1268 // +-----> .exit.selector |
1269 // | |
1270 // +----------v----------+
1271 // |
1272 // +--------------------+ |
1273 // | | |
1274 // | original exit <----+
1275 // | |
1276 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001277
1278 RewrittenRangeInfo RRI;
1279
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001280 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001281 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001282 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001283 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001284 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001285
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001286 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001287 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001288 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001289
1290 IRBuilder<> B(PreheaderJump);
1291
1292 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001293 Value *EnterLoopCond = nullptr;
1294 if (Increasing)
1295 EnterLoopCond = IsSignedPredicate
1296 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1297 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1298 else
1299 EnterLoopCond = IsSignedPredicate
1300 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1301 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001302
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001303 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1304 PreheaderJump->eraseFromParent();
1305
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001306 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001307 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001308 Value *TakeBackedgeLoopCond = nullptr;
1309 if (Increasing)
1310 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001311 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1312 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001313 else
1314 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001315 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1316 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001317 Value *CondForBranch = LS.LatchBrExitIdx == 1
1318 ? TakeBackedgeLoopCond
1319 : B.CreateNot(TakeBackedgeLoopCond);
1320
1321 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001322
1323 B.SetInsertPoint(RRI.ExitSelector);
1324
1325 // IterationsLeft - are there any more iterations left, given the original
1326 // upper bound on the induction variable? If not, we branch to the "real"
1327 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001328 Value *IterationsLeft = nullptr;
1329 if (Increasing)
1330 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001331 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1332 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001333 else
1334 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001335 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1336 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001337 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1338
1339 BranchInst *BranchToContinuation =
1340 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1341
1342 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1343 // each of the PHI nodes in the loop header. This feeds into the initial
1344 // value of the same PHI nodes if/when we continue execution.
1345 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001346 auto *PN = dyn_cast<PHINode>(&I);
1347 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001348 break;
1349
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001350 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1351 BranchToContinuation);
1352
1353 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
Serguei Katkov675e3042017-09-21 04:50:41 +00001354 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1355 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001356 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1357 }
1358
Max Kazantseva22742b2017-08-31 05:58:15 +00001359 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001360 BranchToContinuation);
1361 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001362 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001363
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001364 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1365 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1366 for (Instruction &I : *LS.LatchExit) {
1367 if (PHINode *PN = dyn_cast<PHINode>(&I))
1368 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1369 else
1370 break;
1371 }
1372
1373 return RRI;
1374}
1375
1376void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001377 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001378 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001379 unsigned PHIIndex = 0;
1380 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001381 auto *PN = dyn_cast<PHINode>(&I);
1382 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001383 break;
1384
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1386 if (PN->getIncomingBlock(i) == ContinuationBlock)
1387 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1388 }
1389
Sanjoy Dase75ed922015-02-26 08:19:31 +00001390 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001391}
1392
Sanjoy Dase75ed922015-02-26 08:19:31 +00001393BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1394 BasicBlock *OldPreheader,
1395 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001396 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1397 BranchInst::Create(LS.Header, Preheader);
1398
1399 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001400 auto *PN = dyn_cast<PHINode>(&I);
1401 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001402 break;
1403
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001404 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1405 replacePHIBlock(PN, OldPreheader, Preheader);
1406 }
1407
1408 return Preheader;
1409}
1410
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001411void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001412 Loop *ParentLoop = OriginalLoop.getParentLoop();
1413 if (!ParentLoop)
1414 return;
1415
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001416 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001417 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001418}
1419
Sanjoy Das21434472016-08-14 01:04:46 +00001420Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1421 ValueToValueMapTy &VM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001422 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001423 if (Parent)
1424 Parent->addChildLoop(&New);
1425 else
1426 LI.addTopLevelLoop(&New);
1427 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001428
1429 // Add all of the blocks in Original to the new loop.
1430 for (auto *BB : Original->blocks())
1431 if (LI.getLoopFor(BB) == Original)
1432 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1433
1434 // Add all of the subloops to the new loop.
1435 for (Loop *SubLoop : *Original)
1436 createClonedLoopStructure(SubLoop, &New, VM);
1437
1438 return &New;
1439}
1440
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001441bool LoopConstrainer::run() {
1442 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001443 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1444 Preheader = OriginalLoop.getLoopPreheader();
1445 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1446 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001447
1448 OriginalPreheader = Preheader;
1449 MainLoopPreheader = Preheader;
1450
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001451 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1452 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001453 if (!MaybeSR.hasValue()) {
1454 DEBUG(dbgs() << "irce: could not compute subranges\n");
1455 return false;
1456 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001457
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001458 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001459 bool Increasing = MainLoopStructure.IndVarIncreasing;
1460 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001461 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001462
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001463 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001464 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001465
1466 // It would have been better to make `PreLoop' and `PostLoop'
1467 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1468 // constructor.
1469 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001470 bool NeedsPreLoop =
1471 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1472 bool NeedsPostLoop =
1473 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1474
1475 Value *ExitPreLoopAt = nullptr;
1476 Value *ExitMainLoopAt = nullptr;
1477 const SCEVConstant *MinusOneS =
1478 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1479
1480 if (NeedsPreLoop) {
1481 const SCEV *ExitPreLoopAtSCEV = nullptr;
1482
1483 if (Increasing)
1484 ExitPreLoopAtSCEV = *SR.LowLimit;
1485 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001486 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001487 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1488 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1489 << "\n");
1490 return false;
1491 }
1492 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1493 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001494
Sanjoy Dase75ed922015-02-26 08:19:31 +00001495 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1496 ExitPreLoopAt->setName("exit.preloop.at");
1497 }
1498
1499 if (NeedsPostLoop) {
1500 const SCEV *ExitMainLoopAtSCEV = nullptr;
1501
1502 if (Increasing)
1503 ExitMainLoopAtSCEV = *SR.HighLimit;
1504 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001505 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001506 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1507 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1508 << "\n");
1509 return false;
1510 }
1511 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1512 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001513
Sanjoy Dase75ed922015-02-26 08:19:31 +00001514 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1515 ExitMainLoopAt->setName("exit.mainloop.at");
1516 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001517
1518 // We clone these ahead of time so that we don't have to deal with changing
1519 // and temporarily invalid IR as we transform the loops.
1520 if (NeedsPreLoop)
1521 cloneLoop(PreLoop, "preloop");
1522 if (NeedsPostLoop)
1523 cloneLoop(PostLoop, "postloop");
1524
1525 RewrittenRangeInfo PreLoopRRI;
1526
1527 if (NeedsPreLoop) {
1528 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1529 PreLoop.Structure.Header);
1530
1531 MainLoopPreheader =
1532 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001533 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1534 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001535 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1536 PreLoopRRI);
1537 }
1538
1539 BasicBlock *PostLoopPreheader = nullptr;
1540 RewrittenRangeInfo PostLoopRRI;
1541
1542 if (NeedsPostLoop) {
1543 PostLoopPreheader =
1544 createPreheader(PostLoop.Structure, Preheader, "postloop");
1545 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001546 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001547 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1548 PostLoopRRI);
1549 }
1550
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001551 BasicBlock *NewMainLoopPreheader =
1552 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1553 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1554 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1555 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001556
1557 // Some of the above may be nullptr, filter them out before passing to
1558 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001559 auto NewBlocksEnd =
1560 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001561
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001562 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001563
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001564 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001565
Anna Thomas72180322017-06-06 14:54:01 +00001566 // We need to first add all the pre and post loop blocks into the loop
1567 // structures (as part of createClonedLoopStructure), and then update the
1568 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1569 // LI when LoopSimplifyForm is generated.
1570 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001571 if (!PreLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001572 PreL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001573 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001574 }
1575
1576 if (!PostLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001577 PostL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001578 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001579 }
1580
Anna Thomas72180322017-06-06 14:54:01 +00001581 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1582 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1583 formLCSSARecursively(*L, DT, &LI, &SE);
1584 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1585 // Pre/post loops are slow paths, we do not need to perform any loop
1586 // optimizations on them.
1587 if (!IsOriginalLoop)
1588 DisableAllLoopOptsOnLoop(*L);
1589 };
1590 if (PreL)
1591 CanonicalizeLoop(PreL, false);
1592 if (PostL)
1593 CanonicalizeLoop(PostL, false);
1594 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001595
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001596 return true;
1597}
1598
Sanjoy Das95c476d2015-02-21 22:20:22 +00001599/// Computes and returns a range of values for the induction variable (IndVar)
1600/// in which the range check can be safely elided. If it cannot compute such a
1601/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001602Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001603InductiveRangeCheck::computeSafeIterationSpace(
1604 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001605 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1606 // variable, that may or may not exist as a real llvm::Value in the loop) and
1607 // this inductive range check is a range check on the "C + D * I" ("C" is
1608 // getOffset() and "D" is getScale()). We rewrite the value being range
1609 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001610 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001611 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001612 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001613 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1614 //
1615 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1616 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001617 //
1618 // Proof:
1619 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001620 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1621 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1622 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1623 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001624 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001625 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1626 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001627
Sanjoy Das95c476d2015-02-21 22:20:22 +00001628 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1629 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001630
Sanjoy Das95c476d2015-02-21 22:20:22 +00001631 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001632 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001633
Sanjoy Das95c476d2015-02-21 22:20:22 +00001634 const SCEV *A = IndVar->getStart();
1635 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1636 if (!B)
1637 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001638 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001639
1640 const SCEV *C = getOffset();
1641 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1642 if (D != B)
1643 return None;
1644
Max Kazantsev95054702017-08-04 07:41:24 +00001645 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001646
1647 const SCEV *M = SE.getMinusSCEV(C, A);
Sanjoy Das95c476d2015-02-21 22:20:22 +00001648 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001649 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001650
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001651 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1652 // We can potentially do much better here.
1653 if (Value *V = getLength()) {
1654 UpperLimit = SE.getSCEV(V);
1655 } else {
1656 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1657 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1658 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1659 }
1660
1661 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001662 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001663}
1664
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001665static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001666IntersectRange(ScalarEvolution &SE,
1667 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001668 const InductiveRangeCheck::Range &R2) {
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001669 if (R2.isEmpty())
Max Kazantsev25d86552017-10-11 06:53:07 +00001670 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001671 if (!R1.hasValue())
1672 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001673 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001674 // We never return empty ranges from this function, and R1 is supposed to be
1675 // a result of intersection. Thus, R1 is never empty.
1676 assert(!R1Value.isEmpty() && "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001677
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001678 // TODO: we could widen the smaller range and have this work; but for now we
1679 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001680 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001681 return None;
1682
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001683 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1684 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1685
Max Kazantsev25d86552017-10-11 06:53:07 +00001686 // If the resulting range is empty, just return None.
1687 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1688 if (Ret.isEmpty())
1689 return None;
1690 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001691}
1692
1693bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001694 if (skipLoop(L))
1695 return false;
1696
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001697 if (L->getBlocks().size() >= LoopSizeCutoff) {
1698 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1699 return false;
1700 }
1701
1702 BasicBlock *Preheader = L->getLoopPreheader();
1703 if (!Preheader) {
1704 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1705 return false;
1706 }
1707
1708 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001709 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001710 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001711 BranchProbabilityInfo &BPI =
1712 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001713
1714 for (auto BBI : L->getBlocks())
1715 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001716 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1717 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001718
1719 if (RangeChecks.empty())
1720 return false;
1721
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001722 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1723 OS << "irce: looking at loop "; L->print(OS);
1724 OS << "irce: loop has " << RangeChecks.size()
1725 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001726 for (InductiveRangeCheck &IRC : RangeChecks)
1727 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001728 };
1729
1730 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1731
1732 if (PrintRangeChecks)
1733 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001734
Sanjoy Dase75ed922015-02-26 08:19:31 +00001735 const char *FailureReason = nullptr;
1736 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001737 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001738 if (!MaybeLoopStructure.hasValue()) {
1739 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1740 << "\n";);
1741 return false;
1742 }
1743 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001744 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001745 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001746
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001747 Optional<InductiveRangeCheck::Range> SafeIterRange;
1748 Instruction *ExprInsertPt = Preheader->getTerminator();
1749
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001750 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001751
1752 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001753 for (InductiveRangeCheck &IRC : RangeChecks) {
1754 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001755 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001756 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001757 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001758 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev25d86552017-10-11 06:53:07 +00001759 assert(!MaybeSafeIterRange.getValue().isEmpty() &&
1760 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001761 RangeChecksToEliminate.push_back(IRC);
1762 SafeIterRange = MaybeSafeIterRange.getValue();
1763 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001764 }
1765 }
1766
1767 if (!SafeIterRange.hasValue())
1768 return false;
1769
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001770 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001771 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1772 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001773 bool Changed = LC.run();
1774
1775 if (Changed) {
1776 auto PrintConstrainedLoopInfo = [L]() {
1777 dbgs() << "irce: in function ";
1778 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1779 dbgs() << "constrained ";
1780 L->print(dbgs());
1781 };
1782
1783 DEBUG(PrintConstrainedLoopInfo());
1784
1785 if (PrintChangedLoops)
1786 PrintConstrainedLoopInfo();
1787
1788 // Optimize away the now-redundant range checks.
1789
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001790 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1791 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001792 ? ConstantInt::getTrue(Context)
1793 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001794 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001795 }
1796 }
1797
1798 return Changed;
1799}
1800
1801Pass *llvm::createInductiveRangeCheckEliminationPass() {
1802 return new InductiveRangeCheckElimination;
1803}