blob: b3d8aa65d609b6dc5d5ee826b961826bc324d26b [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 Dasa1837a32015-01-16 01:03:22 +000082#define DEBUG_TYPE "irce"
83
84namespace {
85
86/// An inductive range check is conditional branch in a loop with
87///
88/// 1. a very cold successor (i.e. the branch jumps to that successor very
89/// rarely)
90///
91/// and
92///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000093/// 2. a condition that is provably true for some contiguous range of values
94/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000095///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000096class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000097 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +000098 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000099 // Range check of the form "0 <= I".
100 RANGE_CHECK_LOWER = 1,
101
102 // Range check of the form "I < L" where L is known positive.
103 RANGE_CHECK_UPPER = 2,
104
105 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
106 // conditions.
107 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
108
109 // Unrecognized range check condition.
110 RANGE_CHECK_UNKNOWN = (unsigned)-1
111 };
112
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000113 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000114
Sanjoy Dasee77a482016-05-26 01:50:18 +0000115 const SCEV *Offset = nullptr;
116 const SCEV *Scale = nullptr;
117 Value *Length = nullptr;
118 Use *CheckUse = nullptr;
119 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000120
Sanjoy Das337d46b2015-03-24 19:29:18 +0000121 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
122 ScalarEvolution &SE, Value *&Index,
123 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000124
Sanjoy Dasa0992682016-05-26 00:09:02 +0000125 static void
126 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
127 SmallVectorImpl<InductiveRangeCheck> &Checks,
128 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000129
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000130public:
131 const SCEV *getOffset() const { return Offset; }
132 const SCEV *getScale() const { return Scale; }
133 Value *getLength() const { return Length; }
134
135 void print(raw_ostream &OS) const {
136 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000137 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000138 OS << " Offset: ";
139 Offset->print(OS);
140 OS << " Scale: ";
141 Scale->print(OS);
142 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000143 if (Length)
144 Length->print(OS);
145 else
146 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000147 OS << "\n CheckUse: ";
148 getCheckUse()->getUser()->print(OS);
149 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000150 }
151
152#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
153 void dump() {
154 print(dbgs());
155 }
156#endif
157
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000158 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000159
Sanjoy Das351db052015-01-22 09:32:02 +0000160 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
161 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
162
163 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000164 const SCEV *Begin;
165 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000166
167 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000168 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000169 assert(Begin->getType() == End->getType() && "ill-typed range!");
170 }
171
172 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000173 const SCEV *getBegin() const { return Begin; }
174 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000175 };
176
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000177 /// This is the value the condition of the branch needs to evaluate to for the
178 /// branch to take the hot successor (see (1) above).
179 bool getPassingDirection() { return true; }
180
Sanjoy Das95c476d2015-02-21 22:20:22 +0000181 /// Computes a range for the induction variable (IndVar) in which the range
182 /// check is redundant and can be constant-folded away. The induction
183 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000184 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000185 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000186
Sanjoy Dasa0992682016-05-26 00:09:02 +0000187 /// Parse out a set of inductive range checks from \p BI and append them to \p
188 /// Checks.
189 ///
190 /// NB! There may be conditions feeding into \p BI that aren't inductive range
191 /// checks, and hence don't end up in \p Checks.
192 static void
193 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
194 BranchProbabilityInfo &BPI,
195 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000196};
197
198class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000199public:
200 static char ID;
201 InductiveRangeCheckElimination() : LoopPass(ID) {
202 initializeInductiveRangeCheckEliminationPass(
203 *PassRegistry::getPassRegistry());
204 }
205
206 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000207 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000208 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000209 }
210
211 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
212};
213
214char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000215}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000216
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000217INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
218 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000219INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000220INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000221INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
222 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000223
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000224StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000225 InductiveRangeCheck::RangeCheckKind RCK) {
226 switch (RCK) {
227 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
228 return "RANGE_CHECK_UNKNOWN";
229
230 case InductiveRangeCheck::RANGE_CHECK_UPPER:
231 return "RANGE_CHECK_UPPER";
232
233 case InductiveRangeCheck::RANGE_CHECK_LOWER:
234 return "RANGE_CHECK_LOWER";
235
236 case InductiveRangeCheck::RANGE_CHECK_BOTH:
237 return "RANGE_CHECK_BOTH";
238 }
239
240 llvm_unreachable("unknown range check type!");
241}
242
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000243/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000244/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000245/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000246/// range checked, and set `Length` to the upper limit `Index` is being range
247/// checked with if (and only if) the range check type is stronger or equal to
248/// RANGE_CHECK_UPPER.
249///
250InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000251InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
252 ScalarEvolution &SE, Value *&Index,
253 Value *&Length) {
254
255 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
256 const SCEV *S = SE.getSCEV(V);
257 if (isa<SCEVCouldNotCompute>(S))
258 return false;
259
260 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
261 SE.isKnownNonNegative(S);
262 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000263
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000264 using namespace llvm::PatternMatch;
265
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000266 ICmpInst::Predicate Pred = ICI->getPredicate();
267 Value *LHS = ICI->getOperand(0);
268 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000269
270 switch (Pred) {
271 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000272 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000273
274 case ICmpInst::ICMP_SLE:
275 std::swap(LHS, RHS);
276 // fallthrough
277 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000278 if (match(RHS, m_ConstantInt<0>())) {
279 Index = LHS;
280 return RANGE_CHECK_LOWER;
281 }
282 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000283
284 case ICmpInst::ICMP_SLT:
285 std::swap(LHS, RHS);
286 // fallthrough
287 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000288 if (match(RHS, m_ConstantInt<-1>())) {
289 Index = LHS;
290 return RANGE_CHECK_LOWER;
291 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000292
Sanjoy Das337d46b2015-03-24 19:29:18 +0000293 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000294 Index = RHS;
295 Length = LHS;
296 return RANGE_CHECK_UPPER;
297 }
298 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000299
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000300 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000301 std::swap(LHS, RHS);
302 // fallthrough
303 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000304 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000305 Index = RHS;
306 Length = LHS;
307 return RANGE_CHECK_BOTH;
308 }
309 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000310 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000311
312 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000313}
314
Sanjoy Dasa0992682016-05-26 00:09:02 +0000315void InductiveRangeCheck::extractRangeChecksFromCond(
316 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
317 SmallVectorImpl<InductiveRangeCheck> &Checks,
318 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000319 using namespace llvm::PatternMatch;
320
Sanjoy Das8fe88922016-05-26 00:08:24 +0000321 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000322 if (!Visited.insert(Condition).second)
323 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000324
Sanjoy Dasa0992682016-05-26 00:09:02 +0000325 if (match(Condition, m_And(m_Value(), m_Value()))) {
326 SmallVector<InductiveRangeCheck, 8> SubChecks;
327 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
328 SubChecks, Visited);
329 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
330 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000331
Sanjoy Dasa0992682016-05-26 00:09:02 +0000332 if (SubChecks.size() == 2) {
333 // Handle a special case where we know how to merge two checks separately
334 // checking the upper and lower bounds into a full range check.
335 const auto &RChkA = SubChecks[0];
336 const auto &RChkB = SubChecks[1];
337 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
338 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000339
Sanjoy Dasa0992682016-05-26 00:09:02 +0000340 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
341 // But if one of them is a RANGE_CHECK_LOWER and the other is a
342 // RANGE_CHECK_UPPER (only possibility if they're different) then
343 // together they form a RANGE_CHECK_BOTH.
344 SubChecks[0].Kind =
345 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
346 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
347 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000348
Sanjoy Dasa0992682016-05-26 00:09:02 +0000349 // We updated one of the checks in place, now erase the other.
350 SubChecks.pop_back();
351 }
352 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000353
Sanjoy Dasa0992682016-05-26 00:09:02 +0000354 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
355 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000356 }
357
Sanjoy Dasa0992682016-05-26 00:09:02 +0000358 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
359 if (!ICI)
360 return;
361
362 Value *Length = nullptr, *Index;
363 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
364 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
365 return;
366
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000367 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000368 bool IsAffineIndex =
369 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
370
371 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000372 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000373
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000374 InductiveRangeCheck IRC;
375 IRC.Length = Length;
376 IRC.Offset = IndexAddRec->getStart();
377 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000378 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000379 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000380 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000381}
382
Sanjoy Dasa0992682016-05-26 00:09:02 +0000383void InductiveRangeCheck::extractRangeChecksFromBranch(
384 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
385 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000386
387 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000388 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000389
390 BranchProbability LikelyTaken(15, 16);
391
Sanjoy Dasbb969792016-07-22 00:40:56 +0000392 if (!SkipProfitabilityChecks &&
393 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000394 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000395
Sanjoy Dasa0992682016-05-26 00:09:02 +0000396 SmallPtrSet<Value *, 8> Visited;
397 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
398 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000399}
400
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000401namespace {
402
Sanjoy Dase75ed922015-02-26 08:19:31 +0000403// Keeps track of the structure of a loop. This is similar to llvm::Loop,
404// except that it is more lightweight and can track the state of a loop through
405// changing and potentially invalid IR. This structure also formalizes the
406// kinds of loops we can deal with -- ones that have a single latch that is also
407// an exiting block *and* have a canonical induction variable.
408struct LoopStructure {
409 const char *Tag;
410
411 BasicBlock *Header;
412 BasicBlock *Latch;
413
414 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
415 // successor is `LatchExit', the exit block of the loop.
416 BranchInst *LatchBr;
417 BasicBlock *LatchExit;
418 unsigned LatchBrExitIdx;
419
420 Value *IndVarNext;
421 Value *IndVarStart;
422 Value *LoopExitAt;
423 bool IndVarIncreasing;
424
425 LoopStructure()
426 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
427 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
428 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
429
430 template <typename M> LoopStructure map(M Map) const {
431 LoopStructure Result;
432 Result.Tag = Tag;
433 Result.Header = cast<BasicBlock>(Map(Header));
434 Result.Latch = cast<BasicBlock>(Map(Latch));
435 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
436 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
437 Result.LatchBrExitIdx = LatchBrExitIdx;
438 Result.IndVarNext = Map(IndVarNext);
439 Result.IndVarStart = Map(IndVarStart);
440 Result.LoopExitAt = Map(LoopExitAt);
441 Result.IndVarIncreasing = IndVarIncreasing;
442 return Result;
443 }
444
Sanjoy Dase91665d2015-02-26 08:56:04 +0000445 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
446 BranchProbabilityInfo &BPI,
447 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000448 const char *&);
449};
450
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000451/// This class is used to constrain loops to run within a given iteration space.
452/// The algorithm this class implements is given a Loop and a range [Begin,
453/// End). The algorithm then tries to break out a "main loop" out of the loop
454/// it is given in a way that the "main loop" runs with the induction variable
455/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
456/// loops to run any remaining iterations. The pre loop runs any iterations in
457/// which the induction variable is < Begin, and the post loop runs any
458/// iterations in which the induction variable is >= End.
459///
460class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000461 // The representation of a clone of the original loop we started out with.
462 struct ClonedLoop {
463 // The cloned blocks
464 std::vector<BasicBlock *> Blocks;
465
466 // `Map` maps values in the clonee into values in the cloned version
467 ValueToValueMapTy Map;
468
469 // An instance of `LoopStructure` for the cloned loop
470 LoopStructure Structure;
471 };
472
473 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
474 // more details on what these fields mean.
475 struct RewrittenRangeInfo {
476 BasicBlock *PseudoExit;
477 BasicBlock *ExitSelector;
478 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000479 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000480
Sanjoy Dase75ed922015-02-26 08:19:31 +0000481 RewrittenRangeInfo()
482 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000483 };
484
485 // Calculated subranges we restrict the iteration space of the main loop to.
486 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000487 // these fields are computed. `LowLimit` is None if there is no restriction
488 // on low end of the restricted iteration space of the main loop. `HighLimit`
489 // is None if there is no restriction on high end of the restricted iteration
490 // space of the main loop.
491
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000492 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000493 Optional<const SCEV *> LowLimit;
494 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000495 };
496
497 // A utility function that does a `replaceUsesOfWith' on the incoming block
498 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
499 // incoming block list with `ReplaceBy'.
500 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
501 BasicBlock *ReplaceBy);
502
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000503 // Compute a safe set of limits for the main loop to run in -- effectively the
504 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000505 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000506 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000507 Optional<SubRanges> calculateSubRanges() const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000508
509 // Clone `OriginalLoop' and return the result in CLResult. The IR after
510 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
511 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
512 // but there is no such edge.
513 //
514 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
515
516 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
517 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
518 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
519 // `OriginalHeaderCount'.
520 //
521 // If there are iterations left to execute, control is made to jump to
522 // `ContinuationBlock', otherwise they take the normal loop exit. The
523 // returned `RewrittenRangeInfo' object is populated as follows:
524 //
525 // .PseudoExit is a basic block that unconditionally branches to
526 // `ContinuationBlock'.
527 //
528 // .ExitSelector is a basic block that decides, on exit from the loop,
529 // whether to branch to the "true" exit or to `PseudoExit'.
530 //
531 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
532 // for each PHINode in the loop header on taking the pseudo exit.
533 //
534 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
535 // preheader because it is made to branch to the loop header only
536 // conditionally.
537 //
538 RewrittenRangeInfo
539 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
540 Value *ExitLoopAt,
541 BasicBlock *ContinuationBlock) const;
542
543 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
544 // function creates a new preheader for `LS' and returns it.
545 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000546 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
547 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000548
549 // `ContinuationBlockAndPreheader' was the continuation block for some call to
550 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
551 // This function rewrites the PHI nodes in `LS.Header' to start with the
552 // correct value.
553 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000554 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000555 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
556
557 // Even though we do not preserve any passes at this time, we at least need to
558 // keep the parent loop structure consistent. The `LPPassManager' seems to
559 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000560 // blocks denoted by BBs to this loops parent loop if required.
561 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562
563 // Some global state.
564 Function &F;
565 LLVMContext &Ctx;
566 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000567 DominatorTree &DT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000568
569 // Information about the original loop we started out with.
570 Loop &OriginalLoop;
Sanjoy Das83a72852016-08-02 19:32:01 +0000571 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000572 const SCEV *LatchTakenCount;
573 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000574
575 // The preheader of the main loop. This may or may not be different from
576 // `OriginalPreheader'.
577 BasicBlock *MainLoopPreheader;
578
579 // The range we need to run the main loop in.
580 InductiveRangeCheck::Range Range;
581
582 // The structure of the main loop (see comment at the beginning of this class
583 // for a definition)
584 LoopStructure MainLoopStructure;
585
586public:
Sanjoy Dase75ed922015-02-26 08:19:31 +0000587 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000588 ScalarEvolution &SE, DominatorTree &DT,
589 InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000590 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das83a72852016-08-02 19:32:01 +0000591 SE(SE), DT(DT), OriginalLoop(L), LI(LI), LatchTakenCount(nullptr),
592 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
593 MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000594
595 // Entry point for the algorithm. Returns true on success.
596 bool run();
597};
598
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000599}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000600
601void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
602 BasicBlock *ReplaceBy) {
603 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
604 if (PN->getIncomingBlock(i) == Block)
605 PN->setIncomingBlock(i, ReplaceBy);
606}
607
Sanjoy Dase75ed922015-02-26 08:19:31 +0000608static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
609 APInt SMax =
610 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
611 return SE.getSignedRange(S).contains(SMax) &&
612 SE.getUnsignedRange(S).contains(SMax);
613}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000614
Sanjoy Dase75ed922015-02-26 08:19:31 +0000615static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
616 APInt SMin =
617 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
618 return SE.getSignedRange(S).contains(SMin) &&
619 SE.getUnsignedRange(S).contains(SMin);
620}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621
Sanjoy Dase75ed922015-02-26 08:19:31 +0000622Optional<LoopStructure>
Sanjoy Dase91665d2015-02-26 08:56:04 +0000623LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
624 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000625 if (!L.isLoopSimplifyForm()) {
626 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000627 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000628 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000629
630 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000631 assert(Latch && "Simplified loops only have one latch!");
632
Sanjoy Dase75ed922015-02-26 08:19:31 +0000633 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000634 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000635 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000636 }
637
Sanjoy Dase75ed922015-02-26 08:19:31 +0000638 BasicBlock *Header = L.getHeader();
639 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000640 if (!Preheader) {
641 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000642 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000643 }
644
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000645 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000646 if (!LatchBr || LatchBr->isUnconditional()) {
647 FailureReason = "latch terminator not conditional branch";
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 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652
Sanjoy Dase91665d2015-02-26 08:56:04 +0000653 BranchProbability ExitProbability =
654 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
655
Sanjoy Dasbb969792016-07-22 00:40:56 +0000656 if (!SkipProfitabilityChecks &&
657 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000658 FailureReason = "short running loop, not profitable";
659 return None;
660 }
661
Sanjoy Dase75ed922015-02-26 08:19:31 +0000662 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
663 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
664 FailureReason = "latch terminator branch not conditional on integral icmp";
665 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000666 }
667
Sanjoy Dase75ed922015-02-26 08:19:31 +0000668 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
669 if (isa<SCEVCouldNotCompute>(LatchCount)) {
670 FailureReason = "could not compute latch count";
671 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000672 }
673
Sanjoy Dase75ed922015-02-26 08:19:31 +0000674 ICmpInst::Predicate Pred = ICI->getPredicate();
675 Value *LeftValue = ICI->getOperand(0);
676 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
677 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
678
679 Value *RightValue = ICI->getOperand(1);
680 const SCEV *RightSCEV = SE.getSCEV(RightValue);
681
682 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
683 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
684 if (isa<SCEVAddRecExpr>(RightSCEV)) {
685 std::swap(LeftSCEV, RightSCEV);
686 std::swap(LeftValue, RightValue);
687 Pred = ICmpInst::getSwappedPredicate(Pred);
688 } else {
689 FailureReason = "no add recurrences in the icmp";
690 return None;
691 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000692 }
693
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000694 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
695 if (AR->getNoWrapFlags(SCEV::FlagNSW))
696 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000697
698 IntegerType *Ty = cast<IntegerType>(AR->getType());
699 IntegerType *WideTy =
700 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
701
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000702 const SCEVAddRecExpr *ExtendAfterOp =
703 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
704 if (ExtendAfterOp) {
705 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
706 const SCEV *ExtendedStep =
707 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
708
709 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
710 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
711
712 if (NoSignedWrap)
713 return true;
714 }
715
716 // We may have proved this when computing the sign extension above.
717 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
718 };
719
720 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
721 if (!AR->isAffine())
722 return false;
723
Sanjoy Dase75ed922015-02-26 08:19:31 +0000724 // Currently we only work with induction variables that have been proved to
725 // not wrap. This restriction can potentially be lifted in the future.
726
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000727 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000728 return false;
729
730 if (const SCEVConstant *StepExpr =
731 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
732 ConstantInt *StepCI = StepExpr->getValue();
733 if (StepCI->isOne() || StepCI->isMinusOne()) {
734 IsIncreasing = StepCI->isOne();
735 return true;
736 }
737 }
738
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000739 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000740 };
741
742 // `ICI` is interpreted as taking the backedge if the *next* value of the
743 // induction variable satisfies some constraint.
744
745 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
746 bool IsIncreasing = false;
747 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
748 FailureReason = "LHS in icmp not induction variable";
749 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000750 }
751
Sanjoy Dase75ed922015-02-26 08:19:31 +0000752 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
753 // TODO: generalize the predicates here to also match their unsigned variants.
754 if (IsIncreasing) {
755 bool FoundExpectedPred =
756 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
757 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
758
759 if (!FoundExpectedPred) {
760 FailureReason = "expected icmp slt semantically, found something else";
761 return None;
762 }
763
764 if (LatchBrExitIdx == 0) {
765 if (CanBeSMax(SE, RightSCEV)) {
766 // TODO: this restriction is easily removable -- we just have to
767 // remember that the icmp was an slt and not an sle.
768 FailureReason = "limit may overflow when coercing sle to slt";
769 return None;
770 }
771
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000772 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000773 RightValue = B.CreateAdd(RightValue, One);
774 }
775
776 } else {
777 bool FoundExpectedPred =
778 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
779 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
780
781 if (!FoundExpectedPred) {
782 FailureReason = "expected icmp sgt semantically, found something else";
783 return None;
784 }
785
786 if (LatchBrExitIdx == 0) {
787 if (CanBeSMin(SE, RightSCEV)) {
788 // TODO: this restriction is easily removable -- we just have to
789 // remember that the icmp was an sgt and not an sge.
790 FailureReason = "limit may overflow when coercing sge to sgt";
791 return None;
792 }
793
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000794 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000795 RightValue = B.CreateSub(RightValue, One);
796 }
797 }
798
799 const SCEV *StartNext = IndVarNext->getStart();
800 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
801 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
802
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000803 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
804
Sanjoy Dase75ed922015-02-26 08:19:31 +0000805 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000806 ScalarEvolution::LoopInvariant &&
807 "loop variant exit count doesn't make sense!");
808
Sanjoy Dase75ed922015-02-26 08:19:31 +0000809 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000810 const DataLayout &DL = Preheader->getModule()->getDataLayout();
811 Value *IndVarStartV =
812 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000813 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000814 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000815
Sanjoy Dase75ed922015-02-26 08:19:31 +0000816 LoopStructure Result;
817
818 Result.Tag = "main";
819 Result.Header = Header;
820 Result.Latch = Latch;
821 Result.LatchBr = LatchBr;
822 Result.LatchExit = LatchExit;
823 Result.LatchBrExitIdx = LatchBrExitIdx;
824 Result.IndVarStart = IndVarStartV;
825 Result.IndVarNext = LeftValue;
826 Result.IndVarIncreasing = IsIncreasing;
827 Result.LoopExitAt = RightValue;
828
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000829 FailureReason = nullptr;
830
Sanjoy Dase75ed922015-02-26 08:19:31 +0000831 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000832}
833
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000834Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000835LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000836 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
837
Sanjoy Das351db052015-01-22 09:32:02 +0000838 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000839 return None;
840
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000841 LoopConstrainer::SubRanges Result;
842
843 // I think we can be more aggressive here and make this nuw / nsw if the
844 // addition that feeds into the icmp for the latch's terminating branch is nuw
845 // / nsw. In any case, a wrapping 2's complement addition is safe.
846 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000847 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
848 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000849
Sanjoy Dase75ed922015-02-26 08:19:31 +0000850 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000851
Sanjoy Dase75ed922015-02-26 08:19:31 +0000852 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
853 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000854
855 const SCEV *Smallest = nullptr, *Greatest = nullptr;
856
857 if (Increasing) {
858 Smallest = Start;
859 Greatest = End;
860 } else {
861 // These two computations may sign-overflow. Here is why that is okay:
862 //
863 // We know that the induction variable does not sign-overflow on any
864 // iteration except the last one, and it starts at `Start` and ends at
865 // `End`, decrementing by one every time.
866 //
867 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
868 // induction variable is decreasing we know that that the smallest value
869 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
870 //
871 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
872 // that case, `Clamp` will always return `Smallest` and
873 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
874 // will be an empty range. Returning an empty range is always safe.
875 //
876
877 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
878 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
879 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000880
881 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
882 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
883 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000884
885 // In some cases we can prove that we don't need a pre or post loop
886
887 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000888 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
889 if (!ProvablyNoPreloop)
890 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000891
892 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000893 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
894 if (!ProvablyNoPostLoop)
895 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000896
897 return Result;
898}
899
900void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
901 const char *Tag) const {
902 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
903 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
904 Result.Blocks.push_back(Clone);
905 Result.Map[BB] = Clone;
906 }
907
908 auto GetClonedValue = [&Result](Value *V) {
909 assert(V && "null values not in domain!");
910 auto It = Result.Map.find(V);
911 if (It == Result.Map.end())
912 return V;
913 return static_cast<Value *>(It->second);
914 };
915
916 Result.Structure = MainLoopStructure.map(GetClonedValue);
917 Result.Structure.Tag = Tag;
918
919 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
920 BasicBlock *ClonedBB = Result.Blocks[i];
921 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
922
923 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
924
925 for (Instruction &I : *ClonedBB)
926 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000927 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000928
929 // Exit blocks will now have one more predecessor and their PHI nodes need
930 // to be edited to reflect that. No phi nodes need to be introduced because
931 // the loop is in LCSSA.
932
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000933 for (auto *SBB : successors(OriginalBB)) {
934 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000935 continue; // not an exit block
936
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000937 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +0000938 auto *PN = dyn_cast<PHINode>(&I);
939 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000940 break;
941
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000942 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
943 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
944 }
945 }
946 }
947}
948
949LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000950 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000951 BasicBlock *ContinuationBlock) const {
952
953 // We start with a loop with a single latch:
954 //
955 // +--------------------+
956 // | |
957 // | preheader |
958 // | |
959 // +--------+-----------+
960 // | ----------------\
961 // | / |
962 // +--------v----v------+ |
963 // | | |
964 // | header | |
965 // | | |
966 // +--------------------+ |
967 // |
968 // ..... |
969 // |
970 // +--------------------+ |
971 // | | |
972 // | latch >----------/
973 // | |
974 // +-------v------------+
975 // |
976 // |
977 // | +--------------------+
978 // | | |
979 // +---> original exit |
980 // | |
981 // +--------------------+
982 //
983 // We change the control flow to look like
984 //
985 //
986 // +--------------------+
987 // | |
988 // | preheader >-------------------------+
989 // | | |
990 // +--------v-----------+ |
991 // | /-------------+ |
992 // | / | |
993 // +--------v--v--------+ | |
994 // | | | |
995 // | header | | +--------+ |
996 // | | | | | |
997 // +--------------------+ | | +-----v-----v-----------+
998 // | | | |
999 // | | | .pseudo.exit |
1000 // | | | |
1001 // | | +-----------v-----------+
1002 // | | |
1003 // ..... | | |
1004 // | | +--------v-------------+
1005 // +--------------------+ | | | |
1006 // | | | | | ContinuationBlock |
1007 // | latch >------+ | | |
1008 // | | | +----------------------+
1009 // +---------v----------+ |
1010 // | |
1011 // | |
1012 // | +---------------^-----+
1013 // | | |
1014 // +-----> .exit.selector |
1015 // | |
1016 // +----------v----------+
1017 // |
1018 // +--------------------+ |
1019 // | | |
1020 // | original exit <----+
1021 // | |
1022 // +--------------------+
1023 //
1024
1025 RewrittenRangeInfo RRI;
1026
1027 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1028 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001029 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001030 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001031 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001032
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001033 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001034 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001035
1036 IRBuilder<> B(PreheaderJump);
1037
1038 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001039 Value *EnterLoopCond = Increasing
1040 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1041 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1042
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001043 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1044 PreheaderJump->eraseFromParent();
1045
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001046 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001047 B.SetInsertPoint(LS.LatchBr);
1048 Value *TakeBackedgeLoopCond =
1049 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1050 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1051 Value *CondForBranch = LS.LatchBrExitIdx == 1
1052 ? TakeBackedgeLoopCond
1053 : B.CreateNot(TakeBackedgeLoopCond);
1054
1055 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001056
1057 B.SetInsertPoint(RRI.ExitSelector);
1058
1059 // IterationsLeft - are there any more iterations left, given the original
1060 // upper bound on the induction variable? If not, we branch to the "real"
1061 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001062 Value *IterationsLeft = Increasing
1063 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1064 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001065 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1066
1067 BranchInst *BranchToContinuation =
1068 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1069
1070 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1071 // each of the PHI nodes in the loop header. This feeds into the initial
1072 // value of the same PHI nodes if/when we continue execution.
1073 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001074 auto *PN = dyn_cast<PHINode>(&I);
1075 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001076 break;
1077
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001078 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1079 BranchToContinuation);
1080
1081 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1082 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1083 RRI.ExitSelector);
1084 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1085 }
1086
Sanjoy Dase75ed922015-02-26 08:19:31 +00001087 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1088 BranchToContinuation);
1089 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1090 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1091
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001092 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1093 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1094 for (Instruction &I : *LS.LatchExit) {
1095 if (PHINode *PN = dyn_cast<PHINode>(&I))
1096 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1097 else
1098 break;
1099 }
1100
1101 return RRI;
1102}
1103
1104void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001105 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001106 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1107
1108 unsigned PHIIndex = 0;
1109 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001110 auto *PN = dyn_cast<PHINode>(&I);
1111 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001112 break;
1113
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001114 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1115 if (PN->getIncomingBlock(i) == ContinuationBlock)
1116 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1117 }
1118
Sanjoy Dase75ed922015-02-26 08:19:31 +00001119 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001120}
1121
Sanjoy Dase75ed922015-02-26 08:19:31 +00001122BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1123 BasicBlock *OldPreheader,
1124 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001125
1126 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1127 BranchInst::Create(LS.Header, Preheader);
1128
1129 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001130 auto *PN = dyn_cast<PHINode>(&I);
1131 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001132 break;
1133
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001134 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1135 replacePHIBlock(PN, OldPreheader, Preheader);
1136 }
1137
1138 return Preheader;
1139}
1140
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001141void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001142 Loop *ParentLoop = OriginalLoop.getParentLoop();
1143 if (!ParentLoop)
1144 return;
1145
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001146 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001147 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001148}
1149
1150bool LoopConstrainer::run() {
1151 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001152 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1153 Preheader = OriginalLoop.getLoopPreheader();
1154 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1155 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001156
1157 OriginalPreheader = Preheader;
1158 MainLoopPreheader = Preheader;
1159
Sanjoy Dase75ed922015-02-26 08:19:31 +00001160 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001161 if (!MaybeSR.hasValue()) {
1162 DEBUG(dbgs() << "irce: could not compute subranges\n");
1163 return false;
1164 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001165
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001166 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001167 bool Increasing = MainLoopStructure.IndVarIncreasing;
1168 IntegerType *IVTy =
1169 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1170
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001171 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001172 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001173
1174 // It would have been better to make `PreLoop' and `PostLoop'
1175 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1176 // constructor.
1177 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001178 bool NeedsPreLoop =
1179 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1180 bool NeedsPostLoop =
1181 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1182
1183 Value *ExitPreLoopAt = nullptr;
1184 Value *ExitMainLoopAt = nullptr;
1185 const SCEVConstant *MinusOneS =
1186 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1187
1188 if (NeedsPreLoop) {
1189 const SCEV *ExitPreLoopAtSCEV = nullptr;
1190
1191 if (Increasing)
1192 ExitPreLoopAtSCEV = *SR.LowLimit;
1193 else {
1194 if (CanBeSMin(SE, *SR.HighLimit)) {
1195 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1196 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1197 << "\n");
1198 return false;
1199 }
1200 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1201 }
1202
1203 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1204 ExitPreLoopAt->setName("exit.preloop.at");
1205 }
1206
1207 if (NeedsPostLoop) {
1208 const SCEV *ExitMainLoopAtSCEV = nullptr;
1209
1210 if (Increasing)
1211 ExitMainLoopAtSCEV = *SR.HighLimit;
1212 else {
1213 if (CanBeSMin(SE, *SR.LowLimit)) {
1214 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1215 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1216 << "\n");
1217 return false;
1218 }
1219 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1220 }
1221
1222 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1223 ExitMainLoopAt->setName("exit.mainloop.at");
1224 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001225
1226 // We clone these ahead of time so that we don't have to deal with changing
1227 // and temporarily invalid IR as we transform the loops.
1228 if (NeedsPreLoop)
1229 cloneLoop(PreLoop, "preloop");
1230 if (NeedsPostLoop)
1231 cloneLoop(PostLoop, "postloop");
1232
1233 RewrittenRangeInfo PreLoopRRI;
1234
1235 if (NeedsPreLoop) {
1236 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1237 PreLoop.Structure.Header);
1238
1239 MainLoopPreheader =
1240 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001241 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1242 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001243 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1244 PreLoopRRI);
1245 }
1246
1247 BasicBlock *PostLoopPreheader = nullptr;
1248 RewrittenRangeInfo PostLoopRRI;
1249
1250 if (NeedsPostLoop) {
1251 PostLoopPreheader =
1252 createPreheader(PostLoop.Structure, Preheader, "postloop");
1253 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001254 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001255 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1256 PostLoopRRI);
1257 }
1258
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001259 BasicBlock *NewMainLoopPreheader =
1260 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1261 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1262 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1263 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001264
1265 // Some of the above may be nullptr, filter them out before passing to
1266 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001267 auto NewBlocksEnd =
1268 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001269
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001270 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1271 addToParentLoopIfNeeded(PreLoop.Blocks);
1272 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001273
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001274 DT.recalculate(F);
Sanjoy Das83a72852016-08-02 19:32:01 +00001275 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dascf181862016-08-06 00:01:56 +00001276 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001277
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001278 return true;
1279}
1280
Sanjoy Das95c476d2015-02-21 22:20:22 +00001281/// Computes and returns a range of values for the induction variable (IndVar)
1282/// in which the range check can be safely elided. If it cannot compute such a
1283/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001284Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001285InductiveRangeCheck::computeSafeIterationSpace(
1286 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001287 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1288 // variable, that may or may not exist as a real llvm::Value in the loop) and
1289 // this inductive range check is a range check on the "C + D * I" ("C" is
1290 // getOffset() and "D" is getScale()). We rewrite the value being range
1291 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1292 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1293 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001294 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001295 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001296 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001297 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1298 //
1299 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1300 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001301 //
1302 // Proof:
1303 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001304 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1305 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1306 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1307 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001308 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001309 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1310 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001311
Sanjoy Das95c476d2015-02-21 22:20:22 +00001312 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1313 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001314
Sanjoy Das95c476d2015-02-21 22:20:22 +00001315 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001316 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001317
Sanjoy Das95c476d2015-02-21 22:20:22 +00001318 const SCEV *A = IndVar->getStart();
1319 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1320 if (!B)
1321 return None;
1322
1323 const SCEV *C = getOffset();
1324 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1325 if (D != B)
1326 return None;
1327
1328 ConstantInt *ConstD = D->getValue();
1329 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1330 return None;
1331
1332 const SCEV *M = SE.getMinusSCEV(C, A);
1333
1334 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001335 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001336
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001337 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1338 // We can potentially do much better here.
1339 if (Value *V = getLength()) {
1340 UpperLimit = SE.getSCEV(V);
1341 } else {
1342 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1343 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1344 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1345 }
1346
1347 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001348 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001349}
1350
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001351static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001352IntersectRange(ScalarEvolution &SE,
1353 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001354 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001355 if (!R1.hasValue())
1356 return R2;
1357 auto &R1Value = R1.getValue();
1358
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001359 // TODO: we could widen the smaller range and have this work; but for now we
1360 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001361 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001362 return None;
1363
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001364 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1365 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1366
1367 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001368}
1369
1370bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001371 if (skipLoop(L))
1372 return false;
1373
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001374 if (L->getBlocks().size() >= LoopSizeCutoff) {
1375 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1376 return false;
1377 }
1378
1379 BasicBlock *Preheader = L->getLoopPreheader();
1380 if (!Preheader) {
1381 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1382 return false;
1383 }
1384
1385 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001386 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001387 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001388 BranchProbabilityInfo &BPI =
1389 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001390
1391 for (auto BBI : L->getBlocks())
1392 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001393 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1394 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001395
1396 if (RangeChecks.empty())
1397 return false;
1398
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001399 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1400 OS << "irce: looking at loop "; L->print(OS);
1401 OS << "irce: loop has " << RangeChecks.size()
1402 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001403 for (InductiveRangeCheck &IRC : RangeChecks)
1404 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001405 };
1406
1407 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1408
1409 if (PrintRangeChecks)
1410 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001411
Sanjoy Dase75ed922015-02-26 08:19:31 +00001412 const char *FailureReason = nullptr;
1413 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001414 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001415 if (!MaybeLoopStructure.hasValue()) {
1416 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1417 << "\n";);
1418 return false;
1419 }
1420 LoopStructure LS = MaybeLoopStructure.getValue();
1421 bool Increasing = LS.IndVarIncreasing;
1422 const SCEV *MinusOne =
1423 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1424 const SCEVAddRecExpr *IndVar =
1425 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1426
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001427 Optional<InductiveRangeCheck::Range> SafeIterRange;
1428 Instruction *ExprInsertPt = Preheader->getTerminator();
1429
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001430 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001431
1432 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001433 for (InductiveRangeCheck &IRC : RangeChecks) {
1434 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001435 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001436 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001437 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001438 if (MaybeSafeIterRange.hasValue()) {
1439 RangeChecksToEliminate.push_back(IRC);
1440 SafeIterRange = MaybeSafeIterRange.getValue();
1441 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001442 }
1443 }
1444
1445 if (!SafeIterRange.hasValue())
1446 return false;
1447
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001448 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001449 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001450 SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001451 bool Changed = LC.run();
1452
1453 if (Changed) {
1454 auto PrintConstrainedLoopInfo = [L]() {
1455 dbgs() << "irce: in function ";
1456 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1457 dbgs() << "constrained ";
1458 L->print(dbgs());
1459 };
1460
1461 DEBUG(PrintConstrainedLoopInfo());
1462
1463 if (PrintChangedLoops)
1464 PrintConstrainedLoopInfo();
1465
1466 // Optimize away the now-redundant range checks.
1467
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001468 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1469 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001470 ? ConstantInt::getTrue(Context)
1471 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001472 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001473 }
1474 }
1475
1476 return Changed;
1477}
1478
1479Pass *llvm::createInductiveRangeCheckEliminationPass() {
1480 return new InductiveRangeCheckElimination;
1481}