blob: 6c136a6f87a1916cfbd38f789371b913d98c4b0a [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"
Sanjoy Dascf181862016-08-06 00:01:56 +000062#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000063#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000064
65using namespace llvm;
66
Benjamin Kramer970eac42015-02-06 17:51:54 +000067static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
68 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000069
Benjamin Kramer970eac42015-02-06 17:51:54 +000070static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
71 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +000072
Sanjoy Das9c1bfae2015-03-17 01:40:22 +000073static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
74 cl::init(false));
75
Sanjoy Dase91665d2015-02-26 08:56:04 +000076static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
77 cl::Hidden, cl::init(10));
78
Sanjoy Dasbb969792016-07-22 00:40:56 +000079static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
80 cl::Hidden, cl::init(false));
81
Sanjoy Das7a18a232016-08-14 01:04:36 +000082static const char *ClonedLoopTag = "irce.loop.clone";
83
Sanjoy Dasa1837a32015-01-16 01:03:22 +000084#define DEBUG_TYPE "irce"
85
86namespace {
87
88/// An inductive range check is conditional branch in a loop with
89///
90/// 1. a very cold successor (i.e. the branch jumps to that successor very
91/// rarely)
92///
93/// and
94///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000095/// 2. a condition that is provably true for some contiguous range of values
96/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +000097///
Sanjoy Dasa1837a32015-01-16 01:03:22 +000098class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +000099 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000100 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000101 // Range check of the form "0 <= I".
102 RANGE_CHECK_LOWER = 1,
103
104 // Range check of the form "I < L" where L is known positive.
105 RANGE_CHECK_UPPER = 2,
106
107 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
108 // conditions.
109 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
110
111 // Unrecognized range check condition.
112 RANGE_CHECK_UNKNOWN = (unsigned)-1
113 };
114
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000115 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000116
Sanjoy Dasee77a482016-05-26 01:50:18 +0000117 const SCEV *Offset = nullptr;
118 const SCEV *Scale = nullptr;
119 Value *Length = nullptr;
120 Use *CheckUse = nullptr;
121 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000122
Sanjoy Das337d46b2015-03-24 19:29:18 +0000123 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
124 ScalarEvolution &SE, Value *&Index,
125 Value *&Length);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000126
Sanjoy Dasa0992682016-05-26 00:09:02 +0000127 static void
128 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
129 SmallVectorImpl<InductiveRangeCheck> &Checks,
130 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000131
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000132public:
133 const SCEV *getOffset() const { return Offset; }
134 const SCEV *getScale() const { return Scale; }
135 Value *getLength() const { return Length; }
136
137 void print(raw_ostream &OS) const {
138 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000139 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000140 OS << " Offset: ";
141 Offset->print(OS);
142 OS << " Scale: ";
143 Scale->print(OS);
144 OS << " Length: ";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000145 if (Length)
146 Length->print(OS);
147 else
148 OS << "(null)";
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000149 OS << "\n CheckUse: ";
150 getCheckUse()->getUser()->print(OS);
151 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000152 }
153
Davide Italianod1279df2016-08-18 15:55:49 +0000154 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155 void dump() {
156 print(dbgs());
157 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000158
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000159 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000160
Sanjoy Das351db052015-01-22 09:32:02 +0000161 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
162 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
163
164 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000165 const SCEV *Begin;
166 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000167
168 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000169 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000170 assert(Begin->getType() == End->getType() && "ill-typed range!");
171 }
172
173 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000174 const SCEV *getBegin() const { return Begin; }
175 const SCEV *getEnd() const { return End; }
Sanjoy Das351db052015-01-22 09:32:02 +0000176 };
177
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000178 /// This is the value the condition of the branch needs to evaluate to for the
179 /// branch to take the hot successor (see (1) above).
180 bool getPassingDirection() { return true; }
181
Sanjoy Das95c476d2015-02-21 22:20:22 +0000182 /// Computes a range for the induction variable (IndVar) in which the range
183 /// check is redundant and can be constant-folded away. The induction
184 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000185 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Sanjoy Das59776732016-05-21 02:31:51 +0000186 const SCEVAddRecExpr *IndVar) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000187
Sanjoy Dasa0992682016-05-26 00:09:02 +0000188 /// Parse out a set of inductive range checks from \p BI and append them to \p
189 /// Checks.
190 ///
191 /// NB! There may be conditions feeding into \p BI that aren't inductive range
192 /// checks, and hence don't end up in \p Checks.
193 static void
194 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
195 BranchProbabilityInfo &BPI,
196 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000197};
198
199class InductiveRangeCheckElimination : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000200public:
201 static char ID;
202 InductiveRangeCheckElimination() : LoopPass(ID) {
203 initializeInductiveRangeCheckEliminationPass(
204 *PassRegistry::getPassRegistry());
205 }
206
207 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000208 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000209 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000210 }
211
212 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
213};
214
215char InductiveRangeCheckElimination::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000216}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000217
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000218INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
219 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000220INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000221INITIALIZE_PASS_DEPENDENCY(LoopPass)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000222INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
223 "Inductive range check elimination", false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000224
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000225StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000226 InductiveRangeCheck::RangeCheckKind RCK) {
227 switch (RCK) {
228 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
229 return "RANGE_CHECK_UNKNOWN";
230
231 case InductiveRangeCheck::RANGE_CHECK_UPPER:
232 return "RANGE_CHECK_UPPER";
233
234 case InductiveRangeCheck::RANGE_CHECK_LOWER:
235 return "RANGE_CHECK_LOWER";
236
237 case InductiveRangeCheck::RANGE_CHECK_BOTH:
238 return "RANGE_CHECK_BOTH";
239 }
240
241 llvm_unreachable("unknown range check type!");
242}
243
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000244/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000245/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000246/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000247/// range checked, and set `Length` to the upper limit `Index` is being range
248/// checked with if (and only if) the range check type is stronger or equal to
249/// RANGE_CHECK_UPPER.
250///
251InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000252InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
253 ScalarEvolution &SE, Value *&Index,
254 Value *&Length) {
255
256 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
257 const SCEV *S = SE.getSCEV(V);
258 if (isa<SCEVCouldNotCompute>(S))
259 return false;
260
261 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
262 SE.isKnownNonNegative(S);
263 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000264
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000265 using namespace llvm::PatternMatch;
266
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000267 ICmpInst::Predicate Pred = ICI->getPredicate();
268 Value *LHS = ICI->getOperand(0);
269 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000270
271 switch (Pred) {
272 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000273 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000274
275 case ICmpInst::ICMP_SLE:
276 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000277 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000278 case ICmpInst::ICMP_SGE:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000279 if (match(RHS, m_ConstantInt<0>())) {
280 Index = LHS;
281 return RANGE_CHECK_LOWER;
282 }
283 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000284
285 case ICmpInst::ICMP_SLT:
286 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000287 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000288 case ICmpInst::ICMP_SGT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000289 if (match(RHS, m_ConstantInt<-1>())) {
290 Index = LHS;
291 return RANGE_CHECK_LOWER;
292 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000293
Sanjoy Das337d46b2015-03-24 19:29:18 +0000294 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000295 Index = RHS;
296 Length = LHS;
297 return RANGE_CHECK_UPPER;
298 }
299 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000300
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000302 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000303 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000304 case ICmpInst::ICMP_UGT:
Sanjoy Das337d46b2015-03-24 19:29:18 +0000305 if (IsNonNegativeAndNotLoopVarying(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306 Index = RHS;
307 Length = LHS;
308 return RANGE_CHECK_BOTH;
309 }
310 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000311 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000312
313 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000314}
315
Sanjoy Dasa0992682016-05-26 00:09:02 +0000316void InductiveRangeCheck::extractRangeChecksFromCond(
317 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
318 SmallVectorImpl<InductiveRangeCheck> &Checks,
319 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000320 using namespace llvm::PatternMatch;
321
Sanjoy Das8fe88922016-05-26 00:08:24 +0000322 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000323 if (!Visited.insert(Condition).second)
324 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000325
Sanjoy Dasa0992682016-05-26 00:09:02 +0000326 if (match(Condition, m_And(m_Value(), m_Value()))) {
327 SmallVector<InductiveRangeCheck, 8> SubChecks;
328 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
329 SubChecks, Visited);
330 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
331 SubChecks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000332
Sanjoy Dasa0992682016-05-26 00:09:02 +0000333 if (SubChecks.size() == 2) {
334 // Handle a special case where we know how to merge two checks separately
335 // checking the upper and lower bounds into a full range check.
336 const auto &RChkA = SubChecks[0];
337 const auto &RChkB = SubChecks[1];
338 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
339 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000340
Sanjoy Dasa0992682016-05-26 00:09:02 +0000341 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
342 // But if one of them is a RANGE_CHECK_LOWER and the other is a
343 // RANGE_CHECK_UPPER (only possibility if they're different) then
344 // together they form a RANGE_CHECK_BOTH.
345 SubChecks[0].Kind =
346 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
347 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
348 SubChecks[0].CheckUse = &ConditionUse;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000349
Sanjoy Dasa0992682016-05-26 00:09:02 +0000350 // We updated one of the checks in place, now erase the other.
351 SubChecks.pop_back();
352 }
353 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354
Sanjoy Dasa0992682016-05-26 00:09:02 +0000355 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
356 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000357 }
358
Sanjoy Dasa0992682016-05-26 00:09:02 +0000359 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
360 if (!ICI)
361 return;
362
363 Value *Length = nullptr, *Index;
364 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
365 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
366 return;
367
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000368 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000369 bool IsAffineIndex =
370 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
371
372 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000373 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000374
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000375 InductiveRangeCheck IRC;
376 IRC.Length = Length;
377 IRC.Offset = IndexAddRec->getStart();
378 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000379 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000380 IRC.Kind = RCKind;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000381 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000382}
383
Sanjoy Dasa0992682016-05-26 00:09:02 +0000384void InductiveRangeCheck::extractRangeChecksFromBranch(
385 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
386 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000387
388 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000389 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000390
391 BranchProbability LikelyTaken(15, 16);
392
Sanjoy Dasbb969792016-07-22 00:40:56 +0000393 if (!SkipProfitabilityChecks &&
394 BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000396
Sanjoy Dasa0992682016-05-26 00:09:02 +0000397 SmallPtrSet<Value *, 8> Visited;
398 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
399 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000400}
401
Anna Thomas65ca8e92016-12-13 21:05:21 +0000402// Add metadata to the loop L to disable loop optimizations. Callers need to
403// confirm that optimizing loop L is not beneficial.
404static void DisableAllLoopOptsOnLoop(Loop &L) {
405 // We do not care about any existing loopID related metadata for L, since we
406 // are setting all loop metadata to false.
407 LLVMContext &Context = L.getHeader()->getContext();
408 // Reserve first location for self reference to the LoopID metadata node.
409 MDNode *Dummy = MDNode::get(Context, {});
410 MDNode *DisableUnroll = MDNode::get(
411 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
412 Metadata *FalseVal =
413 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
414 MDNode *DisableVectorize = MDNode::get(
415 Context,
416 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
417 MDNode *DisableLICMVersioning = MDNode::get(
418 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
419 MDNode *DisableDistribution= MDNode::get(
420 Context,
421 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
422 MDNode *NewLoopID =
423 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
424 DisableLICMVersioning, DisableDistribution});
425 // Set operand 0 to refer to the loop id itself.
426 NewLoopID->replaceOperandWith(0, NewLoopID);
427 L.setLoopID(NewLoopID);
428}
429
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000430namespace {
431
Sanjoy Dase75ed922015-02-26 08:19:31 +0000432// Keeps track of the structure of a loop. This is similar to llvm::Loop,
433// except that it is more lightweight and can track the state of a loop through
434// changing and potentially invalid IR. This structure also formalizes the
435// kinds of loops we can deal with -- ones that have a single latch that is also
436// an exiting block *and* have a canonical induction variable.
437struct LoopStructure {
438 const char *Tag;
439
440 BasicBlock *Header;
441 BasicBlock *Latch;
442
443 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
444 // successor is `LatchExit', the exit block of the loop.
445 BranchInst *LatchBr;
446 BasicBlock *LatchExit;
447 unsigned LatchBrExitIdx;
448
Sanjoy Dasec892132017-02-07 23:59:07 +0000449 // The loop represented by this instance of LoopStructure is semantically
450 // equivalent to:
451 //
452 // intN_ty inc = IndVarIncreasing ? 1 : -1;
453 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
454 //
455 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarNext)
456 // ... body ...
457
Sanjoy Dase75ed922015-02-26 08:19:31 +0000458 Value *IndVarNext;
459 Value *IndVarStart;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000460 Value *IndVarStep;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000461 Value *LoopExitAt;
462 bool IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000463 bool IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000464
465 LoopStructure()
466 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
467 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000468 IndVarStart(nullptr), IndVarStep(nullptr), LoopExitAt(nullptr),
469 IndVarIncreasing(false), IsSignedPredicate(true) {}
Sanjoy Dase75ed922015-02-26 08:19:31 +0000470
471 template <typename M> LoopStructure map(M Map) const {
472 LoopStructure Result;
473 Result.Tag = Tag;
474 Result.Header = cast<BasicBlock>(Map(Header));
475 Result.Latch = cast<BasicBlock>(Map(Latch));
476 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
477 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
478 Result.LatchBrExitIdx = LatchBrExitIdx;
479 Result.IndVarNext = Map(IndVarNext);
480 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000481 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000482 Result.LoopExitAt = Map(LoopExitAt);
483 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000484 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000485 return Result;
486 }
487
Sanjoy Dase91665d2015-02-26 08:56:04 +0000488 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
489 BranchProbabilityInfo &BPI,
490 Loop &,
Sanjoy Dase75ed922015-02-26 08:19:31 +0000491 const char *&);
492};
493
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000494/// This class is used to constrain loops to run within a given iteration space.
495/// The algorithm this class implements is given a Loop and a range [Begin,
496/// End). The algorithm then tries to break out a "main loop" out of the loop
497/// it is given in a way that the "main loop" runs with the induction variable
498/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
499/// loops to run any remaining iterations. The pre loop runs any iterations in
500/// which the induction variable is < Begin, and the post loop runs any
501/// iterations in which the induction variable is >= End.
502///
503class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000504 // The representation of a clone of the original loop we started out with.
505 struct ClonedLoop {
506 // The cloned blocks
507 std::vector<BasicBlock *> Blocks;
508
509 // `Map` maps values in the clonee into values in the cloned version
510 ValueToValueMapTy Map;
511
512 // An instance of `LoopStructure` for the cloned loop
513 LoopStructure Structure;
514 };
515
516 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
517 // more details on what these fields mean.
518 struct RewrittenRangeInfo {
519 BasicBlock *PseudoExit;
520 BasicBlock *ExitSelector;
521 std::vector<PHINode *> PHIValuesAtPseudoExit;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000522 PHINode *IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000523
Sanjoy Dase75ed922015-02-26 08:19:31 +0000524 RewrittenRangeInfo()
525 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000526 };
527
528 // Calculated subranges we restrict the iteration space of the main loop to.
529 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000530 // these fields are computed. `LowLimit` is None if there is no restriction
531 // on low end of the restricted iteration space of the main loop. `HighLimit`
532 // is None if there is no restriction on high end of the restricted iteration
533 // space of the main loop.
534
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000535 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000536 Optional<const SCEV *> LowLimit;
537 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000538 };
539
540 // A utility function that does a `replaceUsesOfWith' on the incoming block
541 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
542 // incoming block list with `ReplaceBy'.
543 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
544 BasicBlock *ReplaceBy);
545
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000546 // Compute a safe set of limits for the main loop to run in -- effectively the
547 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000548 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000549 //
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000550 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000551
552 // Clone `OriginalLoop' and return the result in CLResult. The IR after
553 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
554 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
555 // but there is no such edge.
556 //
557 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
558
Sanjoy Das21434472016-08-14 01:04:46 +0000559 // Create the appropriate loop structure needed to describe a cloned copy of
560 // `Original`. The clone is described by `VM`.
561 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
562 ValueToValueMapTy &VM);
563
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000564 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
565 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
566 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
567 // `OriginalHeaderCount'.
568 //
569 // If there are iterations left to execute, control is made to jump to
570 // `ContinuationBlock', otherwise they take the normal loop exit. The
571 // returned `RewrittenRangeInfo' object is populated as follows:
572 //
573 // .PseudoExit is a basic block that unconditionally branches to
574 // `ContinuationBlock'.
575 //
576 // .ExitSelector is a basic block that decides, on exit from the loop,
577 // whether to branch to the "true" exit or to `PseudoExit'.
578 //
579 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
580 // for each PHINode in the loop header on taking the pseudo exit.
581 //
582 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
583 // preheader because it is made to branch to the loop header only
584 // conditionally.
585 //
586 RewrittenRangeInfo
587 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
588 Value *ExitLoopAt,
589 BasicBlock *ContinuationBlock) const;
590
591 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
592 // function creates a new preheader for `LS' and returns it.
593 //
Sanjoy Dase75ed922015-02-26 08:19:31 +0000594 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
595 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000596
597 // `ContinuationBlockAndPreheader' was the continuation block for some call to
598 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
599 // This function rewrites the PHI nodes in `LS.Header' to start with the
600 // correct value.
601 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000602 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000603 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
604
605 // Even though we do not preserve any passes at this time, we at least need to
606 // keep the parent loop structure consistent. The `LPPassManager' seems to
607 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000608 // blocks denoted by BBs to this loops parent loop if required.
609 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000610
611 // Some global state.
612 Function &F;
613 LLVMContext &Ctx;
614 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000615 DominatorTree &DT;
Sanjoy Das21434472016-08-14 01:04:46 +0000616 LPPassManager &LPM;
Sanjoy Das35459f02016-08-14 01:04:50 +0000617 LoopInfo &LI;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000618
619 // Information about the original loop we started out with.
620 Loop &OriginalLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621 const SCEV *LatchTakenCount;
622 BasicBlock *OriginalPreheader;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000623
624 // The preheader of the main loop. This may or may not be different from
625 // `OriginalPreheader'.
626 BasicBlock *MainLoopPreheader;
627
628 // The range we need to run the main loop in.
629 InductiveRangeCheck::Range Range;
630
631 // The structure of the main loop (see comment at the beginning of this class
632 // for a definition)
633 LoopStructure MainLoopStructure;
634
635public:
Sanjoy Das21434472016-08-14 01:04:46 +0000636 LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
637 const LoopStructure &LS, ScalarEvolution &SE,
638 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000639 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Sanjoy Das35459f02016-08-14 01:04:50 +0000640 SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L),
Sanjoy Das21434472016-08-14 01:04:46 +0000641 LatchTakenCount(nullptr), OriginalPreheader(nullptr),
642 MainLoopPreheader(nullptr), Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000643
644 // Entry point for the algorithm. Returns true on success.
645 bool run();
646};
647
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000648}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000649
650void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
651 BasicBlock *ReplaceBy) {
652 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
653 if (PN->getIncomingBlock(i) == Block)
654 PN->setIncomingBlock(i, ReplaceBy);
655}
656
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000657static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
658 APInt Max = Signed ?
659 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
660 APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
661 return SE.getSignedRange(S).contains(Max) &&
662 SE.getUnsignedRange(S).contains(Max);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000663}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000664
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000665static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
666 bool Signed) {
667 // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
668 assert(SE.isKnownNonNegative(S2) &&
669 "We expected the 2nd arg to be non-negative!");
670 const SCEV *Max = SE.getConstant(
671 Signed ? APInt::getSignedMaxValue(
672 cast<IntegerType>(S1->getType())->getBitWidth())
673 : APInt::getMaxValue(
674 cast<IntegerType>(S1->getType())->getBitWidth()));
675 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
676 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
677 S1, CapForS1);
678}
679
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000680static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
681 APInt Min = Signed ?
682 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
683 APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
684 return SE.getSignedRange(S).contains(Min) &&
685 SE.getUnsignedRange(S).contains(Min);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000686}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000687
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000688static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
689 bool Signed) {
690 // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
691 assert(SE.isKnownNonPositive(S2) &&
692 "We expected the 2nd arg to be non-positive!");
693 const SCEV *Max = SE.getConstant(
694 Signed ? APInt::getSignedMinValue(
695 cast<IntegerType>(S1->getType())->getBitWidth())
696 : APInt::getMinValue(
697 cast<IntegerType>(S1->getType())->getBitWidth()));
698 const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
699 return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
700 S1, CapForS1);
701}
702
Sanjoy Dase75ed922015-02-26 08:19:31 +0000703Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000704LoopStructure::parseLoopStructure(ScalarEvolution &SE,
705 BranchProbabilityInfo &BPI,
Sanjoy Dase91665d2015-02-26 08:56:04 +0000706 Loop &L, const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000707 if (!L.isLoopSimplifyForm()) {
708 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000709 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000710 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000711
712 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000713 assert(Latch && "Simplified loops only have one latch!");
714
Sanjoy Das7a18a232016-08-14 01:04:36 +0000715 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
716 FailureReason = "loop has already been cloned";
717 return None;
718 }
719
Sanjoy Dase75ed922015-02-26 08:19:31 +0000720 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000721 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000722 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000723 }
724
Sanjoy Dase75ed922015-02-26 08:19:31 +0000725 BasicBlock *Header = L.getHeader();
726 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000727 if (!Preheader) {
728 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000729 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000730 }
731
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000732 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000733 if (!LatchBr || LatchBr->isUnconditional()) {
734 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000735 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000736 }
737
Sanjoy Dase75ed922015-02-26 08:19:31 +0000738 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000739
Sanjoy Dase91665d2015-02-26 08:56:04 +0000740 BranchProbability ExitProbability =
741 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
742
Sanjoy Dasbb969792016-07-22 00:40:56 +0000743 if (!SkipProfitabilityChecks &&
744 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000745 FailureReason = "short running loop, not profitable";
746 return None;
747 }
748
Sanjoy Dase75ed922015-02-26 08:19:31 +0000749 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
750 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
751 FailureReason = "latch terminator branch not conditional on integral icmp";
752 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000753 }
754
Sanjoy Dase75ed922015-02-26 08:19:31 +0000755 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
756 if (isa<SCEVCouldNotCompute>(LatchCount)) {
757 FailureReason = "could not compute latch count";
758 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000759 }
760
Sanjoy Dase75ed922015-02-26 08:19:31 +0000761 ICmpInst::Predicate Pred = ICI->getPredicate();
762 Value *LeftValue = ICI->getOperand(0);
763 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
764 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
765
766 Value *RightValue = ICI->getOperand(1);
767 const SCEV *RightSCEV = SE.getSCEV(RightValue);
768
769 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
770 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
771 if (isa<SCEVAddRecExpr>(RightSCEV)) {
772 std::swap(LeftSCEV, RightSCEV);
773 std::swap(LeftValue, RightValue);
774 Pred = ICmpInst::getSwappedPredicate(Pred);
775 } else {
776 FailureReason = "no add recurrences in the icmp";
777 return None;
778 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000779 }
780
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000781 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
782 if (AR->getNoWrapFlags(SCEV::FlagNSW))
783 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000784
785 IntegerType *Ty = cast<IntegerType>(AR->getType());
786 IntegerType *WideTy =
787 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
788
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000789 const SCEVAddRecExpr *ExtendAfterOp =
790 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
791 if (ExtendAfterOp) {
792 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
793 const SCEV *ExtendedStep =
794 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
795
796 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
797 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
798
799 if (NoSignedWrap)
800 return true;
801 }
802
803 // We may have proved this when computing the sign extension above.
804 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
805 };
806
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000807 // Here we check whether the suggested AddRec is an induction variable that
808 // can be handled (i.e. with known constant step), and if yes, calculate its
809 // step and identify whether it is increasing or decreasing.
810 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
811 ConstantInt *&StepCI) {
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000812 if (!AR->isAffine())
813 return false;
814
Sanjoy Dase75ed922015-02-26 08:19:31 +0000815 // Currently we only work with induction variables that have been proved to
816 // not wrap. This restriction can potentially be lifted in the future.
817
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000818 if (!HasNoSignedWrap(AR))
Sanjoy Dase75ed922015-02-26 08:19:31 +0000819 return false;
820
821 if (const SCEVConstant *StepExpr =
822 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000823 StepCI = StepExpr->getValue();
Max Kazantsev85da7542017-08-01 06:27:51 +0000824 assert(!StepCI->isZero() && "Zero step?");
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000825 IsIncreasing = !StepCI->isNegative();
826 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000827 }
828
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000829 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000830 };
831
832 // `ICI` is interpreted as taking the backedge if the *next* value of the
833 // induction variable satisfies some constraint.
834
835 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
836 bool IsIncreasing = false;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000837 bool IsSignedPredicate = true;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000838 ConstantInt *StepCI;
839 if (!IsInductionVar(IndVarNext, IsIncreasing, StepCI)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000840 FailureReason = "LHS in icmp not induction variable";
841 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000842 }
843
Sanjoy Dasec892132017-02-07 23:59:07 +0000844 const SCEV *StartNext = IndVarNext->getStart();
845 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
846 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000847 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000848
Sanjoy Dase75ed922015-02-26 08:19:31 +0000849 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000850 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000851 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000852 if (StepCI->isOne()) {
853 // Try to turn eq/ne predicates to those we can work with.
854 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
855 // while (++i != len) { while (++i < len) {
856 // ... ---> ...
857 // } }
858 // If both parts are known non-negative, it is profitable to use
859 // unsigned comparison in increasing loop. This allows us to make the
860 // comparison check against "RightSCEV + 1" more optimistic.
861 if (SE.isKnownNonNegative(IndVarStart) &&
862 SE.isKnownNonNegative(RightSCEV))
863 Pred = ICmpInst::ICMP_ULT;
864 else
865 Pred = ICmpInst::ICMP_SLT;
866 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
867 !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
868 // while (true) { while (true) {
869 // if (++i == len) ---> if (++i > len - 1)
870 // break; break;
871 // ... ...
872 // } }
873 // TODO: Insert ICMP_UGT if both are non-negative?
874 Pred = ICmpInst::ICMP_SGT;
875 RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
876 DecreasedRightValueByOne = true;
877 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000878 }
879
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000880 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
881 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000882 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000883 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000884
885 if (!FoundExpectedPred) {
886 FailureReason = "expected icmp slt semantically, found something else";
887 return None;
888 }
889
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000890 IsSignedPredicate =
891 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
892 // The predicate that we need to check that the induction variable lies
893 // within bounds.
894 ICmpInst::Predicate BoundPred =
895 IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
896
Sanjoy Dase75ed922015-02-26 08:19:31 +0000897 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000898 const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
899 SE.getOne(Step->getType()));
900 if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000901 // TODO: this restriction is easily removable -- we just have to
902 // remember that the icmp was an slt and not an sle.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000903 FailureReason = "limit may overflow when coercing le to lt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000904 return None;
905 }
906
Sanjoy Dasec892132017-02-07 23:59:07 +0000907 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000908 &L, BoundPred, IndVarStart,
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000909 SE.getAddExpr(RightSCEV, Step))) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000910 FailureReason = "Induction variable start not bounded by upper limit";
911 return None;
912 }
913
Max Kazantsev2c627a92017-07-18 04:53:48 +0000914 // We need to increase the right value unless we have already decreased
915 // it virtually when we replaced EQ with SGT.
916 if (!DecreasedRightValueByOne) {
917 IRBuilder<> B(Preheader->getTerminator());
918 RightValue = B.CreateAdd(RightValue, One);
919 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000920 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000921 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000922 FailureReason = "Induction variable start not bounded by upper limit";
923 return None;
924 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000925 assert(!DecreasedRightValueByOne &&
926 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000927 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000928 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000929 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000930 if (StepCI->isMinusOne()) {
931 // Try to turn eq/ne predicates to those we can work with.
932 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
933 // while (--i != len) { while (--i > len) {
934 // ... ---> ...
935 // } }
936 // We intentionally don't turn the predicate into UGT even if we know
937 // that both operands are non-negative, because it will only pessimize
938 // our check against "RightSCEV - 1".
939 Pred = ICmpInst::ICMP_SGT;
940 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
941 !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
942 // while (true) { while (true) {
943 // if (--i == len) ---> if (--i < len + 1)
944 // break; break;
945 // ... ...
946 // } }
947 // TODO: Insert ICMP_ULT if both are non-negative?
948 Pred = ICmpInst::ICMP_SLT;
949 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
950 IncreasedRightValueByOne = true;
951 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000952 }
953
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000954 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
955 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
956
Sanjoy Dase75ed922015-02-26 08:19:31 +0000957 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000958 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000959
960 if (!FoundExpectedPred) {
961 FailureReason = "expected icmp sgt semantically, found something else";
962 return None;
963 }
964
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000965 IsSignedPredicate =
966 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
967 // The predicate that we need to check that the induction variable lies
968 // within bounds.
969 ICmpInst::Predicate BoundPred =
970 IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
971
Sanjoy Dase75ed922015-02-26 08:19:31 +0000972 if (LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000973 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
974 if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000975 // TODO: this restriction is easily removable -- we just have to
976 // remember that the icmp was an sgt and not an sge.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000977 FailureReason = "limit may overflow when coercing ge to gt";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000978 return None;
979 }
980
Sanjoy Dasec892132017-02-07 23:59:07 +0000981 if (!SE.isLoopEntryGuardedByCond(
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000982 &L, BoundPred, IndVarStart,
Sanjoy Dasec892132017-02-07 23:59:07 +0000983 SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
984 FailureReason = "Induction variable start not bounded by lower limit";
985 return None;
986 }
987
Max Kazantsev2c627a92017-07-18 04:53:48 +0000988 // We need to decrease the right value unless we have already increased
989 // it virtually when we replaced EQ with SLT.
990 if (!IncreasedRightValueByOne) {
991 IRBuilder<> B(Preheader->getTerminator());
992 RightValue = B.CreateSub(RightValue, One);
993 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000994 } else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000995 if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
Sanjoy Dasec892132017-02-07 23:59:07 +0000996 FailureReason = "Induction variable start not bounded by lower limit";
997 return None;
998 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000999 assert(!IncreasedRightValueByOne &&
1000 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001001 }
1002 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001003 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1004
Sanjoy Dase75ed922015-02-26 08:19:31 +00001005 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001006 ScalarEvolution::LoopInvariant &&
1007 "loop variant exit count doesn't make sense!");
1008
Sanjoy Dase75ed922015-02-26 08:19:31 +00001009 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001010 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1011 Value *IndVarStartV =
1012 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001013 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001014 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001015
Sanjoy Dase75ed922015-02-26 08:19:31 +00001016 LoopStructure Result;
1017
1018 Result.Tag = "main";
1019 Result.Header = Header;
1020 Result.Latch = Latch;
1021 Result.LatchBr = LatchBr;
1022 Result.LatchExit = LatchExit;
1023 Result.LatchBrExitIdx = LatchBrExitIdx;
1024 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001025 Result.IndVarStep = StepCI;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001026 Result.IndVarNext = LeftValue;
1027 Result.IndVarIncreasing = IsIncreasing;
1028 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001029 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001030
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001031 FailureReason = nullptr;
1032
Sanjoy Dase75ed922015-02-26 08:19:31 +00001033 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001034}
1035
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001036Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001037LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001038 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1039
Sanjoy Das351db052015-01-22 09:32:02 +00001040 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001041 return None;
1042
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001043 LoopConstrainer::SubRanges Result;
1044
1045 // I think we can be more aggressive here and make this nuw / nsw if the
1046 // addition that feeds into the icmp for the latch's terminating branch is nuw
1047 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001048 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1049 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001050
Sanjoy Dase75ed922015-02-26 08:19:31 +00001051 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001052
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001053 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1054 // [Smallest, GreatestSeen] is the range of values the induction variable
1055 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001056
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001057 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001058
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001059 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001060 if (Increasing) {
1061 Smallest = Start;
1062 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001063 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1064 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001065 } else {
1066 // These two computations may sign-overflow. Here is why that is okay:
1067 //
1068 // We know that the induction variable does not sign-overflow on any
1069 // iteration except the last one, and it starts at `Start` and ends at
1070 // `End`, decrementing by one every time.
1071 //
1072 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1073 // induction variable is decreasing we know that that the smallest value
1074 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1075 //
1076 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1077 // that case, `Clamp` will always return `Smallest` and
1078 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1079 // will be an empty range. Returning an empty range is always safe.
1080 //
1081
Max Kazantsev6c466a32017-06-28 04:57:45 +00001082 Smallest = SE.getAddExpr(End, One);
1083 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001084 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001085 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001086
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001087 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
1088 return IsSignedPredicate
1089 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1090 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001091 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001092
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001093 // In some cases we can prove that we don't need a pre or post loop.
1094 ICmpInst::Predicate PredLE =
1095 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1096 ICmpInst::Predicate PredLT =
1097 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001098
1099 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001100 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001101 if (!ProvablyNoPreloop)
1102 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001103
1104 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001105 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001106 if (!ProvablyNoPostLoop)
1107 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001108
1109 return Result;
1110}
1111
1112void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1113 const char *Tag) const {
1114 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1115 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1116 Result.Blocks.push_back(Clone);
1117 Result.Map[BB] = Clone;
1118 }
1119
1120 auto GetClonedValue = [&Result](Value *V) {
1121 assert(V && "null values not in domain!");
1122 auto It = Result.Map.find(V);
1123 if (It == Result.Map.end())
1124 return V;
1125 return static_cast<Value *>(It->second);
1126 };
1127
Sanjoy Das7a18a232016-08-14 01:04:36 +00001128 auto *ClonedLatch =
1129 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1130 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1131 MDNode::get(Ctx, {}));
1132
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001133 Result.Structure = MainLoopStructure.map(GetClonedValue);
1134 Result.Structure.Tag = Tag;
1135
1136 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1137 BasicBlock *ClonedBB = Result.Blocks[i];
1138 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1139
1140 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1141
1142 for (Instruction &I : *ClonedBB)
1143 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001144 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001145
1146 // Exit blocks will now have one more predecessor and their PHI nodes need
1147 // to be edited to reflect that. No phi nodes need to be introduced because
1148 // the loop is in LCSSA.
1149
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001150 for (auto *SBB : successors(OriginalBB)) {
1151 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001152 continue; // not an exit block
1153
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001154 for (Instruction &I : *SBB) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001155 auto *PN = dyn_cast<PHINode>(&I);
1156 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001157 break;
1158
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001159 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1160 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1161 }
1162 }
1163 }
1164}
1165
1166LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001167 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168 BasicBlock *ContinuationBlock) const {
1169
1170 // We start with a loop with a single latch:
1171 //
1172 // +--------------------+
1173 // | |
1174 // | preheader |
1175 // | |
1176 // +--------+-----------+
1177 // | ----------------\
1178 // | / |
1179 // +--------v----v------+ |
1180 // | | |
1181 // | header | |
1182 // | | |
1183 // +--------------------+ |
1184 // |
1185 // ..... |
1186 // |
1187 // +--------------------+ |
1188 // | | |
1189 // | latch >----------/
1190 // | |
1191 // +-------v------------+
1192 // |
1193 // |
1194 // | +--------------------+
1195 // | | |
1196 // +---> original exit |
1197 // | |
1198 // +--------------------+
1199 //
1200 // We change the control flow to look like
1201 //
1202 //
1203 // +--------------------+
1204 // | |
1205 // | preheader >-------------------------+
1206 // | | |
1207 // +--------v-----------+ |
1208 // | /-------------+ |
1209 // | / | |
1210 // +--------v--v--------+ | |
1211 // | | | |
1212 // | header | | +--------+ |
1213 // | | | | | |
1214 // +--------------------+ | | +-----v-----v-----------+
1215 // | | | |
1216 // | | | .pseudo.exit |
1217 // | | | |
1218 // | | +-----------v-----------+
1219 // | | |
1220 // ..... | | |
1221 // | | +--------v-------------+
1222 // +--------------------+ | | | |
1223 // | | | | | ContinuationBlock |
1224 // | latch >------+ | | |
1225 // | | | +----------------------+
1226 // +---------v----------+ |
1227 // | |
1228 // | |
1229 // | +---------------^-----+
1230 // | | |
1231 // +-----> .exit.selector |
1232 // | |
1233 // +----------v----------+
1234 // |
1235 // +--------------------+ |
1236 // | | |
1237 // | original exit <----+
1238 // | |
1239 // +--------------------+
1240 //
1241
1242 RewrittenRangeInfo RRI;
1243
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001244 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001245 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001246 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001247 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001248 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001249
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001250 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001251 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001252 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001253
1254 IRBuilder<> B(PreheaderJump);
1255
1256 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001257 Value *EnterLoopCond = nullptr;
1258 if (Increasing)
1259 EnterLoopCond = IsSignedPredicate
1260 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1261 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1262 else
1263 EnterLoopCond = IsSignedPredicate
1264 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1265 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001266
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001267 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1268 PreheaderJump->eraseFromParent();
1269
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001270 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001271 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001272 Value *TakeBackedgeLoopCond = nullptr;
1273 if (Increasing)
1274 TakeBackedgeLoopCond = IsSignedPredicate
1275 ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1276 : B.CreateICmpULT(LS.IndVarNext, ExitSubloopAt);
1277 else
1278 TakeBackedgeLoopCond = IsSignedPredicate
1279 ? B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt)
1280 : B.CreateICmpUGT(LS.IndVarNext, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001281 Value *CondForBranch = LS.LatchBrExitIdx == 1
1282 ? TakeBackedgeLoopCond
1283 : B.CreateNot(TakeBackedgeLoopCond);
1284
1285 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001286
1287 B.SetInsertPoint(RRI.ExitSelector);
1288
1289 // IterationsLeft - are there any more iterations left, given the original
1290 // upper bound on the induction variable? If not, we branch to the "real"
1291 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001292 Value *IterationsLeft = nullptr;
1293 if (Increasing)
1294 IterationsLeft = IsSignedPredicate
1295 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1296 : B.CreateICmpULT(LS.IndVarNext, LS.LoopExitAt);
1297 else
1298 IterationsLeft = IsSignedPredicate
1299 ? B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt)
1300 : B.CreateICmpUGT(LS.IndVarNext, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001301 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1302
1303 BranchInst *BranchToContinuation =
1304 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1305
1306 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1307 // each of the PHI nodes in the loop header. This feeds into the initial
1308 // value of the same PHI nodes if/when we continue execution.
1309 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001310 auto *PN = dyn_cast<PHINode>(&I);
1311 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001312 break;
1313
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001314 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1315 BranchToContinuation);
1316
1317 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1318 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1319 RRI.ExitSelector);
1320 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1321 }
1322
Sanjoy Dase75ed922015-02-26 08:19:31 +00001323 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1324 BranchToContinuation);
1325 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1326 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1327
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001328 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1329 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1330 for (Instruction &I : *LS.LatchExit) {
1331 if (PHINode *PN = dyn_cast<PHINode>(&I))
1332 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1333 else
1334 break;
1335 }
1336
1337 return RRI;
1338}
1339
1340void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001341 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001342 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1343
1344 unsigned PHIIndex = 0;
1345 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001346 auto *PN = dyn_cast<PHINode>(&I);
1347 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001348 break;
1349
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001350 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1351 if (PN->getIncomingBlock(i) == ContinuationBlock)
1352 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1353 }
1354
Sanjoy Dase75ed922015-02-26 08:19:31 +00001355 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001356}
1357
Sanjoy Dase75ed922015-02-26 08:19:31 +00001358BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1359 BasicBlock *OldPreheader,
1360 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001361
1362 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1363 BranchInst::Create(LS.Header, Preheader);
1364
1365 for (Instruction &I : *LS.Header) {
Sanjoy Dasf2b7baf2016-08-13 22:00:12 +00001366 auto *PN = dyn_cast<PHINode>(&I);
1367 if (!PN)
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001368 break;
1369
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001370 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1371 replacePHIBlock(PN, OldPreheader, Preheader);
1372 }
1373
1374 return Preheader;
1375}
1376
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001377void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001378 Loop *ParentLoop = OriginalLoop.getParentLoop();
1379 if (!ParentLoop)
1380 return;
1381
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001382 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001383 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001384}
1385
Sanjoy Das21434472016-08-14 01:04:46 +00001386Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1387 ValueToValueMapTy &VM) {
Chandler Carruth29c22d22017-05-25 03:01:31 +00001388 Loop &New = *new Loop();
1389 if (Parent)
1390 Parent->addChildLoop(&New);
1391 else
1392 LI.addTopLevelLoop(&New);
1393 LPM.addLoop(New);
Sanjoy Das21434472016-08-14 01:04:46 +00001394
1395 // Add all of the blocks in Original to the new loop.
1396 for (auto *BB : Original->blocks())
1397 if (LI.getLoopFor(BB) == Original)
1398 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1399
1400 // Add all of the subloops to the new loop.
1401 for (Loop *SubLoop : *Original)
1402 createClonedLoopStructure(SubLoop, &New, VM);
1403
1404 return &New;
1405}
1406
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001407bool LoopConstrainer::run() {
1408 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001409 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1410 Preheader = OriginalLoop.getLoopPreheader();
1411 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1412 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001413
1414 OriginalPreheader = Preheader;
1415 MainLoopPreheader = Preheader;
1416
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001417 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1418 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001419 if (!MaybeSR.hasValue()) {
1420 DEBUG(dbgs() << "irce: could not compute subranges\n");
1421 return false;
1422 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001423
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001424 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001425 bool Increasing = MainLoopStructure.IndVarIncreasing;
1426 IntegerType *IVTy =
1427 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1428
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001429 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001430 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001431
1432 // It would have been better to make `PreLoop' and `PostLoop'
1433 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1434 // constructor.
1435 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001436 bool NeedsPreLoop =
1437 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1438 bool NeedsPostLoop =
1439 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1440
1441 Value *ExitPreLoopAt = nullptr;
1442 Value *ExitMainLoopAt = nullptr;
1443 const SCEVConstant *MinusOneS =
1444 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1445
1446 if (NeedsPreLoop) {
1447 const SCEV *ExitPreLoopAtSCEV = nullptr;
1448
1449 if (Increasing)
1450 ExitPreLoopAtSCEV = *SR.LowLimit;
1451 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001452 if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001453 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1454 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1455 << "\n");
1456 return false;
1457 }
1458 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1459 }
1460
1461 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1462 ExitPreLoopAt->setName("exit.preloop.at");
1463 }
1464
1465 if (NeedsPostLoop) {
1466 const SCEV *ExitMainLoopAtSCEV = nullptr;
1467
1468 if (Increasing)
1469 ExitMainLoopAtSCEV = *SR.HighLimit;
1470 else {
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001471 if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
Sanjoy Dase75ed922015-02-26 08:19:31 +00001472 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1473 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1474 << "\n");
1475 return false;
1476 }
1477 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1478 }
1479
1480 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1481 ExitMainLoopAt->setName("exit.mainloop.at");
1482 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001483
1484 // We clone these ahead of time so that we don't have to deal with changing
1485 // and temporarily invalid IR as we transform the loops.
1486 if (NeedsPreLoop)
1487 cloneLoop(PreLoop, "preloop");
1488 if (NeedsPostLoop)
1489 cloneLoop(PostLoop, "postloop");
1490
1491 RewrittenRangeInfo PreLoopRRI;
1492
1493 if (NeedsPreLoop) {
1494 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1495 PreLoop.Structure.Header);
1496
1497 MainLoopPreheader =
1498 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001499 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1500 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001501 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1502 PreLoopRRI);
1503 }
1504
1505 BasicBlock *PostLoopPreheader = nullptr;
1506 RewrittenRangeInfo PostLoopRRI;
1507
1508 if (NeedsPostLoop) {
1509 PostLoopPreheader =
1510 createPreheader(PostLoop.Structure, Preheader, "postloop");
1511 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001512 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001513 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1514 PostLoopRRI);
1515 }
1516
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001517 BasicBlock *NewMainLoopPreheader =
1518 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1519 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1520 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1521 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001522
1523 // Some of the above may be nullptr, filter them out before passing to
1524 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001525 auto NewBlocksEnd =
1526 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001527
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001528 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001529
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001530 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001531
Anna Thomas72180322017-06-06 14:54:01 +00001532 // We need to first add all the pre and post loop blocks into the loop
1533 // structures (as part of createClonedLoopStructure), and then update the
1534 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1535 // LI when LoopSimplifyForm is generated.
1536 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001537 if (!PreLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001538 PreL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001539 &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001540 }
1541
1542 if (!PostLoop.Blocks.empty()) {
Anna Thomas72180322017-06-06 14:54:01 +00001543 PostL = createClonedLoopStructure(
Sanjoy Das21434472016-08-14 01:04:46 +00001544 &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
Sanjoy Das21434472016-08-14 01:04:46 +00001545 }
1546
Anna Thomas72180322017-06-06 14:54:01 +00001547 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1548 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1549 formLCSSARecursively(*L, DT, &LI, &SE);
1550 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1551 // Pre/post loops are slow paths, we do not need to perform any loop
1552 // optimizations on them.
1553 if (!IsOriginalLoop)
1554 DisableAllLoopOptsOnLoop(*L);
1555 };
1556 if (PreL)
1557 CanonicalizeLoop(PreL, false);
1558 if (PostL)
1559 CanonicalizeLoop(PostL, false);
1560 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001561
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001562 return true;
1563}
1564
Sanjoy Das95c476d2015-02-21 22:20:22 +00001565/// Computes and returns a range of values for the induction variable (IndVar)
1566/// in which the range check can be safely elided. If it cannot compute such a
1567/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001568Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001569InductiveRangeCheck::computeSafeIterationSpace(
1570 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001571 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1572 // variable, that may or may not exist as a real llvm::Value in the loop) and
1573 // this inductive range check is a range check on the "C + D * I" ("C" is
1574 // getOffset() and "D" is getScale()). We rewrite the value being range
1575 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001576 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001577 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001578 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001579 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1580 //
1581 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1582 // and subtractions are twos-complement wrapping and comparisons are signed.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001583 //
1584 // Proof:
1585 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001586 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1587 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1588 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1589 // overflown.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001590 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001591 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1592 // Hence 0 <= (IndVar + M) < L
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001593
Sanjoy Das95c476d2015-02-21 22:20:22 +00001594 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1595 // 127, IndVar = 126 and L = -2 in an i8 world.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001596
Sanjoy Das95c476d2015-02-21 22:20:22 +00001597 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001598 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001599
Sanjoy Das95c476d2015-02-21 22:20:22 +00001600 const SCEV *A = IndVar->getStart();
1601 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1602 if (!B)
1603 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001604 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001605
1606 const SCEV *C = getOffset();
1607 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1608 if (D != B)
1609 return None;
1610
1611 ConstantInt *ConstD = D->getValue();
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001612 assert(!ConstD->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001613
1614 const SCEV *M = SE.getMinusSCEV(C, A);
Sanjoy Das95c476d2015-02-21 22:20:22 +00001615 const SCEV *Begin = SE.getNegativeSCEV(M);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001616 const SCEV *UpperLimit = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001617
Sanjoy Dase2cde6f2015-03-17 00:42:13 +00001618 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1619 // We can potentially do much better here.
1620 if (Value *V = getLength()) {
1621 UpperLimit = SE.getSCEV(V);
1622 } else {
1623 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1624 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1625 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1626 }
1627
1628 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
Sanjoy Das351db052015-01-22 09:32:02 +00001629 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001630}
1631
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001632static Optional<InductiveRangeCheck::Range>
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001633IntersectRange(ScalarEvolution &SE,
1634 const Optional<InductiveRangeCheck::Range> &R1,
Sanjoy Das59776732016-05-21 02:31:51 +00001635 const InductiveRangeCheck::Range &R2) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001636 if (!R1.hasValue())
1637 return R2;
1638 auto &R1Value = R1.getValue();
1639
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001640 // TODO: we could widen the smaller range and have this work; but for now we
1641 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001642 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001643 return None;
1644
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001645 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1646 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1647
1648 return InductiveRangeCheck::Range(NewBegin, NewEnd);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001649}
1650
1651bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001652 if (skipLoop(L))
1653 return false;
1654
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001655 if (L->getBlocks().size() >= LoopSizeCutoff) {
1656 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1657 return false;
1658 }
1659
1660 BasicBlock *Preheader = L->getLoopPreheader();
1661 if (!Preheader) {
1662 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1663 return false;
1664 }
1665
1666 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001667 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001668 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Cong Houab23bfb2015-07-15 22:48:29 +00001669 BranchProbabilityInfo &BPI =
1670 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001671
1672 for (auto BBI : L->getBlocks())
1673 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001674 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1675 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001676
1677 if (RangeChecks.empty())
1678 return false;
1679
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001680 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1681 OS << "irce: looking at loop "; L->print(OS);
1682 OS << "irce: loop has " << RangeChecks.size()
1683 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001684 for (InductiveRangeCheck &IRC : RangeChecks)
1685 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001686 };
1687
1688 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1689
1690 if (PrintRangeChecks)
1691 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001692
Sanjoy Dase75ed922015-02-26 08:19:31 +00001693 const char *FailureReason = nullptr;
1694 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001695 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001696 if (!MaybeLoopStructure.hasValue()) {
1697 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1698 << "\n";);
1699 return false;
1700 }
1701 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001702 const SCEVAddRecExpr *IndVar =
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001703 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarNext), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001704
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001705 Optional<InductiveRangeCheck::Range> SafeIterRange;
1706 Instruction *ExprInsertPt = Preheader->getTerminator();
1707
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001708 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001709
1710 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001711 for (InductiveRangeCheck &IRC : RangeChecks) {
1712 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001713 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001714 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001715 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001716 if (MaybeSafeIterRange.hasValue()) {
1717 RangeChecksToEliminate.push_back(IRC);
1718 SafeIterRange = MaybeSafeIterRange.getValue();
1719 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001720 }
1721 }
1722
1723 if (!SafeIterRange.hasValue())
1724 return false;
1725
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001726 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Sanjoy Das21434472016-08-14 01:04:46 +00001727 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1728 LS, SE, DT, SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001729 bool Changed = LC.run();
1730
1731 if (Changed) {
1732 auto PrintConstrainedLoopInfo = [L]() {
1733 dbgs() << "irce: in function ";
1734 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1735 dbgs() << "constrained ";
1736 L->print(dbgs());
1737 };
1738
1739 DEBUG(PrintConstrainedLoopInfo());
1740
1741 if (PrintChangedLoops)
1742 PrintConstrainedLoopInfo();
1743
1744 // Optimize away the now-redundant range checks.
1745
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001746 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1747 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001748 ? ConstantInt::getTrue(Context)
1749 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001750 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001751 }
1752 }
1753
1754 return Changed;
1755}
1756
1757Pass *llvm::createInductiveRangeCheckEliminationPass() {
1758 return new InductiveRangeCheckElimination;
1759}