blob: 3f9432e4651f79db9986fb6951d27b8c1b95c6c3 [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 Das2a2f14d2016-08-13 23:36:35 +0000625 if (!L.isLoopSimplifyForm())
626 return None;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000627
628 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000629 assert(Latch && "Simplified loops only have one latch!");
630
Sanjoy Dase75ed922015-02-26 08:19:31 +0000631 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000632 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000633 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000634 }
635
Sanjoy Dase75ed922015-02-26 08:19:31 +0000636 BasicBlock *Header = L.getHeader();
637 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000638 if (!Preheader) {
639 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000640 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000641 }
642
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000643 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000644 if (!LatchBr || LatchBr->isUnconditional()) {
645 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000646 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000647 }
648
Sanjoy Dase75ed922015-02-26 08:19:31 +0000649 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000650
Sanjoy Dase91665d2015-02-26 08:56:04 +0000651 BranchProbability ExitProbability =
652 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
653
Sanjoy Dasbb969792016-07-22 00:40:56 +0000654 if (!SkipProfitabilityChecks &&
655 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000656 FailureReason = "short running loop, not profitable";
657 return None;
658 }
659
Sanjoy Dase75ed922015-02-26 08:19:31 +0000660 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
661 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
662 FailureReason = "latch terminator branch not conditional on integral icmp";
663 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000664 }
665
Sanjoy Dase75ed922015-02-26 08:19:31 +0000666 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
667 if (isa<SCEVCouldNotCompute>(LatchCount)) {
668 FailureReason = "could not compute latch count";
669 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000670 }
671
Sanjoy Dase75ed922015-02-26 08:19:31 +0000672 ICmpInst::Predicate Pred = ICI->getPredicate();
673 Value *LeftValue = ICI->getOperand(0);
674 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
675 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
676
677 Value *RightValue = ICI->getOperand(1);
678 const SCEV *RightSCEV = SE.getSCEV(RightValue);
679
680 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
681 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
682 if (isa<SCEVAddRecExpr>(RightSCEV)) {
683 std::swap(LeftSCEV, RightSCEV);
684 std::swap(LeftValue, RightValue);
685 Pred = ICmpInst::getSwappedPredicate(Pred);
686 } else {
687 FailureReason = "no add recurrences in the icmp";
688 return None;
689 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000690 }
691
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000692 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
693 if (AR->getNoWrapFlags(SCEV::FlagNSW))
694 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000695
696 IntegerType *Ty = cast<IntegerType>(AR->getType());
697 IntegerType *WideTy =
698 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
699
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000700 const SCEVAddRecExpr *ExtendAfterOp =
701 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
702 if (ExtendAfterOp) {
703 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
704 const SCEV *ExtendedStep =
705 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
706
707 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
708 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
709
710 if (NoSignedWrap)
711 return true;
712 }
713
714 // We may have proved this when computing the sign extension above.
715 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
716 };
717
718 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
719 if (!AR->isAffine())
720 return false;
721
Sanjoy Dase75ed922015-02-26 08:19:31 +0000722 // Currently we only work with induction variables that have been proved to
723 // not wrap. This restriction can potentially be lifted in the future.
724
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000725 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000726 return false;
727
728 if (const SCEVConstant *StepExpr =
729 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
730 ConstantInt *StepCI = StepExpr->getValue();
731 if (StepCI->isOne() || StepCI->isMinusOne()) {
732 IsIncreasing = StepCI->isOne();
733 return true;
734 }
735 }
736
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000737 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000738 };
739
740 // `ICI` is interpreted as taking the backedge if the *next* value of the
741 // induction variable satisfies some constraint.
742
743 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
744 bool IsIncreasing = false;
745 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
746 FailureReason = "LHS in icmp not induction variable";
747 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000748 }
749
Sanjoy Dase75ed922015-02-26 08:19:31 +0000750 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
751 // TODO: generalize the predicates here to also match their unsigned variants.
752 if (IsIncreasing) {
753 bool FoundExpectedPred =
754 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
755 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
756
757 if (!FoundExpectedPred) {
758 FailureReason = "expected icmp slt semantically, found something else";
759 return None;
760 }
761
762 if (LatchBrExitIdx == 0) {
763 if (CanBeSMax(SE, RightSCEV)) {
764 // TODO: this restriction is easily removable -- we just have to
765 // remember that the icmp was an slt and not an sle.
766 FailureReason = "limit may overflow when coercing sle to slt";
767 return None;
768 }
769
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000770 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000771 RightValue = B.CreateAdd(RightValue, One);
772 }
773
774 } else {
775 bool FoundExpectedPred =
776 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
777 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
778
779 if (!FoundExpectedPred) {
780 FailureReason = "expected icmp sgt semantically, found something else";
781 return None;
782 }
783
784 if (LatchBrExitIdx == 0) {
785 if (CanBeSMin(SE, RightSCEV)) {
786 // TODO: this restriction is easily removable -- we just have to
787 // remember that the icmp was an sgt and not an sge.
788 FailureReason = "limit may overflow when coercing sge to sgt";
789 return None;
790 }
791
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000792 IRBuilder<> B(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000793 RightValue = B.CreateSub(RightValue, One);
794 }
795 }
796
797 const SCEV *StartNext = IndVarNext->getStart();
798 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
799 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
800
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000801 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
802
Sanjoy Dase75ed922015-02-26 08:19:31 +0000803 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000804 ScalarEvolution::LoopInvariant &&
805 "loop variant exit count doesn't make sense!");
806
Sanjoy Dase75ed922015-02-26 08:19:31 +0000807 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000808 const DataLayout &DL = Preheader->getModule()->getDataLayout();
809 Value *IndVarStartV =
810 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000811 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +0000812 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000813
Sanjoy Dase75ed922015-02-26 08:19:31 +0000814 LoopStructure Result;
815
816 Result.Tag = "main";
817 Result.Header = Header;
818 Result.Latch = Latch;
819 Result.LatchBr = LatchBr;
820 Result.LatchExit = LatchExit;
821 Result.LatchBrExitIdx = LatchBrExitIdx;
822 Result.IndVarStart = IndVarStartV;
823 Result.IndVarNext = LeftValue;
824 Result.IndVarIncreasing = IsIncreasing;
825 Result.LoopExitAt = RightValue;
826
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000827 FailureReason = nullptr;
828
Sanjoy Dase75ed922015-02-26 08:19:31 +0000829 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000830}
831
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000832Optional<LoopConstrainer::SubRanges>
Sanjoy Dase75ed922015-02-26 08:19:31 +0000833LoopConstrainer::calculateSubRanges() const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000834 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
835
Sanjoy Das351db052015-01-22 09:32:02 +0000836 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000837 return None;
838
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000839 LoopConstrainer::SubRanges Result;
840
841 // I think we can be more aggressive here and make this nuw / nsw if the
842 // addition that feeds into the icmp for the latch's terminating branch is nuw
843 // / nsw. In any case, a wrapping 2's complement addition is safe.
844 ConstantInt *One = ConstantInt::get(Ty, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000845 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
846 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000847
Sanjoy Dase75ed922015-02-26 08:19:31 +0000848 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000849
Sanjoy Dase75ed922015-02-26 08:19:31 +0000850 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
851 // range of values the induction variable takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +0000852
853 const SCEV *Smallest = nullptr, *Greatest = nullptr;
854
855 if (Increasing) {
856 Smallest = Start;
857 Greatest = End;
858 } else {
859 // These two computations may sign-overflow. Here is why that is okay:
860 //
861 // We know that the induction variable does not sign-overflow on any
862 // iteration except the last one, and it starts at `Start` and ends at
863 // `End`, decrementing by one every time.
864 //
865 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
866 // induction variable is decreasing we know that that the smallest value
867 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
868 //
869 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
870 // that case, `Clamp` will always return `Smallest` and
871 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
872 // will be an empty range. Returning an empty range is always safe.
873 //
874
875 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
876 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
877 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000878
879 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
880 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
881 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000882
883 // In some cases we can prove that we don't need a pre or post loop
884
885 bool ProvablyNoPreloop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000886 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
887 if (!ProvablyNoPreloop)
888 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000889
890 bool ProvablyNoPostLoop =
Sanjoy Dase75ed922015-02-26 08:19:31 +0000891 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
892 if (!ProvablyNoPostLoop)
893 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000894
895 return Result;
896}
897
898void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
899 const char *Tag) const {
900 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
901 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
902 Result.Blocks.push_back(Clone);
903 Result.Map[BB] = Clone;
904 }
905
906 auto GetClonedValue = [&Result](Value *V) {
907 assert(V && "null values not in domain!");
908 auto It = Result.Map.find(V);
909 if (It == Result.Map.end())
910 return V;
911 return static_cast<Value *>(It->second);
912 };
913
914 Result.Structure = MainLoopStructure.map(GetClonedValue);
915 Result.Structure.Tag = Tag;
916
917 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
918 BasicBlock *ClonedBB = Result.Blocks[i];
919 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
920
921 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
922
923 for (Instruction &I : *ClonedBB)
924 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000925 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000926
927 // Exit blocks will now have one more predecessor and their PHI nodes need
928 // to be edited to reflect that. No phi nodes need to be introduced because
929 // the loop is in LCSSA.
930
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000931 for (auto *SBB : successors(OriginalBB)) {
932 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000933 continue; // not an exit block
934
Sanjoy Dasd1d62a12016-08-13 22:00:09 +0000935 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +0000936 auto *PN = dyn_cast<PHINode>(&I);
937 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000938 break;
939
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000940 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
941 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
942 }
943 }
944 }
945}
946
947LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000948 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000949 BasicBlock *ContinuationBlock) const {
950
951 // We start with a loop with a single latch:
952 //
953 // +--------------------+
954 // | |
955 // | preheader |
956 // | |
957 // +--------+-----------+
958 // | ----------------\
959 // | / |
960 // +--------v----v------+ |
961 // | | |
962 // | header | |
963 // | | |
964 // +--------------------+ |
965 // |
966 // ..... |
967 // |
968 // +--------------------+ |
969 // | | |
970 // | latch >----------/
971 // | |
972 // +-------v------------+
973 // |
974 // |
975 // | +--------------------+
976 // | | |
977 // +---> original exit |
978 // | |
979 // +--------------------+
980 //
981 // We change the control flow to look like
982 //
983 //
984 // +--------------------+
985 // | |
986 // | preheader >-------------------------+
987 // | | |
988 // +--------v-----------+ |
989 // | /-------------+ |
990 // | / | |
991 // +--------v--v--------+ | |
992 // | | | |
993 // | header | | +--------+ |
994 // | | | | | |
995 // +--------------------+ | | +-----v-----v-----------+
996 // | | | |
997 // | | | .pseudo.exit |
998 // | | | |
999 // | | +-----------v-----------+
1000 // | | |
1001 // ..... | | |
1002 // | | +--------v-------------+
1003 // +--------------------+ | | | |
1004 // | | | | | ContinuationBlock |
1005 // | latch >------+ | | |
1006 // | | | +----------------------+
1007 // +---------v----------+ |
1008 // | |
1009 // | |
1010 // | +---------------^-----+
1011 // | | |
1012 // +-----> .exit.selector |
1013 // | |
1014 // +----------v----------+
1015 // |
1016 // +--------------------+ |
1017 // | | |
1018 // | original exit <----+
1019 // | |
1020 // +--------------------+
1021 //
1022
1023 RewrittenRangeInfo RRI;
1024
1025 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1026 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001027 &F, &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001028 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +00001029 &*BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001030
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001031 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001032 bool Increasing = LS.IndVarIncreasing;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001033
1034 IRBuilder<> B(PreheaderJump);
1035
1036 // EnterLoopCond - is it okay to start executing this `LS'?
Sanjoy Dase75ed922015-02-26 08:19:31 +00001037 Value *EnterLoopCond = Increasing
1038 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1039 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1040
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001041 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1042 PreheaderJump->eraseFromParent();
1043
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001044 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001045 B.SetInsertPoint(LS.LatchBr);
1046 Value *TakeBackedgeLoopCond =
1047 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1048 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1049 Value *CondForBranch = LS.LatchBrExitIdx == 1
1050 ? TakeBackedgeLoopCond
1051 : B.CreateNot(TakeBackedgeLoopCond);
1052
1053 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001054
1055 B.SetInsertPoint(RRI.ExitSelector);
1056
1057 // IterationsLeft - are there any more iterations left, given the original
1058 // upper bound on the induction variable? If not, we branch to the "real"
1059 // exit.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001060 Value *IterationsLeft = Increasing
1061 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1062 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001063 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1064
1065 BranchInst *BranchToContinuation =
1066 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1067
1068 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1069 // each of the PHI nodes in the loop header. This feeds into the initial
1070 // value of the same PHI nodes if/when we continue execution.
1071 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001072 auto *PN = dyn_cast<PHINode>(&I);
1073 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001074 break;
1075
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001076 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1077 BranchToContinuation);
1078
1079 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1080 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1081 RRI.ExitSelector);
1082 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1083 }
1084
Sanjoy Dase75ed922015-02-26 08:19:31 +00001085 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1086 BranchToContinuation);
1087 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1088 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1089
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001090 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1091 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1092 for (Instruction &I : *LS.LatchExit) {
1093 if (PHINode *PN = dyn_cast<PHINode>(&I))
1094 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1095 else
1096 break;
1097 }
1098
1099 return RRI;
1100}
1101
1102void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001103 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001104 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1105
1106 unsigned PHIIndex = 0;
1107 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001108 auto *PN = dyn_cast<PHINode>(&I);
1109 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001110 break;
1111
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001112 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1113 if (PN->getIncomingBlock(i) == ContinuationBlock)
1114 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1115 }
1116
Sanjoy Dase75ed922015-02-26 08:19:31 +00001117 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001118}
1119
Sanjoy Dase75ed922015-02-26 08:19:31 +00001120BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1121 BasicBlock *OldPreheader,
1122 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001123
1124 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1125 BranchInst::Create(LS.Header, Preheader);
1126
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 replacePHIBlock(PN, OldPreheader, Preheader);
1134 }
1135
1136 return Preheader;
1137}
1138
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001139void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001140 Loop *ParentLoop = OriginalLoop.getParentLoop();
1141 if (!ParentLoop)
1142 return;
1143
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001144 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001145 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001146}
1147
1148bool LoopConstrainer::run() {
1149 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001150 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1151 Preheader = OriginalLoop.getLoopPreheader();
1152 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1153 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001154
1155 OriginalPreheader = Preheader;
1156 MainLoopPreheader = Preheader;
1157
Sanjoy Dase75ed922015-02-26 08:19:31 +00001158 Optional<SubRanges> MaybeSR = calculateSubRanges();
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001159 if (!MaybeSR.hasValue()) {
1160 DEBUG(dbgs() << "irce: could not compute subranges\n");
1161 return false;
1162 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001163
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001164 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001165 bool Increasing = MainLoopStructure.IndVarIncreasing;
1166 IntegerType *IVTy =
1167 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1168
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001170 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001171
1172 // It would have been better to make `PreLoop' and `PostLoop'
1173 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1174 // constructor.
1175 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001176 bool NeedsPreLoop =
1177 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1178 bool NeedsPostLoop =
1179 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1180
1181 Value *ExitPreLoopAt = nullptr;
1182 Value *ExitMainLoopAt = nullptr;
1183 const SCEVConstant *MinusOneS =
1184 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1185
1186 if (NeedsPreLoop) {
1187 const SCEV *ExitPreLoopAtSCEV = nullptr;
1188
1189 if (Increasing)
1190 ExitPreLoopAtSCEV = *SR.LowLimit;
1191 else {
1192 if (CanBeSMin(SE, *SR.HighLimit)) {
1193 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1194 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1195 << "\n");
1196 return false;
1197 }
1198 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1199 }
1200
1201 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1202 ExitPreLoopAt->setName("exit.preloop.at");
1203 }
1204
1205 if (NeedsPostLoop) {
1206 const SCEV *ExitMainLoopAtSCEV = nullptr;
1207
1208 if (Increasing)
1209 ExitMainLoopAtSCEV = *SR.HighLimit;
1210 else {
1211 if (CanBeSMin(SE, *SR.LowLimit)) {
1212 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1213 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1214 << "\n");
1215 return false;
1216 }
1217 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1218 }
1219
1220 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1221 ExitMainLoopAt->setName("exit.mainloop.at");
1222 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001223
1224 // We clone these ahead of time so that we don't have to deal with changing
1225 // and temporarily invalid IR as we transform the loops.
1226 if (NeedsPreLoop)
1227 cloneLoop(PreLoop, "preloop");
1228 if (NeedsPostLoop)
1229 cloneLoop(PostLoop, "postloop");
1230
1231 RewrittenRangeInfo PreLoopRRI;
1232
1233 if (NeedsPreLoop) {
1234 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1235 PreLoop.Structure.Header);
1236
1237 MainLoopPreheader =
1238 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001239 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1240 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001241 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1242 PreLoopRRI);
1243 }
1244
1245 BasicBlock *PostLoopPreheader = nullptr;
1246 RewrittenRangeInfo PostLoopRRI;
1247
1248 if (NeedsPostLoop) {
1249 PostLoopPreheader =
1250 createPreheader(PostLoop.Structure, Preheader, "postloop");
1251 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001252 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001253 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1254 PostLoopRRI);
1255 }
1256
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001257 BasicBlock *NewMainLoopPreheader =
1258 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1259 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1260 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1261 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001262
1263 // Some of the above may be nullptr, filter them out before passing to
1264 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001265 auto NewBlocksEnd =
1266 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001267
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001268 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1269 addToParentLoopIfNeeded(PreLoop.Blocks);
1270 addToParentLoopIfNeeded(PostLoop.Blocks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001271
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001272 DT.recalculate(F);
Sanjoy Das83a72852016-08-02 19:32:01 +00001273 formLCSSARecursively(OriginalLoop, DT, &LI, &SE);
Sanjoy Dascf181862016-08-06 00:01:56 +00001274 simplifyLoop(&OriginalLoop, &DT, &LI, &SE, nullptr, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001275
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001276 return true;
1277}
1278
Sanjoy Das95c476d2015-02-21 22:20:22 +00001279/// Computes and returns a range of values for the induction variable (IndVar)
1280/// in which the range check can be safely elided. If it cannot compute such a
1281/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001282Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001283InductiveRangeCheck::computeSafeIterationSpace(
1284 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001285 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1286 // variable, that may or may not exist as a real llvm::Value in the loop) and
1287 // this inductive range check is a range check on the "C + D * I" ("C" is
1288 // getOffset() and "D" is getScale()). We rewrite the value being range
1289 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1290 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1291 // can be generalized as needed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001292 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001293 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001294 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001295 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1296 //
1297 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1298 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001299 //
1300 // Proof:
1301 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001302 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1303 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1304 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1305 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001306 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001307 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1308 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001309
Sanjoy Das95c476d2015-02-21 22:20:22 +00001310 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1311 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001312
Sanjoy Das95c476d2015-02-21 22:20:22 +00001313 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001314 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001315
Sanjoy Das95c476d2015-02-21 22:20:22 +00001316 const SCEV *A = IndVar->getStart();
1317 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1318 if (!B)
1319 return None;
1320
1321 const SCEV *C = getOffset();
1322 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1323 if (D != B)
1324 return None;
1325
1326 ConstantInt *ConstD = D->getValue();
1327 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1328 return None;
1329
1330 const SCEV *M = SE.getMinusSCEV(C, A);
1331
1332 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001333 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001334
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001335 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1336 // We can potentially do much better here.
1337 if (Value *V = getLength()) {
1338 UpperLimit = SE.getSCEV(V);
1339 } else {
1340 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1341 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1342 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1343 }
1344
1345 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001346 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001347}
1348
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001349static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001350IntersectRange(ScalarEvolution &SE,
1351 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001352 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001353 if (!R1.hasValue())
1354 return R2;
1355 auto &R1Value = R1.getValue();
1356
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001357 // TODO: we could widen the smaller range and have this work; but for now we
1358 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001359 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001360 return None;
1361
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001362 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1363 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1364
1365 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001366}
1367
1368bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001369 if (skipLoop(L))
1370 return false;
1371
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001372 if (L->getBlocks().size() >= LoopSizeCutoff) {
1373 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1374 return false;
1375 }
1376
1377 BasicBlock *Preheader = L->getLoopPreheader();
1378 if (!Preheader) {
1379 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1380 return false;
1381 }
1382
1383 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001384 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001385 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001386 BranchProbabilityInfo &BPI =
1387 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001388
1389 for (auto BBI : L->getBlocks())
1390 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001391 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1392 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001393
1394 if (RangeChecks.empty())
1395 return false;
1396
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001397 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1398 OS << "irce: looking at loop "; L->print(OS);
1399 OS << "irce: loop has " << RangeChecks.size()
1400 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001401 for (InductiveRangeCheck &IRC : RangeChecks)
1402 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001403 };
1404
1405 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1406
1407 if (PrintRangeChecks)
1408 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001409
Sanjoy Dase75ed922015-02-26 08:19:31 +00001410 const char *FailureReason = nullptr;
1411 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001412 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001413 if (!MaybeLoopStructure.hasValue()) {
1414 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1415 << "\n";);
1416 return false;
1417 }
1418 LoopStructure LS = MaybeLoopStructure.getValue();
1419 bool Increasing = LS.IndVarIncreasing;
1420 const SCEV *MinusOne =
1421 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1422 const SCEVAddRecExpr *IndVar =
1423 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1424
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001425 Optional<InductiveRangeCheck::Range> SafeIterRange;
1426 Instruction *ExprInsertPt = Preheader->getTerminator();
1427
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001428 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001429
1430 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001431 for (InductiveRangeCheck &IRC : RangeChecks) {
1432 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001433 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001434 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001435 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001436 if (MaybeSafeIterRange.hasValue()) {
1437 RangeChecksToEliminate.push_back(IRC);
1438 SafeIterRange = MaybeSafeIterRange.getValue();
1439 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001440 }
1441 }
1442
1443 if (!SafeIterRange.hasValue())
1444 return false;
1445
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001446 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001447 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001448 SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001449 bool Changed = LC.run();
1450
1451 if (Changed) {
1452 auto PrintConstrainedLoopInfo = [L]() {
1453 dbgs() << "irce: in function ";
1454 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1455 dbgs() << "constrained ";
1456 L->print(dbgs());
1457 };
1458
1459 DEBUG(PrintConstrainedLoopInfo());
1460
1461 if (PrintChangedLoops)
1462 PrintConstrainedLoopInfo();
1463
1464 // Optimize away the now-redundant range checks.
1465
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001466 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1467 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001468 ? ConstantInt::getTrue(Context)
1469 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001470 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001471 }
1472 }
1473
1474 return Changed;
1475}
1476
1477Pass *llvm::createInductiveRangeCheckEliminationPass() {
1478 return new InductiveRangeCheckElimination;
1479}