blob: aa7c2b3144745a448b0941b04dc587a837cb80c8 [file] [log] [blame]
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
Sanjoy Dasa1837a32015-01-16 01:03:22 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00009//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000010// The InductiveRangeCheckElimination pass splits a loop's iteration space into
11// three disjoint ranges. It does that in a way such that the loop running in
12// the middle loop provably does not need range checks. As an example, it will
13// convert
14//
15// len = < known positive >
16// for (i = 0; i < n; i++) {
17// if (0 <= i && i < len) {
18// do_something();
19// } else {
20// throw_out_of_bounds();
21// }
22// }
23//
24// to
25//
26// len = < known positive >
27// limit = smin(n, len)
28// // no first segment
29// for (i = 0; i < limit; i++) {
30// if (0 <= i && i < len) { // this check is fully redundant
31// do_something();
32// } else {
33// throw_out_of_bounds();
34// }
35// }
36// for (i = limit; i < n; i++) {
37// if (0 <= i && i < len) {
38// do_something();
39// } else {
40// throw_out_of_bounds();
41// }
42// }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000043//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000044//===----------------------------------------------------------------------===//
45
Fedor Sergeev194a4072018-03-15 11:01:19 +000046#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000047#include "llvm/ADT/APInt.h"
48#include "llvm/ADT/ArrayRef.h"
49#include "llvm/ADT/None.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000050#include "llvm/ADT/Optional.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000051#include "llvm/ADT/SmallPtrSet.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/ADT/StringRef.h"
54#include "llvm/ADT/Twine.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000055#include "llvm/Analysis/BranchProbabilityInfo.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +000056#include "llvm/Analysis/LoopAnalysisManager.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000057#include "llvm/Analysis/LoopInfo.h"
58#include "llvm/Analysis/LoopPass.h"
59#include "llvm/Analysis/ScalarEvolution.h"
60#include "llvm/Analysis/ScalarEvolutionExpander.h"
61#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000062#include "llvm/IR/BasicBlock.h"
63#include "llvm/IR/CFG.h"
64#include "llvm/IR/Constants.h"
65#include "llvm/IR/DerivedTypes.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000066#include "llvm/IR/Dominators.h"
67#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000068#include "llvm/IR/IRBuilder.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000069#include "llvm/IR/InstrTypes.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000070#include "llvm/IR/Instructions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000071#include "llvm/IR/Metadata.h"
72#include "llvm/IR/Module.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000073#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000074#include "llvm/IR/Type.h"
75#include "llvm/IR/Use.h"
76#include "llvm/IR/User.h"
77#include "llvm/IR/Value.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000078#include "llvm/Pass.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000079#include "llvm/Support/BranchProbability.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Compiler.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000083#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000084#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000085#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000086#include "llvm/Transforms/Scalar.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000087#include "llvm/Transforms/Utils/Cloning.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000088#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000089#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000090#include "llvm/Transforms/Utils/ValueMapper.h"
91#include <algorithm>
92#include <cassert>
93#include <iterator>
94#include <limits>
95#include <utility>
96#include <vector>
Sanjoy Dasa1837a32015-01-16 01:03:22 +000097
98using namespace llvm;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000099using namespace llvm::PatternMatch;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000100
Benjamin Kramer970eac42015-02-06 17:51:54 +0000101static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
102 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000103
Benjamin Kramer970eac42015-02-06 17:51:54 +0000104static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
105 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000106
Sanjoy Das9c1bfae2015-03-17 01:40:22 +0000107static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
108 cl::init(false));
109
Sanjoy Dase91665d2015-02-26 08:56:04 +0000110static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
111 cl::Hidden, cl::init(10));
112
Sanjoy Dasbb969792016-07-22 00:40:56 +0000113static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
114 cl::Hidden, cl::init(false));
115
Max Kazantsev8aacef62017-10-04 06:53:22 +0000116static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
Max Kazantsev9ac70212017-10-25 06:47:39 +0000117 cl::Hidden, cl::init(true));
Max Kazantsev8aacef62017-10-04 06:53:22 +0000118
Sanjoy Das7a18a232016-08-14 01:04:36 +0000119static const char *ClonedLoopTag = "irce.loop.clone";
120
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000121#define DEBUG_TYPE "irce"
122
123namespace {
124
125/// An inductive range check is conditional branch in a loop with
126///
127/// 1. a very cold successor (i.e. the branch jumps to that successor very
128/// rarely)
129///
130/// and
131///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000132/// 2. a condition that is provably true for some contiguous range of values
133/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000134///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000135class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000136 // Classifies a range check
Reid Kleckner0b168592015-03-17 16:50:20 +0000137 enum RangeCheckKind : unsigned {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000138 // Range check of the form "0 <= I".
139 RANGE_CHECK_LOWER = 1,
140
141 // Range check of the form "I < L" where L is known positive.
142 RANGE_CHECK_UPPER = 2,
143
144 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
145 // conditions.
146 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
147
148 // Unrecognized range check condition.
149 RANGE_CHECK_UNKNOWN = (unsigned)-1
150 };
151
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000152 static StringRef rangeCheckKindToStr(RangeCheckKind);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000153
Max Kazantsev84286ce2017-10-31 06:19:05 +0000154 const SCEV *Begin = nullptr;
155 const SCEV *Step = nullptr;
156 const SCEV *End = nullptr;
Sanjoy Dasee77a482016-05-26 01:50:18 +0000157 Use *CheckUse = nullptr;
158 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000159 bool IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000160
Sanjoy Das337d46b2015-03-24 19:29:18 +0000161 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
162 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000163 Value *&Length, bool &IsSigned);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000164
Sanjoy Dasa0992682016-05-26 00:09:02 +0000165 static void
166 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
167 SmallVectorImpl<InductiveRangeCheck> &Checks,
168 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000169
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000170public:
Max Kazantsev84286ce2017-10-31 06:19:05 +0000171 const SCEV *getBegin() const { return Begin; }
172 const SCEV *getStep() const { return Step; }
173 const SCEV *getEnd() const { return End; }
Max Kazantsev9ac70212017-10-25 06:47:39 +0000174 bool isSigned() const { return IsSigned; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000175
176 void print(raw_ostream &OS) const {
177 OS << "InductiveRangeCheck:\n";
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000178 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
Max Kazantsev84286ce2017-10-31 06:19:05 +0000179 OS << " Begin: ";
180 Begin->print(OS);
181 OS << " Step: ";
182 Step->print(OS);
183 OS << " End: ";
Max Kazantsevef057602018-01-12 10:00:26 +0000184 End->print(OS);
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000185 OS << "\n CheckUse: ";
186 getCheckUse()->getUser()->print(OS);
187 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000188 }
189
Davide Italianod1279df2016-08-18 15:55:49 +0000190 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000191 void dump() {
192 print(dbgs());
193 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000194
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000195 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000196
Sanjoy Das351db052015-01-22 09:32:02 +0000197 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
Max Kazantsevd0fe5022018-01-15 05:44:43 +0000198 /// R.getEnd() le R.getBegin(), then R denotes the empty range.
Sanjoy Das351db052015-01-22 09:32:02 +0000199
200 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000201 const SCEV *Begin;
202 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000203
204 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000205 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000206 assert(Begin->getType() == End->getType() && "ill-typed range!");
207 }
208
209 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000210 const SCEV *getBegin() const { return Begin; }
211 const SCEV *getEnd() const { return End; }
Max Kazantsev4332a942017-10-25 06:10:02 +0000212 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
213 if (Begin == End)
214 return true;
215 if (IsSigned)
216 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
217 else
218 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
219 }
Sanjoy Das351db052015-01-22 09:32:02 +0000220 };
221
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000222 /// This is the value the condition of the branch needs to evaluate to for the
223 /// branch to take the hot successor (see (1) above).
224 bool getPassingDirection() { return true; }
225
Sanjoy Das95c476d2015-02-21 22:20:22 +0000226 /// Computes a range for the induction variable (IndVar) in which the range
227 /// check is redundant and can be constant-folded away. The induction
228 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000229 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Max Kazantsev26846782017-11-20 06:07:57 +0000230 const SCEVAddRecExpr *IndVar,
231 bool IsLatchSigned) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000232
Sanjoy Dasa0992682016-05-26 00:09:02 +0000233 /// Parse out a set of inductive range checks from \p BI and append them to \p
234 /// Checks.
235 ///
236 /// NB! There may be conditions feeding into \p BI that aren't inductive range
237 /// checks, and hence don't end up in \p Checks.
238 static void
239 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000240 BranchProbabilityInfo *BPI,
Sanjoy Dasa0992682016-05-26 00:09:02 +0000241 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000242};
243
Fedor Sergeev194a4072018-03-15 11:01:19 +0000244class InductiveRangeCheckElimination {
245 ScalarEvolution &SE;
246 BranchProbabilityInfo *BPI;
247 DominatorTree &DT;
248 LoopInfo &LI;
249
250public:
251 InductiveRangeCheckElimination(ScalarEvolution &SE,
252 BranchProbabilityInfo *BPI, DominatorTree &DT,
253 LoopInfo &LI)
254 : SE(SE), BPI(BPI), DT(DT), LI(LI) {}
255
256 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
257};
258
259class IRCELegacyPass : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000260public:
261 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000262
Fedor Sergeev194a4072018-03-15 11:01:19 +0000263 IRCELegacyPass() : LoopPass(ID) {
264 initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000265 }
266
267 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000268 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000269 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000270 }
271
272 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
273};
274
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000275} // end anonymous namespace
276
Fedor Sergeev194a4072018-03-15 11:01:19 +0000277char IRCELegacyPass::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000278
Fedor Sergeev194a4072018-03-15 11:01:19 +0000279INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce",
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000280 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000281INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000282INITIALIZE_PASS_DEPENDENCY(LoopPass)
Fedor Sergeev194a4072018-03-15 11:01:19 +0000283INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination",
284 false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000285
Sanjoy Das2eac48d2016-03-09 02:34:19 +0000286StringRef InductiveRangeCheck::rangeCheckKindToStr(
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000287 InductiveRangeCheck::RangeCheckKind RCK) {
288 switch (RCK) {
289 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
290 return "RANGE_CHECK_UNKNOWN";
291
292 case InductiveRangeCheck::RANGE_CHECK_UPPER:
293 return "RANGE_CHECK_UPPER";
294
295 case InductiveRangeCheck::RANGE_CHECK_LOWER:
296 return "RANGE_CHECK_LOWER";
297
298 case InductiveRangeCheck::RANGE_CHECK_BOTH:
299 return "RANGE_CHECK_BOTH";
300 }
301
302 llvm_unreachable("unknown range check type!");
303}
304
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000305/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000306/// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000307/// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000308/// range checked, and set `Length` to the upper limit `Index` is being range
309/// checked with if (and only if) the range check type is stronger or equal to
310/// RANGE_CHECK_UPPER.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000311InductiveRangeCheck::RangeCheckKind
Sanjoy Das337d46b2015-03-24 19:29:18 +0000312InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
313 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000314 Value *&Length, bool &IsSigned) {
Max Kazantsev8624a472018-04-09 06:01:22 +0000315 auto IsLoopInvariant = [&SE, L](Value *V) {
316 return SE.isLoopInvariant(SE.getSCEV(V), L);
Sanjoy Das337d46b2015-03-24 19:29:18 +0000317 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000318
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000319 ICmpInst::Predicate Pred = ICI->getPredicate();
320 Value *LHS = ICI->getOperand(0);
321 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000322
323 switch (Pred) {
324 default:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000325 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000326
327 case ICmpInst::ICMP_SLE:
328 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000329 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000330 case ICmpInst::ICMP_SGE:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000331 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000332 if (match(RHS, m_ConstantInt<0>())) {
333 Index = LHS;
334 return RANGE_CHECK_LOWER;
335 }
336 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000337
338 case ICmpInst::ICMP_SLT:
339 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000340 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000341 case ICmpInst::ICMP_SGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000342 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000343 if (match(RHS, m_ConstantInt<-1>())) {
344 Index = LHS;
345 return RANGE_CHECK_LOWER;
346 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000347
Max Kazantsev8624a472018-04-09 06:01:22 +0000348 if (IsLoopInvariant(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000349 Index = RHS;
350 Length = LHS;
351 return RANGE_CHECK_UPPER;
352 }
353 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000354
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000355 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000356 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000357 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000358 case ICmpInst::ICMP_UGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000359 IsSigned = false;
Max Kazantsev8624a472018-04-09 06:01:22 +0000360 if (IsLoopInvariant(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000361 Index = RHS;
362 Length = LHS;
363 return RANGE_CHECK_BOTH;
364 }
365 return RANGE_CHECK_UNKNOWN;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000366 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000367
368 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000369}
370
Sanjoy Dasa0992682016-05-26 00:09:02 +0000371void InductiveRangeCheck::extractRangeChecksFromCond(
372 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
373 SmallVectorImpl<InductiveRangeCheck> &Checks,
374 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000375 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000376 if (!Visited.insert(Condition).second)
377 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000378
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000379 // TODO: Do the same for OR, XOR, NOT etc?
Sanjoy Dasa0992682016-05-26 00:09:02 +0000380 if (match(Condition, m_And(m_Value(), m_Value()))) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000381 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000382 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000383 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000384 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000385 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000386 }
387
Sanjoy Dasa0992682016-05-26 00:09:02 +0000388 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
389 if (!ICI)
390 return;
391
392 Value *Length = nullptr, *Index;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000393 bool IsSigned;
394 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
396 return;
397
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000398 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000399 bool IsAffineIndex =
400 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
401
402 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000403 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000404
Max Kazantsevef057602018-01-12 10:00:26 +0000405 const SCEV *End = nullptr;
406 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
407 // We can potentially do much better here.
408 if (Length)
409 End = SE.getSCEV(Length);
410 else {
411 assert(RCKind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
412 // So far we can only reach this point for Signed range check. This may
413 // change in future. In this case we will need to pick Unsigned max for the
414 // unsigned range check.
415 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth();
416 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
417 End = SIntMax;
418 }
419
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000420 InductiveRangeCheck IRC;
Max Kazantsevef057602018-01-12 10:00:26 +0000421 IRC.End = End;
Max Kazantsev84286ce2017-10-31 06:19:05 +0000422 IRC.Begin = IndexAddRec->getStart();
423 IRC.Step = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000424 IRC.CheckUse = &ConditionUse;
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000425 IRC.Kind = RCKind;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000426 IRC.IsSigned = IsSigned;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000427 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000428}
429
Sanjoy Dasa0992682016-05-26 00:09:02 +0000430void InductiveRangeCheck::extractRangeChecksFromBranch(
Fedor Sergeev194a4072018-03-15 11:01:19 +0000431 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
Sanjoy Dasa0992682016-05-26 00:09:02 +0000432 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000433 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000434 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000435
436 BranchProbability LikelyTaken(15, 16);
437
Fedor Sergeev194a4072018-03-15 11:01:19 +0000438 if (!SkipProfitabilityChecks && BPI &&
439 BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000440 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000441
Sanjoy Dasa0992682016-05-26 00:09:02 +0000442 SmallPtrSet<Value *, 8> Visited;
443 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
444 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000445}
446
Anna Thomas65ca8e92016-12-13 21:05:21 +0000447// Add metadata to the loop L to disable loop optimizations. Callers need to
448// confirm that optimizing loop L is not beneficial.
449static void DisableAllLoopOptsOnLoop(Loop &L) {
450 // We do not care about any existing loopID related metadata for L, since we
451 // are setting all loop metadata to false.
452 LLVMContext &Context = L.getHeader()->getContext();
453 // Reserve first location for self reference to the LoopID metadata node.
454 MDNode *Dummy = MDNode::get(Context, {});
455 MDNode *DisableUnroll = MDNode::get(
456 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
457 Metadata *FalseVal =
458 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
459 MDNode *DisableVectorize = MDNode::get(
460 Context,
461 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
462 MDNode *DisableLICMVersioning = MDNode::get(
463 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
464 MDNode *DisableDistribution= MDNode::get(
465 Context,
466 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
467 MDNode *NewLoopID =
468 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
469 DisableLICMVersioning, DisableDistribution});
470 // Set operand 0 to refer to the loop id itself.
471 NewLoopID->replaceOperandWith(0, NewLoopID);
472 L.setLoopID(NewLoopID);
473}
474
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000475namespace {
476
Sanjoy Dase75ed922015-02-26 08:19:31 +0000477// Keeps track of the structure of a loop. This is similar to llvm::Loop,
478// except that it is more lightweight and can track the state of a loop through
479// changing and potentially invalid IR. This structure also formalizes the
480// kinds of loops we can deal with -- ones that have a single latch that is also
481// an exiting block *and* have a canonical induction variable.
482struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000483 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000484
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000485 BasicBlock *Header = nullptr;
486 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000487
488 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
489 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000490 BranchInst *LatchBr = nullptr;
491 BasicBlock *LatchExit = nullptr;
492 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000493
Sanjoy Dasec892132017-02-07 23:59:07 +0000494 // The loop represented by this instance of LoopStructure is semantically
495 // equivalent to:
496 //
497 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000498 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000499 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000500 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000501 // ... body ...
502
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000503 Value *IndVarBase = nullptr;
504 Value *IndVarStart = nullptr;
505 Value *IndVarStep = nullptr;
506 Value *LoopExitAt = nullptr;
507 bool IndVarIncreasing = false;
508 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000509
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000510 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000511
512 template <typename M> LoopStructure map(M Map) const {
513 LoopStructure Result;
514 Result.Tag = Tag;
515 Result.Header = cast<BasicBlock>(Map(Header));
516 Result.Latch = cast<BasicBlock>(Map(Latch));
517 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
518 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
519 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000520 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000521 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000522 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000523 Result.LoopExitAt = Map(LoopExitAt);
524 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000525 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000526 return Result;
527 }
528
Sanjoy Dase91665d2015-02-26 08:56:04 +0000529 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000530 BranchProbabilityInfo *BPI,
531 Loop &, const char *&);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000532};
533
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000534/// This class is used to constrain loops to run within a given iteration space.
535/// The algorithm this class implements is given a Loop and a range [Begin,
536/// End). The algorithm then tries to break out a "main loop" out of the loop
537/// it is given in a way that the "main loop" runs with the induction variable
538/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
539/// loops to run any remaining iterations. The pre loop runs any iterations in
540/// which the induction variable is < Begin, and the post loop runs any
541/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000542class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000543 // The representation of a clone of the original loop we started out with.
544 struct ClonedLoop {
545 // The cloned blocks
546 std::vector<BasicBlock *> Blocks;
547
548 // `Map` maps values in the clonee into values in the cloned version
549 ValueToValueMapTy Map;
550
551 // An instance of `LoopStructure` for the cloned loop
552 LoopStructure Structure;
553 };
554
555 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
556 // more details on what these fields mean.
557 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000558 BasicBlock *PseudoExit = nullptr;
559 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000560 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000561 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000562
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000563 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000564 };
565
566 // Calculated subranges we restrict the iteration space of the main loop to.
567 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000568 // these fields are computed. `LowLimit` is None if there is no restriction
569 // on low end of the restricted iteration space of the main loop. `HighLimit`
570 // is None if there is no restriction on high end of the restricted iteration
571 // space of the main loop.
572
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000573 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000574 Optional<const SCEV *> LowLimit;
575 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000576 };
577
578 // A utility function that does a `replaceUsesOfWith' on the incoming block
579 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
580 // incoming block list with `ReplaceBy'.
581 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
582 BasicBlock *ReplaceBy);
583
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000584 // Compute a safe set of limits for the main loop to run in -- effectively the
585 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000586 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000587 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000588
589 // Clone `OriginalLoop' and return the result in CLResult. The IR after
590 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
591 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
592 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000593 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
594
Sanjoy Das21434472016-08-14 01:04:46 +0000595 // Create the appropriate loop structure needed to describe a cloned copy of
596 // `Original`. The clone is described by `VM`.
597 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000598 ValueToValueMapTy &VM, bool IsSubloop);
Sanjoy Das21434472016-08-14 01:04:46 +0000599
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000600 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
601 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
602 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
603 // `OriginalHeaderCount'.
604 //
605 // If there are iterations left to execute, control is made to jump to
606 // `ContinuationBlock', otherwise they take the normal loop exit. The
607 // returned `RewrittenRangeInfo' object is populated as follows:
608 //
609 // .PseudoExit is a basic block that unconditionally branches to
610 // `ContinuationBlock'.
611 //
612 // .ExitSelector is a basic block that decides, on exit from the loop,
613 // whether to branch to the "true" exit or to `PseudoExit'.
614 //
615 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
616 // for each PHINode in the loop header on taking the pseudo exit.
617 //
618 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
619 // preheader because it is made to branch to the loop header only
620 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000621 RewrittenRangeInfo
622 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
623 Value *ExitLoopAt,
624 BasicBlock *ContinuationBlock) const;
625
626 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
627 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000628 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
629 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000630
631 // `ContinuationBlockAndPreheader' was the continuation block for some call to
632 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
633 // This function rewrites the PHI nodes in `LS.Header' to start with the
634 // correct value.
635 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000636 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000637 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
638
639 // Even though we do not preserve any passes at this time, we at least need to
640 // keep the parent loop structure consistent. The `LPPassManager' seems to
641 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000642 // blocks denoted by BBs to this loops parent loop if required.
643 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000644
645 // Some global state.
646 Function &F;
647 LLVMContext &Ctx;
648 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000649 DominatorTree &DT;
Sanjoy Das35459f02016-08-14 01:04:50 +0000650 LoopInfo &LI;
Fedor Sergeev194a4072018-03-15 11:01:19 +0000651 function_ref<void(Loop *, bool)> LPMAddNewLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000652
653 // Information about the original loop we started out with.
654 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000655
656 const SCEV *LatchTakenCount = nullptr;
657 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000658
659 // The preheader of the main loop. This may or may not be different from
660 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000661 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000662
663 // The range we need to run the main loop in.
664 InductiveRangeCheck::Range Range;
665
666 // The structure of the main loop (see comment at the beginning of this class
667 // for a definition)
668 LoopStructure MainLoopStructure;
669
670public:
Fedor Sergeev194a4072018-03-15 11:01:19 +0000671 LoopConstrainer(Loop &L, LoopInfo &LI,
672 function_ref<void(Loop *, bool)> LPMAddNewLoop,
Sanjoy Das21434472016-08-14 01:04:46 +0000673 const LoopStructure &LS, ScalarEvolution &SE,
674 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000675 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Fedor Sergeev194a4072018-03-15 11:01:19 +0000676 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
677 Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000678
679 // Entry point for the algorithm. Returns true on success.
680 bool run();
681};
682
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000683} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000684
685void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
686 BasicBlock *ReplaceBy) {
687 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
688 if (PN->getIncomingBlock(i) == Block)
689 PN->setIncomingBlock(i, ReplaceBy);
690}
691
Sam Parker90b7f4f2018-03-27 08:24:53 +0000692static bool CannotBeMaxInLoop(const SCEV *BoundSCEV, Loop *L,
693 ScalarEvolution &SE, bool Signed) {
694 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
695 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
696 APInt::getMaxValue(BitWidth);
697 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
698 return SE.isAvailableAtLoopEntry(BoundSCEV, L) &&
699 SE.isLoopEntryGuardedByCond(L, Predicate, BoundSCEV,
700 SE.getConstant(Max));
701}
702
703/// Given a loop with an deccreasing induction variable, is it possible to
704/// safely calculate the bounds of a new loop using the given Predicate.
705static bool isSafeDecreasingBound(const SCEV *Start,
706 const SCEV *BoundSCEV, const SCEV *Step,
707 ICmpInst::Predicate Pred,
708 unsigned LatchBrExitIdx,
709 Loop *L, ScalarEvolution &SE) {
710 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
711 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
712 return false;
713
714 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
715 return false;
716
717 assert(SE.isKnownNegative(Step) && "expecting negative step");
718
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000719 LLVM_DEBUG(dbgs() << "irce: isSafeDecreasingBound with:\n");
720 LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
721 LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
722 LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
723 LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
724 << "\n");
725 LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
Sam Parker90b7f4f2018-03-27 08:24:53 +0000726
727 bool IsSigned = ICmpInst::isSigned(Pred);
728 // The predicate that we need to check that the induction variable lies
729 // within bounds.
730 ICmpInst::Predicate BoundPred =
731 IsSigned ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
732
733 if (LatchBrExitIdx == 1)
734 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
735
736 assert(LatchBrExitIdx == 0 &&
737 "LatchBrExitIdx should be either 0 or 1");
738
739 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
740 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
741 APInt Min = IsSigned ? APInt::getSignedMinValue(BitWidth) :
742 APInt::getMinValue(BitWidth);
743 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
744
745 const SCEV *MinusOne =
746 SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType()));
747
748 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, MinusOne) &&
749 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit);
750
Sanjoy Dase75ed922015-02-26 08:19:31 +0000751}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000752
Sam Parker53a423a2018-03-26 09:29:42 +0000753/// Given a loop with an increasing induction variable, is it possible to
754/// safely calculate the bounds of a new loop using the given Predicate.
755static bool isSafeIncreasingBound(const SCEV *Start,
756 const SCEV *BoundSCEV, const SCEV *Step,
757 ICmpInst::Predicate Pred,
758 unsigned LatchBrExitIdx,
759 Loop *L, ScalarEvolution &SE) {
760 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
761 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
762 return false;
763
764 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
765 return false;
766
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000767 LLVM_DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n");
768 LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
769 LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
770 LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
771 LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
772 << "\n");
773 LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
Sam Parker53a423a2018-03-26 09:29:42 +0000774
775 bool IsSigned = ICmpInst::isSigned(Pred);
776 // The predicate that we need to check that the induction variable lies
777 // within bounds.
778 ICmpInst::Predicate BoundPred =
779 IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
780
781 if (LatchBrExitIdx == 1)
782 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
783
784 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
785
786 const SCEV *StepMinusOne =
787 SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
788 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
789 APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) :
790 APInt::getMaxValue(BitWidth);
791 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
792
793 return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start,
794 SE.getAddExpr(BoundSCEV, Step)) &&
795 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit));
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000796}
797
Sam Parker53a423a2018-03-26 09:29:42 +0000798static bool CannotBeMinInLoop(const SCEV *BoundSCEV, Loop *L,
799 ScalarEvolution &SE, bool Signed) {
800 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
801 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
802 APInt::getMinValue(BitWidth);
803 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
804 return SE.isAvailableAtLoopEntry(BoundSCEV, L) &&
805 SE.isLoopEntryGuardedByCond(L, Predicate, BoundSCEV,
806 SE.getConstant(Min));
Sanjoy Dase75ed922015-02-26 08:19:31 +0000807}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000808
Max Kazantsev9b903732018-05-15 01:21:56 +0000809static bool isKnownNonNegativeInLoop(const SCEV *BoundSCEV, const Loop *L,
Sam Parker97375352018-04-12 12:49:40 +0000810 ScalarEvolution &SE) {
811 const SCEV *Zero = SE.getZero(BoundSCEV->getType());
812 return SE.isAvailableAtLoopEntry(BoundSCEV, L) &&
813 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, BoundSCEV, Zero);
814}
815
Sanjoy Dase75ed922015-02-26 08:19:31 +0000816Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000817LoopStructure::parseLoopStructure(ScalarEvolution &SE,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000818 BranchProbabilityInfo *BPI, Loop &L,
819 const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000820 if (!L.isLoopSimplifyForm()) {
821 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000822 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000823 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000824
825 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000826 assert(Latch && "Simplified loops only have one latch!");
827
Sanjoy Das7a18a232016-08-14 01:04:36 +0000828 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
829 FailureReason = "loop has already been cloned";
830 return None;
831 }
832
Sanjoy Dase75ed922015-02-26 08:19:31 +0000833 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000834 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000835 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000836 }
837
Sanjoy Dase75ed922015-02-26 08:19:31 +0000838 BasicBlock *Header = L.getHeader();
839 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000840 if (!Preheader) {
841 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000842 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000843 }
844
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000845 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000846 if (!LatchBr || LatchBr->isUnconditional()) {
847 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000848 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000849 }
850
Sanjoy Dase75ed922015-02-26 08:19:31 +0000851 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000852
Sanjoy Dase91665d2015-02-26 08:56:04 +0000853 BranchProbability ExitProbability =
Fedor Sergeev194a4072018-03-15 11:01:19 +0000854 BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx)
855 : BranchProbability::getZero();
Sanjoy Dase91665d2015-02-26 08:56:04 +0000856
Sanjoy Dasbb969792016-07-22 00:40:56 +0000857 if (!SkipProfitabilityChecks &&
858 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000859 FailureReason = "short running loop, not profitable";
860 return None;
861 }
862
Sanjoy Dase75ed922015-02-26 08:19:31 +0000863 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
864 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
865 FailureReason = "latch terminator branch not conditional on integral icmp";
866 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000867 }
868
Sanjoy Dase75ed922015-02-26 08:19:31 +0000869 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
870 if (isa<SCEVCouldNotCompute>(LatchCount)) {
871 FailureReason = "could not compute latch count";
872 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000873 }
874
Sanjoy Dase75ed922015-02-26 08:19:31 +0000875 ICmpInst::Predicate Pred = ICI->getPredicate();
876 Value *LeftValue = ICI->getOperand(0);
877 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
878 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
879
880 Value *RightValue = ICI->getOperand(1);
881 const SCEV *RightSCEV = SE.getSCEV(RightValue);
882
883 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
884 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
885 if (isa<SCEVAddRecExpr>(RightSCEV)) {
886 std::swap(LeftSCEV, RightSCEV);
887 std::swap(LeftValue, RightValue);
888 Pred = ICmpInst::getSwappedPredicate(Pred);
889 } else {
890 FailureReason = "no add recurrences in the icmp";
891 return None;
892 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000893 }
894
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000895 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
896 if (AR->getNoWrapFlags(SCEV::FlagNSW))
897 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000898
899 IntegerType *Ty = cast<IntegerType>(AR->getType());
900 IntegerType *WideTy =
901 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
902
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000903 const SCEVAddRecExpr *ExtendAfterOp =
904 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
905 if (ExtendAfterOp) {
906 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
907 const SCEV *ExtendedStep =
908 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
909
910 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
911 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
912
913 if (NoSignedWrap)
914 return true;
915 }
916
917 // We may have proved this when computing the sign extension above.
918 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
919 };
920
Serguei Katkov675e3042017-09-21 04:50:41 +0000921 // `ICI` is interpreted as taking the backedge if the *next* value of the
922 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000923
Max Kazantseva22742b2017-08-31 05:58:15 +0000924 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sam Parker3c190512018-04-18 13:50:28 +0000925 if (!IndVarBase->isAffine()) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000926 FailureReason = "LHS in icmp not induction variable";
927 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000928 }
Sam Parker3c190512018-04-18 13:50:28 +0000929 const SCEV* StepRec = IndVarBase->getStepRecurrence(SE);
Max Kazantsev786032c2018-05-04 07:34:35 +0000930 if (!isa<SCEVConstant>(StepRec)) {
Sam Parker3c190512018-04-18 13:50:28 +0000931 FailureReason = "LHS in icmp not induction variable";
932 return None;
933 }
Max Kazantsev786032c2018-05-04 07:34:35 +0000934 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
935
Sam Parker3c190512018-04-18 13:50:28 +0000936 if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
937 FailureReason = "LHS in icmp needs nsw for equality predicates";
938 return None;
939 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000940
Sam Parker3c190512018-04-18 13:50:28 +0000941 assert(!StepCI->isZero() && "Zero step?");
942 bool IsIncreasing = !StepCI->isNegative();
943 bool IsSignedPredicate = ICmpInst::isSigned(Pred);
Serguei Katkov675e3042017-09-21 04:50:41 +0000944 const SCEV *StartNext = IndVarBase->getStart();
945 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
946 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000947 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000948
Sanjoy Dase75ed922015-02-26 08:19:31 +0000949 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000950 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000951 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000952 if (StepCI->isOne()) {
953 // Try to turn eq/ne predicates to those we can work with.
954 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
955 // while (++i != len) { while (++i < len) {
956 // ... ---> ...
957 // } }
958 // If both parts are known non-negative, it is profitable to use
959 // unsigned comparison in increasing loop. This allows us to make the
960 // comparison check against "RightSCEV + 1" more optimistic.
Sam Parker97375352018-04-12 12:49:40 +0000961 if (isKnownNonNegativeInLoop(IndVarStart, &L, SE) &&
962 isKnownNonNegativeInLoop(RightSCEV, &L, SE))
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000963 Pred = ICmpInst::ICMP_ULT;
964 else
965 Pred = ICmpInst::ICMP_SLT;
Sam Parker53a423a2018-03-26 09:29:42 +0000966 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000967 // while (true) { while (true) {
968 // if (++i == len) ---> if (++i > len - 1)
969 // break; break;
970 // ... ...
971 // } }
Sam Parker53a423a2018-03-26 09:29:42 +0000972 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
973 CannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) {
974 Pred = ICmpInst::ICMP_UGT;
975 RightSCEV = SE.getMinusSCEV(RightSCEV,
976 SE.getOne(RightSCEV->getType()));
977 DecreasedRightValueByOne = true;
978 } else if (CannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) {
979 Pred = ICmpInst::ICMP_SGT;
980 RightSCEV = SE.getMinusSCEV(RightSCEV,
981 SE.getOne(RightSCEV->getType()));
982 DecreasedRightValueByOne = true;
983 }
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000984 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000985 }
986
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000987 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
988 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000989 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000990 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000991
992 if (!FoundExpectedPred) {
993 FailureReason = "expected icmp slt semantically, found something else";
994 return None;
995 }
996
Sam Parker53a423a2018-03-26 09:29:42 +0000997 IsSignedPredicate = ICmpInst::isSigned(Pred);
Max Kazantsev8aacef62017-10-04 06:53:22 +0000998 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
999 FailureReason = "unsigned latch conditions are explicitly prohibited";
1000 return None;
1001 }
1002
Sam Parker53a423a2018-03-26 09:29:42 +00001003 if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
1004 LatchBrExitIdx, &L, SE)) {
1005 FailureReason = "Unsafe loop bounds";
1006 return None;
1007 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001008 if (LatchBrExitIdx == 0) {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001009 // We need to increase the right value unless we have already decreased
1010 // it virtually when we replaced EQ with SGT.
1011 if (!DecreasedRightValueByOne) {
1012 IRBuilder<> B(Preheader->getTerminator());
1013 RightValue = B.CreateAdd(RightValue, One);
1014 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001015 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001016 assert(!DecreasedRightValueByOne &&
1017 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001018 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001019 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001020 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001021 if (StepCI->isMinusOne()) {
1022 // Try to turn eq/ne predicates to those we can work with.
1023 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
1024 // while (--i != len) { while (--i > len) {
1025 // ... ---> ...
1026 // } }
1027 // We intentionally don't turn the predicate into UGT even if we know
1028 // that both operands are non-negative, because it will only pessimize
1029 // our check against "RightSCEV - 1".
1030 Pred = ICmpInst::ICMP_SGT;
Sam Parker90b7f4f2018-03-27 08:24:53 +00001031 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001032 // while (true) { while (true) {
1033 // if (--i == len) ---> if (--i < len + 1)
1034 // break; break;
1035 // ... ...
1036 // } }
Sam Parker90b7f4f2018-03-27 08:24:53 +00001037 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
1038 CannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
1039 Pred = ICmpInst::ICMP_ULT;
1040 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
1041 IncreasedRightValueByOne = true;
1042 } else if (CannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
1043 Pred = ICmpInst::ICMP_SLT;
1044 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
1045 IncreasedRightValueByOne = true;
1046 }
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001047 }
Max Kazantsev2c627a92017-07-18 04:53:48 +00001048 }
1049
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001050 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
1051 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
1052
Sanjoy Dase75ed922015-02-26 08:19:31 +00001053 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001054 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001055
1056 if (!FoundExpectedPred) {
1057 FailureReason = "expected icmp sgt semantically, found something else";
1058 return None;
1059 }
1060
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001061 IsSignedPredicate =
1062 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +00001063
Max Kazantsev8aacef62017-10-04 06:53:22 +00001064 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
1065 FailureReason = "unsigned latch conditions are explicitly prohibited";
1066 return None;
1067 }
1068
Sam Parker90b7f4f2018-03-27 08:24:53 +00001069 if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
1070 LatchBrExitIdx, &L, SE)) {
1071 FailureReason = "Unsafe bounds";
1072 return None;
1073 }
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001074
Sanjoy Dase75ed922015-02-26 08:19:31 +00001075 if (LatchBrExitIdx == 0) {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001076 // We need to decrease the right value unless we have already increased
1077 // it virtually when we replaced EQ with SLT.
1078 if (!IncreasedRightValueByOne) {
1079 IRBuilder<> B(Preheader->getTerminator());
1080 RightValue = B.CreateSub(RightValue, One);
1081 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001082 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001083 assert(!IncreasedRightValueByOne &&
1084 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001085 }
1086 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001087 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1088
Sanjoy Dase75ed922015-02-26 08:19:31 +00001089 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001090 ScalarEvolution::LoopInvariant &&
1091 "loop variant exit count doesn't make sense!");
1092
Sanjoy Dase75ed922015-02-26 08:19:31 +00001093 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001094 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1095 Value *IndVarStartV =
1096 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001097 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001098 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001099
Sanjoy Dase75ed922015-02-26 08:19:31 +00001100 LoopStructure Result;
1101
1102 Result.Tag = "main";
1103 Result.Header = Header;
1104 Result.Latch = Latch;
1105 Result.LatchBr = LatchBr;
1106 Result.LatchExit = LatchExit;
1107 Result.LatchBrExitIdx = LatchBrExitIdx;
1108 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001109 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001110 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001111 Result.IndVarIncreasing = IsIncreasing;
1112 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001113 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001114
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001115 FailureReason = nullptr;
1116
Sanjoy Dase75ed922015-02-26 08:19:31 +00001117 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001118}
1119
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001120Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001121LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001122 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1123
Sanjoy Das351db052015-01-22 09:32:02 +00001124 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001125 return None;
1126
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001127 LoopConstrainer::SubRanges Result;
1128
1129 // I think we can be more aggressive here and make this nuw / nsw if the
1130 // addition that feeds into the icmp for the latch's terminating branch is nuw
1131 // / nsw. In any case, a wrapping 2's complement addition is safe.
Sanjoy Dase75ed922015-02-26 08:19:31 +00001132 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1133 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001134
Sanjoy Dase75ed922015-02-26 08:19:31 +00001135 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001136
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001137 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1138 // [Smallest, GreatestSeen] is the range of values the induction variable
1139 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001140
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001141 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001142
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001143 const SCEV *One = SE.getOne(Ty);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001144 if (Increasing) {
1145 Smallest = Start;
1146 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001147 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1148 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001149 } else {
1150 // These two computations may sign-overflow. Here is why that is okay:
1151 //
1152 // We know that the induction variable does not sign-overflow on any
1153 // iteration except the last one, and it starts at `Start` and ends at
1154 // `End`, decrementing by one every time.
1155 //
1156 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1157 // induction variable is decreasing we know that that the smallest value
1158 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1159 //
1160 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1161 // that case, `Clamp` will always return `Smallest` and
1162 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1163 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001164
Max Kazantsev6c466a32017-06-28 04:57:45 +00001165 Smallest = SE.getAddExpr(End, One);
1166 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001167 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001168 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001169
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001170 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev6f5229d72017-11-01 13:21:56 +00001171 return IsSignedPredicate
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001172 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1173 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001174 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001175
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001176 // In some cases we can prove that we don't need a pre or post loop.
1177 ICmpInst::Predicate PredLE =
1178 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1179 ICmpInst::Predicate PredLT =
1180 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001181
1182 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001183 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001184 if (!ProvablyNoPreloop)
1185 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001186
1187 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001188 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001189 if (!ProvablyNoPostLoop)
1190 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001191
1192 return Result;
1193}
1194
1195void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1196 const char *Tag) const {
1197 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1198 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1199 Result.Blocks.push_back(Clone);
1200 Result.Map[BB] = Clone;
1201 }
1202
1203 auto GetClonedValue = [&Result](Value *V) {
1204 assert(V && "null values not in domain!");
1205 auto It = Result.Map.find(V);
1206 if (It == Result.Map.end())
1207 return V;
1208 return static_cast<Value *>(It->second);
1209 };
1210
Sanjoy Das7a18a232016-08-14 01:04:36 +00001211 auto *ClonedLatch =
1212 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1213 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1214 MDNode::get(Ctx, {}));
1215
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001216 Result.Structure = MainLoopStructure.map(GetClonedValue);
1217 Result.Structure.Tag = Tag;
1218
1219 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1220 BasicBlock *ClonedBB = Result.Blocks[i];
1221 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1222
1223 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1224
1225 for (Instruction &I : *ClonedBB)
1226 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001227 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001228
1229 // Exit blocks will now have one more predecessor and their PHI nodes need
1230 // to be edited to reflect that. No phi nodes need to be introduced because
1231 // the loop is in LCSSA.
1232
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001233 for (auto *SBB : successors(OriginalBB)) {
1234 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001235 continue; // not an exit block
1236
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001237 for (PHINode &PN : SBB->phis()) {
1238 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
1239 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001240 }
1241 }
1242 }
1243}
1244
1245LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001246 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001247 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001248 // We start with a loop with a single latch:
1249 //
1250 // +--------------------+
1251 // | |
1252 // | preheader |
1253 // | |
1254 // +--------+-----------+
1255 // | ----------------\
1256 // | / |
1257 // +--------v----v------+ |
1258 // | | |
1259 // | header | |
1260 // | | |
1261 // +--------------------+ |
1262 // |
1263 // ..... |
1264 // |
1265 // +--------------------+ |
1266 // | | |
1267 // | latch >----------/
1268 // | |
1269 // +-------v------------+
1270 // |
1271 // |
1272 // | +--------------------+
1273 // | | |
1274 // +---> original exit |
1275 // | |
1276 // +--------------------+
1277 //
1278 // We change the control flow to look like
1279 //
1280 //
1281 // +--------------------+
1282 // | |
1283 // | preheader >-------------------------+
1284 // | | |
1285 // +--------v-----------+ |
1286 // | /-------------+ |
1287 // | / | |
1288 // +--------v--v--------+ | |
1289 // | | | |
1290 // | header | | +--------+ |
1291 // | | | | | |
1292 // +--------------------+ | | +-----v-----v-----------+
1293 // | | | |
1294 // | | | .pseudo.exit |
1295 // | | | |
1296 // | | +-----------v-----------+
1297 // | | |
1298 // ..... | | |
1299 // | | +--------v-------------+
1300 // +--------------------+ | | | |
1301 // | | | | | ContinuationBlock |
1302 // | latch >------+ | | |
1303 // | | | +----------------------+
1304 // +---------v----------+ |
1305 // | |
1306 // | |
1307 // | +---------------^-----+
1308 // | | |
1309 // +-----> .exit.selector |
1310 // | |
1311 // +----------v----------+
1312 // |
1313 // +--------------------+ |
1314 // | | |
1315 // | original exit <----+
1316 // | |
1317 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001318
1319 RewrittenRangeInfo RRI;
1320
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001321 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001322 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001323 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001324 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001325 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001326
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001327 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001328 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001329 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001330
1331 IRBuilder<> B(PreheaderJump);
1332
1333 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001334 Value *EnterLoopCond = nullptr;
1335 if (Increasing)
1336 EnterLoopCond = IsSignedPredicate
1337 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1338 : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1339 else
1340 EnterLoopCond = IsSignedPredicate
1341 ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1342 : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001343
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001344 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1345 PreheaderJump->eraseFromParent();
1346
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001347 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001348 B.SetInsertPoint(LS.LatchBr);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001349 Value *TakeBackedgeLoopCond = nullptr;
1350 if (Increasing)
1351 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001352 ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1353 : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001354 else
1355 TakeBackedgeLoopCond = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001356 ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1357 : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001358 Value *CondForBranch = LS.LatchBrExitIdx == 1
1359 ? TakeBackedgeLoopCond
1360 : B.CreateNot(TakeBackedgeLoopCond);
1361
1362 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001363
1364 B.SetInsertPoint(RRI.ExitSelector);
1365
1366 // IterationsLeft - are there any more iterations left, given the original
1367 // upper bound on the induction variable? If not, we branch to the "real"
1368 // exit.
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001369 Value *IterationsLeft = nullptr;
1370 if (Increasing)
1371 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001372 ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1373 : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001374 else
1375 IterationsLeft = IsSignedPredicate
Max Kazantseva22742b2017-08-31 05:58:15 +00001376 ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1377 : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001378 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1379
1380 BranchInst *BranchToContinuation =
1381 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1382
1383 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1384 // each of the PHI nodes in the loop header. This feeds into the initial
1385 // value of the same PHI nodes if/when we continue execution.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001386 for (PHINode &PN : LS.Header->phis()) {
1387 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001388 BranchToContinuation);
1389
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001390 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
1391 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
Serguei Katkov675e3042017-09-21 04:50:41 +00001392 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001393 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1394 }
1395
Max Kazantseva22742b2017-08-31 05:58:15 +00001396 RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001397 BranchToContinuation);
1398 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
Max Kazantseva22742b2017-08-31 05:58:15 +00001399 RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001400
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001401 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1402 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001403 for (PHINode &PN : LS.LatchExit->phis())
1404 replacePHIBlock(&PN, LS.Latch, RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001405
1406 return RRI;
1407}
1408
1409void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001410 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001411 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001412 unsigned PHIIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001413 for (PHINode &PN : LS.Header->phis())
1414 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i)
1415 if (PN.getIncomingBlock(i) == ContinuationBlock)
1416 PN.setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001417
Sanjoy Dase75ed922015-02-26 08:19:31 +00001418 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001419}
1420
Sanjoy Dase75ed922015-02-26 08:19:31 +00001421BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1422 BasicBlock *OldPreheader,
1423 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001424 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1425 BranchInst::Create(LS.Header, Preheader);
1426
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001427 for (PHINode &PN : LS.Header->phis())
1428 for (unsigned i = 0, e = PN.getNumIncomingValues(); i < e; ++i)
1429 replacePHIBlock(&PN, OldPreheader, Preheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001430
1431 return Preheader;
1432}
1433
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001434void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001435 Loop *ParentLoop = OriginalLoop.getParentLoop();
1436 if (!ParentLoop)
1437 return;
1438
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001439 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001440 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001441}
1442
Sanjoy Das21434472016-08-14 01:04:46 +00001443Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
Fedor Sergeev194a4072018-03-15 11:01:19 +00001444 ValueToValueMapTy &VM,
1445 bool IsSubloop) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001446 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001447 if (Parent)
1448 Parent->addChildLoop(&New);
1449 else
1450 LI.addTopLevelLoop(&New);
Fedor Sergeev194a4072018-03-15 11:01:19 +00001451 LPMAddNewLoop(&New, IsSubloop);
Sanjoy Das21434472016-08-14 01:04:46 +00001452
1453 // Add all of the blocks in Original to the new loop.
1454 for (auto *BB : Original->blocks())
1455 if (LI.getLoopFor(BB) == Original)
1456 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1457
1458 // Add all of the subloops to the new loop.
1459 for (Loop *SubLoop : *Original)
Fedor Sergeev194a4072018-03-15 11:01:19 +00001460 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
Sanjoy Das21434472016-08-14 01:04:46 +00001461
1462 return &New;
1463}
1464
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001465bool LoopConstrainer::run() {
1466 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001467 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1468 Preheader = OriginalLoop.getLoopPreheader();
1469 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1470 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001471
1472 OriginalPreheader = Preheader;
1473 MainLoopPreheader = Preheader;
1474
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001475 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1476 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001477 if (!MaybeSR.hasValue()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001478 LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001479 return false;
1480 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001481
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001482 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001483 bool Increasing = MainLoopStructure.IndVarIncreasing;
1484 IntegerType *IVTy =
Max Kazantseva22742b2017-08-31 05:58:15 +00001485 cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001486
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001487 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001488 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001489
1490 // It would have been better to make `PreLoop' and `PostLoop'
1491 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1492 // constructor.
1493 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001494 bool NeedsPreLoop =
1495 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1496 bool NeedsPostLoop =
1497 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1498
1499 Value *ExitPreLoopAt = nullptr;
1500 Value *ExitMainLoopAt = nullptr;
1501 const SCEVConstant *MinusOneS =
1502 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1503
1504 if (NeedsPreLoop) {
1505 const SCEV *ExitPreLoopAtSCEV = nullptr;
1506
1507 if (Increasing)
1508 ExitPreLoopAtSCEV = *SR.LowLimit;
1509 else {
Sam Parker53a423a2018-03-26 09:29:42 +00001510 if (CannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
1511 IsSignedPredicate))
1512 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1513 else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001514 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1515 << "preloop exit limit. HighLimit = "
1516 << *(*SR.HighLimit) << "\n");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001517 return false;
1518 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001519 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001520
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001521 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001522 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1523 << " preloop exit limit " << *ExitPreLoopAtSCEV
1524 << " at block " << InsertPt->getParent()->getName()
1525 << "\n");
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001526 return false;
1527 }
1528
Sanjoy Dase75ed922015-02-26 08:19:31 +00001529 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1530 ExitPreLoopAt->setName("exit.preloop.at");
1531 }
1532
1533 if (NeedsPostLoop) {
1534 const SCEV *ExitMainLoopAtSCEV = nullptr;
1535
1536 if (Increasing)
1537 ExitMainLoopAtSCEV = *SR.HighLimit;
1538 else {
Sam Parker53a423a2018-03-26 09:29:42 +00001539 if (CannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
1540 IsSignedPredicate))
1541 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1542 else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001543 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1544 << "mainloop exit limit. LowLimit = "
1545 << *(*SR.LowLimit) << "\n");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001546 return false;
1547 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001548 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001549
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001550 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001551 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1552 << " main loop exit limit " << *ExitMainLoopAtSCEV
1553 << " at block " << InsertPt->getParent()->getName()
1554 << "\n");
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001555 return false;
1556 }
1557
Sanjoy Dase75ed922015-02-26 08:19:31 +00001558 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1559 ExitMainLoopAt->setName("exit.mainloop.at");
1560 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001561
1562 // We clone these ahead of time so that we don't have to deal with changing
1563 // and temporarily invalid IR as we transform the loops.
1564 if (NeedsPreLoop)
1565 cloneLoop(PreLoop, "preloop");
1566 if (NeedsPostLoop)
1567 cloneLoop(PostLoop, "postloop");
1568
1569 RewrittenRangeInfo PreLoopRRI;
1570
1571 if (NeedsPreLoop) {
1572 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1573 PreLoop.Structure.Header);
1574
1575 MainLoopPreheader =
1576 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001577 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1578 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001579 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1580 PreLoopRRI);
1581 }
1582
1583 BasicBlock *PostLoopPreheader = nullptr;
1584 RewrittenRangeInfo PostLoopRRI;
1585
1586 if (NeedsPostLoop) {
1587 PostLoopPreheader =
1588 createPreheader(PostLoop.Structure, Preheader, "postloop");
1589 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001590 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001591 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1592 PostLoopRRI);
1593 }
1594
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001595 BasicBlock *NewMainLoopPreheader =
1596 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1597 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1598 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1599 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001600
1601 // Some of the above may be nullptr, filter them out before passing to
1602 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001603 auto NewBlocksEnd =
1604 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001605
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001606 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001607
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001608 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001609
Anna Thomas72180322017-06-06 14:54:01 +00001610 // We need to first add all the pre and post loop blocks into the loop
1611 // structures (as part of createClonedLoopStructure), and then update the
1612 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1613 // LI when LoopSimplifyForm is generated.
1614 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001615 if (!PreLoop.Blocks.empty()) {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001616 PreL = createClonedLoopStructure(&OriginalLoop,
1617 OriginalLoop.getParentLoop(), PreLoop.Map,
1618 /* IsSubLoop */ false);
Sanjoy Das21434472016-08-14 01:04:46 +00001619 }
1620
1621 if (!PostLoop.Blocks.empty()) {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001622 PostL =
1623 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
1624 PostLoop.Map, /* IsSubLoop */ false);
Sanjoy Das21434472016-08-14 01:04:46 +00001625 }
1626
Anna Thomas72180322017-06-06 14:54:01 +00001627 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1628 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1629 formLCSSARecursively(*L, DT, &LI, &SE);
1630 simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1631 // Pre/post loops are slow paths, we do not need to perform any loop
1632 // optimizations on them.
1633 if (!IsOriginalLoop)
1634 DisableAllLoopOptsOnLoop(*L);
1635 };
1636 if (PreL)
1637 CanonicalizeLoop(PreL, false);
1638 if (PostL)
1639 CanonicalizeLoop(PostL, false);
1640 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001641
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001642 return true;
1643}
1644
Sanjoy Das95c476d2015-02-21 22:20:22 +00001645/// Computes and returns a range of values for the induction variable (IndVar)
1646/// in which the range check can be safely elided. If it cannot compute such a
1647/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001648Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001649InductiveRangeCheck::computeSafeIterationSpace(
Max Kazantsev26846782017-11-20 06:07:57 +00001650 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar,
1651 bool IsLatchSigned) const {
Sanjoy Das95c476d2015-02-21 22:20:22 +00001652 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1653 // variable, that may or may not exist as a real llvm::Value in the loop) and
1654 // this inductive range check is a range check on the "C + D * I" ("C" is
Max Kazantsev84286ce2017-10-31 06:19:05 +00001655 // getBegin() and "D" is getStep()). We rewrite the value being range
Sanjoy Das95c476d2015-02-21 22:20:22 +00001656 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001657 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001658 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001659 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001660 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1661 //
Max Kazantsev26846782017-11-20 06:07:57 +00001662 // Here L stands for upper limit of the safe iteration space.
1663 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
1664 // overflows when calculating (0 - M) and (L - M) we, depending on type of
1665 // IV's iteration space, limit the calculations by borders of the iteration
1666 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
1667 // If we figured out that "anything greater than (-M) is safe", we strengthen
1668 // this to "everything greater than 0 is safe", assuming that values between
1669 // -M and 0 just do not exist in unsigned iteration space, and we don't want
1670 // to deal with overflown values.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001671
Sanjoy Das95c476d2015-02-21 22:20:22 +00001672 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001673 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001674
Sanjoy Das95c476d2015-02-21 22:20:22 +00001675 const SCEV *A = IndVar->getStart();
1676 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1677 if (!B)
1678 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001679 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001680
Max Kazantsev84286ce2017-10-31 06:19:05 +00001681 const SCEV *C = getBegin();
1682 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
Sanjoy Das95c476d2015-02-21 22:20:22 +00001683 if (D != B)
1684 return None;
1685
Max Kazantsev95054702017-08-04 07:41:24 +00001686 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Max Kazantsev26846782017-11-20 06:07:57 +00001687 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1688 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
Sanjoy Das95c476d2015-02-21 22:20:22 +00001689
Max Kazantsevb57ca092018-02-12 05:16:28 +00001690 // Subtract Y from X so that it does not go through border of the IV
Max Kazantsev26846782017-11-20 06:07:57 +00001691 // iteration space. Mathematically, it is equivalent to:
1692 //
Max Kazantsevb57ca092018-02-12 05:16:28 +00001693 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
Max Kazantsev26846782017-11-20 06:07:57 +00001694 //
Max Kazantsevb57ca092018-02-12 05:16:28 +00001695 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
Max Kazantsev26846782017-11-20 06:07:57 +00001696 // any width of bit grid). But after we take min/max, the result is
1697 // guaranteed to be within [INT_MIN, INT_MAX].
1698 //
1699 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
1700 // values, depending on type of latch condition that defines IV iteration
1701 // space.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001702 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
Max Kazantsev26846782017-11-20 06:07:57 +00001703 if (IsLatchSigned) {
1704 // X is a number from signed range, Y is interpreted as signed.
1705 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
1706 // thing we should care about is that we didn't cross SINT_MAX.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001707 // So, if Y is positive, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001708 // Rule 1: Y > 0 ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001709 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001710 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001711 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
Max Kazantsev26846782017-11-20 06:07:57 +00001712 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
Max Kazantsevb57ca092018-02-12 05:16:28 +00001713 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
Max Kazantsev26846782017-11-20 06:07:57 +00001714 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
Max Kazantsev716e6472017-11-23 06:14:39 +00001715 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
1716 SCEV::FlagNSW);
Max Kazantsev26846782017-11-20 06:07:57 +00001717 } else
1718 // X is a number from unsigned range, Y is interpreted as signed.
1719 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
1720 // thing we should care about is that we didn't cross zero.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001721 // So, if Y is negative, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001722 // Rule 1: Y <s 0 ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001723 // If 0 <= Y <= X, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001724 // Rule 2: Y <=s X ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001725 // If 0 <= X < Y, we should stop at 0 and can only subtract X.
Max Kazantsev26846782017-11-20 06:07:57 +00001726 // Rule 3: Y >s X ---> X.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001727 // It gives us smin(X, Y) to subtract in all cases.
Max Kazantsev716e6472017-11-23 06:14:39 +00001728 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
Max Kazantsev26846782017-11-20 06:07:57 +00001729 };
Sanjoy Das95c476d2015-02-21 22:20:22 +00001730 const SCEV *M = SE.getMinusSCEV(C, A);
Max Kazantsev26846782017-11-20 06:07:57 +00001731 const SCEV *Zero = SE.getZero(M->getType());
Max Kazantsevb57ca092018-02-12 05:16:28 +00001732 const SCEV *Begin = ClampedSubtract(Zero, M);
1733 const SCEV *End = ClampedSubtract(getEnd(), M);
Sanjoy Das351db052015-01-22 09:32:02 +00001734 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001735}
1736
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001737static Optional<InductiveRangeCheck::Range>
Max Kazantsev9ac70212017-10-25 06:47:39 +00001738IntersectSignedRange(ScalarEvolution &SE,
1739 const Optional<InductiveRangeCheck::Range> &R1,
1740 const InductiveRangeCheck::Range &R2) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001741 if (R2.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001742 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001743 if (!R1.hasValue())
1744 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001745 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001746 // We never return empty ranges from this function, and R1 is supposed to be
1747 // a result of intersection. Thus, R1 is never empty.
Max Kazantsev4332a942017-10-25 06:10:02 +00001748 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1749 "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001750
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001751 // TODO: we could widen the smaller range and have this work; but for now we
1752 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001753 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001754 return None;
1755
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001756 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1757 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1758
Max Kazantsev25d86552017-10-11 06:53:07 +00001759 // If the resulting range is empty, just return None.
1760 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
Max Kazantsev4332a942017-10-25 06:10:02 +00001761 if (Ret.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001762 return None;
1763 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001764}
1765
Max Kazantsev9ac70212017-10-25 06:47:39 +00001766static Optional<InductiveRangeCheck::Range>
1767IntersectUnsignedRange(ScalarEvolution &SE,
1768 const Optional<InductiveRangeCheck::Range> &R1,
1769 const InductiveRangeCheck::Range &R2) {
1770 if (R2.isEmpty(SE, /* IsSigned */ false))
1771 return None;
1772 if (!R1.hasValue())
1773 return R2;
1774 auto &R1Value = R1.getValue();
1775 // We never return empty ranges from this function, and R1 is supposed to be
1776 // a result of intersection. Thus, R1 is never empty.
1777 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1778 "We should never have empty R1!");
1779
1780 // TODO: we could widen the smaller range and have this work; but for now we
1781 // bail out to keep things simple.
1782 if (R1Value.getType() != R2.getType())
1783 return None;
1784
1785 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1786 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1787
1788 // If the resulting range is empty, just return None.
1789 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1790 if (Ret.isEmpty(SE, /* IsSigned */ false))
1791 return None;
1792 return Ret;
1793}
1794
Fedor Sergeev194a4072018-03-15 11:01:19 +00001795PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM,
1796 LoopStandardAnalysisResults &AR,
1797 LPMUpdater &U) {
1798 Function *F = L.getHeader()->getParent();
1799 const auto &FAM =
1800 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
1801 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
1802 InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI);
1803 auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) {
1804 if (!IsSubloop)
1805 U.addSiblingLoops(NL);
1806 };
1807 bool Changed = IRCE.run(&L, LPMAddNewLoop);
1808 if (!Changed)
1809 return PreservedAnalyses::all();
1810
1811 return getLoopPassPreservedAnalyses();
1812}
1813
1814bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001815 if (skipLoop(L))
1816 return false;
1817
Fedor Sergeev194a4072018-03-15 11:01:19 +00001818 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1819 BranchProbabilityInfo &BPI =
1820 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1821 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1822 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1823 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
1824 auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) {
1825 LPM.addLoop(*NL);
1826 };
1827 return IRCE.run(L, LPMAddNewLoop);
1828}
1829
1830bool InductiveRangeCheckElimination::run(
1831 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001832 if (L->getBlocks().size() >= LoopSizeCutoff) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001833 LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001834 return false;
1835 }
1836
1837 BasicBlock *Preheader = L->getLoopPreheader();
1838 if (!Preheader) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001839 LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001840 return false;
1841 }
1842
1843 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001844 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001845
1846 for (auto BBI : L->getBlocks())
1847 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001848 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1849 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001850
1851 if (RangeChecks.empty())
1852 return false;
1853
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001854 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1855 OS << "irce: looking at loop "; L->print(OS);
1856 OS << "irce: loop has " << RangeChecks.size()
1857 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001858 for (InductiveRangeCheck &IRC : RangeChecks)
1859 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001860 };
1861
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001862 LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001863
1864 if (PrintRangeChecks)
1865 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001866
Sanjoy Dase75ed922015-02-26 08:19:31 +00001867 const char *FailureReason = nullptr;
1868 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001869 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001870 if (!MaybeLoopStructure.hasValue()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001871 LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
1872 << FailureReason << "\n";);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001873 return false;
1874 }
1875 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001876 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001877 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001878
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001879 Optional<InductiveRangeCheck::Range> SafeIterRange;
1880 Instruction *ExprInsertPt = Preheader->getTerminator();
1881
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001882 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Max Kazantsev9ac70212017-10-25 06:47:39 +00001883 // Basing on the type of latch predicate, we interpret the IV iteration range
1884 // as signed or unsigned range. We use different min/max functions (signed or
1885 // unsigned) when intersecting this range with safe iteration ranges implied
1886 // by range checks.
1887 auto IntersectRange =
1888 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001889
1890 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001891 for (InductiveRangeCheck &IRC : RangeChecks) {
Max Kazantsev26846782017-11-20 06:07:57 +00001892 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1893 LS.IsSignedPredicate);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001894 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001895 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001896 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001897 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001898 assert(
1899 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1900 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001901 RangeChecksToEliminate.push_back(IRC);
1902 SafeIterRange = MaybeSafeIterRange.getValue();
1903 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001904 }
1905 }
1906
1907 if (!SafeIterRange.hasValue())
1908 return false;
1909
Fedor Sergeev194a4072018-03-15 11:01:19 +00001910 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1911 SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001912 bool Changed = LC.run();
1913
1914 if (Changed) {
1915 auto PrintConstrainedLoopInfo = [L]() {
1916 dbgs() << "irce: in function ";
1917 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1918 dbgs() << "constrained ";
1919 L->print(dbgs());
1920 };
1921
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001922 LLVM_DEBUG(PrintConstrainedLoopInfo());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001923
1924 if (PrintChangedLoops)
1925 PrintConstrainedLoopInfo();
1926
1927 // Optimize away the now-redundant range checks.
1928
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001929 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1930 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001931 ? ConstantInt::getTrue(Context)
1932 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001933 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001934 }
1935 }
1936
1937 return Changed;
1938}
1939
1940Pass *llvm::createInductiveRangeCheckEliminationPass() {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001941 return new IRCELegacyPass();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001942}