blob: 997d68838152fb274bd044c079114a6e85b3fb4e [file] [log] [blame]
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
Sanjoy Dasa1837a32015-01-16 01:03:22 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sanjoy Dasa1837a32015-01-16 01:03:22 +00006//
7//===----------------------------------------------------------------------===//
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00008//
Sanjoy Dasa1837a32015-01-16 01:03:22 +00009// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000042//
Sanjoy Dasa1837a32015-01-16 01:03:22 +000043//===----------------------------------------------------------------------===//
44
Fedor Sergeev194a4072018-03-15 11:01:19 +000045#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000046#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/None.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000049#include "llvm/ADT/Optional.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000050#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/ADT/StringRef.h"
53#include "llvm/ADT/Twine.h"
Sanjoy Dasdcf26512015-01-27 21:38:12 +000054#include "llvm/Analysis/BranchProbabilityInfo.h"
Fedor Sergeev194a4072018-03-15 11:01:19 +000055#include "llvm/Analysis/LoopAnalysisManager.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000056#include "llvm/Analysis/LoopInfo.h"
57#include "llvm/Analysis/LoopPass.h"
58#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/ScalarEvolutionExpander.h"
60#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000061#include "llvm/IR/BasicBlock.h"
62#include "llvm/IR/CFG.h"
63#include "llvm/IR/Constants.h"
64#include "llvm/IR/DerivedTypes.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000065#include "llvm/IR/Dominators.h"
66#include "llvm/IR/Function.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000067#include "llvm/IR/IRBuilder.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000068#include "llvm/IR/InstrTypes.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000069#include "llvm/IR/Instructions.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000070#include "llvm/IR/Metadata.h"
71#include "llvm/IR/Module.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000072#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000073#include "llvm/IR/Type.h"
74#include "llvm/IR/Use.h"
75#include "llvm/IR/User.h"
76#include "llvm/IR/Value.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000077#include "llvm/Pass.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000078#include "llvm/Support/BranchProbability.h"
79#include "llvm/Support/Casting.h"
80#include "llvm/Support/CommandLine.h"
81#include "llvm/Support/Compiler.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000082#include "llvm/Support/Debug.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000083#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000084#include "llvm/Support/raw_ostream.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000085#include "llvm/Transforms/Scalar.h"
Sanjoy Dasa1837a32015-01-16 01:03:22 +000086#include "llvm/Transforms/Utils/Cloning.h"
Sanjoy Dascf181862016-08-06 00:01:56 +000087#include "llvm/Transforms/Utils/LoopSimplify.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000088#include "llvm/Transforms/Utils/LoopUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000089#include "llvm/Transforms/Utils/ValueMapper.h"
90#include <algorithm>
91#include <cassert>
92#include <iterator>
93#include <limits>
94#include <utility>
95#include <vector>
Sanjoy Dasa1837a32015-01-16 01:03:22 +000096
97using namespace llvm;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000098using namespace llvm::PatternMatch;
Sanjoy Dasa1837a32015-01-16 01:03:22 +000099
Benjamin Kramer970eac42015-02-06 17:51:54 +0000100static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
101 cl::init(64));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000102
Benjamin Kramer970eac42015-02-06 17:51:54 +0000103static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
104 cl::init(false));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000105
Sanjoy Das9c1bfae2015-03-17 01:40:22 +0000106static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
107 cl::init(false));
108
Sanjoy Dase91665d2015-02-26 08:56:04 +0000109static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
110 cl::Hidden, cl::init(10));
111
Sanjoy Dasbb969792016-07-22 00:40:56 +0000112static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
113 cl::Hidden, cl::init(false));
114
Max Kazantsev8aacef62017-10-04 06:53:22 +0000115static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
Max Kazantsev9ac70212017-10-25 06:47:39 +0000116 cl::Hidden, cl::init(true));
Max Kazantsev8aacef62017-10-04 06:53:22 +0000117
Max Kazantsevd9aee3c2019-01-23 07:20:56 +0000118static cl::opt<bool> AllowNarrowLatchCondition(
Max Kazantsev34eeeec2019-01-30 11:25:12 +0000119 "irce-allow-narrow-latch", cl::Hidden, cl::init(true),
Max Kazantsevd9aee3c2019-01-23 07:20:56 +0000120 cl::desc("If set to true, IRCE may eliminate wide range checks in loops "
121 "with narrow latch condition."));
122
Sanjoy Das7a18a232016-08-14 01:04:36 +0000123static const char *ClonedLoopTag = "irce.loop.clone";
124
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000125#define DEBUG_TYPE "irce"
126
127namespace {
128
129/// An inductive range check is conditional branch in a loop with
130///
131/// 1. a very cold successor (i.e. the branch jumps to that successor very
132/// rarely)
133///
134/// and
135///
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000136/// 2. a condition that is provably true for some contiguous range of values
137/// taken by the containing loop's induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000138///
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000139class InductiveRangeCheck {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000140
Max Kazantsev84286ce2017-10-31 06:19:05 +0000141 const SCEV *Begin = nullptr;
142 const SCEV *Step = nullptr;
143 const SCEV *End = nullptr;
Sanjoy Dasee77a482016-05-26 01:50:18 +0000144 Use *CheckUse = nullptr;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000145 bool IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000146
Max Kazantsev80242ee2019-01-15 10:48:45 +0000147 static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
148 Value *&Index, Value *&Length,
149 bool &IsSigned);
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000150
Sanjoy Dasa0992682016-05-26 00:09:02 +0000151 static void
152 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
153 SmallVectorImpl<InductiveRangeCheck> &Checks,
154 SmallPtrSetImpl<Value *> &Visited);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000155
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000156public:
Max Kazantsev84286ce2017-10-31 06:19:05 +0000157 const SCEV *getBegin() const { return Begin; }
158 const SCEV *getStep() const { return Step; }
159 const SCEV *getEnd() const { return End; }
Max Kazantsev9ac70212017-10-25 06:47:39 +0000160 bool isSigned() const { return IsSigned; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000161
162 void print(raw_ostream &OS) const {
163 OS << "InductiveRangeCheck:\n";
Max Kazantsev84286ce2017-10-31 06:19:05 +0000164 OS << " Begin: ";
165 Begin->print(OS);
166 OS << " Step: ";
167 Step->print(OS);
168 OS << " End: ";
Max Kazantsevef057602018-01-12 10:00:26 +0000169 End->print(OS);
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000170 OS << "\n CheckUse: ";
171 getCheckUse()->getUser()->print(OS);
172 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000173 }
174
Davide Italianod1279df2016-08-18 15:55:49 +0000175 LLVM_DUMP_METHOD
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000176 void dump() {
177 print(dbgs());
178 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000179
Sanjoy Dasaa83c472016-05-23 22:16:45 +0000180 Use *getCheckUse() const { return CheckUse; }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000181
Sanjoy Das351db052015-01-22 09:32:02 +0000182 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
Max Kazantsevd0fe5022018-01-15 05:44:43 +0000183 /// R.getEnd() le R.getBegin(), then R denotes the empty range.
Sanjoy Das351db052015-01-22 09:32:02 +0000184
185 class Range {
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000186 const SCEV *Begin;
187 const SCEV *End;
Sanjoy Das351db052015-01-22 09:32:02 +0000188
189 public:
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000190 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
Sanjoy Das351db052015-01-22 09:32:02 +0000191 assert(Begin->getType() == End->getType() && "ill-typed range!");
192 }
193
194 Type *getType() const { return Begin->getType(); }
Sanjoy Das7fc60da2015-02-21 22:07:32 +0000195 const SCEV *getBegin() const { return Begin; }
196 const SCEV *getEnd() const { return End; }
Max Kazantsev4332a942017-10-25 06:10:02 +0000197 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
198 if (Begin == End)
199 return true;
200 if (IsSigned)
201 return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
202 else
203 return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
204 }
Sanjoy Das351db052015-01-22 09:32:02 +0000205 };
206
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000207 /// This is the value the condition of the branch needs to evaluate to for the
208 /// branch to take the hot successor (see (1) above).
209 bool getPassingDirection() { return true; }
210
Sanjoy Das95c476d2015-02-21 22:20:22 +0000211 /// Computes a range for the induction variable (IndVar) in which the range
212 /// check is redundant and can be constant-folded away. The induction
213 /// variable is not required to be the canonical {0,+,1} induction variable.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000214 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
Max Kazantsev26846782017-11-20 06:07:57 +0000215 const SCEVAddRecExpr *IndVar,
216 bool IsLatchSigned) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000217
Sanjoy Dasa0992682016-05-26 00:09:02 +0000218 /// Parse out a set of inductive range checks from \p BI and append them to \p
219 /// Checks.
220 ///
221 /// NB! There may be conditions feeding into \p BI that aren't inductive range
222 /// checks, and hence don't end up in \p Checks.
223 static void
224 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000225 BranchProbabilityInfo *BPI,
Sanjoy Dasa0992682016-05-26 00:09:02 +0000226 SmallVectorImpl<InductiveRangeCheck> &Checks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000227};
228
Fedor Sergeev194a4072018-03-15 11:01:19 +0000229class InductiveRangeCheckElimination {
230 ScalarEvolution &SE;
231 BranchProbabilityInfo *BPI;
232 DominatorTree &DT;
233 LoopInfo &LI;
234
235public:
236 InductiveRangeCheckElimination(ScalarEvolution &SE,
237 BranchProbabilityInfo *BPI, DominatorTree &DT,
238 LoopInfo &LI)
239 : SE(SE), BPI(BPI), DT(DT), LI(LI) {}
240
241 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
242};
243
244class IRCELegacyPass : public LoopPass {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000245public:
246 static char ID;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000247
Fedor Sergeev194a4072018-03-15 11:01:19 +0000248 IRCELegacyPass() : LoopPass(ID) {
249 initializeIRCELegacyPassPass(*PassRegistry::getPassRegistry());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000250 }
251
252 void getAnalysisUsage(AnalysisUsage &AU) const override {
Cong Houab23bfb2015-07-15 22:48:29 +0000253 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000254 getLoopAnalysisUsage(AU);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000255 }
256
257 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
258};
259
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000260} // end anonymous namespace
261
Fedor Sergeev194a4072018-03-15 11:01:19 +0000262char IRCELegacyPass::ID = 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000263
Fedor Sergeev194a4072018-03-15 11:01:19 +0000264INITIALIZE_PASS_BEGIN(IRCELegacyPass, "irce",
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000265 "Inductive range check elimination", false, false)
Sanjoy Dasda0d79e2015-09-09 03:47:18 +0000266INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000267INITIALIZE_PASS_DEPENDENCY(LoopPass)
Fedor Sergeev194a4072018-03-15 11:01:19 +0000268INITIALIZE_PASS_END(IRCELegacyPass, "irce", "Inductive range check elimination",
269 false, false)
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000270
Sanjoy Dasf13900f2016-03-09 02:34:15 +0000271/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
Max Kazantsev80242ee2019-01-15 10:48:45 +0000272/// be interpreted as a range check, return false and set `Index` and `Length`
273/// to `nullptr`. Otherwise set `Index` to the value being range checked, and
274/// set `Length` to the upper limit `Index` is being range checked.
275bool
Sanjoy Das337d46b2015-03-24 19:29:18 +0000276InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
277 ScalarEvolution &SE, Value *&Index,
Max Kazantsev9ac70212017-10-25 06:47:39 +0000278 Value *&Length, bool &IsSigned) {
Max Kazantsev8624a472018-04-09 06:01:22 +0000279 auto IsLoopInvariant = [&SE, L](Value *V) {
280 return SE.isLoopInvariant(SE.getSCEV(V), L);
Sanjoy Das337d46b2015-03-24 19:29:18 +0000281 };
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000282
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000283 ICmpInst::Predicate Pred = ICI->getPredicate();
284 Value *LHS = ICI->getOperand(0);
285 Value *RHS = ICI->getOperand(1);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000286
287 switch (Pred) {
288 default:
Max Kazantsev80242ee2019-01-15 10:48:45 +0000289 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000290
291 case ICmpInst::ICMP_SLE:
292 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000293 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000294 case ICmpInst::ICMP_SGE:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000295 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000296 if (match(RHS, m_ConstantInt<0>())) {
297 Index = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000298 return true; // Lower.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000299 }
Max Kazantsev80242ee2019-01-15 10:48:45 +0000300 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000301
302 case ICmpInst::ICMP_SLT:
303 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000304 LLVM_FALLTHROUGH;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000305 case ICmpInst::ICMP_SGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000306 IsSigned = true;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000307 if (match(RHS, m_ConstantInt<-1>())) {
308 Index = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000309 return true; // Lower.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000310 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000311
Max Kazantsev8624a472018-04-09 06:01:22 +0000312 if (IsLoopInvariant(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000313 Index = RHS;
314 Length = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000315 return true; // Upper.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000316 }
Max Kazantsev80242ee2019-01-15 10:48:45 +0000317 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000318
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000319 case ICmpInst::ICMP_ULT:
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000320 std::swap(LHS, RHS);
Justin Bognerb03fd122016-08-17 05:10:15 +0000321 LLVM_FALLTHROUGH;
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000322 case ICmpInst::ICMP_UGT:
Max Kazantsev9ac70212017-10-25 06:47:39 +0000323 IsSigned = false;
Max Kazantsev8624a472018-04-09 06:01:22 +0000324 if (IsLoopInvariant(LHS)) {
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000325 Index = RHS;
326 Length = LHS;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000327 return true; // Both lower and upper.
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000328 }
Max Kazantsev80242ee2019-01-15 10:48:45 +0000329 return false;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000330 }
Sanjoy Dase2cde6f2015-03-17 00:42:13 +0000331
332 llvm_unreachable("default clause returns!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000333}
334
Sanjoy Dasa0992682016-05-26 00:09:02 +0000335void InductiveRangeCheck::extractRangeChecksFromCond(
336 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
337 SmallVectorImpl<InductiveRangeCheck> &Checks,
338 SmallPtrSetImpl<Value *> &Visited) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000339 Value *Condition = ConditionUse.get();
Sanjoy Dasa0992682016-05-26 00:09:02 +0000340 if (!Visited.insert(Condition).second)
341 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000342
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000343 // TODO: Do the same for OR, XOR, NOT etc?
Sanjoy Dasa0992682016-05-26 00:09:02 +0000344 if (match(Condition, m_And(m_Value(), m_Value()))) {
Sanjoy Dasa0992682016-05-26 00:09:02 +0000345 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000346 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000347 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
Max Kazantsev1ac6e8a2017-11-17 06:49:26 +0000348 Checks, Visited);
Sanjoy Dasa0992682016-05-26 00:09:02 +0000349 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000350 }
351
Sanjoy Dasa0992682016-05-26 00:09:02 +0000352 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
353 if (!ICI)
354 return;
355
356 Value *Length = nullptr, *Index;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000357 bool IsSigned;
Max Kazantsev80242ee2019-01-15 10:48:45 +0000358 if (!parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned))
Sanjoy Dasa0992682016-05-26 00:09:02 +0000359 return;
360
Sanjoy Das5fd7ac42016-05-24 17:19:56 +0000361 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000362 bool IsAffineIndex =
363 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
364
365 if (!IsAffineIndex)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000366 return;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000367
Max Kazantsevef057602018-01-12 10:00:26 +0000368 const SCEV *End = nullptr;
369 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
370 // We can potentially do much better here.
371 if (Length)
372 End = SE.getSCEV(Length);
373 else {
Max Kazantsevef057602018-01-12 10:00:26 +0000374 // So far we can only reach this point for Signed range check. This may
375 // change in future. In this case we will need to pick Unsigned max for the
376 // unsigned range check.
377 unsigned BitWidth = cast<IntegerType>(IndexAddRec->getType())->getBitWidth();
378 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
379 End = SIntMax;
380 }
381
Sanjoy Dasc5b11692016-05-21 02:52:13 +0000382 InductiveRangeCheck IRC;
Max Kazantsevef057602018-01-12 10:00:26 +0000383 IRC.End = End;
Max Kazantsev84286ce2017-10-31 06:19:05 +0000384 IRC.Begin = IndexAddRec->getStart();
385 IRC.Step = IndexAddRec->getStepRecurrence(SE);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000386 IRC.CheckUse = &ConditionUse;
Max Kazantsev9ac70212017-10-25 06:47:39 +0000387 IRC.IsSigned = IsSigned;
Sanjoy Dasa0992682016-05-26 00:09:02 +0000388 Checks.push_back(IRC);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000389}
390
Sanjoy Dasa0992682016-05-26 00:09:02 +0000391void InductiveRangeCheck::extractRangeChecksFromBranch(
Fedor Sergeev194a4072018-03-15 11:01:19 +0000392 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
Sanjoy Dasa0992682016-05-26 00:09:02 +0000393 SmallVectorImpl<InductiveRangeCheck> &Checks) {
Sanjoy Das8fe88922016-05-26 00:08:24 +0000394 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
Sanjoy Dasa0992682016-05-26 00:09:02 +0000395 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000396
397 BranchProbability LikelyTaken(15, 16);
398
Fedor Sergeev194a4072018-03-15 11:01:19 +0000399 if (!SkipProfitabilityChecks && BPI &&
400 BPI->getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
Sanjoy Dasa0992682016-05-26 00:09:02 +0000401 return;
Sanjoy Das8fe88922016-05-26 00:08:24 +0000402
Sanjoy Dasa0992682016-05-26 00:09:02 +0000403 SmallPtrSet<Value *, 8> Visited;
404 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
405 Checks, Visited);
Sanjoy Das8fe88922016-05-26 00:08:24 +0000406}
407
Anna Thomas65ca8e92016-12-13 21:05:21 +0000408// Add metadata to the loop L to disable loop optimizations. Callers need to
409// confirm that optimizing loop L is not beneficial.
410static void DisableAllLoopOptsOnLoop(Loop &L) {
411 // We do not care about any existing loopID related metadata for L, since we
412 // are setting all loop metadata to false.
413 LLVMContext &Context = L.getHeader()->getContext();
414 // Reserve first location for self reference to the LoopID metadata node.
415 MDNode *Dummy = MDNode::get(Context, {});
416 MDNode *DisableUnroll = MDNode::get(
417 Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
418 Metadata *FalseVal =
419 ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
420 MDNode *DisableVectorize = MDNode::get(
421 Context,
422 {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
423 MDNode *DisableLICMVersioning = MDNode::get(
424 Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
425 MDNode *DisableDistribution= MDNode::get(
426 Context,
427 {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
428 MDNode *NewLoopID =
429 MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
430 DisableLICMVersioning, DisableDistribution});
431 // Set operand 0 to refer to the loop id itself.
432 NewLoopID->replaceOperandWith(0, NewLoopID);
433 L.setLoopID(NewLoopID);
434}
435
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000436namespace {
437
Sanjoy Dase75ed922015-02-26 08:19:31 +0000438// Keeps track of the structure of a loop. This is similar to llvm::Loop,
439// except that it is more lightweight and can track the state of a loop through
440// changing and potentially invalid IR. This structure also formalizes the
441// kinds of loops we can deal with -- ones that have a single latch that is also
442// an exiting block *and* have a canonical induction variable.
443struct LoopStructure {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000444 const char *Tag = "";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000445
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000446 BasicBlock *Header = nullptr;
447 BasicBlock *Latch = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000448
449 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
450 // successor is `LatchExit', the exit block of the loop.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000451 BranchInst *LatchBr = nullptr;
452 BasicBlock *LatchExit = nullptr;
453 unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
Sanjoy Dase75ed922015-02-26 08:19:31 +0000454
Sanjoy Dasec892132017-02-07 23:59:07 +0000455 // The loop represented by this instance of LoopStructure is semantically
456 // equivalent to:
457 //
458 // intN_ty inc = IndVarIncreasing ? 1 : -1;
Serguei Katkov675e3042017-09-21 04:50:41 +0000459 // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
Sanjoy Dasec892132017-02-07 23:59:07 +0000460 //
Serguei Katkov675e3042017-09-21 04:50:41 +0000461 // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
Sanjoy Dasec892132017-02-07 23:59:07 +0000462 // ... body ...
463
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000464 Value *IndVarBase = nullptr;
465 Value *IndVarStart = nullptr;
466 Value *IndVarStep = nullptr;
467 Value *LoopExitAt = nullptr;
468 bool IndVarIncreasing = false;
469 bool IsSignedPredicate = true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000470
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000471 LoopStructure() = default;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000472
473 template <typename M> LoopStructure map(M Map) const {
474 LoopStructure Result;
475 Result.Tag = Tag;
476 Result.Header = cast<BasicBlock>(Map(Header));
477 Result.Latch = cast<BasicBlock>(Map(Latch));
478 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
479 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
480 Result.LatchBrExitIdx = LatchBrExitIdx;
Max Kazantseva22742b2017-08-31 05:58:15 +0000481 Result.IndVarBase = Map(IndVarBase);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000482 Result.IndVarStart = Map(IndVarStart);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000483 Result.IndVarStep = Map(IndVarStep);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000484 Result.LoopExitAt = Map(LoopExitAt);
485 Result.IndVarIncreasing = IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000486 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000487 return Result;
488 }
489
Sanjoy Dase91665d2015-02-26 08:56:04 +0000490 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000491 BranchProbabilityInfo *BPI,
492 Loop &, const char *&);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000493};
494
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000495/// This class is used to constrain loops to run within a given iteration space.
496/// The algorithm this class implements is given a Loop and a range [Begin,
497/// End). The algorithm then tries to break out a "main loop" out of the loop
498/// it is given in a way that the "main loop" runs with the induction variable
499/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
500/// loops to run any remaining iterations. The pre loop runs any iterations in
501/// which the induction variable is < Begin, and the post loop runs any
502/// iterations in which the induction variable is >= End.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000503class LoopConstrainer {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000504 // The representation of a clone of the original loop we started out with.
505 struct ClonedLoop {
506 // The cloned blocks
507 std::vector<BasicBlock *> Blocks;
508
509 // `Map` maps values in the clonee into values in the cloned version
510 ValueToValueMapTy Map;
511
512 // An instance of `LoopStructure` for the cloned loop
513 LoopStructure Structure;
514 };
515
516 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
517 // more details on what these fields mean.
518 struct RewrittenRangeInfo {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000519 BasicBlock *PseudoExit = nullptr;
520 BasicBlock *ExitSelector = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000521 std::vector<PHINode *> PHIValuesAtPseudoExit;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000522 PHINode *IndVarEnd = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000523
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000524 RewrittenRangeInfo() = default;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000525 };
526
527 // Calculated subranges we restrict the iteration space of the main loop to.
528 // See the implementation of `calculateSubRanges' for more details on how
Sanjoy Dase75ed922015-02-26 08:19:31 +0000529 // these fields are computed. `LowLimit` is None if there is no restriction
530 // on low end of the restricted iteration space of the main loop. `HighLimit`
531 // is None if there is no restriction on high end of the restricted iteration
532 // space of the main loop.
533
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000534 struct SubRanges {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000535 Optional<const SCEV *> LowLimit;
536 Optional<const SCEV *> HighLimit;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000537 };
538
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000539 // Compute a safe set of limits for the main loop to run in -- effectively the
540 // intersection of `Range' and the iteration space of the original loop.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000541 // Return None if unable to compute the set of subranges.
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000542 Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000543
544 // Clone `OriginalLoop' and return the result in CLResult. The IR after
545 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
546 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
547 // but there is no such edge.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000548 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
549
Sanjoy Das21434472016-08-14 01:04:46 +0000550 // Create the appropriate loop structure needed to describe a cloned copy of
551 // `Original`. The clone is described by `VM`.
552 Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000553 ValueToValueMapTy &VM, bool IsSubloop);
Sanjoy Das21434472016-08-14 01:04:46 +0000554
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000555 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
556 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
557 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
558 // `OriginalHeaderCount'.
559 //
560 // If there are iterations left to execute, control is made to jump to
561 // `ContinuationBlock', otherwise they take the normal loop exit. The
562 // returned `RewrittenRangeInfo' object is populated as follows:
563 //
564 // .PseudoExit is a basic block that unconditionally branches to
565 // `ContinuationBlock'.
566 //
567 // .ExitSelector is a basic block that decides, on exit from the loop,
568 // whether to branch to the "true" exit or to `PseudoExit'.
569 //
570 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
571 // for each PHINode in the loop header on taking the pseudo exit.
572 //
573 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
574 // preheader because it is made to branch to the loop header only
575 // conditionally.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000576 RewrittenRangeInfo
577 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
578 Value *ExitLoopAt,
579 BasicBlock *ContinuationBlock) const;
580
581 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
582 // function creates a new preheader for `LS' and returns it.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000583 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
584 const char *Tag) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000585
586 // `ContinuationBlockAndPreheader' was the continuation block for some call to
587 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
588 // This function rewrites the PHI nodes in `LS.Header' to start with the
589 // correct value.
590 void rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +0000591 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000592 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
593
594 // Even though we do not preserve any passes at this time, we at least need to
595 // keep the parent loop structure consistent. The `LPPassManager' seems to
596 // verify this after running a loop pass. This function adds the list of
Benjamin Kramer39f76ac2015-02-06 14:43:49 +0000597 // blocks denoted by BBs to this loops parent loop if required.
598 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000599
600 // Some global state.
601 Function &F;
602 LLVMContext &Ctx;
603 ScalarEvolution &SE;
Sanjoy Dasf45e03e2016-08-02 19:31:54 +0000604 DominatorTree &DT;
Sanjoy Das35459f02016-08-14 01:04:50 +0000605 LoopInfo &LI;
Fedor Sergeev194a4072018-03-15 11:01:19 +0000606 function_ref<void(Loop *, bool)> LPMAddNewLoop;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000607
608 // Information about the original loop we started out with.
609 Loop &OriginalLoop;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000610
611 const SCEV *LatchTakenCount = nullptr;
612 BasicBlock *OriginalPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000613
614 // The preheader of the main loop. This may or may not be different from
615 // `OriginalPreheader'.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000616 BasicBlock *MainLoopPreheader = nullptr;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000617
618 // The range we need to run the main loop in.
619 InductiveRangeCheck::Range Range;
620
621 // The structure of the main loop (see comment at the beginning of this class
622 // for a definition)
623 LoopStructure MainLoopStructure;
624
625public:
Fedor Sergeev194a4072018-03-15 11:01:19 +0000626 LoopConstrainer(Loop &L, LoopInfo &LI,
627 function_ref<void(Loop *, bool)> LPMAddNewLoop,
Sanjoy Das21434472016-08-14 01:04:46 +0000628 const LoopStructure &LS, ScalarEvolution &SE,
629 DominatorTree &DT, InductiveRangeCheck::Range R)
Sanjoy Dase75ed922015-02-26 08:19:31 +0000630 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
Fedor Sergeev194a4072018-03-15 11:01:19 +0000631 SE(SE), DT(DT), LI(LI), LPMAddNewLoop(LPMAddNewLoop), OriginalLoop(L),
632 Range(R), MainLoopStructure(LS) {}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000633
634 // Entry point for the algorithm. Returns true on success.
635 bool run();
636};
637
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000638} // end anonymous namespace
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000639
Sam Parker90b7f4f2018-03-27 08:24:53 +0000640/// Given a loop with an deccreasing induction variable, is it possible to
641/// safely calculate the bounds of a new loop using the given Predicate.
642static bool isSafeDecreasingBound(const SCEV *Start,
643 const SCEV *BoundSCEV, const SCEV *Step,
644 ICmpInst::Predicate Pred,
645 unsigned LatchBrExitIdx,
646 Loop *L, ScalarEvolution &SE) {
647 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
648 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
649 return false;
650
651 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
652 return false;
653
654 assert(SE.isKnownNegative(Step) && "expecting negative step");
655
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000656 LLVM_DEBUG(dbgs() << "irce: isSafeDecreasingBound with:\n");
657 LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
658 LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
659 LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
660 LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
661 << "\n");
662 LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
Sam Parker90b7f4f2018-03-27 08:24:53 +0000663
664 bool IsSigned = ICmpInst::isSigned(Pred);
665 // The predicate that we need to check that the induction variable lies
666 // within bounds.
667 ICmpInst::Predicate BoundPred =
668 IsSigned ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
669
670 if (LatchBrExitIdx == 1)
671 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
672
673 assert(LatchBrExitIdx == 0 &&
674 "LatchBrExitIdx should be either 0 or 1");
Fangrui Songf78650a2018-07-30 19:41:25 +0000675
Sam Parker90b7f4f2018-03-27 08:24:53 +0000676 const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
677 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
678 APInt Min = IsSigned ? APInt::getSignedMinValue(BitWidth) :
679 APInt::getMinValue(BitWidth);
680 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Min), StepPlusOne);
681
682 const SCEV *MinusOne =
683 SE.getMinusSCEV(BoundSCEV, SE.getOne(BoundSCEV->getType()));
684
685 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, MinusOne) &&
686 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit);
687
Sanjoy Dase75ed922015-02-26 08:19:31 +0000688}
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000689
Sam Parker53a423a2018-03-26 09:29:42 +0000690/// Given a loop with an increasing induction variable, is it possible to
691/// safely calculate the bounds of a new loop using the given Predicate.
692static bool isSafeIncreasingBound(const SCEV *Start,
693 const SCEV *BoundSCEV, const SCEV *Step,
694 ICmpInst::Predicate Pred,
695 unsigned LatchBrExitIdx,
696 Loop *L, ScalarEvolution &SE) {
697 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SGT &&
698 Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_UGT)
699 return false;
700
701 if (!SE.isAvailableAtLoopEntry(BoundSCEV, L))
702 return false;
703
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000704 LLVM_DEBUG(dbgs() << "irce: isSafeIncreasingBound with:\n");
705 LLVM_DEBUG(dbgs() << "irce: Start: " << *Start << "\n");
706 LLVM_DEBUG(dbgs() << "irce: Step: " << *Step << "\n");
707 LLVM_DEBUG(dbgs() << "irce: BoundSCEV: " << *BoundSCEV << "\n");
708 LLVM_DEBUG(dbgs() << "irce: Pred: " << ICmpInst::getPredicateName(Pred)
709 << "\n");
710 LLVM_DEBUG(dbgs() << "irce: LatchExitBrIdx: " << LatchBrExitIdx << "\n");
Sam Parker53a423a2018-03-26 09:29:42 +0000711
712 bool IsSigned = ICmpInst::isSigned(Pred);
713 // The predicate that we need to check that the induction variable lies
714 // within bounds.
715 ICmpInst::Predicate BoundPred =
716 IsSigned ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
717
718 if (LatchBrExitIdx == 1)
719 return SE.isLoopEntryGuardedByCond(L, BoundPred, Start, BoundSCEV);
720
721 assert(LatchBrExitIdx == 0 && "LatchBrExitIdx should be 0 or 1");
722
723 const SCEV *StepMinusOne =
724 SE.getMinusSCEV(Step, SE.getOne(Step->getType()));
725 unsigned BitWidth = cast<IntegerType>(BoundSCEV->getType())->getBitWidth();
Fangrui Songf78650a2018-07-30 19:41:25 +0000726 APInt Max = IsSigned ? APInt::getSignedMaxValue(BitWidth) :
Sam Parker53a423a2018-03-26 09:29:42 +0000727 APInt::getMaxValue(BitWidth);
728 const SCEV *Limit = SE.getMinusSCEV(SE.getConstant(Max), StepMinusOne);
729
730 return (SE.isLoopEntryGuardedByCond(L, BoundPred, Start,
731 SE.getAddExpr(BoundSCEV, Step)) &&
732 SE.isLoopEntryGuardedByCond(L, BoundPred, BoundSCEV, Limit));
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000733}
734
Sanjoy Dase75ed922015-02-26 08:19:31 +0000735Optional<LoopStructure>
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000736LoopStructure::parseLoopStructure(ScalarEvolution &SE,
Fedor Sergeev194a4072018-03-15 11:01:19 +0000737 BranchProbabilityInfo *BPI, Loop &L,
738 const char *&FailureReason) {
Sanjoy Das43fdc542016-08-14 01:04:31 +0000739 if (!L.isLoopSimplifyForm()) {
740 FailureReason = "loop not in LoopSimplify form";
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000741 return None;
Sanjoy Das43fdc542016-08-14 01:04:31 +0000742 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000743
744 BasicBlock *Latch = L.getLoopLatch();
Sanjoy Das2a2f14d2016-08-13 23:36:35 +0000745 assert(Latch && "Simplified loops only have one latch!");
746
Sanjoy Das7a18a232016-08-14 01:04:36 +0000747 if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
748 FailureReason = "loop has already been cloned";
749 return None;
750 }
751
Sanjoy Dase75ed922015-02-26 08:19:31 +0000752 if (!L.isLoopExiting(Latch)) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000753 FailureReason = "no loop latch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000754 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000755 }
756
Sanjoy Dase75ed922015-02-26 08:19:31 +0000757 BasicBlock *Header = L.getHeader();
758 BasicBlock *Preheader = L.getLoopPreheader();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000759 if (!Preheader) {
760 FailureReason = "no preheader";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000761 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000762 }
763
Sanjoy Das81c00fe2016-06-23 18:03:26 +0000764 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000765 if (!LatchBr || LatchBr->isUnconditional()) {
766 FailureReason = "latch terminator not conditional branch";
Sanjoy Dase75ed922015-02-26 08:19:31 +0000767 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000768 }
769
Sanjoy Dase75ed922015-02-26 08:19:31 +0000770 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000771
Sanjoy Dase91665d2015-02-26 08:56:04 +0000772 BranchProbability ExitProbability =
Fedor Sergeev194a4072018-03-15 11:01:19 +0000773 BPI ? BPI->getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx)
774 : BranchProbability::getZero();
Sanjoy Dase91665d2015-02-26 08:56:04 +0000775
Sanjoy Dasbb969792016-07-22 00:40:56 +0000776 if (!SkipProfitabilityChecks &&
777 ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
Sanjoy Dase91665d2015-02-26 08:56:04 +0000778 FailureReason = "short running loop, not profitable";
779 return None;
780 }
781
Sanjoy Dase75ed922015-02-26 08:19:31 +0000782 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
783 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
784 FailureReason = "latch terminator branch not conditional on integral icmp";
785 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000786 }
787
Sanjoy Dase75ed922015-02-26 08:19:31 +0000788 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
789 if (isa<SCEVCouldNotCompute>(LatchCount)) {
790 FailureReason = "could not compute latch count";
791 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000792 }
793
Sanjoy Dase75ed922015-02-26 08:19:31 +0000794 ICmpInst::Predicate Pred = ICI->getPredicate();
795 Value *LeftValue = ICI->getOperand(0);
796 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
797 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
798
799 Value *RightValue = ICI->getOperand(1);
800 const SCEV *RightSCEV = SE.getSCEV(RightValue);
801
802 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
803 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
804 if (isa<SCEVAddRecExpr>(RightSCEV)) {
805 std::swap(LeftSCEV, RightSCEV);
806 std::swap(LeftValue, RightValue);
807 Pred = ICmpInst::getSwappedPredicate(Pred);
808 } else {
809 FailureReason = "no add recurrences in the icmp";
810 return None;
811 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000812 }
813
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000814 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
815 if (AR->getNoWrapFlags(SCEV::FlagNSW))
816 return true;
Sanjoy Dase75ed922015-02-26 08:19:31 +0000817
818 IntegerType *Ty = cast<IntegerType>(AR->getType());
819 IntegerType *WideTy =
820 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
821
Sanjoy Das45dc94a2015-03-24 19:29:22 +0000822 const SCEVAddRecExpr *ExtendAfterOp =
823 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
824 if (ExtendAfterOp) {
825 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
826 const SCEV *ExtendedStep =
827 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
828
829 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
830 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
831
832 if (NoSignedWrap)
833 return true;
834 }
835
836 // We may have proved this when computing the sign extension above.
837 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
838 };
839
Serguei Katkov675e3042017-09-21 04:50:41 +0000840 // `ICI` is interpreted as taking the backedge if the *next* value of the
841 // induction variable satisfies some constraint.
Sanjoy Dase75ed922015-02-26 08:19:31 +0000842
Max Kazantseva22742b2017-08-31 05:58:15 +0000843 const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
Sam Parker3c190512018-04-18 13:50:28 +0000844 if (!IndVarBase->isAffine()) {
Sanjoy Dase75ed922015-02-26 08:19:31 +0000845 FailureReason = "LHS in icmp not induction variable";
846 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000847 }
Sam Parker3c190512018-04-18 13:50:28 +0000848 const SCEV* StepRec = IndVarBase->getStepRecurrence(SE);
Max Kazantsev786032c2018-05-04 07:34:35 +0000849 if (!isa<SCEVConstant>(StepRec)) {
Sam Parker3c190512018-04-18 13:50:28 +0000850 FailureReason = "LHS in icmp not induction variable";
851 return None;
852 }
Max Kazantsev786032c2018-05-04 07:34:35 +0000853 ConstantInt *StepCI = cast<SCEVConstant>(StepRec)->getValue();
854
Sam Parker3c190512018-04-18 13:50:28 +0000855 if (ICI->isEquality() && !HasNoSignedWrap(IndVarBase)) {
856 FailureReason = "LHS in icmp needs nsw for equality predicates";
857 return None;
858 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000859
Sam Parker3c190512018-04-18 13:50:28 +0000860 assert(!StepCI->isZero() && "Zero step?");
861 bool IsIncreasing = !StepCI->isNegative();
Fangrui Songb251cc02019-07-12 14:58:15 +0000862 bool IsSignedPredicate;
Serguei Katkov675e3042017-09-21 04:50:41 +0000863 const SCEV *StartNext = IndVarBase->getStart();
864 const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
865 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000866 const SCEV *Step = SE.getSCEV(StepCI);
Sanjoy Dasec892132017-02-07 23:59:07 +0000867
Sanjoy Dase75ed922015-02-26 08:19:31 +0000868 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000869 if (IsIncreasing) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000870 bool DecreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000871 if (StepCI->isOne()) {
872 // Try to turn eq/ne predicates to those we can work with.
873 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
874 // while (++i != len) { while (++i < len) {
875 // ... ---> ...
876 // } }
877 // If both parts are known non-negative, it is profitable to use
878 // unsigned comparison in increasing loop. This allows us to make the
879 // comparison check against "RightSCEV + 1" more optimistic.
Sam Parker97375352018-04-12 12:49:40 +0000880 if (isKnownNonNegativeInLoop(IndVarStart, &L, SE) &&
881 isKnownNonNegativeInLoop(RightSCEV, &L, SE))
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000882 Pred = ICmpInst::ICMP_ULT;
883 else
884 Pred = ICmpInst::ICMP_SLT;
Sam Parker53a423a2018-03-26 09:29:42 +0000885 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000886 // while (true) { while (true) {
887 // if (++i == len) ---> if (++i > len - 1)
888 // break; break;
889 // ... ...
890 // } }
Sam Parker53a423a2018-03-26 09:29:42 +0000891 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000892 cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/false)) {
Sam Parker53a423a2018-03-26 09:29:42 +0000893 Pred = ICmpInst::ICMP_UGT;
894 RightSCEV = SE.getMinusSCEV(RightSCEV,
895 SE.getOne(RightSCEV->getType()));
896 DecreasedRightValueByOne = true;
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000897 } else if (cannotBeMinInLoop(RightSCEV, &L, SE, /*Signed*/true)) {
Sam Parker53a423a2018-03-26 09:29:42 +0000898 Pred = ICmpInst::ICMP_SGT;
899 RightSCEV = SE.getMinusSCEV(RightSCEV,
900 SE.getOne(RightSCEV->getType()));
901 DecreasedRightValueByOne = true;
902 }
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000903 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000904 }
905
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000906 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
907 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000908 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000909 (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000910
911 if (!FoundExpectedPred) {
912 FailureReason = "expected icmp slt semantically, found something else";
913 return None;
914 }
915
Sam Parker53a423a2018-03-26 09:29:42 +0000916 IsSignedPredicate = ICmpInst::isSigned(Pred);
Max Kazantsev8aacef62017-10-04 06:53:22 +0000917 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
918 FailureReason = "unsigned latch conditions are explicitly prohibited";
919 return None;
920 }
921
Sam Parker53a423a2018-03-26 09:29:42 +0000922 if (!isSafeIncreasingBound(IndVarStart, RightSCEV, Step, Pred,
923 LatchBrExitIdx, &L, SE)) {
924 FailureReason = "Unsafe loop bounds";
925 return None;
926 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000927 if (LatchBrExitIdx == 0) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000928 // We need to increase the right value unless we have already decreased
929 // it virtually when we replaced EQ with SGT.
930 if (!DecreasedRightValueByOne) {
931 IRBuilder<> B(Preheader->getTerminator());
932 RightValue = B.CreateAdd(RightValue, One);
933 }
Sanjoy Dasec892132017-02-07 23:59:07 +0000934 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000935 assert(!DecreasedRightValueByOne &&
936 "Right value can be decreased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +0000937 }
Sanjoy Dase75ed922015-02-26 08:19:31 +0000938 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000939 bool IncreasedRightValueByOne = false;
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000940 if (StepCI->isMinusOne()) {
941 // Try to turn eq/ne predicates to those we can work with.
942 if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
943 // while (--i != len) { while (--i > len) {
944 // ... ---> ...
945 // } }
946 // We intentionally don't turn the predicate into UGT even if we know
947 // that both operands are non-negative, because it will only pessimize
948 // our check against "RightSCEV - 1".
949 Pred = ICmpInst::ICMP_SGT;
Sam Parker90b7f4f2018-03-27 08:24:53 +0000950 else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0) {
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000951 // while (true) { while (true) {
952 // if (--i == len) ---> if (--i < len + 1)
953 // break; break;
954 // ... ...
955 // } }
Sam Parker90b7f4f2018-03-27 08:24:53 +0000956 if (IndVarBase->getNoWrapFlags(SCEV::FlagNUW) &&
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000957 cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ false)) {
Sam Parker90b7f4f2018-03-27 08:24:53 +0000958 Pred = ICmpInst::ICMP_ULT;
959 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
960 IncreasedRightValueByOne = true;
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000961 } else if (cannotBeMaxInLoop(RightSCEV, &L, SE, /* Signed */ true)) {
Sam Parker90b7f4f2018-03-27 08:24:53 +0000962 Pred = ICmpInst::ICMP_SLT;
963 RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
964 IncreasedRightValueByOne = true;
965 }
Max Kazantsev2f6ae282017-08-04 07:01:04 +0000966 }
Max Kazantsev2c627a92017-07-18 04:53:48 +0000967 }
968
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000969 bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
970 bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
971
Sanjoy Dase75ed922015-02-26 08:19:31 +0000972 bool FoundExpectedPred =
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000973 (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
Sanjoy Dase75ed922015-02-26 08:19:31 +0000974
975 if (!FoundExpectedPred) {
976 FailureReason = "expected icmp sgt semantically, found something else";
977 return None;
978 }
979
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000980 IsSignedPredicate =
981 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
Max Kazantsev8aacef62017-10-04 06:53:22 +0000982
Max Kazantsev8aacef62017-10-04 06:53:22 +0000983 if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
984 FailureReason = "unsigned latch conditions are explicitly prohibited";
985 return None;
986 }
987
Sam Parker90b7f4f2018-03-27 08:24:53 +0000988 if (!isSafeDecreasingBound(IndVarStart, RightSCEV, Step, Pred,
989 LatchBrExitIdx, &L, SE)) {
990 FailureReason = "Unsafe bounds";
991 return None;
992 }
Max Kazantsev07da1ab2017-08-04 05:40:20 +0000993
Sanjoy Dase75ed922015-02-26 08:19:31 +0000994 if (LatchBrExitIdx == 0) {
Max Kazantsev2c627a92017-07-18 04:53:48 +0000995 // We need to decrease the right value unless we have already increased
996 // it virtually when we replaced EQ with SLT.
997 if (!IncreasedRightValueByOne) {
998 IRBuilder<> B(Preheader->getTerminator());
999 RightValue = B.CreateSub(RightValue, One);
1000 }
Sanjoy Dasec892132017-02-07 23:59:07 +00001001 } else {
Max Kazantsev2c627a92017-07-18 04:53:48 +00001002 assert(!IncreasedRightValueByOne &&
1003 "Right value can be increased only for LatchBrExitIdx == 0!");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001004 }
1005 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001006 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1007
Sanjoy Dase75ed922015-02-26 08:19:31 +00001008 assert(SE.getLoopDisposition(LatchCount, &L) ==
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001009 ScalarEvolution::LoopInvariant &&
1010 "loop variant exit count doesn't make sense!");
1011
Sanjoy Dase75ed922015-02-26 08:19:31 +00001012 assert(!L.contains(LatchExit) && "expected an exit block!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001013 const DataLayout &DL = Preheader->getModule()->getDataLayout();
1014 Value *IndVarStartV =
1015 SCEVExpander(SE, DL, "irce")
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001016 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001017 IndVarStartV->setName("indvar.start");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001018
Sanjoy Dase75ed922015-02-26 08:19:31 +00001019 LoopStructure Result;
1020
1021 Result.Tag = "main";
1022 Result.Header = Header;
1023 Result.Latch = Latch;
1024 Result.LatchBr = LatchBr;
1025 Result.LatchExit = LatchExit;
1026 Result.LatchBrExitIdx = LatchBrExitIdx;
1027 Result.IndVarStart = IndVarStartV;
Max Kazantsev2f6ae282017-08-04 07:01:04 +00001028 Result.IndVarStep = StepCI;
Max Kazantseva22742b2017-08-31 05:58:15 +00001029 Result.IndVarBase = LeftValue;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001030 Result.IndVarIncreasing = IsIncreasing;
1031 Result.LoopExitAt = RightValue;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001032 Result.IsSignedPredicate = IsSignedPredicate;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001033
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001034 FailureReason = nullptr;
1035
Sanjoy Dase75ed922015-02-26 08:19:31 +00001036 return Result;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001037}
1038
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001039/// If the type of \p S matches with \p Ty, return \p S. Otherwise, return
1040/// signed or unsigned extension of \p S to type \p Ty.
1041static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE,
1042 bool Signed) {
1043 return Signed ? SE.getNoopOrSignExtend(S, Ty) : SE.getNoopOrZeroExtend(S, Ty);
1044}
1045
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001046Optional<LoopConstrainer::SubRanges>
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001047LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001048 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1049
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001050 auto *RTy = cast<IntegerType>(Range.getType());
1051
1052 // We only support wide range checks and narrow latches.
1053 if (!AllowNarrowLatchCondition && RTy != Ty)
1054 return None;
1055 if (RTy->getBitWidth() < Ty->getBitWidth())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001056 return None;
1057
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001058 LoopConstrainer::SubRanges Result;
1059
1060 // I think we can be more aggressive here and make this nuw / nsw if the
1061 // addition that feeds into the icmp for the latch's terminating branch is nuw
1062 // / nsw. In any case, a wrapping 2's complement addition is safe.
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001063 const SCEV *Start = NoopOrExtend(SE.getSCEV(MainLoopStructure.IndVarStart),
1064 RTy, SE, IsSignedPredicate);
1065 const SCEV *End = NoopOrExtend(SE.getSCEV(MainLoopStructure.LoopExitAt), RTy,
1066 SE, IsSignedPredicate);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001067
Sanjoy Dase75ed922015-02-26 08:19:31 +00001068 bool Increasing = MainLoopStructure.IndVarIncreasing;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001069
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001070 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1071 // [Smallest, GreatestSeen] is the range of values the induction variable
1072 // takes.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001073
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001074 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001075
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001076 const SCEV *One = SE.getOne(RTy);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001077 if (Increasing) {
1078 Smallest = Start;
1079 Greatest = End;
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001080 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1081 GreatestSeen = SE.getMinusSCEV(End, One);
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001082 } else {
1083 // These two computations may sign-overflow. Here is why that is okay:
1084 //
1085 // We know that the induction variable does not sign-overflow on any
1086 // iteration except the last one, and it starts at `Start` and ends at
1087 // `End`, decrementing by one every time.
1088 //
1089 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1090 // induction variable is decreasing we know that that the smallest value
1091 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1092 //
1093 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
1094 // that case, `Clamp` will always return `Smallest` and
1095 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1096 // will be an empty range. Returning an empty range is always safe.
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001097
Max Kazantsev6c466a32017-06-28 04:57:45 +00001098 Smallest = SE.getAddExpr(End, One);
1099 Greatest = SE.getAddExpr(Start, One);
Max Kazantsevf80ffa12017-07-14 06:35:03 +00001100 GreatestSeen = Start;
Sanjoy Das7a0b7f52015-03-17 00:42:16 +00001101 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001102
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001103 auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
Max Kazantsev6f5229d72017-11-01 13:21:56 +00001104 return IsSignedPredicate
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001105 ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1106 : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001107 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001108
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001109 // In some cases we can prove that we don't need a pre or post loop.
1110 ICmpInst::Predicate PredLE =
1111 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1112 ICmpInst::Predicate PredLT =
1113 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001114
1115 bool ProvablyNoPreloop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001116 SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001117 if (!ProvablyNoPreloop)
1118 Result.LowLimit = Clamp(Range.getBegin());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001119
1120 bool ProvablyNoPostLoop =
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001121 SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001122 if (!ProvablyNoPostLoop)
1123 Result.HighLimit = Clamp(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001124
1125 return Result;
1126}
1127
1128void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1129 const char *Tag) const {
1130 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1131 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1132 Result.Blocks.push_back(Clone);
1133 Result.Map[BB] = Clone;
1134 }
1135
1136 auto GetClonedValue = [&Result](Value *V) {
1137 assert(V && "null values not in domain!");
1138 auto It = Result.Map.find(V);
1139 if (It == Result.Map.end())
1140 return V;
1141 return static_cast<Value *>(It->second);
1142 };
1143
Sanjoy Das7a18a232016-08-14 01:04:36 +00001144 auto *ClonedLatch =
1145 cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1146 ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1147 MDNode::get(Ctx, {}));
1148
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001149 Result.Structure = MainLoopStructure.map(GetClonedValue);
1150 Result.Structure.Tag = Tag;
1151
1152 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1153 BasicBlock *ClonedBB = Result.Blocks[i];
1154 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1155
1156 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1157
1158 for (Instruction &I : *ClonedBB)
1159 RemapInstruction(&I, Result.Map,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00001160 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001161
1162 // Exit blocks will now have one more predecessor and their PHI nodes need
1163 // to be edited to reflect that. No phi nodes need to be introduced because
1164 // the loop is in LCSSA.
1165
Sanjoy Dasd1d62a12016-08-13 22:00:09 +00001166 for (auto *SBB : successors(OriginalBB)) {
1167 if (OriginalLoop.contains(SBB))
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001168 continue; // not an exit block
1169
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001170 for (PHINode &PN : SBB->phis()) {
1171 Value *OldIncoming = PN.getIncomingValueForBlock(OriginalBB);
1172 PN.addIncoming(GetClonedValue(OldIncoming), ClonedBB);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001173 }
1174 }
1175 }
1176}
1177
1178LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001179 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001180 BasicBlock *ContinuationBlock) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001181 // We start with a loop with a single latch:
1182 //
1183 // +--------------------+
1184 // | |
1185 // | preheader |
1186 // | |
1187 // +--------+-----------+
1188 // | ----------------\
1189 // | / |
1190 // +--------v----v------+ |
1191 // | | |
1192 // | header | |
1193 // | | |
1194 // +--------------------+ |
1195 // |
1196 // ..... |
1197 // |
1198 // +--------------------+ |
1199 // | | |
1200 // | latch >----------/
1201 // | |
1202 // +-------v------------+
1203 // |
1204 // |
1205 // | +--------------------+
1206 // | | |
1207 // +---> original exit |
1208 // | |
1209 // +--------------------+
1210 //
1211 // We change the control flow to look like
1212 //
1213 //
1214 // +--------------------+
1215 // | |
1216 // | preheader >-------------------------+
1217 // | | |
1218 // +--------v-----------+ |
1219 // | /-------------+ |
1220 // | / | |
1221 // +--------v--v--------+ | |
1222 // | | | |
1223 // | header | | +--------+ |
1224 // | | | | | |
1225 // +--------------------+ | | +-----v-----v-----------+
1226 // | | | |
1227 // | | | .pseudo.exit |
1228 // | | | |
1229 // | | +-----------v-----------+
1230 // | | |
1231 // ..... | | |
1232 // | | +--------v-------------+
1233 // +--------------------+ | | | |
1234 // | | | | | ContinuationBlock |
1235 // | latch >------+ | | |
1236 // | | | +----------------------+
1237 // +---------v----------+ |
1238 // | |
1239 // | |
1240 // | +---------------^-----+
1241 // | | |
1242 // +-----> .exit.selector |
1243 // | |
1244 // +----------v----------+
1245 // |
1246 // +--------------------+ |
1247 // | | |
1248 // | original exit <----+
1249 // | |
1250 // +--------------------+
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001251
1252 RewrittenRangeInfo RRI;
1253
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001254 BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001255 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001256 &F, BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001257 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
Duncan P. N. Exon Smith3bcaa812016-08-17 01:16:17 +00001258 BBInsertLocation);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001259
Sanjoy Das81c00fe2016-06-23 18:03:26 +00001260 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001261 bool Increasing = LS.IndVarIncreasing;
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001262 bool IsSignedPredicate = LS.IsSignedPredicate;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001263
1264 IRBuilder<> B(PreheaderJump);
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001265 auto *RangeTy = Range.getBegin()->getType();
1266 auto NoopOrExt = [&](Value *V) {
1267 if (V->getType() == RangeTy)
1268 return V;
1269 return IsSignedPredicate ? B.CreateSExt(V, RangeTy, "wide." + V->getName())
1270 : B.CreateZExt(V, RangeTy, "wide." + V->getName());
1271 };
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001272
1273 // EnterLoopCond - is it okay to start executing this `LS'?
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001274 Value *EnterLoopCond = nullptr;
Max Kazantsevf8a0e0d2019-01-15 11:16:14 +00001275 auto Pred =
1276 Increasing
1277 ? (IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT)
1278 : (IsSignedPredicate ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001279 Value *IndVarStart = NoopOrExt(LS.IndVarStart);
Max Kazantsevee613082019-01-17 06:20:42 +00001280 EnterLoopCond = B.CreateICmp(Pred, IndVarStart, ExitSubloopAt);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001281
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001282 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1283 PreheaderJump->eraseFromParent();
1284
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001285 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001286 B.SetInsertPoint(LS.LatchBr);
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001287 Value *IndVarBase = NoopOrExt(LS.IndVarBase);
Max Kazantsevee613082019-01-17 06:20:42 +00001288 Value *TakeBackedgeLoopCond = B.CreateICmp(Pred, IndVarBase, ExitSubloopAt);
Max Kazantsevf8a0e0d2019-01-15 11:16:14 +00001289
Sanjoy Dase75ed922015-02-26 08:19:31 +00001290 Value *CondForBranch = LS.LatchBrExitIdx == 1
1291 ? TakeBackedgeLoopCond
1292 : B.CreateNot(TakeBackedgeLoopCond);
1293
1294 LS.LatchBr->setCondition(CondForBranch);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001295
1296 B.SetInsertPoint(RRI.ExitSelector);
1297
1298 // IterationsLeft - are there any more iterations left, given the original
1299 // upper bound on the induction variable? If not, we branch to the "real"
1300 // exit.
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001301 Value *LoopExitAt = NoopOrExt(LS.LoopExitAt);
Max Kazantsevee613082019-01-17 06:20:42 +00001302 Value *IterationsLeft = B.CreateICmp(Pred, IndVarBase, LoopExitAt);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001303 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1304
1305 BranchInst *BranchToContinuation =
1306 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1307
1308 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1309 // each of the PHI nodes in the loop header. This feeds into the initial
1310 // value of the same PHI nodes if/when we continue execution.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001311 for (PHINode &PN : LS.Header->phis()) {
1312 PHINode *NewPHI = PHINode::Create(PN.getType(), 2, PN.getName() + ".copy",
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001313 BranchToContinuation);
1314
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001315 NewPHI->addIncoming(PN.getIncomingValueForBlock(Preheader), Preheader);
1316 NewPHI->addIncoming(PN.getIncomingValueForBlock(LS.Latch),
Serguei Katkov675e3042017-09-21 04:50:41 +00001317 RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001318 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1319 }
1320
Max Kazantsevee613082019-01-17 06:20:42 +00001321 RRI.IndVarEnd = PHINode::Create(IndVarBase->getType(), 2, "indvar.end",
Sanjoy Dase75ed922015-02-26 08:19:31 +00001322 BranchToContinuation);
Max Kazantsevee613082019-01-17 06:20:42 +00001323 RRI.IndVarEnd->addIncoming(IndVarStart, Preheader);
1324 RRI.IndVarEnd->addIncoming(IndVarBase, RRI.ExitSelector);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001325
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001326 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1327 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
Roman Lebedev1a1b9222019-05-05 18:59:39 +00001328 LS.LatchExit->replacePhiUsesWith(LS.Latch, RRI.ExitSelector);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001329
1330 return RRI;
1331}
1332
1333void LoopConstrainer::rewriteIncomingValuesForPHIs(
Sanjoy Dase75ed922015-02-26 08:19:31 +00001334 LoopStructure &LS, BasicBlock *ContinuationBlock,
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001335 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001336 unsigned PHIIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00001337 for (PHINode &PN : LS.Header->phis())
Whitney Tsang15b7f5b2019-06-17 14:38:56 +00001338 PN.setIncomingValueForBlock(ContinuationBlock,
1339 RRI.PHIValuesAtPseudoExit[PHIIndex++]);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001340
Sanjoy Dase75ed922015-02-26 08:19:31 +00001341 LS.IndVarStart = RRI.IndVarEnd;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001342}
1343
Sanjoy Dase75ed922015-02-26 08:19:31 +00001344BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1345 BasicBlock *OldPreheader,
1346 const char *Tag) const {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001347 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1348 BranchInst::Create(LS.Header, Preheader);
1349
Roman Lebedev1a1b9222019-05-05 18:59:39 +00001350 LS.Header->replacePhiUsesWith(OldPreheader, Preheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001351
1352 return Preheader;
1353}
1354
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001355void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001356 Loop *ParentLoop = OriginalLoop.getParentLoop();
1357 if (!ParentLoop)
1358 return;
1359
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001360 for (BasicBlock *BB : BBs)
Sanjoy Das83a72852016-08-02 19:32:01 +00001361 ParentLoop->addBasicBlockToLoop(BB, LI);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001362}
1363
Sanjoy Das21434472016-08-14 01:04:46 +00001364Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
Fedor Sergeev194a4072018-03-15 11:01:19 +00001365 ValueToValueMapTy &VM,
1366 bool IsSubloop) {
Sanjoy Dasdef17292017-09-28 02:45:42 +00001367 Loop &New = *LI.AllocateLoop();
Chandler Carruth29c22d22017-05-25 03:01:31 +00001368 if (Parent)
1369 Parent->addChildLoop(&New);
1370 else
1371 LI.addTopLevelLoop(&New);
Fedor Sergeev194a4072018-03-15 11:01:19 +00001372 LPMAddNewLoop(&New, IsSubloop);
Sanjoy Das21434472016-08-14 01:04:46 +00001373
1374 // Add all of the blocks in Original to the new loop.
1375 for (auto *BB : Original->blocks())
1376 if (LI.getLoopFor(BB) == Original)
1377 New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1378
1379 // Add all of the subloops to the new loop.
1380 for (Loop *SubLoop : *Original)
Fedor Sergeev194a4072018-03-15 11:01:19 +00001381 createClonedLoopStructure(SubLoop, &New, VM, /* IsSubloop */ true);
Sanjoy Das21434472016-08-14 01:04:46 +00001382
1383 return &New;
1384}
1385
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001386bool LoopConstrainer::run() {
1387 BasicBlock *Preheader = nullptr;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001388 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1389 Preheader = OriginalLoop.getLoopPreheader();
1390 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1391 "preconditions!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001392
1393 OriginalPreheader = Preheader;
1394 MainLoopPreheader = Preheader;
1395
Max Kazantsev07da1ab2017-08-04 05:40:20 +00001396 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1397 Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001398 if (!MaybeSR.hasValue()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001399 LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001400 return false;
1401 }
Sanjoy Dase75ed922015-02-26 08:19:31 +00001402
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001403 SubRanges SR = MaybeSR.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001404 bool Increasing = MainLoopStructure.IndVarIncreasing;
1405 IntegerType *IVTy =
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001406 cast<IntegerType>(Range.getBegin()->getType());
Sanjoy Dase75ed922015-02-26 08:19:31 +00001407
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001408 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001409 Instruction *InsertPt = OriginalPreheader->getTerminator();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001410
1411 // It would have been better to make `PreLoop' and `PostLoop'
1412 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1413 // constructor.
1414 ClonedLoop PreLoop, PostLoop;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001415 bool NeedsPreLoop =
1416 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1417 bool NeedsPostLoop =
1418 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1419
1420 Value *ExitPreLoopAt = nullptr;
1421 Value *ExitMainLoopAt = nullptr;
1422 const SCEVConstant *MinusOneS =
1423 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1424
1425 if (NeedsPreLoop) {
1426 const SCEV *ExitPreLoopAtSCEV = nullptr;
1427
1428 if (Increasing)
1429 ExitPreLoopAtSCEV = *SR.LowLimit;
Max Kazantsev78a54352019-01-15 10:01:46 +00001430 else if (cannotBeMinInLoop(*SR.HighLimit, &OriginalLoop, SE,
1431 IsSignedPredicate))
1432 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001433 else {
Max Kazantsev78a54352019-01-15 10:01:46 +00001434 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1435 << "preloop exit limit. HighLimit = "
1436 << *(*SR.HighLimit) << "\n");
1437 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001438 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001439
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001440 if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001441 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1442 << " preloop exit limit " << *ExitPreLoopAtSCEV
1443 << " at block " << InsertPt->getParent()->getName()
1444 << "\n");
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001445 return false;
1446 }
1447
Sanjoy Dase75ed922015-02-26 08:19:31 +00001448 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1449 ExitPreLoopAt->setName("exit.preloop.at");
1450 }
1451
1452 if (NeedsPostLoop) {
1453 const SCEV *ExitMainLoopAtSCEV = nullptr;
1454
1455 if (Increasing)
1456 ExitMainLoopAtSCEV = *SR.HighLimit;
Max Kazantsev78a54352019-01-15 10:01:46 +00001457 else if (cannotBeMinInLoop(*SR.LowLimit, &OriginalLoop, SE,
1458 IsSignedPredicate))
1459 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001460 else {
Max Kazantsev78a54352019-01-15 10:01:46 +00001461 LLVM_DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1462 << "mainloop exit limit. LowLimit = "
1463 << *(*SR.LowLimit) << "\n");
1464 return false;
Sanjoy Dase75ed922015-02-26 08:19:31 +00001465 }
Serguei Katkov675e3042017-09-21 04:50:41 +00001466
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001467 if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001468 LLVM_DEBUG(dbgs() << "irce: could not prove that it is safe to expand the"
1469 << " main loop exit limit " << *ExitMainLoopAtSCEV
1470 << " at block " << InsertPt->getParent()->getName()
1471 << "\n");
Max Kazantsevb1b8aff2017-11-16 06:06:27 +00001472 return false;
1473 }
1474
Sanjoy Dase75ed922015-02-26 08:19:31 +00001475 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1476 ExitMainLoopAt->setName("exit.mainloop.at");
1477 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001478
1479 // We clone these ahead of time so that we don't have to deal with changing
1480 // and temporarily invalid IR as we transform the loops.
1481 if (NeedsPreLoop)
1482 cloneLoop(PreLoop, "preloop");
1483 if (NeedsPostLoop)
1484 cloneLoop(PostLoop, "postloop");
1485
1486 RewrittenRangeInfo PreLoopRRI;
1487
1488 if (NeedsPreLoop) {
1489 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1490 PreLoop.Structure.Header);
1491
1492 MainLoopPreheader =
1493 createPreheader(MainLoopStructure, Preheader, "mainloop");
Sanjoy Dase75ed922015-02-26 08:19:31 +00001494 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1495 ExitPreLoopAt, MainLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001496 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1497 PreLoopRRI);
1498 }
1499
1500 BasicBlock *PostLoopPreheader = nullptr;
1501 RewrittenRangeInfo PostLoopRRI;
1502
1503 if (NeedsPostLoop) {
1504 PostLoopPreheader =
1505 createPreheader(PostLoop.Structure, Preheader, "postloop");
1506 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
Sanjoy Dase75ed922015-02-26 08:19:31 +00001507 ExitMainLoopAt, PostLoopPreheader);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001508 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1509 PostLoopRRI);
1510 }
1511
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001512 BasicBlock *NewMainLoopPreheader =
1513 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1514 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1515 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1516 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001517
1518 // Some of the above may be nullptr, filter them out before passing to
1519 // addToParentLoopIfNeeded.
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001520 auto NewBlocksEnd =
1521 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001522
Benjamin Kramer39f76ac2015-02-06 14:43:49 +00001523 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001524
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001525 DT.recalculate(F);
Sanjoy Das21434472016-08-14 01:04:46 +00001526
Anna Thomas72180322017-06-06 14:54:01 +00001527 // We need to first add all the pre and post loop blocks into the loop
1528 // structures (as part of createClonedLoopStructure), and then update the
1529 // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1530 // LI when LoopSimplifyForm is generated.
1531 Loop *PreL = nullptr, *PostL = nullptr;
Sanjoy Das21434472016-08-14 01:04:46 +00001532 if (!PreLoop.Blocks.empty()) {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001533 PreL = createClonedLoopStructure(&OriginalLoop,
1534 OriginalLoop.getParentLoop(), PreLoop.Map,
1535 /* IsSubLoop */ false);
Sanjoy Das21434472016-08-14 01:04:46 +00001536 }
1537
1538 if (!PostLoop.Blocks.empty()) {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001539 PostL =
1540 createClonedLoopStructure(&OriginalLoop, OriginalLoop.getParentLoop(),
1541 PostLoop.Map, /* IsSubLoop */ false);
Sanjoy Das21434472016-08-14 01:04:46 +00001542 }
1543
Anna Thomas72180322017-06-06 14:54:01 +00001544 // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1545 auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1546 formLCSSARecursively(*L, DT, &LI, &SE);
Alina Sbirleaf31eba62019-05-08 17:05:36 +00001547 simplifyLoop(L, &DT, &LI, &SE, nullptr, nullptr, true);
Anna Thomas72180322017-06-06 14:54:01 +00001548 // Pre/post loops are slow paths, we do not need to perform any loop
1549 // optimizations on them.
1550 if (!IsOriginalLoop)
1551 DisableAllLoopOptsOnLoop(*L);
1552 };
1553 if (PreL)
1554 CanonicalizeLoop(PreL, false);
1555 if (PostL)
1556 CanonicalizeLoop(PostL, false);
1557 CanonicalizeLoop(&OriginalLoop, true);
Sanjoy Dasf45e03e2016-08-02 19:31:54 +00001558
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001559 return true;
1560}
1561
Sanjoy Das95c476d2015-02-21 22:20:22 +00001562/// Computes and returns a range of values for the induction variable (IndVar)
1563/// in which the range check can be safely elided. If it cannot compute such a
1564/// range, returns None.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001565Optional<InductiveRangeCheck::Range>
Sanjoy Das59776732016-05-21 02:31:51 +00001566InductiveRangeCheck::computeSafeIterationSpace(
Max Kazantsev26846782017-11-20 06:07:57 +00001567 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar,
1568 bool IsLatchSigned) const {
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001569 // We can deal when types of latch check and range checks don't match in case
1570 // if latch check is more narrow.
1571 auto *IVType = cast<IntegerType>(IndVar->getType());
1572 auto *RCType = cast<IntegerType>(getBegin()->getType());
1573 if (IVType->getBitWidth() > RCType->getBitWidth())
1574 return None;
Sanjoy Das95c476d2015-02-21 22:20:22 +00001575 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1576 // variable, that may or may not exist as a real llvm::Value in the loop) and
1577 // this inductive range check is a range check on the "C + D * I" ("C" is
Max Kazantsev84286ce2017-10-31 06:19:05 +00001578 // getBegin() and "D" is getStep()). We rewrite the value being range
Sanjoy Das95c476d2015-02-21 22:20:22 +00001579 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001580 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001581 // The actual inequalities we solve are of the form
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001582 //
Sanjoy Das95c476d2015-02-21 22:20:22 +00001583 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1584 //
Max Kazantsev26846782017-11-20 06:07:57 +00001585 // Here L stands for upper limit of the safe iteration space.
1586 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
1587 // overflows when calculating (0 - M) and (L - M) we, depending on type of
1588 // IV's iteration space, limit the calculations by borders of the iteration
1589 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
1590 // If we figured out that "anything greater than (-M) is safe", we strengthen
1591 // this to "everything greater than 0 is safe", assuming that values between
1592 // -M and 0 just do not exist in unsigned iteration space, and we don't want
1593 // to deal with overflown values.
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001594
Sanjoy Das95c476d2015-02-21 22:20:22 +00001595 if (!IndVar->isAffine())
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001596 return None;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001597
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001598 const SCEV *A = NoopOrExtend(IndVar->getStart(), RCType, SE, IsLatchSigned);
1599 const SCEVConstant *B = dyn_cast<SCEVConstant>(
1600 NoopOrExtend(IndVar->getStepRecurrence(SE), RCType, SE, IsLatchSigned));
Sanjoy Das95c476d2015-02-21 22:20:22 +00001601 if (!B)
1602 return None;
Max Kazantseve4c220e2017-08-01 06:49:29 +00001603 assert(!B->isZero() && "Recurrence with zero step?");
Sanjoy Das95c476d2015-02-21 22:20:22 +00001604
Max Kazantsev84286ce2017-10-31 06:19:05 +00001605 const SCEV *C = getBegin();
1606 const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep());
Sanjoy Das95c476d2015-02-21 22:20:22 +00001607 if (D != B)
1608 return None;
1609
Max Kazantsev95054702017-08-04 07:41:24 +00001610 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
Max Kazantsevd9aee3c2019-01-23 07:20:56 +00001611 unsigned BitWidth = RCType->getBitWidth();
Max Kazantsev26846782017-11-20 06:07:57 +00001612 const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
Sanjoy Das95c476d2015-02-21 22:20:22 +00001613
Max Kazantsevb57ca092018-02-12 05:16:28 +00001614 // Subtract Y from X so that it does not go through border of the IV
Max Kazantsev26846782017-11-20 06:07:57 +00001615 // iteration space. Mathematically, it is equivalent to:
1616 //
Max Kazantsevb57ca092018-02-12 05:16:28 +00001617 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
Max Kazantsev26846782017-11-20 06:07:57 +00001618 //
Max Kazantsevb57ca092018-02-12 05:16:28 +00001619 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
Max Kazantsev26846782017-11-20 06:07:57 +00001620 // any width of bit grid). But after we take min/max, the result is
1621 // guaranteed to be within [INT_MIN, INT_MAX].
1622 //
1623 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
1624 // values, depending on type of latch condition that defines IV iteration
1625 // space.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001626 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
Max Kazantsevc0b268f2018-05-19 13:06:37 +00001627 // FIXME: The current implementation assumes that X is in [0, SINT_MAX].
1628 // This is required to ensure that SINT_MAX - X does not overflow signed and
1629 // that X - Y does not overflow unsigned if Y is negative. Can we lift this
1630 // restriction and make it work for negative X either?
Max Kazantsev26846782017-11-20 06:07:57 +00001631 if (IsLatchSigned) {
1632 // X is a number from signed range, Y is interpreted as signed.
1633 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
1634 // thing we should care about is that we didn't cross SINT_MAX.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001635 // So, if Y is positive, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001636 // Rule 1: Y > 0 ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001637 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001638 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001639 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
Max Kazantsev26846782017-11-20 06:07:57 +00001640 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
Max Kazantsevb57ca092018-02-12 05:16:28 +00001641 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
Max Kazantsev26846782017-11-20 06:07:57 +00001642 const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax);
Max Kazantsev716e6472017-11-23 06:14:39 +00001643 return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax),
1644 SCEV::FlagNSW);
Max Kazantsev26846782017-11-20 06:07:57 +00001645 } else
1646 // X is a number from unsigned range, Y is interpreted as signed.
1647 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
1648 // thing we should care about is that we didn't cross zero.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001649 // So, if Y is negative, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001650 // Rule 1: Y <s 0 ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001651 // If 0 <= Y <= X, we subtract Y safely.
Max Kazantsev26846782017-11-20 06:07:57 +00001652 // Rule 2: Y <=s X ---> Y.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001653 // If 0 <= X < Y, we should stop at 0 and can only subtract X.
Max Kazantsev26846782017-11-20 06:07:57 +00001654 // Rule 3: Y >s X ---> X.
Max Kazantsevb57ca092018-02-12 05:16:28 +00001655 // It gives us smin(X, Y) to subtract in all cases.
Max Kazantsev716e6472017-11-23 06:14:39 +00001656 return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW);
Max Kazantsev26846782017-11-20 06:07:57 +00001657 };
Sanjoy Das95c476d2015-02-21 22:20:22 +00001658 const SCEV *M = SE.getMinusSCEV(C, A);
Max Kazantsev26846782017-11-20 06:07:57 +00001659 const SCEV *Zero = SE.getZero(M->getType());
Max Kazantsevc0b268f2018-05-19 13:06:37 +00001660
1661 // This function returns SCEV equal to 1 if X is non-negative 0 otherwise.
1662 auto SCEVCheckNonNegative = [&](const SCEV *X) {
1663 const Loop *L = IndVar->getLoop();
1664 const SCEV *One = SE.getOne(X->getType());
1665 // Can we trivially prove that X is a non-negative or negative value?
1666 if (isKnownNonNegativeInLoop(X, L, SE))
1667 return One;
1668 else if (isKnownNegativeInLoop(X, L, SE))
1669 return Zero;
1670 // If not, we will have to figure it out during the execution.
1671 // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.
1672 const SCEV *NegOne = SE.getNegativeSCEV(One);
1673 return SE.getAddExpr(SE.getSMaxExpr(SE.getSMinExpr(X, Zero), NegOne), One);
1674 };
1675 // FIXME: Current implementation of ClampedSubtract implicitly assumes that
1676 // X is non-negative (in sense of a signed value). We need to re-implement
1677 // this function in a way that it will correctly handle negative X as well.
1678 // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can
1679 // end up with a negative X and produce wrong results. So currently we ensure
1680 // that if getEnd() is negative then both ends of the safe range are zero.
1681 // Note that this may pessimize elimination of unsigned range checks against
1682 // negative values.
1683 const SCEV *REnd = getEnd();
1684 const SCEV *EndIsNonNegative = SCEVCheckNonNegative(REnd);
1685
1686 const SCEV *Begin = SE.getMulExpr(ClampedSubtract(Zero, M), EndIsNonNegative);
1687 const SCEV *End = SE.getMulExpr(ClampedSubtract(REnd, M), EndIsNonNegative);
Sanjoy Das351db052015-01-22 09:32:02 +00001688 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001689}
1690
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001691static Optional<InductiveRangeCheck::Range>
Max Kazantsev9ac70212017-10-25 06:47:39 +00001692IntersectSignedRange(ScalarEvolution &SE,
1693 const Optional<InductiveRangeCheck::Range> &R1,
1694 const InductiveRangeCheck::Range &R2) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001695 if (R2.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001696 return None;
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001697 if (!R1.hasValue())
1698 return R2;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001699 auto &R1Value = R1.getValue();
Max Kazantsev3612d4b2017-10-19 05:33:28 +00001700 // We never return empty ranges from this function, and R1 is supposed to be
1701 // a result of intersection. Thus, R1 is never empty.
Max Kazantsev4332a942017-10-25 06:10:02 +00001702 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1703 "We should never have empty R1!");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001704
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001705 // TODO: we could widen the smaller range and have this work; but for now we
1706 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001707 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001708 return None;
1709
Sanjoy Das7fc60da2015-02-21 22:07:32 +00001710 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1711 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1712
Max Kazantsev25d86552017-10-11 06:53:07 +00001713 // If the resulting range is empty, just return None.
1714 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
Max Kazantsev4332a942017-10-25 06:10:02 +00001715 if (Ret.isEmpty(SE, /* IsSigned */ true))
Max Kazantsev25d86552017-10-11 06:53:07 +00001716 return None;
1717 return Ret;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001718}
1719
Max Kazantsev9ac70212017-10-25 06:47:39 +00001720static Optional<InductiveRangeCheck::Range>
1721IntersectUnsignedRange(ScalarEvolution &SE,
1722 const Optional<InductiveRangeCheck::Range> &R1,
1723 const InductiveRangeCheck::Range &R2) {
1724 if (R2.isEmpty(SE, /* IsSigned */ false))
1725 return None;
1726 if (!R1.hasValue())
1727 return R2;
1728 auto &R1Value = R1.getValue();
1729 // We never return empty ranges from this function, and R1 is supposed to be
1730 // a result of intersection. Thus, R1 is never empty.
1731 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1732 "We should never have empty R1!");
1733
1734 // TODO: we could widen the smaller range and have this work; but for now we
1735 // bail out to keep things simple.
1736 if (R1Value.getType() != R2.getType())
1737 return None;
1738
1739 const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1740 const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1741
1742 // If the resulting range is empty, just return None.
1743 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1744 if (Ret.isEmpty(SE, /* IsSigned */ false))
1745 return None;
1746 return Ret;
1747}
1748
Fedor Sergeev194a4072018-03-15 11:01:19 +00001749PreservedAnalyses IRCEPass::run(Loop &L, LoopAnalysisManager &AM,
1750 LoopStandardAnalysisResults &AR,
1751 LPMUpdater &U) {
1752 Function *F = L.getHeader()->getParent();
1753 const auto &FAM =
1754 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
1755 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
1756 InductiveRangeCheckElimination IRCE(AR.SE, BPI, AR.DT, AR.LI);
1757 auto LPMAddNewLoop = [&U](Loop *NL, bool IsSubloop) {
1758 if (!IsSubloop)
1759 U.addSiblingLoops(NL);
1760 };
1761 bool Changed = IRCE.run(&L, LPMAddNewLoop);
1762 if (!Changed)
1763 return PreservedAnalyses::all();
1764
1765 return getLoopPassPreservedAnalyses();
1766}
1767
1768bool IRCELegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kaylor50271f72016-05-03 22:32:30 +00001769 if (skipLoop(L))
1770 return false;
1771
Fedor Sergeev194a4072018-03-15 11:01:19 +00001772 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1773 BranchProbabilityInfo &BPI =
1774 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1775 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1776 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1777 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI);
1778 auto LPMAddNewLoop = [&LPM](Loop *NL, bool /* IsSubLoop */) {
1779 LPM.addLoop(*NL);
1780 };
1781 return IRCE.run(L, LPMAddNewLoop);
1782}
1783
1784bool InductiveRangeCheckElimination::run(
1785 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001786 if (L->getBlocks().size() >= LoopSizeCutoff) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001787 LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001788 return false;
1789 }
1790
1791 BasicBlock *Preheader = L->getLoopPreheader();
1792 if (!Preheader) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001793 LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001794 return false;
1795 }
1796
1797 LLVMContext &Context = Preheader->getContext();
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001798 SmallVector<InductiveRangeCheck, 16> RangeChecks;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001799
1800 for (auto BBI : L->getBlocks())
1801 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
Sanjoy Dasa0992682016-05-26 00:09:02 +00001802 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1803 RangeChecks);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001804
1805 if (RangeChecks.empty())
1806 return false;
1807
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001808 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1809 OS << "irce: looking at loop "; L->print(OS);
1810 OS << "irce: loop has " << RangeChecks.size()
1811 << " inductive range checks: \n";
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001812 for (InductiveRangeCheck &IRC : RangeChecks)
1813 IRC.print(OS);
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001814 };
1815
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001816 LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
Sanjoy Das9c1bfae2015-03-17 01:40:22 +00001817
1818 if (PrintRangeChecks)
1819 PrintRecognizedRangeChecks(errs());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001820
Sanjoy Dase75ed922015-02-26 08:19:31 +00001821 const char *FailureReason = nullptr;
1822 Optional<LoopStructure> MaybeLoopStructure =
Sanjoy Dase91665d2015-02-26 08:56:04 +00001823 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001824 if (!MaybeLoopStructure.hasValue()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001825 LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
1826 << FailureReason << "\n";);
Sanjoy Dase75ed922015-02-26 08:19:31 +00001827 return false;
1828 }
1829 LoopStructure LS = MaybeLoopStructure.getValue();
Sanjoy Dase75ed922015-02-26 08:19:31 +00001830 const SCEVAddRecExpr *IndVar =
Serguei Katkov675e3042017-09-21 04:50:41 +00001831 cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
Sanjoy Dase75ed922015-02-26 08:19:31 +00001832
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001833 Optional<InductiveRangeCheck::Range> SafeIterRange;
1834 Instruction *ExprInsertPt = Preheader->getTerminator();
1835
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001836 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
Max Kazantsev9ac70212017-10-25 06:47:39 +00001837 // Basing on the type of latch predicate, we interpret the IV iteration range
1838 // as signed or unsigned range. We use different min/max functions (signed or
1839 // unsigned) when intersecting this range with safe iteration ranges implied
1840 // by range checks.
1841 auto IntersectRange =
1842 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001843
1844 IRBuilder<> B(ExprInsertPt);
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001845 for (InductiveRangeCheck &IRC : RangeChecks) {
Max Kazantsev26846782017-11-20 06:07:57 +00001846 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1847 LS.IsSignedPredicate);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001848 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001849 auto MaybeSafeIterRange =
Sanjoy Das59776732016-05-21 02:31:51 +00001850 IntersectRange(SE, SafeIterRange, Result.getValue());
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001851 if (MaybeSafeIterRange.hasValue()) {
Max Kazantsev4332a942017-10-25 06:10:02 +00001852 assert(
1853 !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1854 "We should never return empty ranges!");
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001855 RangeChecksToEliminate.push_back(IRC);
1856 SafeIterRange = MaybeSafeIterRange.getValue();
1857 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001858 }
1859 }
1860
1861 if (!SafeIterRange.hasValue())
1862 return false;
1863
Fedor Sergeev194a4072018-03-15 11:01:19 +00001864 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1865 SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001866 bool Changed = LC.run();
1867
1868 if (Changed) {
1869 auto PrintConstrainedLoopInfo = [L]() {
1870 dbgs() << "irce: in function ";
1871 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1872 dbgs() << "constrained ";
1873 L->print(dbgs());
1874 };
1875
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001876 LLVM_DEBUG(PrintConstrainedLoopInfo());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001877
1878 if (PrintChangedLoops)
1879 PrintConstrainedLoopInfo();
1880
1881 // Optimize away the now-redundant range checks.
1882
Sanjoy Dasc5b11692016-05-21 02:52:13 +00001883 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1884 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001885 ? ConstantInt::getTrue(Context)
1886 : ConstantInt::getFalse(Context);
Sanjoy Dasaa83c472016-05-23 22:16:45 +00001887 IRC.getCheckUse()->set(FoldedRangeCheck);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001888 }
1889 }
1890
1891 return Changed;
1892}
1893
1894Pass *llvm::createInductiveRangeCheckEliminationPass() {
Fedor Sergeev194a4072018-03-15 11:01:19 +00001895 return new IRCELegacyPass();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001896}