blob: c8e58a1e93a763a63a7d7d386d8519158c1ac033 [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",
Max Kazantsev9ac70212017-10-25 06:47:39 +0000115 cl::Hidden, cl::init(true));
Max Kazantsev8aacef62017-10-04 06:53:22 +0000116
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
Max Kazantsev84286ce2017-10-31 06:19:05 +0000152 const SCEV *Begin = nullptr;
153 const SCEV *Step = nullptr;
154 const SCEV *End = nullptr;
Sanjoy Dasee77a482016-05-26 01:50:18 +0000155 Use *CheckUse = nullptr;
156 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000157 bool IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000158
Sanjoy Das337d46b2015-03-24 19:29:18 +0000159 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
160 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000161 Value *&Length, bool &IsSigned);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000162
Sanjoy Dasa0992682016-05-26 00:09:02 +0000163 static void
164 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
165 SmallVectorImpl<InductiveRangeCheck> &Checks,
166 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000167
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000168public:
Max Kazantsev84286ce2017-10-31 06:19:05 +0000169 const SCEV *getBegin() const { return Begin; }
170 const SCEV *getStep() const { return Step; }
171 const SCEV *getEnd() const { return End; }
Max Kazantsev9ac70212017-10-25 06:47:39 +0000172 bool isSigned() const { return IsSigned; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000173
174 void print(raw_ostream &OS) const {
175 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000176 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Max Kazantsev84286ce2017-10-31 06:19:05 +0000177 OS << " Begin: ";
178 Begin->print(OS);
179 OS << " Step: ";
180 Step->print(OS);
181 OS << " End: ";
Max Kazantsevef057602018-01-12 10:00:26 +0000182 End->print(OS);
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000183 OS << "\n CheckUse: ";
184 getCheckUse()->getUser()->print(OS);
185 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000186 }
187
Davide Italianod1279df2016-08-18 15:55:49 +0000188 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000189 void dump() {
190 print(dbgs());
191 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000192
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000193 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000194
Sanjoy Das351db052015-01-22 09:32:02 +0000195 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
Max Kazantsevd0fe5022018-01-15 05:44:43 +0000196 /// R.getEnd() le R.getBegin(), then R denotes the empty range.
Sanjoy Das351db052015-01-22 09:32:02 +0000197
198 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000199 const SCEV *Begin;
200 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000201
202 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000203 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000204 assert(Begin->getType() == End->getType() && "ill-typed range!");
205 }
206
207 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000208 const SCEV *getBegin() const { return Begin; }
209 const SCEV *getEnd() const { return End; }
Max Kazantsev4332a942017-10-25 06:10:02 +0000210 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
211 if (Begin == End)
212 return true;
213 if (IsSigned)
214 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
215 else
216 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
217 }
Sanjoy Das351db052015-01-22 09:32:02 +0000218 };
219
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000220 /// This is the value the condition of the branch needs to evaluate to for the
221 /// branch to take the hot successor (see (1) above).
222 bool getPassingDirection() { return true; }
223
Sanjoy Das95c476d2015-02-21 22:20:22 +0000224 /// Computes a range for the induction variable (IndVar) in which the range
225 /// check is redundant and can be constant-folded away. The induction
226 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000227 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Max Kazantsev26846782017-11-20 06:07:57 +0000228 const SCEVAddRecExpr *IndVar,
229 bool IsLatchSigned) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000230
Sanjoy Dasa0992682016-05-26 00:09:02 +0000231 /// Parse out a set of inductive range checks from \p BI and append them to \p
232 /// Checks.
233 ///
234 /// NB! There may be conditions feeding into \p BI that aren't inductive range
235 /// checks, and hence don't end up in \p Checks.
236 static void
237 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
238 BranchProbabilityInfo &BPI,
239 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000240};
241
242class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000243public:
244 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000245
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000246 InductiveRangeCheckElimination() : LoopPass(ID) {
247 initializeInductiveRangeCheckEliminationPass(
248 *PassRegistry::getPassRegistry());
249 }
250
251 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000252 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000253 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000254 }
255
256 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
257};
258
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000259} // end anonymous namespace
260
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000261char InductiveRangeCheckElimination::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000262
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000263INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
264 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000265INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000266INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000267INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
268 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000269
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000270StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000271 InductiveRangeCheck::RangeCheckKind RCK) {
272 switch (RCK) {
273 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
274 return "RANGE_CHECK_UNKNOWN";
275
276 case InductiveRangeCheck::RANGE_CHECK_UPPER:
277 return "RANGE_CHECK_UPPER";
278
279 case InductiveRangeCheck::RANGE_CHECK_LOWER:
280 return "RANGE_CHECK_LOWER";
281
282 case InductiveRangeCheck::RANGE_CHECK_BOTH:
283 return "RANGE_CHECK_BOTH";
284 }
285
286 llvm_unreachable("unknown range check type!");
287}
288
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000289/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000290/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000291/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000292/// range checked, and set `Length` to the upper limit `Index` is being range
293/// checked with if (and only if) the range check type is stronger or equal to
294/// RANGE_CHECK_UPPER.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000296InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
297 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000298 Value *&Length, bool &IsSigned) {
Sanjoy Das337d46b2015-03-24 19:29:18 +0000299 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
300 const SCEV *S = SE.getSCEV(V);
301 if (isa<SCEVCouldNotCompute>(S))
302 return false;
303
304 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
305 SE.isKnownNonNegative(S);
306 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000307
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000308 ICmpInst::Predicate Pred = ICI->getPredicate();
309 Value *LHS = ICI->getOperand(0);
310 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000311
312 switch (Pred) {
313 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000314 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000315
316 case ICmpInst::ICMP_SLE:
317 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000318 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000319 case ICmpInst::ICMP_SGE:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000320 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000321 if (match(RHS, m_ConstantInt<0>())) {
322 Index = LHS;
323 return RANGE_CHECK_LOWER;
324 }
325 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326
327 case ICmpInst::ICMP_SLT:
328 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000329 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000330 case ICmpInst::ICMP_SGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000331 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000332 if (match(RHS, m_ConstantInt<-1>())) {
333 Index = LHS;
334 return RANGE_CHECK_LOWER;
335 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000336
Sanjoy Das337d46b2015-03-24 19:29:18 +0000337 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000338 Index = RHS;
339 Length = LHS;
340 return RANGE_CHECK_UPPER;
341 }
342 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000343
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000344 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000345 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000346 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000347 case ICmpInst::ICMP_UGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000348 IsSigned = false;
Sanjoy Das337d46b2015-03-24 19:29:18 +0000349 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000350 Index = RHS;
351 Length = LHS;
352 return RANGE_CHECK_BOTH;
353 }
354 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000356
357 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358}
359
Sanjoy Dasa0992682016-05-26 00:09:02 +0000360void InductiveRangeCheck::extractRangeChecksFromCond(
361 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
362 SmallVectorImpl<InductiveRangeCheck> &Checks,
363 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000364 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000365 if (!Visited.insert(Condition).second)
366 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000367
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000368 // TODO: Do the same for OR, XOR, NOT etc?
Sanjoy Dasa0992682016-05-26 00:09:02 +0000369 if (match(Condition, m_And(m_Value(), m_Value()))) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000370 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000371 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000372 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000373 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000374 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000375 }
376
Sanjoy Dasa0992682016-05-26 00:09:02 +0000377 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
378 if (!ICI)
379 return;
380
381 Value *Length = nullptr, *Index;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000382 bool IsSigned;
383 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000384 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
385 return;
386
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000387 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000388 bool IsAffineIndex =
389 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
390
391 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000392 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000393
Max Kazantsevef057602018-01-12 10:00:26 +0000394 const SCEV *End = nullptr;
395 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
396 // We can potentially do much better here.
397 if (Length)
398 End = SE.getSCEV(Length);
399 else {
400 assert(RCKind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
401 // So far we can only reach this point for Signed range check. This may
402 // change in future. In this case we will need to pick Unsigned max for the
403 // unsigned range check.
404 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth();
405 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
406 End = SIntMax;
407 }
408
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000409 InductiveRangeCheck IRC;
Max Kazantsevef057602018-01-12 10:00:26 +0000410 IRC.End = End;
Max Kazantsev84286ce2017-10-31 06:19:05 +0000411 IRC.Begin = IndexAddRec->getStart();
412 IRC.Step = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000413 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000414 IRC.Kind = RCKind;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000415 IRC.IsSigned = IsSigned;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000416 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000417}
418
Sanjoy Dasa0992682016-05-26 00:09:02 +0000419void InductiveRangeCheck::extractRangeChecksFromBranch(
420 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
421 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000422 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000423 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000424
425 BranchProbability LikelyTaken(15, 16);
426
Sanjoy Dasbb969792016-07-22 00:40:56 +0000427 if (!SkipProfitabilityChecks &&
428 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000429 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000430
Sanjoy Dasa0992682016-05-26 00:09:02 +0000431 SmallPtrSet<Value *, 8> Visited;
432 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
433 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000434}
435
Anna Thomas65ca8e92016-12-13 21:05:21 +0000436// Add metadata to the loop L to disable loop optimizations. Callers need to
437// confirm that optimizing loop L is not beneficial.
438static void DisableAllLoopOptsOnLoop(Loop &L) {
439 // We do not care about any existing loopID related metadata for L, since we
440 // are setting all loop metadata to false.
441 LLVMContext &Context = L.getHeader()->getContext();
442 // Reserve first location for self reference to the LoopID metadata node.
443 MDNode *Dummy = MDNode::get(Context, {});
444 MDNode *DisableUnroll = MDNode::get(
445 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
446 Metadata *FalseVal =
447 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
448 MDNode *DisableVectorize = MDNode::get(
449 Context,
450 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
451 MDNode *DisableLICMVersioning = MDNode::get(
452 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
453 MDNode *DisableDistribution= MDNode::get(
454 Context,
455 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
456 MDNode *NewLoopID =
457 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
458 DisableLICMVersioning, DisableDistribution});
459 // Set operand 0 to refer to the loop id itself.
460 NewLoopID->replaceOperandWith(0, NewLoopID);
461 L.setLoopID(NewLoopID);
462}
463
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000464namespace {
465
Sanjoy Dase75ed922015-02-26 08:19:31 +0000466// Keeps track of the structure of a loop. This is similar to llvm::Loop,
467// except that it is more lightweight and can track the state of a loop through
468// changing and potentially invalid IR. This structure also formalizes the
469// kinds of loops we can deal with -- ones that have a single latch that is also
470// an exiting block *and* have a canonical induction variable.
471struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000472 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000473
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000474 BasicBlock *Header = nullptr;
475 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000476
477 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
478 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000479 BranchInst *LatchBr = nullptr;
480 BasicBlock *LatchExit = nullptr;
481 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000482
Sanjoy Dasec892132017-02-07 23:59:07 +0000483 // The loop represented by this instance of LoopStructure is semantically
484 // equivalent to:
485 //
486 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000487 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000488 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000489 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000490 // ... body ...
491
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000492 Value *IndVarBase = nullptr;
493 Value *IndVarStart = nullptr;
494 Value *IndVarStep = nullptr;
495 Value *LoopExitAt = nullptr;
496 bool IndVarIncreasing = false;
497 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000498
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000499 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000500
501 template <typename M> LoopStructure map(M Map) const {
502 LoopStructure Result;
503 Result.Tag = Tag;
504 Result.Header = cast<BasicBlock>(Map(Header));
505 Result.Latch = cast<BasicBlock>(Map(Latch));
506 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
507 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
508 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000509 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000510 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000511 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000512 Result.LoopExitAt = Map(LoopExitAt);
513 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000514 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000515 return Result;
516 }
517
Sanjoy Dase91665d2015-02-26 08:56:04 +0000518 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
519 BranchProbabilityInfo &BPI,
520 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000521 const char *&);
522};
523
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000524/// This class is used to constrain loops to run within a given iteration space.
525/// The algorithm this class implements is given a Loop and a range [Begin,
526/// End). The algorithm then tries to break out a "main loop" out of the loop
527/// it is given in a way that the "main loop" runs with the induction variable
528/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
529/// loops to run any remaining iterations. The pre loop runs any iterations in
530/// which the induction variable is < Begin, and the post loop runs any
531/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000532class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000533 // The representation of a clone of the original loop we started out with.
534 struct ClonedLoop {
535 // The cloned blocks
536 std::vector<BasicBlock *> Blocks;
537
538 // `Map` maps values in the clonee into values in the cloned version
539 ValueToValueMapTy Map;
540
541 // An instance of `LoopStructure` for the cloned loop
542 LoopStructure Structure;
543 };
544
545 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
546 // more details on what these fields mean.
547 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000548 BasicBlock *PseudoExit = nullptr;
549 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000550 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000551 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000552
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000553 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000554 };
555
556 // Calculated subranges we restrict the iteration space of the main loop to.
557 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000558 // these fields are computed. `LowLimit` is None if there is no restriction
559 // on low end of the restricted iteration space of the main loop. `HighLimit`
560 // is None if there is no restriction on high end of the restricted iteration
561 // space of the main loop.
562
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000563 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000564 Optional<const SCEV *> LowLimit;
565 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000566 };
567
568 // A utility function that does a `replaceUsesOfWith' on the incoming block
569 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
570 // incoming block list with `ReplaceBy'.
571 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
572 BasicBlock *ReplaceBy);
573
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000574 // Compute a safe set of limits for the main loop to run in -- effectively the
575 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000576 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000577 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000578
579 // Clone `OriginalLoop' and return the result in CLResult. The IR after
580 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
581 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
582 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000583 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
584
Sanjoy Das21434472016-08-14 01:04:46 +0000585 // Create the appropriate loop structure needed to describe a cloned copy of
586 // `Original`. The clone is described by `VM`.
587 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
588 ValueToValueMapTy &VM);
589
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000590 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
591 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
592 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
593 // `OriginalHeaderCount'.
594 //
595 // If there are iterations left to execute, control is made to jump to
596 // `ContinuationBlock', otherwise they take the normal loop exit. The
597 // returned `RewrittenRangeInfo' object is populated as follows:
598 //
599 // .PseudoExit is a basic block that unconditionally branches to
600 // `ContinuationBlock'.
601 //
602 // .ExitSelector is a basic block that decides, on exit from the loop,
603 // whether to branch to the "true" exit or to `PseudoExit'.
604 //
605 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
606 // for each PHINode in the loop header on taking the pseudo exit.
607 //
608 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
609 // preheader because it is made to branch to the loop header only
610 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000611 RewrittenRangeInfo
612 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
613 Value *ExitLoopAt,
614 BasicBlock *ContinuationBlock) const;
615
616 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
617 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000618 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
619 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000620
621 // `ContinuationBlockAndPreheader' was the continuation block for some call to
622 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
623 // This function rewrites the PHI nodes in `LS.Header' to start with the
624 // correct value.
625 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000626 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000627 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
628
629 // Even though we do not preserve any passes at this time, we at least need to
630 // keep the parent loop structure consistent. The `LPPassManager' seems to
631 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000632 // blocks denoted by BBs to this loops parent loop if required.
633 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000634
635 // Some global state.
636 Function &F;
637 LLVMContext &Ctx;
638 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000639 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000640 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000641 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000642
643 // Information about the original loop we started out with.
644 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000645
646 const SCEV *LatchTakenCount = nullptr;
647 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000648
649 // The preheader of the main loop. This may or may not be different from
650 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000651 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652
653 // The range we need to run the main loop in.
654 InductiveRangeCheck::Range Range;
655
656 // The structure of the main loop (see comment at the beginning of this class
657 // for a definition)
658 LoopStructure MainLoopStructure;
659
660public:
Sanjoy Das21434472016-08-14 01:04:46 +0000661 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
662 const LoopStructure &LS, ScalarEvolution &SE,
663 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000664 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000665 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R),
666 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000667
668 // Entry point for the algorithm. Returns true on success.
669 bool run();
670};
671
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000672} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000673
674void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
675 BasicBlock *ReplaceBy) {
676 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
677 if (PN->getIncomingBlock(i) == Block)
678 PN->setIncomingBlock(i, ReplaceBy);
679}
680
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000681static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
682 APInt Max = Signed ?
683 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
684 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
685 return SE.getSignedRange(S).contains(Max) &&
686 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000687}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000688
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000689static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
690 bool Signed) {
691 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
692 assert(SE.isKnownNonNegative(S2) &&
693 "We expected the 2nd arg to be non-negative!");
694 const SCEV *Max = SE.getConstant(
695 Signed ? APInt::getSignedMaxValue(
696 cast<IntegerType>(S1->getType())->getBitWidth())
697 : APInt::getMaxValue(
698 cast<IntegerType>(S1->getType())->getBitWidth()));
699 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
700 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
701 S1, CapForS1);
702}
703
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000704static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
705 APInt Min = Signed ?
706 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
707 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
708 return SE.getSignedRange(S).contains(Min) &&
709 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000710}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000711
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000712static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
713 bool Signed) {
714 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
715 assert(SE.isKnownNonPositive(S2) &&
716 "We expected the 2nd arg to be non-positive!");
717 const SCEV *Max = SE.getConstant(
718 Signed ? APInt::getSignedMinValue(
719 cast<IntegerType>(S1->getType())->getBitWidth())
720 : APInt::getMinValue(
721 cast<IntegerType>(S1->getType())->getBitWidth()));
722 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
723 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
724 S1, CapForS1);
725}
726
Sanjoy Dase75ed922015-02-26 08:19:31 +0000727Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000728LoopStructure::parseLoopStructure(ScalarEvolution &SE,
729 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000730 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000731 if (!L.isLoopSimplifyForm()) {
732 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000733 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000734 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000735
736 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000737 assert(Latch && "Simplified loops only have one latch!");
738
Sanjoy Das7a18a232016-08-14 01:04:36 +0000739 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
740 FailureReason = "loop has already been cloned";
741 return None;
742 }
743
Sanjoy Dase75ed922015-02-26 08:19:31 +0000744 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000745 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000746 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000747 }
748
Sanjoy Dase75ed922015-02-26 08:19:31 +0000749 BasicBlock *Header = L.getHeader();
750 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000751 if (!Preheader) {
752 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000753 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000754 }
755
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000756 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000757 if (!LatchBr || LatchBr->isUnconditional()) {
758 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000759 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000760 }
761
Sanjoy Dase75ed922015-02-26 08:19:31 +0000762 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000763
Sanjoy Dase91665d2015-02-26 08:56:04 +0000764 BranchProbability ExitProbability =
765 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
766
Sanjoy Dasbb969792016-07-22 00:40:56 +0000767 if (!SkipProfitabilityChecks &&
768 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000769 FailureReason = "short running loop, not profitable";
770 return None;
771 }
772
Sanjoy Dase75ed922015-02-26 08:19:31 +0000773 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
774 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
775 FailureReason = "latch terminator branch not conditional on integral icmp";
776 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000777 }
778
Sanjoy Dase75ed922015-02-26 08:19:31 +0000779 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
780 if (isa<SCEVCouldNotCompute>(LatchCount)) {
781 FailureReason = "could not compute latch count";
782 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000783 }
784
Sanjoy Dase75ed922015-02-26 08:19:31 +0000785 ICmpInst::Predicate Pred = ICI->getPredicate();
786 Value *LeftValue = ICI->getOperand(0);
787 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
788 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
789
790 Value *RightValue = ICI->getOperand(1);
791 const SCEV *RightSCEV = SE.getSCEV(RightValue);
792
793 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
794 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
795 if (isa<SCEVAddRecExpr>(RightSCEV)) {
796 std::swap(LeftSCEV, RightSCEV);
797 std::swap(LeftValue, RightValue);
798 Pred = ICmpInst::getSwappedPredicate(Pred);
799 } else {
800 FailureReason = "no add recurrences in the icmp";
801 return None;
802 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000803 }
804
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000805 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
806 if (AR->getNoWrapFlags(SCEV::FlagNSW))
807 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000808
809 IntegerType *Ty = cast<IntegerType>(AR->getType());
810 IntegerType *WideTy =
811 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
812
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000813 const SCEVAddRecExpr *ExtendAfterOp =
814 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
815 if (ExtendAfterOp) {
816 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
817 const SCEV *ExtendedStep =
818 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
819
820 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
821 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
822
823 if (NoSignedWrap)
824 return true;
825 }
826
827 // We may have proved this when computing the sign extension above.
828 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
829 };
830
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000831 // Here we check whether the suggested AddRec is an induction variable that
832 // can be handled (i.e. with known constant step), and if yes, calculate its
833 // step and identify whether it is increasing or decreasing.
834 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
835 ConstantInt *&StepCI) {
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000836 if (!AR->isAffine())
837 return false;
838
Sanjoy Dase75ed922015-02-26 08:19:31 +0000839 // Currently we only work with induction variables that have been proved to
840 // not wrap. This restriction can potentially be lifted in the future.
841
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000842 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000843 return false;
844
845 if (const SCEVConstant *StepExpr =
846 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000847 StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000848 assert(!StepCI->isZero() && "Zero step?");
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000849 IsIncreasing = !StepCI->isNegative();
850 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000851 }
852
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000853 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000854 };
855
Serguei Katkov675e3042017-09-21 04:50:41 +0000856 // `ICI` is interpreted as taking the backedge if the *next* value of the
857 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000858
Max Kazantseva22742b2017-08-31 05:58:15 +0000859 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000860 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000861 bool IsSignedPredicate = true;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000862 ConstantInt *StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +0000863 if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000864 FailureReason = "LHS in icmp not induction variable";
865 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000866 }
867
Serguei Katkov675e3042017-09-21 04:50:41 +0000868 const SCEV *StartNext = IndVarBase->getStart();
869 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
870 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000871 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000872
Sanjoy Dase75ed922015-02-26 08:19:31 +0000873 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000874 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000875 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000876 if (StepCI->isOne()) {
877 // Try to turn eq/ne predicates to those we can work with.
878 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
879 // while (++i != len) { while (++i < len) {
880 // ... ---> ...
881 // } }
882 // If both parts are known non-negative, it is profitable to use
883 // unsigned comparison in increasing loop. This allows us to make the
884 // comparison check against "RightSCEV + 1" more optimistic.
885 if (SE.isKnownNonNegative(IndVarStart) &&
886 SE.isKnownNonNegative(RightSCEV))
887 Pred = ICmpInst::ICMP_ULT;
888 else
889 Pred = ICmpInst::ICMP_SLT;
890 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
891 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
892 // while (true) { while (true) {
893 // if (++i == len) ---> if (++i > len - 1)
894 // break; break;
895 // ... ...
896 // } }
897 // TODO: Insert ICMP_UGT if both are non-negative?
898 Pred = ICmpInst::ICMP_SGT;
899 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
900 DecreasedRightValueByOne = true;
901 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000902 }
903
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000904 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
905 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000906 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000907 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000908
909 if (!FoundExpectedPred) {
910 FailureReason = "expected icmp slt semantically, found something else";
911 return None;
912 }
913
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000914 IsSignedPredicate =
915 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000916
Max Kazantsev8aacef62017-10-04 06:53:22 +0000917 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
918 FailureReason = "unsigned latch conditions are explicitly prohibited";
919 return None;
920 }
921
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000922 // The predicate that we need to check that the induction variable lies
923 // within bounds.
924 ICmpInst::Predicate BoundPred =
925 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
926
Sanjoy Dase75ed922015-02-26 08:19:31 +0000927 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000928 const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
929 SE.getOne(Step->getType()));
930 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000931 // TODO: this restriction is easily removable -- we just have to
932 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000933 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000934 return None;
935 }
936
Sanjoy Dasec892132017-02-07 23:59:07 +0000937 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000938 &L, BoundPred, IndVarStart,
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000939 SE.getAddExpr(RightSCEV, Step))) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000940 FailureReason = "Induction variable start not bounded by upper limit";
941 return None;
942 }
943
Max Kazantsev2c627a92017-07-18 04:53:48 +0000944 // We need to increase the right value unless we have already decreased
945 // it virtually when we replaced EQ with SGT.
946 if (!DecreasedRightValueByOne) {
947 IRBuilder<> B(Preheader->getTerminator());
948 RightValue = B.CreateAdd(RightValue, One);
949 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000950 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000951 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000952 FailureReason = "Induction variable start not bounded by upper limit";
953 return None;
954 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000955 assert(!DecreasedRightValueByOne &&
956 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000957 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000958 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000959 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000960 if (StepCI->isMinusOne()) {
961 // Try to turn eq/ne predicates to those we can work with.
962 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
963 // while (--i != len) { while (--i > len) {
964 // ... ---> ...
965 // } }
966 // We intentionally don't turn the predicate into UGT even if we know
967 // that both operands are non-negative, because it will only pessimize
968 // our check against "RightSCEV - 1".
969 Pred = ICmpInst::ICMP_SGT;
970 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
971 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
972 // while (true) { while (true) {
973 // if (--i == len) ---> if (--i < len + 1)
974 // break; break;
975 // ... ...
976 // } }
977 // TODO: Insert ICMP_ULT if both are non-negative?
978 Pred = ICmpInst::ICMP_SLT;
979 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
980 IncreasedRightValueByOne = true;
981 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000982 }
983
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000984 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
985 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
986
Sanjoy Dase75ed922015-02-26 08:19:31 +0000987 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000988 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000989
990 if (!FoundExpectedPred) {
991 FailureReason = "expected icmp sgt semantically, found something else";
992 return None;
993 }
994
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000995 IsSignedPredicate =
996 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000997
Max Kazantsev8aacef62017-10-04 06:53:22 +0000998 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
999 FailureReason = "unsigned latch conditions are explicitly prohibited";
1000 return None;
1001 }
1002
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001003 // The predicate that we need to check that the induction variable lies
1004 // within bounds.
1005 ICmpInst::Predicate BoundPred =
1006 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
1007
Sanjoy Dase75ed922015-02-26 08:19:31 +00001008 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001009 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
1010 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001011 // TODO: this restriction is easily removable -- we just have to
1012 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001013 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +00001014 return None;
1015 }
1016
Sanjoy Dasec892132017-02-07 23:59:07 +00001017 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001018 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +00001019 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1020 FailureReason = "Induction variable start not bounded by lower limit";
1021 return None;
1022 }
1023
Max Kazantsev2c627a92017-07-18 04:53:48 +00001024 // We need to decrease the right value unless we have already increased
1025 // it virtually when we replaced EQ with SLT.
1026 if (!IncreasedRightValueByOne) {
1027 IRBuilder<> B(Preheader->getTerminator());
1028 RightValue = B.CreateSub(RightValue, One);
1029 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001030 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001031 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +00001032 FailureReason = "Induction variable start not bounded by lower limit";
1033 return None;
1034 }
Max Kazantsev2c627a92017-07-18 04:53:48 +00001035 assert(!IncreasedRightValueByOne &&
1036 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001037 }
1038 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001039 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1040
Sanjoy Dase75ed922015-02-26 08:19:31 +00001041 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001042 ScalarEvolution::LoopInvariant &&
1043 "loop variant exit count doesn't make sense!");
1044
Sanjoy Dase75ed922015-02-26 08:19:31 +00001045 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001046 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1047 Value *IndVarStartV =
1048 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001049 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001050 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001051
Sanjoy Dase75ed922015-02-26 08:19:31 +00001052 LoopStructure Result;
1053
1054 Result.Tag = "main";
1055 Result.Header = Header;
1056 Result.Latch = Latch;
1057 Result.LatchBr = LatchBr;
1058 Result.LatchExit = LatchExit;
1059 Result.LatchBrExitIdx = LatchBrExitIdx;
1060 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001061 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001062 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001063 Result.IndVarIncreasing = IsIncreasing;
1064 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001065 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001066
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001067 FailureReason = nullptr;
1068
Sanjoy Dase75ed922015-02-26 08:19:31 +00001069 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001070}
1071
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001072Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001073LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001074 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1075
Sanjoy Das351db052015-01-22 09:32:02 +00001076 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001077 return None;
1078
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001079 LoopConstrainer::SubRanges Result;
1080
1081 // I think we can be more aggressive here and make this nuw / nsw if the
1082 // addition that feeds into the icmp for the latch's terminating branch is nuw
1083 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001084 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1085 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001086
Sanjoy Dase75ed922015-02-26 08:19:31 +00001087 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001088
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001089 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1090 // [Smallest, GreatestSeen] is the range of values the induction variable
1091 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001092
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001093 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001094
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001095 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001096 if (Increasing) {
1097 Smallest = Start;
1098 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001099 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1100 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001101 } else {
1102 // These two computations may sign-overflow. Here is why that is okay:
1103 //
1104 // We know that the induction variable does not sign-overflow on any
1105 // iteration except the last one, and it starts at `Start` and ends at
1106 // `End`, decrementing by one every time.
1107 //
1108 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1109 // induction variable is decreasing we know that that the smallest value
1110 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1111 //
1112 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1113 // that case, `Clamp` will always return `Smallest` and
1114 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1115 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001116
Max Kazantsev6c466a32017-06-28 04:57:45 +00001117 Smallest = SE.getAddExpr(End, One);
1118 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001119 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001120 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001121
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001122 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev6f5229d72017-11-01 13:21:56 +00001123 return IsSignedPredicate
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001124 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1125 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001126 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001127
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001128 // In some cases we can prove that we don't need a pre or post loop.
1129 ICmpInst::Predicate PredLE =
1130 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1131 ICmpInst::Predicate PredLT =
1132 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001133
1134 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001135 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001136 if (!ProvablyNoPreloop)
1137 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001138
1139 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001140 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001141 if (!ProvablyNoPostLoop)
1142 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001143
1144 return Result;
1145}
1146
1147void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1148 const char *Tag) const {
1149 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1150 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1151 Result.Blocks.push_back(Clone);
1152 Result.Map[BB] = Clone;
1153 }
1154
1155 auto GetClonedValue = [&Result](Value *V) {
1156 assert(V && "null values not in domain!");
1157 auto It = Result.Map.find(V);
1158 if (It == Result.Map.end())
1159 return V;
1160 return static_cast<Value *>(It->second);
1161 };
1162
Sanjoy Das7a18a232016-08-14 01:04:36 +00001163 auto *ClonedLatch =
1164 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1165 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1166 MDNode::get(Ctx, {}));
1167
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168 Result.Structure = MainLoopStructure.map(GetClonedValue);
1169 Result.Structure.Tag = Tag;
1170
1171 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1172 BasicBlock *ClonedBB = Result.Blocks[i];
1173 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1174
1175 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1176
1177 for (Instruction &I : *ClonedBB)
1178 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001179 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001180
1181 // Exit blocks will now have one more predecessor and their PHI nodes need
1182 // to be edited to reflect that. No phi nodes need to be introduced because
1183 // the loop is in LCSSA.
1184
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001185 for (auto *SBB : successors(OriginalBB)) {
1186 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001187 continue; // not an exit block
1188
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001189 for (PHINode &PN : SBB->phis()) {
1190 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
1191 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001192 }
1193 }
1194 }
1195}
1196
1197LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001198 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001199 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001200 // We start with a loop with a single latch:
1201 //
1202 // +--------------------+
1203 // | |
1204 // | preheader |
1205 // | |
1206 // +--------+-----------+
1207 // | ----------------\
1208 // | / |
1209 // +--------v----v------+ |
1210 // | | |
1211 // | header | |
1212 // | | |
1213 // +--------------------+ |
1214 // |
1215 // ..... |
1216 // |
1217 // +--------------------+ |
1218 // | | |
1219 // | latch >----------/
1220 // | |
1221 // +-------v------------+
1222 // |
1223 // |
1224 // | +--------------------+
1225 // | | |
1226 // +---> original exit |
1227 // | |
1228 // +--------------------+
1229 //
1230 // We change the control flow to look like
1231 //
1232 //
1233 // +--------------------+
1234 // | |
1235 // | preheader >-------------------------+
1236 // | | |
1237 // +--------v-----------+ |
1238 // | /-------------+ |
1239 // | / | |
1240 // +--------v--v--------+ | |
1241 // | | | |
1242 // | header | | +--------+ |
1243 // | | | | | |
1244 // +--------------------+ | | +-----v-----v-----------+
1245 // | | | |
1246 // | | | .pseudo.exit |
1247 // | | | |
1248 // | | +-----------v-----------+
1249 // | | |
1250 // ..... | | |
1251 // | | +--------v-------------+
1252 // +--------------------+ | | | |
1253 // | | | | | ContinuationBlock |
1254 // | latch >------+ | | |
1255 // | | | +----------------------+
1256 // +---------v----------+ |
1257 // | |
1258 // | |
1259 // | +---------------^-----+
1260 // | | |
1261 // +-----> .exit.selector |
1262 // | |
1263 // +----------v----------+
1264 // |
1265 // +--------------------+ |
1266 // | | |
1267 // | original exit <----+
1268 // | |
1269 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001270
1271 RewrittenRangeInfo RRI;
1272
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001273 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001274 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001275 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001277 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001278
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001279 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001280 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001281 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001282
1283 IRBuilder<> B(PreheaderJump);
1284
1285 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001286 Value *EnterLoopCond = nullptr;
1287 if (Increasing)
1288 EnterLoopCond = IsSignedPredicate
1289 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1290 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1291 else
1292 EnterLoopCond = IsSignedPredicate
1293 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1294 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001295
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001296 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1297 PreheaderJump->eraseFromParent();
1298
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001299 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001300 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001301 Value *TakeBackedgeLoopCond = nullptr;
1302 if (Increasing)
1303 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001304 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1305 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001306 else
1307 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001308 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1309 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001310 Value *CondForBranch = LS.LatchBrExitIdx == 1
1311 ? TakeBackedgeLoopCond
1312 : B.CreateNot(TakeBackedgeLoopCond);
1313
1314 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001315
1316 B.SetInsertPoint(RRI.ExitSelector);
1317
1318 // IterationsLeft - are there any more iterations left, given the original
1319 // upper bound on the induction variable? If not, we branch to the "real"
1320 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001321 Value *IterationsLeft = nullptr;
1322 if (Increasing)
1323 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001324 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1325 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001326 else
1327 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001328 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1329 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001330 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1331
1332 BranchInst *BranchToContinuation =
1333 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1334
1335 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1336 // each of the PHI nodes in the loop header. This feeds into the initial
1337 // value of the same PHI nodes if/when we continue execution.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001338 for (PHINode &PN : LS.Header->phis()) {
1339 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340 BranchToContinuation);
1341
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001342 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
1343 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
Serguei Katkov675e3042017-09-21 04:50:41 +00001344 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001345 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1346 }
1347
Max Kazantseva22742b2017-08-31 05:58:15 +00001348 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001349 BranchToContinuation);
1350 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001351 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001352
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001353 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1354 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001355 for (PHINode &PN : LS.LatchExit->phis())
1356 replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001357
1358 return RRI;
1359}
1360
1361void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001362 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001364 unsigned PHIIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001365 for (PHINode &PN : LS.Header->phis())
1366 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i)
1367 if (PN.getIncomingBlock(i) == ContinuationBlock)
1368 PN.setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001369
Sanjoy Dase75ed922015-02-26 08:19:31 +00001370 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001371}
1372
Sanjoy Dase75ed922015-02-26 08:19:31 +00001373BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1374 BasicBlock *OldPreheader,
1375 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001376 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1377 BranchInst::Create(LS.Header, Preheader);
1378
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001379 for (PHINode &PN : LS.Header->phis())
1380 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i)
1381 replacePHIBlock(&PN, OldPreheader, Preheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001382
1383 return Preheader;
1384}
1385
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001386void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001387 Loop *ParentLoop = OriginalLoop.getParentLoop();
1388 if (!ParentLoop)
1389 return;
1390
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001391 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001392 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001393}
1394
Sanjoy Das21434472016-08-14 01:04:46 +00001395Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1396 ValueToValueMapTy &VM) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001397 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001398 if (Parent)
1399 Parent->addChildLoop(&New);
1400 else
1401 LI.addTopLevelLoop(&New);
1402 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001403
1404 // Add all of the blocks in Original to the new loop.
1405 for (auto *BB : Original->blocks())
1406 if (LI.getLoopFor(BB) == Original)
1407 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1408
1409 // Add all of the subloops to the new loop.
1410 for (Loop *SubLoop : *Original)
1411 createClonedLoopStructure(SubLoop, &New, VM);
1412
1413 return &New;
1414}
1415
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001416bool LoopConstrainer::run() {
1417 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001418 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1419 Preheader = OriginalLoop.getLoopPreheader();
1420 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1421 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001422
1423 OriginalPreheader = Preheader;
1424 MainLoopPreheader = Preheader;
1425
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001426 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1427 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001428 if (!MaybeSR.hasValue()) {
1429 DEBUG(dbgs() << "irce: could not compute subranges\n");
1430 return false;
1431 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001432
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001433 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001434 bool Increasing = MainLoopStructure.IndVarIncreasing;
1435 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001436 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001437
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001438 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001439 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001440
1441 // It would have been better to make `PreLoop' and `PostLoop'
1442 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1443 // constructor.
1444 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001445 bool NeedsPreLoop =
1446 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1447 bool NeedsPostLoop =
1448 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1449
1450 Value *ExitPreLoopAt = nullptr;
1451 Value *ExitMainLoopAt = nullptr;
1452 const SCEVConstant *MinusOneS =
1453 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1454
1455 if (NeedsPreLoop) {
1456 const SCEV *ExitPreLoopAtSCEV = nullptr;
1457
1458 if (Increasing)
1459 ExitPreLoopAtSCEV = *SR.LowLimit;
1460 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001461 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001462 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1463 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1464 << "\n");
1465 return false;
1466 }
1467 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1468 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001469
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001470 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) {
1471 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1472 << " preloop exit limit " << *ExitPreLoopAtSCEV
1473 << " at block " << InsertPt->getParent()->getName() << "\n");
1474 return false;
1475 }
1476
Sanjoy Dase75ed922015-02-26 08:19:31 +00001477 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1478 ExitPreLoopAt->setName("exit.preloop.at");
1479 }
1480
1481 if (NeedsPostLoop) {
1482 const SCEV *ExitMainLoopAtSCEV = nullptr;
1483
1484 if (Increasing)
1485 ExitMainLoopAtSCEV = *SR.HighLimit;
1486 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001487 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001488 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1489 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1490 << "\n");
1491 return false;
1492 }
1493 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1494 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001495
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001496 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) {
1497 DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1498 << " main loop exit limit " << *ExitMainLoopAtSCEV
1499 << " at block " << InsertPt->getParent()->getName() << "\n");
1500 return false;
1501 }
1502
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(
Max Kazantsev26846782017-11-20 06:07:57 +00001593 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar,
1594 bool IsLatchSigned) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001595 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1596 // variable, that may or may not exist as a real llvm::Value in the loop) and
1597 // this inductive range check is a range check on the "C + D * I" ("C" is
Max Kazantsev84286ce2017-10-31 06:19:05 +00001598 // getBegin() and "D" is getStep()). We rewrite the value being range
Sanjoy Das95c476d2015-02-21 22:20:22 +00001599 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001600 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001601 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001602 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001603 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1604 //
Max Kazantsev26846782017-11-20 06:07:57 +00001605 // Here L stands for upper limit of the safe iteration space.
1606 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
1607 // overflows when calculating (0 - M) and (L - M) we, depending on type of
1608 // IV's iteration space, limit the calculations by borders of the iteration
1609 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
1610 // If we figured out that "anything greater than (-M) is safe", we strengthen
1611 // this to "everything greater than 0 is safe", assuming that values between
1612 // -M and 0 just do not exist in unsigned iteration space, and we don't want
1613 // to deal with overflown values.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001614
Sanjoy Das95c476d2015-02-21 22:20:22 +00001615 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001616 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001617
Sanjoy Das95c476d2015-02-21 22:20:22 +00001618 const SCEV *A = IndVar->getStart();
1619 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1620 if (!B)
1621 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001622 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001623
Max Kazantsev84286ce2017-10-31 06:19:05 +00001624 const SCEV *C = getBegin();
1625 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
Sanjoy Das95c476d2015-02-21 22:20:22 +00001626 if (D != B)
1627 return None;
1628
Max Kazantsev95054702017-08-04 07:41:24 +00001629 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Max Kazantsev26846782017-11-20 06:07:57 +00001630 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1631 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
Sanjoy Das95c476d2015-02-21 22:20:22 +00001632
Max Kazantsev26846782017-11-20 06:07:57 +00001633 // Substract Y from X so that it does not go through border of the IV
1634 // iteration space. Mathematically, it is equivalent to:
1635 //
1636 // ClampedSubstract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
1637 //
1638 // In [1], 'X - Y' is a mathematical substraction (result is not bounded to
1639 // any width of bit grid). But after we take min/max, the result is
1640 // guaranteed to be within [INT_MIN, INT_MAX].
1641 //
1642 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
1643 // values, depending on type of latch condition that defines IV iteration
1644 // space.
1645 auto ClampedSubstract = [&](const SCEV *X, const SCEV *Y) {
1646 assert(SE.isKnownNonNegative(X) &&
1647 "We can only substract from values in [0; SINT_MAX]!");
1648 if (IsLatchSigned) {
1649 // X is a number from signed range, Y is interpreted as signed.
1650 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
1651 // thing we should care about is that we didn't cross SINT_MAX.
1652 // So, if Y is positive, we substract Y safely.
1653 // Rule 1: Y > 0 ---> Y.
1654 // If 0 <= -Y <= (SINT_MAX - X), we substract Y safely.
1655 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
1656 // If 0 <= (SINT_MAX - X) < -Y, we can only substract (X - SINT_MAX).
1657 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
1658 // It gives us smax(Y, X - SINT_MAX) to substract in all cases.
1659 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
Max Kazantsev716e6472017-11-23 06:14:39 +00001660 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
1661 SCEV::FlagNSW);
Max Kazantsev26846782017-11-20 06:07:57 +00001662 } else
1663 // X is a number from unsigned range, Y is interpreted as signed.
1664 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
1665 // thing we should care about is that we didn't cross zero.
1666 // So, if Y is negative, we substract Y safely.
1667 // Rule 1: Y <s 0 ---> Y.
1668 // If 0 <= Y <= X, we substract Y safely.
1669 // Rule 2: Y <=s X ---> Y.
1670 // If 0 <= X < Y, we should stop at 0 and can only substract X.
1671 // Rule 3: Y >s X ---> X.
1672 // It gives us smin(X, Y) to substract in all cases.
Max Kazantsev716e6472017-11-23 06:14:39 +00001673 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
Max Kazantsev26846782017-11-20 06:07:57 +00001674 };
Sanjoy Das95c476d2015-02-21 22:20:22 +00001675 const SCEV *M = SE.getMinusSCEV(C, A);
Max Kazantsev26846782017-11-20 06:07:57 +00001676 const SCEV *Zero = SE.getZero(M->getType());
1677 const SCEV *Begin = ClampedSubstract(Zero, M);
Max Kazantsevef057602018-01-12 10:00:26 +00001678 const SCEV *End = ClampedSubstract(getEnd(), M);
Sanjoy Das351db052015-01-22 09:32:02 +00001679 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001680}
1681
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001682static Optional<InductiveRangeCheck::Range>
Max Kazantsev9ac70212017-10-25 06:47:39 +00001683IntersectSignedRange(ScalarEvolution &SE,
1684 const Optional<InductiveRangeCheck::Range> &R1,
1685 const InductiveRangeCheck::Range &R2) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001686 if (R2.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001687 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001688 if (!R1.hasValue())
1689 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001690 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001691 // We never return empty ranges from this function, and R1 is supposed to be
1692 // a result of intersection. Thus, R1 is never empty.
Max Kazantsev4332a942017-10-25 06:10:02 +00001693 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1694 "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001695
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001696 // TODO: we could widen the smaller range and have this work; but for now we
1697 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001698 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001699 return None;
1700
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001701 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1702 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1703
Max Kazantsev25d86552017-10-11 06:53:07 +00001704 // If the resulting range is empty, just return None.
1705 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
Max Kazantsev4332a942017-10-25 06:10:02 +00001706 if (Ret.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001707 return None;
1708 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001709}
1710
Max Kazantsev9ac70212017-10-25 06:47:39 +00001711static Optional<InductiveRangeCheck::Range>
1712IntersectUnsignedRange(ScalarEvolution &SE,
1713 const Optional<InductiveRangeCheck::Range> &R1,
1714 const InductiveRangeCheck::Range &R2) {
1715 if (R2.isEmpty(SE, /* IsSigned */ false))
1716 return None;
1717 if (!R1.hasValue())
1718 return R2;
1719 auto &R1Value = R1.getValue();
1720 // We never return empty ranges from this function, and R1 is supposed to be
1721 // a result of intersection. Thus, R1 is never empty.
1722 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1723 "We should never have empty R1!");
1724
1725 // TODO: we could widen the smaller range and have this work; but for now we
1726 // bail out to keep things simple.
1727 if (R1Value.getType() != R2.getType())
1728 return None;
1729
1730 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1731 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1732
1733 // If the resulting range is empty, just return None.
1734 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1735 if (Ret.isEmpty(SE, /* IsSigned */ false))
1736 return None;
1737 return Ret;
1738}
1739
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001740bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001741 if (skipLoop(L))
1742 return false;
1743
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001744 if (L->getBlocks().size() >= LoopSizeCutoff) {
1745 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1746 return false;
1747 }
1748
1749 BasicBlock *Preheader = L->getLoopPreheader();
1750 if (!Preheader) {
1751 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1752 return false;
1753 }
1754
1755 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001756 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001757 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001758 BranchProbabilityInfo &BPI =
1759 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001760
1761 for (auto BBI : L->getBlocks())
1762 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001763 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1764 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001765
1766 if (RangeChecks.empty())
1767 return false;
1768
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001769 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1770 OS << "irce: looking at loop "; L->print(OS);
1771 OS << "irce: loop has " << RangeChecks.size()
1772 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001773 for (InductiveRangeCheck &IRC : RangeChecks)
1774 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001775 };
1776
1777 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1778
1779 if (PrintRangeChecks)
1780 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001781
Sanjoy Dase75ed922015-02-26 08:19:31 +00001782 const char *FailureReason = nullptr;
1783 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001784 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001785 if (!MaybeLoopStructure.hasValue()) {
1786 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1787 << "\n";);
1788 return false;
1789 }
1790 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001791 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001792 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001793
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001794 Optional<InductiveRangeCheck::Range> SafeIterRange;
1795 Instruction *ExprInsertPt = Preheader->getTerminator();
1796
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001797 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Max Kazantsev9ac70212017-10-25 06:47:39 +00001798 // Basing on the type of latch predicate, we interpret the IV iteration range
1799 // as signed or unsigned range. We use different min/max functions (signed or
1800 // unsigned) when intersecting this range with safe iteration ranges implied
1801 // by range checks.
1802 auto IntersectRange =
1803 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001804
1805 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001806 for (InductiveRangeCheck &IRC : RangeChecks) {
Max Kazantsev26846782017-11-20 06:07:57 +00001807 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1808 LS.IsSignedPredicate);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001809 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001810 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001811 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001812 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001813 assert(
1814 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1815 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001816 RangeChecksToEliminate.push_back(IRC);
1817 SafeIterRange = MaybeSafeIterRange.getValue();
1818 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001819 }
1820 }
1821
1822 if (!SafeIterRange.hasValue())
1823 return false;
1824
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001825 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001826 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1827 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001828 bool Changed = LC.run();
1829
1830 if (Changed) {
1831 auto PrintConstrainedLoopInfo = [L]() {
1832 dbgs() << "irce: in function ";
1833 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1834 dbgs() << "constrained ";
1835 L->print(dbgs());
1836 };
1837
1838 DEBUG(PrintConstrainedLoopInfo());
1839
1840 if (PrintChangedLoops)
1841 PrintConstrainedLoopInfo();
1842
1843 // Optimize away the now-redundant range checks.
1844
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001845 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1846 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001847 ? ConstantInt::getTrue(Context)
1848 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001849 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001850 }
1851 }
1852
1853 return Changed;
1854}
1855
1856Pass *llvm::createInductiveRangeCheckEliminationPass() {
1857 return new InductiveRangeCheckElimination;
1858}