blob: 7602947d5bd2e4d36d5d35d3e1d3f274ef97e393 [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/Optional.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000045#include "llvm/Analysis/BranchProbabilityInfo.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000046#include "llvm/Analysis/LoopInfo.h"
47#include "llvm/Analysis/LoopPass.h"
48#include "llvm/Analysis/ScalarEvolution.h"
49#include "llvm/Analysis/ScalarEvolutionExpander.h"
50#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000051#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000053#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000054#include "llvm/IR/Instructions.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000055#include "llvm/IR/PatternMatch.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000056#include "llvm/Pass.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000058#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000059#include "llvm/Transforms/Scalar.h"
60#include "llvm/Transforms/Utils/BasicBlockUtils.h"
61#include "llvm/Transforms/Utils/Cloning.h"
62#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000063#include "llvm/Transforms/Utils/LoopSimplify.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064
65using namespace llvm;
66
Benjamin Kramer970eac42015-02-06 17:51:54 +000067static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
68 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000069
Benjamin Kramer970eac42015-02-06 17:51:54 +000070static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
71 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000072
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000073static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
74 cl::init(false));
75
Sanjoy Dase91665d2015-02-26 08:56:04 +000076static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
77 cl::Hidden, cl::init(10));
78
Sanjoy Dasbb969792016-07-22 00:40:56 +000079static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
80 cl::Hidden, cl::init(false));
81
Sanjoy Das7a18a232016-08-14 01:04:36 +000082static const char *ClonedLoopTag = "irce.loop.clone";
83
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084#define DEBUG_TYPE "irce"
85
86namespace {
87
88/// An inductive range check is conditional branch in a loop with
89///
90/// 1. a very cold successor (i.e. the branch jumps to that successor very
91/// rarely)
92///
93/// and
94///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000095/// 2. a condition that is provably true for some contiguous range of values
96/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000097///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000099 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000100 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000101 // Range check of the form "0 <= I".
102 RANGE_CHECK_LOWER = 1,
103
104 // Range check of the form "I < L" where L is known positive.
105 RANGE_CHECK_UPPER = 2,
106
107 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
108 // conditions.
109 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
110
111 // Unrecognized range check condition.
112 RANGE_CHECK_UNKNOWN = (unsigned)-1
113 };
114
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000115 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000116
Sanjoy Dasee77a482016-05-26 01:50:18 +0000117 const SCEV *Offset = nullptr;
118 const SCEV *Scale = nullptr;
119 Value *Length = nullptr;
120 Use *CheckUse = nullptr;
121 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122
Sanjoy Das337d46b2015-03-24 19:29:18 +0000123 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
124 ScalarEvolution &SE, Value *&Index,
125 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000126
Sanjoy Dasa0992682016-05-26 00:09:02 +0000127 static void
128 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
129 SmallVectorImpl<InductiveRangeCheck> &Checks,
130 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132public:
133 const SCEV *getOffset() const { return Offset; }
134 const SCEV *getScale() const { return Scale; }
135 Value *getLength() const { return Length; }
136
137 void print(raw_ostream &OS) const {
138 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000139 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000140 OS << " Offset: ";
141 Offset->print(OS);
142 OS << " Scale: ";
143 Scale->print(OS);
144 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000145 if (Length)
146 Length->print(OS);
147 else
148 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000149 OS << "\n CheckUse: ";
150 getCheckUse()->getUser()->print(OS);
151 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000152 }
153
154#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
155 void dump() {
156 print(dbgs());
157 }
158#endif
159
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000160 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000161
Sanjoy Das351db052015-01-22 09:32:02 +0000162 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
163 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
164
165 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000166 const SCEV *Begin;
167 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000168
169 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000170 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000171 assert(Begin->getType() == End->getType() && "ill-typed range!");
172 }
173
174 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000175 const SCEV *getBegin() const { return Begin; }
176 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000177 };
178
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000179 /// This is the value the condition of the branch needs to evaluate to for the
180 /// branch to take the hot successor (see (1) above).
181 bool getPassingDirection() { return true; }
182
Sanjoy Das95c476d2015-02-21 22:20:22 +0000183 /// Computes a range for the induction variable (IndVar) in which the range
184 /// check is redundant and can be constant-folded away. The induction
185 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000186 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000187 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000188
Sanjoy Dasa0992682016-05-26 00:09:02 +0000189 /// Parse out a set of inductive range checks from \p BI and append them to \p
190 /// Checks.
191 ///
192 /// NB! There may be conditions feeding into \p BI that aren't inductive range
193 /// checks, and hence don't end up in \p Checks.
194 static void
195 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
196 BranchProbabilityInfo &BPI,
197 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000198};
199
200class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000201public:
202 static char ID;
203 InductiveRangeCheckElimination() : LoopPass(ID) {
204 initializeInductiveRangeCheckEliminationPass(
205 *PassRegistry::getPassRegistry());
206 }
207
208 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000209 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000210 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000211 }
212
213 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
214};
215
216char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000217}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000218
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000219INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
220 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000221INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000222INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000223INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
224 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000225
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000226StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000227 InductiveRangeCheck::RangeCheckKind RCK) {
228 switch (RCK) {
229 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
230 return "RANGE_CHECK_UNKNOWN";
231
232 case InductiveRangeCheck::RANGE_CHECK_UPPER:
233 return "RANGE_CHECK_UPPER";
234
235 case InductiveRangeCheck::RANGE_CHECK_LOWER:
236 return "RANGE_CHECK_LOWER";
237
238 case InductiveRangeCheck::RANGE_CHECK_BOTH:
239 return "RANGE_CHECK_BOTH";
240 }
241
242 llvm_unreachable("unknown range check type!");
243}
244
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000245/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000246/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000247/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000248/// range checked, and set `Length` to the upper limit `Index` is being range
249/// checked with if (and only if) the range check type is stronger or equal to
250/// RANGE_CHECK_UPPER.
251///
252InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000253InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
254 ScalarEvolution &SE, Value *&Index,
255 Value *&Length) {
256
257 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
258 const SCEV *S = SE.getSCEV(V);
259 if (isa<SCEVCouldNotCompute>(S))
260 return false;
261
262 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
263 SE.isKnownNonNegative(S);
264 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000265
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000266 using namespace llvm::PatternMatch;
267
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000268 ICmpInst::Predicate Pred = ICI->getPredicate();
269 Value *LHS = ICI->getOperand(0);
270 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000271
272 switch (Pred) {
273 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000274 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000275
276 case ICmpInst::ICMP_SLE:
277 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000278 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000279 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000280 if (match(RHS, m_ConstantInt<0>())) {
281 Index = LHS;
282 return RANGE_CHECK_LOWER;
283 }
284 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000285
286 case ICmpInst::ICMP_SLT:
287 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000288 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000289 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000290 if (match(RHS, m_ConstantInt<-1>())) {
291 Index = LHS;
292 return RANGE_CHECK_LOWER;
293 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000294
Sanjoy Das337d46b2015-03-24 19:29:18 +0000295 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000296 Index = RHS;
297 Length = LHS;
298 return RANGE_CHECK_UPPER;
299 }
300 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000302 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000303 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000304 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000305 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000306 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000307 Index = RHS;
308 Length = LHS;
309 return RANGE_CHECK_BOTH;
310 }
311 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000312 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000313
314 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000315}
316
Sanjoy Dasa0992682016-05-26 00:09:02 +0000317void InductiveRangeCheck::extractRangeChecksFromCond(
318 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
319 SmallVectorImpl<InductiveRangeCheck> &Checks,
320 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000321 using namespace llvm::PatternMatch;
322
Sanjoy Das8fe88922016-05-26 00:08:24 +0000323 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000324 if (!Visited.insert(Condition).second)
325 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000326
Sanjoy Dasa0992682016-05-26 00:09:02 +0000327 if (match(Condition, m_And(m_Value(), m_Value()))) {
328 SmallVector<InductiveRangeCheck, 8> SubChecks;
329 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
330 SubChecks, Visited);
331 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
332 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000333
Sanjoy Dasa0992682016-05-26 00:09:02 +0000334 if (SubChecks.size() == 2) {
335 // Handle a special case where we know how to merge two checks separately
336 // checking the upper and lower bounds into a full range check.
337 const auto &RChkA = SubChecks[0];
338 const auto &RChkB = SubChecks[1];
339 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
340 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000341
Sanjoy Dasa0992682016-05-26 00:09:02 +0000342 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
343 // But if one of them is a RANGE_CHECK_LOWER and the other is a
344 // RANGE_CHECK_UPPER (only possibility if they're different) then
345 // together they form a RANGE_CHECK_BOTH.
346 SubChecks[0].Kind =
347 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
348 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
349 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000350
Sanjoy Dasa0992682016-05-26 00:09:02 +0000351 // We updated one of the checks in place, now erase the other.
352 SubChecks.pop_back();
353 }
354 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355
Sanjoy Dasa0992682016-05-26 00:09:02 +0000356 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
357 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000358 }
359
Sanjoy Dasa0992682016-05-26 00:09:02 +0000360 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
361 if (!ICI)
362 return;
363
364 Value *Length = nullptr, *Index;
365 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
366 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
367 return;
368
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000369 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000370 bool IsAffineIndex =
371 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
372
373 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000374 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000375
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000376 InductiveRangeCheck IRC;
377 IRC.Length = Length;
378 IRC.Offset = IndexAddRec->getStart();
379 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000380 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000381 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000382 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000383}
384
Sanjoy Dasa0992682016-05-26 00:09:02 +0000385void InductiveRangeCheck::extractRangeChecksFromBranch(
386 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
387 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000388
389 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000390 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000391
392 BranchProbability LikelyTaken(15, 16);
393
Sanjoy Dasbb969792016-07-22 00:40:56 +0000394 if (!SkipProfitabilityChecks &&
395 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000396 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000397
Sanjoy Dasa0992682016-05-26 00:09:02 +0000398 SmallPtrSet<Value *, 8> Visited;
399 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
400 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000401}
402
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000403namespace {
404
Sanjoy Dase75ed922015-02-26 08:19:31 +0000405// Keeps track of the structure of a loop. This is similar to llvm::Loop,
406// except that it is more lightweight and can track the state of a loop through
407// changing and potentially invalid IR. This structure also formalizes the
408// kinds of loops we can deal with -- ones that have a single latch that is also
409// an exiting block *and* have a canonical induction variable.
410struct LoopStructure {
411 const char *Tag;
412
413 BasicBlock *Header;
414 BasicBlock *Latch;
415
416 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
417 // successor is `LatchExit', the exit block of the loop.
418 BranchInst *LatchBr;
419 BasicBlock *LatchExit;
420 unsigned LatchBrExitIdx;
421
422 Value *IndVarNext;
423 Value *IndVarStart;
424 Value *LoopExitAt;
425 bool IndVarIncreasing;
426
427 LoopStructure()
428 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
429 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
430 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
431
432 template <typename M> LoopStructure map(M Map) const {
433 LoopStructure Result;
434 Result.Tag = Tag;
435 Result.Header = cast<BasicBlock>(Map(Header));
436 Result.Latch = cast<BasicBlock>(Map(Latch));
437 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
438 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
439 Result.LatchBrExitIdx = LatchBrExitIdx;
440 Result.IndVarNext = Map(IndVarNext);
441 Result.IndVarStart = Map(IndVarStart);
442 Result.LoopExitAt = Map(LoopExitAt);
443 Result.IndVarIncreasing = IndVarIncreasing;
444 return Result;
445 }
446
Sanjoy Dase91665d2015-02-26 08:56:04 +0000447 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
448 BranchProbabilityInfo &BPI,
449 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000450 const char *&);
451};
452
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000453/// This class is used to constrain loops to run within a given iteration space.
454/// The algorithm this class implements is given a Loop and a range [Begin,
455/// End). The algorithm then tries to break out a "main loop" out of the loop
456/// it is given in a way that the "main loop" runs with the induction variable
457/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
458/// loops to run any remaining iterations. The pre loop runs any iterations in
459/// which the induction variable is < Begin, and the post loop runs any
460/// iterations in which the induction variable is >= End.
461///
462class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000463 // The representation of a clone of the original loop we started out with.
464 struct ClonedLoop {
465 // The cloned blocks
466 std::vector<BasicBlock *> Blocks;
467
468 // `Map` maps values in the clonee into values in the cloned version
469 ValueToValueMapTy Map;
470
471 // An instance of `LoopStructure` for the cloned loop
472 LoopStructure Structure;
473 };
474
475 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
476 // more details on what these fields mean.
477 struct RewrittenRangeInfo {
478 BasicBlock *PseudoExit;
479 BasicBlock *ExitSelector;
480 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000481 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000482
Sanjoy Dase75ed922015-02-26 08:19:31 +0000483 RewrittenRangeInfo()
484 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000485 };
486
487 // Calculated subranges we restrict the iteration space of the main loop to.
488 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000489 // these fields are computed. `LowLimit` is None if there is no restriction
490 // on low end of the restricted iteration space of the main loop. `HighLimit`
491 // is None if there is no restriction on high end of the restricted iteration
492 // space of the main loop.
493
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000494 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000495 Optional<const SCEV *> LowLimit;
496 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000497 };
498
499 // A utility function that does a `replaceUsesOfWith' on the incoming block
500 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
501 // incoming block list with `ReplaceBy'.
502 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
503 BasicBlock *ReplaceBy);
504
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000505 // Compute a safe set of limits for the main loop to run in -- effectively the
506 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000507 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000508 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000509 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000510
511 // Clone `OriginalLoop' and return the result in CLResult. The IR after
512 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
513 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
514 // but there is no such edge.
515 //
516 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
517
Sanjoy Das21434472016-08-14 01:04:46 +0000518 // Create the appropriate loop structure needed to describe a cloned copy of
519 // `Original`. The clone is described by `VM`.
520 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
521 ValueToValueMapTy &VM);
522
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000523 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
524 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
525 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
526 // `OriginalHeaderCount'.
527 //
528 // If there are iterations left to execute, control is made to jump to
529 // `ContinuationBlock', otherwise they take the normal loop exit. The
530 // returned `RewrittenRangeInfo' object is populated as follows:
531 //
532 // .PseudoExit is a basic block that unconditionally branches to
533 // `ContinuationBlock'.
534 //
535 // .ExitSelector is a basic block that decides, on exit from the loop,
536 // whether to branch to the "true" exit or to `PseudoExit'.
537 //
538 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
539 // for each PHINode in the loop header on taking the pseudo exit.
540 //
541 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
542 // preheader because it is made to branch to the loop header only
543 // conditionally.
544 //
545 RewrittenRangeInfo
546 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
547 Value *ExitLoopAt,
548 BasicBlock *ContinuationBlock) const;
549
550 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
551 // function creates a new preheader for `LS' and returns it.
552 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000553 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
554 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000555
556 // `ContinuationBlockAndPreheader' was the continuation block for some call to
557 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
558 // This function rewrites the PHI nodes in `LS.Header' to start with the
559 // correct value.
560 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000561 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
563
564 // Even though we do not preserve any passes at this time, we at least need to
565 // keep the parent loop structure consistent. The `LPPassManager' seems to
566 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000567 // blocks denoted by BBs to this loops parent loop if required.
568 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000569
570 // Some global state.
571 Function &F;
572 LLVMContext &Ctx;
573 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000574 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000575 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000576 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000577
578 // Information about the original loop we started out with.
579 Loop &OriginalLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000580 const SCEV *LatchTakenCount;
581 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000582
583 // The preheader of the main loop. This may or may not be different from
584 // `OriginalPreheader'.
585 BasicBlock *MainLoopPreheader;
586
587 // The range we need to run the main loop in.
588 InductiveRangeCheck::Range Range;
589
590 // The structure of the main loop (see comment at the beginning of this class
591 // for a definition)
592 LoopStructure MainLoopStructure;
593
594public:
Sanjoy Das21434472016-08-14 01:04:46 +0000595 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
596 const LoopStructure &LS, ScalarEvolution &SE,
597 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000598 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das35459f02016-08-14 01:04:50 +0000599 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L),
Sanjoy Das21434472016-08-14 01:04:46 +0000600 LatchTakenCount(nullptr), OriginalPreheader(nullptr),
601 MainLoopPreheader(nullptr), Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000602
603 // Entry point for the algorithm. Returns true on success.
604 bool run();
605};
606
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000607}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000608
609void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
610 BasicBlock *ReplaceBy) {
611 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
612 if (PN->getIncomingBlock(i) == Block)
613 PN->setIncomingBlock(i, ReplaceBy);
614}
615
Sanjoy Dase75ed922015-02-26 08:19:31 +0000616static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
617 APInt SMax =
618 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
619 return SE.getSignedRange(S).contains(SMax) &&
620 SE.getUnsignedRange(S).contains(SMax);
621}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000622
Sanjoy Dase75ed922015-02-26 08:19:31 +0000623static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
624 APInt SMin =
625 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
626 return SE.getSignedRange(S).contains(SMin) &&
627 SE.getUnsignedRange(S).contains(SMin);
628}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000629
Sanjoy Dase75ed922015-02-26 08:19:31 +0000630Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000631LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
632 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000633 if (!L.isLoopSimplifyForm()) {
634 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000635 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000636 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000637
638 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000639 assert(Latch && "Simplified loops only have one latch!");
640
Sanjoy Das7a18a232016-08-14 01:04:36 +0000641 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
642 FailureReason = "loop has already been cloned";
643 return None;
644 }
645
Sanjoy Dase75ed922015-02-26 08:19:31 +0000646 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000648 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000649 }
650
Sanjoy Dase75ed922015-02-26 08:19:31 +0000651 BasicBlock *Header = L.getHeader();
652 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000653 if (!Preheader) {
654 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000655 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000656 }
657
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000658 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000659 if (!LatchBr || LatchBr->isUnconditional()) {
660 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000661 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000662 }
663
Sanjoy Dase75ed922015-02-26 08:19:31 +0000664 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000665
Sanjoy Dase91665d2015-02-26 08:56:04 +0000666 BranchProbability ExitProbability =
667 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
668
Sanjoy Dasbb969792016-07-22 00:40:56 +0000669 if (!SkipProfitabilityChecks &&
670 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000671 FailureReason = "short running loop, not profitable";
672 return None;
673 }
674
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
676 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
677 FailureReason = "latch terminator branch not conditional on integral icmp";
678 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000679 }
680
Sanjoy Dase75ed922015-02-26 08:19:31 +0000681 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
682 if (isa<SCEVCouldNotCompute>(LatchCount)) {
683 FailureReason = "could not compute latch count";
684 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000685 }
686
Sanjoy Dase75ed922015-02-26 08:19:31 +0000687 ICmpInst::Predicate Pred = ICI->getPredicate();
688 Value *LeftValue = ICI->getOperand(0);
689 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
690 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
691
692 Value *RightValue = ICI->getOperand(1);
693 const SCEV *RightSCEV = SE.getSCEV(RightValue);
694
695 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
696 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
697 if (isa<SCEVAddRecExpr>(RightSCEV)) {
698 std::swap(LeftSCEV, RightSCEV);
699 std::swap(LeftValue, RightValue);
700 Pred = ICmpInst::getSwappedPredicate(Pred);
701 } else {
702 FailureReason = "no add recurrences in the icmp";
703 return None;
704 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000705 }
706
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000707 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
708 if (AR->getNoWrapFlags(SCEV::FlagNSW))
709 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000710
711 IntegerType *Ty = cast<IntegerType>(AR->getType());
712 IntegerType *WideTy =
713 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
714
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000715 const SCEVAddRecExpr *ExtendAfterOp =
716 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
717 if (ExtendAfterOp) {
718 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
719 const SCEV *ExtendedStep =
720 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
721
722 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
723 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
724
725 if (NoSignedWrap)
726 return true;
727 }
728
729 // We may have proved this when computing the sign extension above.
730 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
731 };
732
733 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
734 if (!AR->isAffine())
735 return false;
736
Sanjoy Dase75ed922015-02-26 08:19:31 +0000737 // Currently we only work with induction variables that have been proved to
738 // not wrap. This restriction can potentially be lifted in the future.
739
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000740 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000741 return false;
742
743 if (const SCEVConstant *StepExpr =
744 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
745 ConstantInt *StepCI = StepExpr->getValue();
746 if (StepCI->isOne() || StepCI->isMinusOne()) {
747 IsIncreasing = StepCI->isOne();
748 return true;
749 }
750 }
751
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000752 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000753 };
754
755 // `ICI` is interpreted as taking the backedge if the *next* value of the
756 // induction variable satisfies some constraint.
757
758 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
759 bool IsIncreasing = false;
760 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
761 FailureReason = "LHS in icmp not induction variable";
762 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000763 }
764
Sanjoy Dase75ed922015-02-26 08:19:31 +0000765 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
766 // TODO: generalize the predicates here to also match their unsigned variants.
767 if (IsIncreasing) {
768 bool FoundExpectedPred =
769 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
770 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
771
772 if (!FoundExpectedPred) {
773 FailureReason = "expected icmp slt semantically, found something else";
774 return None;
775 }
776
777 if (LatchBrExitIdx == 0) {
778 if (CanBeSMax(SE, RightSCEV)) {
779 // TODO: this restriction is easily removable -- we just have to
780 // remember that the icmp was an slt and not an sle.
781 FailureReason = "limit may overflow when coercing sle to slt";
782 return None;
783 }
784
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000785 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000786 RightValue = B.CreateAdd(RightValue, One);
787 }
788
789 } else {
790 bool FoundExpectedPred =
791 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
792 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
793
794 if (!FoundExpectedPred) {
795 FailureReason = "expected icmp sgt semantically, found something else";
796 return None;
797 }
798
799 if (LatchBrExitIdx == 0) {
800 if (CanBeSMin(SE, RightSCEV)) {
801 // TODO: this restriction is easily removable -- we just have to
802 // remember that the icmp was an sgt and not an sge.
803 FailureReason = "limit may overflow when coercing sge to sgt";
804 return None;
805 }
806
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000807 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000808 RightValue = B.CreateSub(RightValue, One);
809 }
810 }
811
812 const SCEV *StartNext = IndVarNext->getStart();
813 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
814 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
815
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000816 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
817
Sanjoy Dase75ed922015-02-26 08:19:31 +0000818 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000819 ScalarEvolution::LoopInvariant &&
820 "loop variant exit count doesn't make sense!");
821
Sanjoy Dase75ed922015-02-26 08:19:31 +0000822 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000823 const DataLayout &DL = Preheader->getModule()->getDataLayout();
824 Value *IndVarStartV =
825 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000826 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000827 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000828
Sanjoy Dase75ed922015-02-26 08:19:31 +0000829 LoopStructure Result;
830
831 Result.Tag = "main";
832 Result.Header = Header;
833 Result.Latch = Latch;
834 Result.LatchBr = LatchBr;
835 Result.LatchExit = LatchExit;
836 Result.LatchBrExitIdx = LatchBrExitIdx;
837 Result.IndVarStart = IndVarStartV;
838 Result.IndVarNext = LeftValue;
839 Result.IndVarIncreasing = IsIncreasing;
840 Result.LoopExitAt = RightValue;
841
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000842 FailureReason = nullptr;
843
Sanjoy Dase75ed922015-02-26 08:19:31 +0000844 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000845}
846
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000847Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000848LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000849 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
850
Sanjoy Das351db052015-01-22 09:32:02 +0000851 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000852 return None;
853
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000854 LoopConstrainer::SubRanges Result;
855
856 // I think we can be more aggressive here and make this nuw / nsw if the
857 // addition that feeds into the icmp for the latch's terminating branch is nuw
858 // / nsw. In any case, a wrapping 2's complement addition is safe.
859 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000860 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
861 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000862
Sanjoy Dase75ed922015-02-26 08:19:31 +0000863 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000864
Sanjoy Dase75ed922015-02-26 08:19:31 +0000865 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
866 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000867
868 const SCEV *Smallest = nullptr, *Greatest = nullptr;
869
870 if (Increasing) {
871 Smallest = Start;
872 Greatest = End;
873 } else {
874 // These two computations may sign-overflow. Here is why that is okay:
875 //
876 // We know that the induction variable does not sign-overflow on any
877 // iteration except the last one, and it starts at `Start` and ends at
878 // `End`, decrementing by one every time.
879 //
880 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
881 // induction variable is decreasing we know that that the smallest value
882 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
883 //
884 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
885 // that case, `Clamp` will always return `Smallest` and
886 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
887 // will be an empty range. Returning an empty range is always safe.
888 //
889
890 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
891 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
892 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000893
894 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
895 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
896 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000897
898 // In some cases we can prove that we don't need a pre or post loop
899
900 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000901 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
902 if (!ProvablyNoPreloop)
903 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000904
905 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000906 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
907 if (!ProvablyNoPostLoop)
908 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000909
910 return Result;
911}
912
913void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
914 const char *Tag) const {
915 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
916 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
917 Result.Blocks.push_back(Clone);
918 Result.Map[BB] = Clone;
919 }
920
921 auto GetClonedValue = [&Result](Value *V) {
922 assert(V && "null values not in domain!");
923 auto It = Result.Map.find(V);
924 if (It == Result.Map.end())
925 return V;
926 return static_cast<Value *>(It->second);
927 };
928
Sanjoy Das7a18a232016-08-14 01:04:36 +0000929 auto *ClonedLatch =
930 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
931 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
932 MDNode::get(Ctx, {}));
933
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000934 Result.Structure = MainLoopStructure.map(GetClonedValue);
935 Result.Structure.Tag = Tag;
936
937 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
938 BasicBlock *ClonedBB = Result.Blocks[i];
939 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
940
941 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
942
943 for (Instruction &I : *ClonedBB)
944 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000945 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000946
947 // Exit blocks will now have one more predecessor and their PHI nodes need
948 // to be edited to reflect that. No phi nodes need to be introduced because
949 // the loop is in LCSSA.
950
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000951 for (auto *SBB : successors(OriginalBB)) {
952 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000953 continue; // not an exit block
954
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000955 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +0000956 auto *PN = dyn_cast<PHINode>(&I);
957 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000958 break;
959
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000960 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
961 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
962 }
963 }
964 }
965}
966
967LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000968 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000969 BasicBlock *ContinuationBlock) const {
970
971 // We start with a loop with a single latch:
972 //
973 // +--------------------+
974 // | |
975 // | preheader |
976 // | |
977 // +--------+-----------+
978 // | ----------------\
979 // | / |
980 // +--------v----v------+ |
981 // | | |
982 // | header | |
983 // | | |
984 // +--------------------+ |
985 // |
986 // ..... |
987 // |
988 // +--------------------+ |
989 // | | |
990 // | latch >----------/
991 // | |
992 // +-------v------------+
993 // |
994 // |
995 // | +--------------------+
996 // | | |
997 // +---> original exit |
998 // | |
999 // +--------------------+
1000 //
1001 // We change the control flow to look like
1002 //
1003 //
1004 // +--------------------+
1005 // | |
1006 // | preheader >-------------------------+
1007 // | | |
1008 // +--------v-----------+ |
1009 // | /-------------+ |
1010 // | / | |
1011 // +--------v--v--------+ | |
1012 // | | | |
1013 // | header | | +--------+ |
1014 // | | | | | |
1015 // +--------------------+ | | +-----v-----v-----------+
1016 // | | | |
1017 // | | | .pseudo.exit |
1018 // | | | |
1019 // | | +-----------v-----------+
1020 // | | |
1021 // ..... | | |
1022 // | | +--------v-------------+
1023 // +--------------------+ | | | |
1024 // | | | | | ContinuationBlock |
1025 // | latch >------+ | | |
1026 // | | | +----------------------+
1027 // +---------v----------+ |
1028 // | |
1029 // | |
1030 // | +---------------^-----+
1031 // | | |
1032 // +-----> .exit.selector |
1033 // | |
1034 // +----------v----------+
1035 // |
1036 // +--------------------+ |
1037 // | | |
1038 // | original exit <----+
1039 // | |
1040 // +--------------------+
1041 //
1042
1043 RewrittenRangeInfo RRI;
1044
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001045 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001046 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001047 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001048 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001049 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001050
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001051 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001052 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001053
1054 IRBuilder<> B(PreheaderJump);
1055
1056 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001057 Value *EnterLoopCond = Increasing
1058 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1059 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1060
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001061 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1062 PreheaderJump->eraseFromParent();
1063
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001064 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001065 B.SetInsertPoint(LS.LatchBr);
1066 Value *TakeBackedgeLoopCond =
1067 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1068 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1069 Value *CondForBranch = LS.LatchBrExitIdx == 1
1070 ? TakeBackedgeLoopCond
1071 : B.CreateNot(TakeBackedgeLoopCond);
1072
1073 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001074
1075 B.SetInsertPoint(RRI.ExitSelector);
1076
1077 // IterationsLeft - are there any more iterations left, given the original
1078 // upper bound on the induction variable? If not, we branch to the "real"
1079 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001080 Value *IterationsLeft = Increasing
1081 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1082 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001083 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1084
1085 BranchInst *BranchToContinuation =
1086 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1087
1088 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1089 // each of the PHI nodes in the loop header. This feeds into the initial
1090 // value of the same PHI nodes if/when we continue execution.
1091 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001092 auto *PN = dyn_cast<PHINode>(&I);
1093 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001094 break;
1095
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001096 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1097 BranchToContinuation);
1098
1099 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1100 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1101 RRI.ExitSelector);
1102 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1103 }
1104
Sanjoy Dase75ed922015-02-26 08:19:31 +00001105 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1106 BranchToContinuation);
1107 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1108 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1109
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001110 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1111 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1112 for (Instruction &I : *LS.LatchExit) {
1113 if (PHINode *PN = dyn_cast<PHINode>(&I))
1114 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1115 else
1116 break;
1117 }
1118
1119 return RRI;
1120}
1121
1122void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001123 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001124 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1125
1126 unsigned PHIIndex = 0;
1127 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001128 auto *PN = dyn_cast<PHINode>(&I);
1129 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001130 break;
1131
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1133 if (PN->getIncomingBlock(i) == ContinuationBlock)
1134 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1135 }
1136
Sanjoy Dase75ed922015-02-26 08:19:31 +00001137 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001138}
1139
Sanjoy Dase75ed922015-02-26 08:19:31 +00001140BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1141 BasicBlock *OldPreheader,
1142 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001143
1144 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1145 BranchInst::Create(LS.Header, Preheader);
1146
1147 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001148 auto *PN = dyn_cast<PHINode>(&I);
1149 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001150 break;
1151
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001152 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1153 replacePHIBlock(PN, OldPreheader, Preheader);
1154 }
1155
1156 return Preheader;
1157}
1158
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001159void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001160 Loop *ParentLoop = OriginalLoop.getParentLoop();
1161 if (!ParentLoop)
1162 return;
1163
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001164 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001165 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001166}
1167
Sanjoy Das21434472016-08-14 01:04:46 +00001168Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1169 ValueToValueMapTy &VM) {
1170 Loop &New = LPM.addLoop(Parent);
1171
1172 // Add all of the blocks in Original to the new loop.
1173 for (auto *BB : Original->blocks())
1174 if (LI.getLoopFor(BB) == Original)
1175 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1176
1177 // Add all of the subloops to the new loop.
1178 for (Loop *SubLoop : *Original)
1179 createClonedLoopStructure(SubLoop, &New, VM);
1180
1181 return &New;
1182}
1183
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001184bool LoopConstrainer::run() {
1185 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001186 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1187 Preheader = OriginalLoop.getLoopPreheader();
1188 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1189 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001190
1191 OriginalPreheader = Preheader;
1192 MainLoopPreheader = Preheader;
1193
Sanjoy Dase75ed922015-02-26 08:19:31 +00001194 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001195 if (!MaybeSR.hasValue()) {
1196 DEBUG(dbgs() << "irce: could not compute subranges\n");
1197 return false;
1198 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001199
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001200 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001201 bool Increasing = MainLoopStructure.IndVarIncreasing;
1202 IntegerType *IVTy =
1203 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1204
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001205 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001206 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001207
1208 // It would have been better to make `PreLoop' and `PostLoop'
1209 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1210 // constructor.
1211 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001212 bool NeedsPreLoop =
1213 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1214 bool NeedsPostLoop =
1215 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1216
1217 Value *ExitPreLoopAt = nullptr;
1218 Value *ExitMainLoopAt = nullptr;
1219 const SCEVConstant *MinusOneS =
1220 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1221
1222 if (NeedsPreLoop) {
1223 const SCEV *ExitPreLoopAtSCEV = nullptr;
1224
1225 if (Increasing)
1226 ExitPreLoopAtSCEV = *SR.LowLimit;
1227 else {
1228 if (CanBeSMin(SE, *SR.HighLimit)) {
1229 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1230 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1231 << "\n");
1232 return false;
1233 }
1234 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1235 }
1236
1237 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1238 ExitPreLoopAt->setName("exit.preloop.at");
1239 }
1240
1241 if (NeedsPostLoop) {
1242 const SCEV *ExitMainLoopAtSCEV = nullptr;
1243
1244 if (Increasing)
1245 ExitMainLoopAtSCEV = *SR.HighLimit;
1246 else {
1247 if (CanBeSMin(SE, *SR.LowLimit)) {
1248 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1249 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1250 << "\n");
1251 return false;
1252 }
1253 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1254 }
1255
1256 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1257 ExitMainLoopAt->setName("exit.mainloop.at");
1258 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001259
1260 // We clone these ahead of time so that we don't have to deal with changing
1261 // and temporarily invalid IR as we transform the loops.
1262 if (NeedsPreLoop)
1263 cloneLoop(PreLoop, "preloop");
1264 if (NeedsPostLoop)
1265 cloneLoop(PostLoop, "postloop");
1266
1267 RewrittenRangeInfo PreLoopRRI;
1268
1269 if (NeedsPreLoop) {
1270 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1271 PreLoop.Structure.Header);
1272
1273 MainLoopPreheader =
1274 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001275 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1276 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001277 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1278 PreLoopRRI);
1279 }
1280
1281 BasicBlock *PostLoopPreheader = nullptr;
1282 RewrittenRangeInfo PostLoopRRI;
1283
1284 if (NeedsPostLoop) {
1285 PostLoopPreheader =
1286 createPreheader(PostLoop.Structure, Preheader, "postloop");
1287 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001288 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001289 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1290 PostLoopRRI);
1291 }
1292
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001293 BasicBlock *NewMainLoopPreheader =
1294 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1295 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1296 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1297 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001298
1299 // Some of the above may be nullptr, filter them out before passing to
1300 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001301 auto NewBlocksEnd =
1302 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001303
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001304 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001305
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001306 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001307
1308 if (!PreLoop.Blocks.empty()) {
1309 auto *L = createClonedLoopStructure(
1310 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
1311 formLCSSARecursively(*L, DT, &LI, &SE);
1312 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1313 }
1314
1315 if (!PostLoop.Blocks.empty()) {
1316 auto *L = createClonedLoopStructure(
1317 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
1318 formLCSSARecursively(*L, DT, &LI, &SE);
1319 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1320 }
1321
Sanjoy Das83a72852016-08-02 19:32:01 +00001322 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dascf181862016-08-06 00:01:56 +00001323 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001324
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001325 return true;
1326}
1327
Sanjoy Das95c476d2015-02-21 22:20:22 +00001328/// Computes and returns a range of values for the induction variable (IndVar)
1329/// in which the range check can be safely elided. If it cannot compute such a
1330/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001331Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001332InductiveRangeCheck::computeSafeIterationSpace(
1333 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001334 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1335 // variable, that may or may not exist as a real llvm::Value in the loop) and
1336 // this inductive range check is a range check on the "C + D * I" ("C" is
1337 // getOffset() and "D" is getScale()). We rewrite the value being range
1338 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1339 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1340 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001341 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001342 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001343 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001344 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1345 //
1346 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1347 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001348 //
1349 // Proof:
1350 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001351 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1352 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1353 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1354 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001355 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001356 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1357 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001358
Sanjoy Das95c476d2015-02-21 22:20:22 +00001359 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1360 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001361
Sanjoy Das95c476d2015-02-21 22:20:22 +00001362 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001364
Sanjoy Das95c476d2015-02-21 22:20:22 +00001365 const SCEV *A = IndVar->getStart();
1366 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1367 if (!B)
1368 return None;
1369
1370 const SCEV *C = getOffset();
1371 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1372 if (D != B)
1373 return None;
1374
1375 ConstantInt *ConstD = D->getValue();
1376 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1377 return None;
1378
1379 const SCEV *M = SE.getMinusSCEV(C, A);
1380
1381 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001382 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001383
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001384 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1385 // We can potentially do much better here.
1386 if (Value *V = getLength()) {
1387 UpperLimit = SE.getSCEV(V);
1388 } else {
1389 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1390 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1391 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1392 }
1393
1394 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001395 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001396}
1397
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001398static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001399IntersectRange(ScalarEvolution &SE,
1400 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001401 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001402 if (!R1.hasValue())
1403 return R2;
1404 auto &R1Value = R1.getValue();
1405
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001406 // TODO: we could widen the smaller range and have this work; but for now we
1407 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001408 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001409 return None;
1410
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001411 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1412 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1413
1414 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001415}
1416
1417bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001418 if (skipLoop(L))
1419 return false;
1420
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001421 if (L->getBlocks().size() >= LoopSizeCutoff) {
1422 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1423 return false;
1424 }
1425
1426 BasicBlock *Preheader = L->getLoopPreheader();
1427 if (!Preheader) {
1428 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1429 return false;
1430 }
1431
1432 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001433 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001434 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001435 BranchProbabilityInfo &BPI =
1436 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001437
1438 for (auto BBI : L->getBlocks())
1439 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001440 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1441 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001442
1443 if (RangeChecks.empty())
1444 return false;
1445
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001446 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1447 OS << "irce: looking at loop "; L->print(OS);
1448 OS << "irce: loop has " << RangeChecks.size()
1449 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001450 for (InductiveRangeCheck &IRC : RangeChecks)
1451 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001452 };
1453
1454 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1455
1456 if (PrintRangeChecks)
1457 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001458
Sanjoy Dase75ed922015-02-26 08:19:31 +00001459 const char *FailureReason = nullptr;
1460 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001461 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001462 if (!MaybeLoopStructure.hasValue()) {
1463 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1464 << "\n";);
1465 return false;
1466 }
1467 LoopStructure LS = MaybeLoopStructure.getValue();
1468 bool Increasing = LS.IndVarIncreasing;
1469 const SCEV *MinusOne =
1470 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1471 const SCEVAddRecExpr *IndVar =
1472 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1473
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001474 Optional<InductiveRangeCheck::Range> SafeIterRange;
1475 Instruction *ExprInsertPt = Preheader->getTerminator();
1476
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001477 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001478
1479 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001480 for (InductiveRangeCheck &IRC : RangeChecks) {
1481 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001482 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001483 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001484 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001485 if (MaybeSafeIterRange.hasValue()) {
1486 RangeChecksToEliminate.push_back(IRC);
1487 SafeIterRange = MaybeSafeIterRange.getValue();
1488 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001489 }
1490 }
1491
1492 if (!SafeIterRange.hasValue())
1493 return false;
1494
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001495 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001496 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1497 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001498 bool Changed = LC.run();
1499
1500 if (Changed) {
1501 auto PrintConstrainedLoopInfo = [L]() {
1502 dbgs() << "irce: in function ";
1503 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1504 dbgs() << "constrained ";
1505 L->print(dbgs());
1506 };
1507
1508 DEBUG(PrintConstrainedLoopInfo());
1509
1510 if (PrintChangedLoops)
1511 PrintConstrainedLoopInfo();
1512
1513 // Optimize away the now-redundant range checks.
1514
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001515 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1516 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001517 ? ConstantInt::getTrue(Context)
1518 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001519 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001520 }
1521 }
1522
1523 return Changed;
1524}
1525
1526Pass *llvm::createInductiveRangeCheckEliminationPass() {
1527 return new InductiveRangeCheckElimination;
1528}