Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 1 | //===- InductiveRangeCheckElimination.cpp - -------------------------------===// |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 9 | // |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 10 | // The InductiveRangeCheckElimination pass splits a loop's iteration space into |
| 11 | // three disjoint ranges. It does that in a way such that the loop running in |
| 12 | // the middle loop provably does not need range checks. As an example, it will |
| 13 | // convert |
| 14 | // |
| 15 | // len = < known positive > |
| 16 | // for (i = 0; i < n; i++) { |
| 17 | // if (0 <= i && i < len) { |
| 18 | // do_something(); |
| 19 | // } else { |
| 20 | // throw_out_of_bounds(); |
| 21 | // } |
| 22 | // } |
| 23 | // |
| 24 | // to |
| 25 | // |
| 26 | // len = < known positive > |
| 27 | // limit = smin(n, len) |
| 28 | // // no first segment |
| 29 | // for (i = 0; i < limit; i++) { |
| 30 | // if (0 <= i && i < len) { // this check is fully redundant |
| 31 | // do_something(); |
| 32 | // } else { |
| 33 | // throw_out_of_bounds(); |
| 34 | // } |
| 35 | // } |
| 36 | // for (i = limit; i < n; i++) { |
| 37 | // if (0 <= i && i < len) { |
| 38 | // do_something(); |
| 39 | // } else { |
| 40 | // throw_out_of_bounds(); |
| 41 | // } |
| 42 | // } |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 43 | // |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 44 | //===----------------------------------------------------------------------===// |
| 45 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 46 | #include "llvm/ADT/APInt.h" |
| 47 | #include "llvm/ADT/ArrayRef.h" |
| 48 | #include "llvm/ADT/None.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 49 | #include "llvm/ADT/Optional.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 50 | #include "llvm/ADT/SmallPtrSet.h" |
| 51 | #include "llvm/ADT/SmallVector.h" |
| 52 | #include "llvm/ADT/StringRef.h" |
| 53 | #include "llvm/ADT/Twine.h" |
Sanjoy Das | dcf2651 | 2015-01-27 21:38:12 +0000 | [diff] [blame] | 54 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 55 | #include "llvm/Analysis/LoopInfo.h" |
| 56 | #include "llvm/Analysis/LoopPass.h" |
| 57 | #include "llvm/Analysis/ScalarEvolution.h" |
| 58 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 59 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 60 | #include "llvm/IR/BasicBlock.h" |
| 61 | #include "llvm/IR/CFG.h" |
| 62 | #include "llvm/IR/Constants.h" |
| 63 | #include "llvm/IR/DerivedTypes.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 64 | #include "llvm/IR/Dominators.h" |
| 65 | #include "llvm/IR/Function.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 66 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 67 | #include "llvm/IR/InstrTypes.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 68 | #include "llvm/IR/Instructions.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 69 | #include "llvm/IR/Metadata.h" |
| 70 | #include "llvm/IR/Module.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 71 | #include "llvm/IR/PatternMatch.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 72 | #include "llvm/IR/Type.h" |
| 73 | #include "llvm/IR/Use.h" |
| 74 | #include "llvm/IR/User.h" |
| 75 | #include "llvm/IR/Value.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 76 | #include "llvm/Pass.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 77 | #include "llvm/Support/BranchProbability.h" |
| 78 | #include "llvm/Support/Casting.h" |
| 79 | #include "llvm/Support/CommandLine.h" |
| 80 | #include "llvm/Support/Compiler.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 81 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 82 | #include "llvm/Support/ErrorHandling.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 83 | #include "llvm/Support/raw_ostream.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 84 | #include "llvm/Transforms/Scalar.h" |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 85 | #include "llvm/Transforms/Utils/Cloning.h" |
Sanjoy Das | cf18186 | 2016-08-06 00:01:56 +0000 | [diff] [blame] | 86 | #include "llvm/Transforms/Utils/LoopSimplify.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 87 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 88 | #include "llvm/Transforms/Utils/ValueMapper.h" |
| 89 | #include <algorithm> |
| 90 | #include <cassert> |
| 91 | #include <iterator> |
| 92 | #include <limits> |
| 93 | #include <utility> |
| 94 | #include <vector> |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 95 | |
| 96 | using namespace llvm; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 97 | using namespace llvm::PatternMatch; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 98 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 99 | static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden, |
| 100 | cl::init(64)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 101 | |
Benjamin Kramer | 970eac4 | 2015-02-06 17:51:54 +0000 | [diff] [blame] | 102 | static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden, |
| 103 | cl::init(false)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 104 | |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 105 | static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden, |
| 106 | cl::init(false)); |
| 107 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 108 | static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal", |
| 109 | cl::Hidden, cl::init(10)); |
| 110 | |
Sanjoy Das | bb96979 | 2016-07-22 00:40:56 +0000 | [diff] [blame] | 111 | static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks", |
| 112 | cl::Hidden, cl::init(false)); |
| 113 | |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 114 | static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch", |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 115 | cl::Hidden, cl::init(true)); |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 116 | |
Sanjoy Das | 7a18a23 | 2016-08-14 01:04:36 +0000 | [diff] [blame] | 117 | static const char *ClonedLoopTag = "irce.loop.clone"; |
| 118 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 119 | #define DEBUG_TYPE "irce" |
| 120 | |
| 121 | namespace { |
| 122 | |
| 123 | /// An inductive range check is conditional branch in a loop with |
| 124 | /// |
| 125 | /// 1. a very cold successor (i.e. the branch jumps to that successor very |
| 126 | /// rarely) |
| 127 | /// |
| 128 | /// and |
| 129 | /// |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 130 | /// 2. a condition that is provably true for some contiguous range of values |
| 131 | /// taken by the containing loop's induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 132 | /// |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 133 | class InductiveRangeCheck { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 134 | // Classifies a range check |
Reid Kleckner | 0b16859 | 2015-03-17 16:50:20 +0000 | [diff] [blame] | 135 | enum RangeCheckKind : unsigned { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 136 | // Range check of the form "0 <= I". |
| 137 | RANGE_CHECK_LOWER = 1, |
| 138 | |
| 139 | // Range check of the form "I < L" where L is known positive. |
| 140 | RANGE_CHECK_UPPER = 2, |
| 141 | |
| 142 | // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER |
| 143 | // conditions. |
| 144 | RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER, |
| 145 | |
| 146 | // Unrecognized range check condition. |
| 147 | RANGE_CHECK_UNKNOWN = (unsigned)-1 |
| 148 | }; |
| 149 | |
Sanjoy Das | 2eac48d | 2016-03-09 02:34:19 +0000 | [diff] [blame] | 150 | static StringRef rangeCheckKindToStr(RangeCheckKind); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 151 | |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 152 | const SCEV *Begin = nullptr; |
| 153 | const SCEV *Step = nullptr; |
| 154 | const SCEV *End = nullptr; |
Sanjoy Das | ee77a48 | 2016-05-26 01:50:18 +0000 | [diff] [blame] | 155 | Use *CheckUse = nullptr; |
| 156 | RangeCheckKind Kind = RANGE_CHECK_UNKNOWN; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 157 | bool IsSigned = true; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 158 | |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 159 | static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI, |
| 160 | ScalarEvolution &SE, Value *&Index, |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 161 | Value *&Length, bool &IsSigned); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 162 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 163 | static void |
| 164 | extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse, |
| 165 | SmallVectorImpl<InductiveRangeCheck> &Checks, |
| 166 | SmallPtrSetImpl<Value *> &Visited); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 167 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 168 | public: |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 169 | const SCEV *getBegin() const { return Begin; } |
| 170 | const SCEV *getStep() const { return Step; } |
| 171 | const SCEV *getEnd() const { return End; } |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 172 | bool isSigned() const { return IsSigned; } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 173 | |
| 174 | void print(raw_ostream &OS) const { |
| 175 | OS << "InductiveRangeCheck:\n"; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 176 | OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n"; |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 177 | OS << " Begin: "; |
| 178 | Begin->print(OS); |
| 179 | OS << " Step: "; |
| 180 | Step->print(OS); |
| 181 | OS << " End: "; |
| 182 | if (End) |
| 183 | End->print(OS); |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 184 | else |
| 185 | OS << "(null)"; |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 186 | OS << "\n CheckUse: "; |
| 187 | getCheckUse()->getUser()->print(OS); |
| 188 | OS << " Operand: " << getCheckUse()->getOperandNo() << "\n"; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 189 | } |
| 190 | |
Davide Italiano | d1279df | 2016-08-18 15:55:49 +0000 | [diff] [blame] | 191 | LLVM_DUMP_METHOD |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 192 | void dump() { |
| 193 | print(dbgs()); |
| 194 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 195 | |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 196 | Use *getCheckUse() const { return CheckUse; } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 197 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 198 | /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If |
| 199 | /// R.getEnd() sle R.getBegin(), then R denotes the empty range. |
| 200 | |
| 201 | class Range { |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 202 | const SCEV *Begin; |
| 203 | const SCEV *End; |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 204 | |
| 205 | public: |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 206 | Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) { |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 207 | assert(Begin->getType() == End->getType() && "ill-typed range!"); |
| 208 | } |
| 209 | |
| 210 | Type *getType() const { return Begin->getType(); } |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 211 | const SCEV *getBegin() const { return Begin; } |
| 212 | const SCEV *getEnd() const { return End; } |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 213 | bool isEmpty(ScalarEvolution &SE, bool IsSigned) const { |
| 214 | if (Begin == End) |
| 215 | return true; |
| 216 | if (IsSigned) |
| 217 | return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End); |
| 218 | else |
| 219 | return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End); |
| 220 | } |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 221 | }; |
| 222 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 223 | /// This is the value the condition of the branch needs to evaluate to for the |
| 224 | /// branch to take the hot successor (see (1) above). |
| 225 | bool getPassingDirection() { return true; } |
| 226 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 227 | /// Computes a range for the induction variable (IndVar) in which the range |
| 228 | /// check is redundant and can be constant-folded away. The induction |
| 229 | /// variable is not required to be the canonical {0,+,1} induction variable. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 230 | Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE, |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 231 | const SCEVAddRecExpr *IndVar, |
| 232 | bool IsLatchSigned) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 233 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 234 | /// Parse out a set of inductive range checks from \p BI and append them to \p |
| 235 | /// Checks. |
| 236 | /// |
| 237 | /// NB! There may be conditions feeding into \p BI that aren't inductive range |
| 238 | /// checks, and hence don't end up in \p Checks. |
| 239 | static void |
| 240 | extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE, |
| 241 | BranchProbabilityInfo &BPI, |
| 242 | SmallVectorImpl<InductiveRangeCheck> &Checks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 243 | }; |
| 244 | |
| 245 | class InductiveRangeCheckElimination : public LoopPass { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 246 | public: |
| 247 | static char ID; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 248 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 249 | InductiveRangeCheckElimination() : LoopPass(ID) { |
| 250 | initializeInductiveRangeCheckEliminationPass( |
| 251 | *PassRegistry::getPassRegistry()); |
| 252 | } |
| 253 | |
| 254 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 255 | AU.addRequired<BranchProbabilityInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 256 | getLoopAnalysisUsage(AU); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 257 | } |
| 258 | |
| 259 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
| 260 | }; |
| 261 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 262 | } // end anonymous namespace |
| 263 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 264 | char InductiveRangeCheckElimination::ID = 0; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 265 | |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 266 | INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce", |
| 267 | "Inductive range check elimination", false, false) |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 268 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 269 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Sanjoy Das | da0d79e | 2015-09-09 03:47:18 +0000 | [diff] [blame] | 270 | INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce", |
| 271 | "Inductive range check elimination", false, false) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 272 | |
Sanjoy Das | 2eac48d | 2016-03-09 02:34:19 +0000 | [diff] [blame] | 273 | StringRef InductiveRangeCheck::rangeCheckKindToStr( |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 274 | InductiveRangeCheck::RangeCheckKind RCK) { |
| 275 | switch (RCK) { |
| 276 | case InductiveRangeCheck::RANGE_CHECK_UNKNOWN: |
| 277 | return "RANGE_CHECK_UNKNOWN"; |
| 278 | |
| 279 | case InductiveRangeCheck::RANGE_CHECK_UPPER: |
| 280 | return "RANGE_CHECK_UPPER"; |
| 281 | |
| 282 | case InductiveRangeCheck::RANGE_CHECK_LOWER: |
| 283 | return "RANGE_CHECK_LOWER"; |
| 284 | |
| 285 | case InductiveRangeCheck::RANGE_CHECK_BOTH: |
| 286 | return "RANGE_CHECK_BOTH"; |
| 287 | } |
| 288 | |
| 289 | llvm_unreachable("unknown range check type!"); |
| 290 | } |
| 291 | |
Sanjoy Das | f13900f | 2016-03-09 02:34:15 +0000 | [diff] [blame] | 292 | /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 293 | /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set |
Sanjoy Das | f13900f | 2016-03-09 02:34:15 +0000 | [diff] [blame] | 294 | /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 295 | /// range checked, and set `Length` to the upper limit `Index` is being range |
| 296 | /// checked with if (and only if) the range check type is stronger or equal to |
| 297 | /// RANGE_CHECK_UPPER. |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 298 | InductiveRangeCheck::RangeCheckKind |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 299 | InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI, |
| 300 | ScalarEvolution &SE, Value *&Index, |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 301 | Value *&Length, bool &IsSigned) { |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 302 | auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) { |
| 303 | const SCEV *S = SE.getSCEV(V); |
| 304 | if (isa<SCEVCouldNotCompute>(S)) |
| 305 | return false; |
| 306 | |
| 307 | return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant && |
| 308 | SE.isKnownNonNegative(S); |
| 309 | }; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 310 | |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 311 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 312 | Value *LHS = ICI->getOperand(0); |
| 313 | Value *RHS = ICI->getOperand(1); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 314 | |
| 315 | switch (Pred) { |
| 316 | default: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 317 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 318 | |
| 319 | case ICmpInst::ICMP_SLE: |
| 320 | std::swap(LHS, RHS); |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame] | 321 | LLVM_FALLTHROUGH; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 322 | case ICmpInst::ICMP_SGE: |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 323 | IsSigned = true; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 324 | if (match(RHS, m_ConstantInt<0>())) { |
| 325 | Index = LHS; |
| 326 | return RANGE_CHECK_LOWER; |
| 327 | } |
| 328 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 329 | |
| 330 | case ICmpInst::ICMP_SLT: |
| 331 | std::swap(LHS, RHS); |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame] | 332 | LLVM_FALLTHROUGH; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 333 | case ICmpInst::ICMP_SGT: |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 334 | IsSigned = true; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 335 | if (match(RHS, m_ConstantInt<-1>())) { |
| 336 | Index = LHS; |
| 337 | return RANGE_CHECK_LOWER; |
| 338 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 339 | |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 340 | if (IsNonNegativeAndNotLoopVarying(LHS)) { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 341 | Index = RHS; |
| 342 | Length = LHS; |
| 343 | return RANGE_CHECK_UPPER; |
| 344 | } |
| 345 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 346 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 347 | case ICmpInst::ICMP_ULT: |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 348 | std::swap(LHS, RHS); |
Justin Bogner | b03fd12 | 2016-08-17 05:10:15 +0000 | [diff] [blame] | 349 | LLVM_FALLTHROUGH; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 350 | case ICmpInst::ICMP_UGT: |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 351 | IsSigned = false; |
Sanjoy Das | 337d46b | 2015-03-24 19:29:18 +0000 | [diff] [blame] | 352 | if (IsNonNegativeAndNotLoopVarying(LHS)) { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 353 | Index = RHS; |
| 354 | Length = LHS; |
| 355 | return RANGE_CHECK_BOTH; |
| 356 | } |
| 357 | return RANGE_CHECK_UNKNOWN; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 358 | } |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 359 | |
| 360 | llvm_unreachable("default clause returns!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 361 | } |
| 362 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 363 | void InductiveRangeCheck::extractRangeChecksFromCond( |
| 364 | Loop *L, ScalarEvolution &SE, Use &ConditionUse, |
| 365 | SmallVectorImpl<InductiveRangeCheck> &Checks, |
| 366 | SmallPtrSetImpl<Value *> &Visited) { |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 367 | Value *Condition = ConditionUse.get(); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 368 | if (!Visited.insert(Condition).second) |
| 369 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 370 | |
Max Kazantsev | 1ac6e8a | 2017-11-17 06:49:26 +0000 | [diff] [blame] | 371 | // TODO: Do the same for OR, XOR, NOT etc? |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 372 | if (match(Condition, m_And(m_Value(), m_Value()))) { |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 373 | extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0), |
Max Kazantsev | 1ac6e8a | 2017-11-17 06:49:26 +0000 | [diff] [blame] | 374 | Checks, Visited); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 375 | extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1), |
Max Kazantsev | 1ac6e8a | 2017-11-17 06:49:26 +0000 | [diff] [blame] | 376 | Checks, Visited); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 377 | return; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 378 | } |
| 379 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 380 | ICmpInst *ICI = dyn_cast<ICmpInst>(Condition); |
| 381 | if (!ICI) |
| 382 | return; |
| 383 | |
| 384 | Value *Length = nullptr, *Index; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 385 | bool IsSigned; |
| 386 | auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned); |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 387 | if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN) |
| 388 | return; |
| 389 | |
Sanjoy Das | 5fd7ac4 | 2016-05-24 17:19:56 +0000 | [diff] [blame] | 390 | const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 391 | bool IsAffineIndex = |
| 392 | IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine(); |
| 393 | |
| 394 | if (!IsAffineIndex) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 395 | return; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 396 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 397 | InductiveRangeCheck IRC; |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 398 | IRC.End = Length ? SE.getSCEV(Length) : nullptr; |
| 399 | IRC.Begin = IndexAddRec->getStart(); |
| 400 | IRC.Step = IndexAddRec->getStepRecurrence(SE); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 401 | IRC.CheckUse = &ConditionUse; |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 402 | IRC.Kind = RCKind; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 403 | IRC.IsSigned = IsSigned; |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 404 | Checks.push_back(IRC); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 405 | } |
| 406 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 407 | void InductiveRangeCheck::extractRangeChecksFromBranch( |
| 408 | BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI, |
| 409 | SmallVectorImpl<InductiveRangeCheck> &Checks) { |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 410 | if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch()) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 411 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 412 | |
| 413 | BranchProbability LikelyTaken(15, 16); |
| 414 | |
Sanjoy Das | bb96979 | 2016-07-22 00:40:56 +0000 | [diff] [blame] | 415 | if (!SkipProfitabilityChecks && |
| 416 | BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 417 | return; |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 418 | |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 419 | SmallPtrSet<Value *, 8> Visited; |
| 420 | InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0), |
| 421 | Checks, Visited); |
Sanjoy Das | 8fe8892 | 2016-05-26 00:08:24 +0000 | [diff] [blame] | 422 | } |
| 423 | |
Anna Thomas | 65ca8e9 | 2016-12-13 21:05:21 +0000 | [diff] [blame] | 424 | // Add metadata to the loop L to disable loop optimizations. Callers need to |
| 425 | // confirm that optimizing loop L is not beneficial. |
| 426 | static void DisableAllLoopOptsOnLoop(Loop &L) { |
| 427 | // We do not care about any existing loopID related metadata for L, since we |
| 428 | // are setting all loop metadata to false. |
| 429 | LLVMContext &Context = L.getHeader()->getContext(); |
| 430 | // Reserve first location for self reference to the LoopID metadata node. |
| 431 | MDNode *Dummy = MDNode::get(Context, {}); |
| 432 | MDNode *DisableUnroll = MDNode::get( |
| 433 | Context, {MDString::get(Context, "llvm.loop.unroll.disable")}); |
| 434 | Metadata *FalseVal = |
| 435 | ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0)); |
| 436 | MDNode *DisableVectorize = MDNode::get( |
| 437 | Context, |
| 438 | {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal}); |
| 439 | MDNode *DisableLICMVersioning = MDNode::get( |
| 440 | Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")}); |
| 441 | MDNode *DisableDistribution= MDNode::get( |
| 442 | Context, |
| 443 | {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal}); |
| 444 | MDNode *NewLoopID = |
| 445 | MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize, |
| 446 | DisableLICMVersioning, DisableDistribution}); |
| 447 | // Set operand 0 to refer to the loop id itself. |
| 448 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 449 | L.setLoopID(NewLoopID); |
| 450 | } |
| 451 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 452 | namespace { |
| 453 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 454 | // Keeps track of the structure of a loop. This is similar to llvm::Loop, |
| 455 | // except that it is more lightweight and can track the state of a loop through |
| 456 | // changing and potentially invalid IR. This structure also formalizes the |
| 457 | // kinds of loops we can deal with -- ones that have a single latch that is also |
| 458 | // an exiting block *and* have a canonical induction variable. |
| 459 | struct LoopStructure { |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 460 | const char *Tag = ""; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 461 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 462 | BasicBlock *Header = nullptr; |
| 463 | BasicBlock *Latch = nullptr; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 464 | |
| 465 | // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th |
| 466 | // successor is `LatchExit', the exit block of the loop. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 467 | BranchInst *LatchBr = nullptr; |
| 468 | BasicBlock *LatchExit = nullptr; |
| 469 | unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 470 | |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 471 | // The loop represented by this instance of LoopStructure is semantically |
| 472 | // equivalent to: |
| 473 | // |
| 474 | // intN_ty inc = IndVarIncreasing ? 1 : -1; |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 475 | // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT; |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 476 | // |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 477 | // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase) |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 478 | // ... body ... |
| 479 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 480 | Value *IndVarBase = nullptr; |
| 481 | Value *IndVarStart = nullptr; |
| 482 | Value *IndVarStep = nullptr; |
| 483 | Value *LoopExitAt = nullptr; |
| 484 | bool IndVarIncreasing = false; |
| 485 | bool IsSignedPredicate = true; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 486 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 487 | LoopStructure() = default; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 488 | |
| 489 | template <typename M> LoopStructure map(M Map) const { |
| 490 | LoopStructure Result; |
| 491 | Result.Tag = Tag; |
| 492 | Result.Header = cast<BasicBlock>(Map(Header)); |
| 493 | Result.Latch = cast<BasicBlock>(Map(Latch)); |
| 494 | Result.LatchBr = cast<BranchInst>(Map(LatchBr)); |
| 495 | Result.LatchExit = cast<BasicBlock>(Map(LatchExit)); |
| 496 | Result.LatchBrExitIdx = LatchBrExitIdx; |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 497 | Result.IndVarBase = Map(IndVarBase); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 498 | Result.IndVarStart = Map(IndVarStart); |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 499 | Result.IndVarStep = Map(IndVarStep); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 500 | Result.LoopExitAt = Map(LoopExitAt); |
| 501 | Result.IndVarIncreasing = IndVarIncreasing; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 502 | Result.IsSignedPredicate = IsSignedPredicate; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 503 | return Result; |
| 504 | } |
| 505 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 506 | static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &, |
| 507 | BranchProbabilityInfo &BPI, |
| 508 | Loop &, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 509 | const char *&); |
| 510 | }; |
| 511 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 512 | /// This class is used to constrain loops to run within a given iteration space. |
| 513 | /// The algorithm this class implements is given a Loop and a range [Begin, |
| 514 | /// End). The algorithm then tries to break out a "main loop" out of the loop |
| 515 | /// it is given in a way that the "main loop" runs with the induction variable |
| 516 | /// in a subset of [Begin, End). The algorithm emits appropriate pre and post |
| 517 | /// loops to run any remaining iterations. The pre loop runs any iterations in |
| 518 | /// which the induction variable is < Begin, and the post loop runs any |
| 519 | /// iterations in which the induction variable is >= End. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 520 | class LoopConstrainer { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 521 | // The representation of a clone of the original loop we started out with. |
| 522 | struct ClonedLoop { |
| 523 | // The cloned blocks |
| 524 | std::vector<BasicBlock *> Blocks; |
| 525 | |
| 526 | // `Map` maps values in the clonee into values in the cloned version |
| 527 | ValueToValueMapTy Map; |
| 528 | |
| 529 | // An instance of `LoopStructure` for the cloned loop |
| 530 | LoopStructure Structure; |
| 531 | }; |
| 532 | |
| 533 | // Result of rewriting the range of a loop. See changeIterationSpaceEnd for |
| 534 | // more details on what these fields mean. |
| 535 | struct RewrittenRangeInfo { |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 536 | BasicBlock *PseudoExit = nullptr; |
| 537 | BasicBlock *ExitSelector = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 538 | std::vector<PHINode *> PHIValuesAtPseudoExit; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 539 | PHINode *IndVarEnd = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 540 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 541 | RewrittenRangeInfo() = default; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 542 | }; |
| 543 | |
| 544 | // Calculated subranges we restrict the iteration space of the main loop to. |
| 545 | // See the implementation of `calculateSubRanges' for more details on how |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 546 | // these fields are computed. `LowLimit` is None if there is no restriction |
| 547 | // on low end of the restricted iteration space of the main loop. `HighLimit` |
| 548 | // is None if there is no restriction on high end of the restricted iteration |
| 549 | // space of the main loop. |
| 550 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 551 | struct SubRanges { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 552 | Optional<const SCEV *> LowLimit; |
| 553 | Optional<const SCEV *> HighLimit; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 554 | }; |
| 555 | |
| 556 | // A utility function that does a `replaceUsesOfWith' on the incoming block |
| 557 | // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's |
| 558 | // incoming block list with `ReplaceBy'. |
| 559 | static void replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 560 | BasicBlock *ReplaceBy); |
| 561 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 562 | // Compute a safe set of limits for the main loop to run in -- effectively the |
| 563 | // intersection of `Range' and the iteration space of the original loop. |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 564 | // Return None if unable to compute the set of subranges. |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 565 | Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 566 | |
| 567 | // Clone `OriginalLoop' and return the result in CLResult. The IR after |
| 568 | // running `cloneLoop' is well formed except for the PHI nodes in CLResult -- |
| 569 | // the PHI nodes say that there is an incoming edge from `OriginalPreheader` |
| 570 | // but there is no such edge. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 571 | void cloneLoop(ClonedLoop &CLResult, const char *Tag) const; |
| 572 | |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 573 | // Create the appropriate loop structure needed to describe a cloned copy of |
| 574 | // `Original`. The clone is described by `VM`. |
| 575 | Loop *createClonedLoopStructure(Loop *Original, Loop *Parent, |
| 576 | ValueToValueMapTy &VM); |
| 577 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 578 | // Rewrite the iteration space of the loop denoted by (LS, Preheader). The |
| 579 | // iteration space of the rewritten loop ends at ExitLoopAt. The start of the |
| 580 | // iteration space is not changed. `ExitLoopAt' is assumed to be slt |
| 581 | // `OriginalHeaderCount'. |
| 582 | // |
| 583 | // If there are iterations left to execute, control is made to jump to |
| 584 | // `ContinuationBlock', otherwise they take the normal loop exit. The |
| 585 | // returned `RewrittenRangeInfo' object is populated as follows: |
| 586 | // |
| 587 | // .PseudoExit is a basic block that unconditionally branches to |
| 588 | // `ContinuationBlock'. |
| 589 | // |
| 590 | // .ExitSelector is a basic block that decides, on exit from the loop, |
| 591 | // whether to branch to the "true" exit or to `PseudoExit'. |
| 592 | // |
| 593 | // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value |
| 594 | // for each PHINode in the loop header on taking the pseudo exit. |
| 595 | // |
| 596 | // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate |
| 597 | // preheader because it is made to branch to the loop header only |
| 598 | // conditionally. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 599 | RewrittenRangeInfo |
| 600 | changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader, |
| 601 | Value *ExitLoopAt, |
| 602 | BasicBlock *ContinuationBlock) const; |
| 603 | |
| 604 | // The loop denoted by `LS' has `OldPreheader' as its preheader. This |
| 605 | // function creates a new preheader for `LS' and returns it. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 606 | BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader, |
| 607 | const char *Tag) const; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 608 | |
| 609 | // `ContinuationBlockAndPreheader' was the continuation block for some call to |
| 610 | // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'. |
| 611 | // This function rewrites the PHI nodes in `LS.Header' to start with the |
| 612 | // correct value. |
| 613 | void rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 614 | LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 615 | const LoopConstrainer::RewrittenRangeInfo &RRI) const; |
| 616 | |
| 617 | // Even though we do not preserve any passes at this time, we at least need to |
| 618 | // keep the parent loop structure consistent. The `LPPassManager' seems to |
| 619 | // verify this after running a loop pass. This function adds the list of |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 620 | // blocks denoted by BBs to this loops parent loop if required. |
| 621 | void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 622 | |
| 623 | // Some global state. |
| 624 | Function &F; |
| 625 | LLVMContext &Ctx; |
| 626 | ScalarEvolution &SE; |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 627 | DominatorTree &DT; |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 628 | LPPassManager &LPM; |
Sanjoy Das | 35459f0 | 2016-08-14 01:04:50 +0000 | [diff] [blame] | 629 | LoopInfo &LI; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 630 | |
| 631 | // Information about the original loop we started out with. |
| 632 | Loop &OriginalLoop; |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 633 | |
| 634 | const SCEV *LatchTakenCount = nullptr; |
| 635 | BasicBlock *OriginalPreheader = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 636 | |
| 637 | // The preheader of the main loop. This may or may not be different from |
| 638 | // `OriginalPreheader'. |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 639 | BasicBlock *MainLoopPreheader = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 640 | |
| 641 | // The range we need to run the main loop in. |
| 642 | InductiveRangeCheck::Range Range; |
| 643 | |
| 644 | // The structure of the main loop (see comment at the beginning of this class |
| 645 | // for a definition) |
| 646 | LoopStructure MainLoopStructure; |
| 647 | |
| 648 | public: |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 649 | LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM, |
| 650 | const LoopStructure &LS, ScalarEvolution &SE, |
| 651 | DominatorTree &DT, InductiveRangeCheck::Range R) |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 652 | : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 653 | SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R), |
| 654 | MainLoopStructure(LS) {} |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 655 | |
| 656 | // Entry point for the algorithm. Returns true on success. |
| 657 | bool run(); |
| 658 | }; |
| 659 | |
Eugene Zelenko | 7f0f9bc | 2017-10-24 21:24:53 +0000 | [diff] [blame] | 660 | } // end anonymous namespace |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 661 | |
| 662 | void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block, |
| 663 | BasicBlock *ReplaceBy) { |
| 664 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
| 665 | if (PN->getIncomingBlock(i) == Block) |
| 666 | PN->setIncomingBlock(i, ReplaceBy); |
| 667 | } |
| 668 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 669 | static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) { |
| 670 | APInt Max = Signed ? |
| 671 | APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) : |
| 672 | APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth()); |
| 673 | return SE.getSignedRange(S).contains(Max) && |
| 674 | SE.getUnsignedRange(S).contains(Max); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 675 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 676 | |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 677 | static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2, |
| 678 | bool Signed) { |
| 679 | // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX. |
| 680 | assert(SE.isKnownNonNegative(S2) && |
| 681 | "We expected the 2nd arg to be non-negative!"); |
| 682 | const SCEV *Max = SE.getConstant( |
| 683 | Signed ? APInt::getSignedMaxValue( |
| 684 | cast<IntegerType>(S1->getType())->getBitWidth()) |
| 685 | : APInt::getMaxValue( |
| 686 | cast<IntegerType>(S1->getType())->getBitWidth())); |
| 687 | const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2); |
| 688 | return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, |
| 689 | S1, CapForS1); |
| 690 | } |
| 691 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 692 | static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) { |
| 693 | APInt Min = Signed ? |
| 694 | APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) : |
| 695 | APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth()); |
| 696 | return SE.getSignedRange(S).contains(Min) && |
| 697 | SE.getUnsignedRange(S).contains(Min); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 698 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 699 | |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 700 | static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2, |
| 701 | bool Signed) { |
| 702 | // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN. |
| 703 | assert(SE.isKnownNonPositive(S2) && |
| 704 | "We expected the 2nd arg to be non-positive!"); |
| 705 | const SCEV *Max = SE.getConstant( |
| 706 | Signed ? APInt::getSignedMinValue( |
| 707 | cast<IntegerType>(S1->getType())->getBitWidth()) |
| 708 | : APInt::getMinValue( |
| 709 | cast<IntegerType>(S1->getType())->getBitWidth())); |
| 710 | const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2); |
| 711 | return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, |
| 712 | S1, CapForS1); |
| 713 | } |
| 714 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 715 | Optional<LoopStructure> |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 716 | LoopStructure::parseLoopStructure(ScalarEvolution &SE, |
| 717 | BranchProbabilityInfo &BPI, |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 718 | Loop &L, const char *&FailureReason) { |
Sanjoy Das | 43fdc54 | 2016-08-14 01:04:31 +0000 | [diff] [blame] | 719 | if (!L.isLoopSimplifyForm()) { |
| 720 | FailureReason = "loop not in LoopSimplify form"; |
Sanjoy Das | 2a2f14d | 2016-08-13 23:36:35 +0000 | [diff] [blame] | 721 | return None; |
Sanjoy Das | 43fdc54 | 2016-08-14 01:04:31 +0000 | [diff] [blame] | 722 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 723 | |
| 724 | BasicBlock *Latch = L.getLoopLatch(); |
Sanjoy Das | 2a2f14d | 2016-08-13 23:36:35 +0000 | [diff] [blame] | 725 | assert(Latch && "Simplified loops only have one latch!"); |
| 726 | |
Sanjoy Das | 7a18a23 | 2016-08-14 01:04:36 +0000 | [diff] [blame] | 727 | if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) { |
| 728 | FailureReason = "loop has already been cloned"; |
| 729 | return None; |
| 730 | } |
| 731 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 732 | if (!L.isLoopExiting(Latch)) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 733 | FailureReason = "no loop latch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 734 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 735 | } |
| 736 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 737 | BasicBlock *Header = L.getHeader(); |
| 738 | BasicBlock *Preheader = L.getLoopPreheader(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 739 | if (!Preheader) { |
| 740 | FailureReason = "no preheader"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 741 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 742 | } |
| 743 | |
Sanjoy Das | 81c00fe | 2016-06-23 18:03:26 +0000 | [diff] [blame] | 744 | BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 745 | if (!LatchBr || LatchBr->isUnconditional()) { |
| 746 | FailureReason = "latch terminator not conditional branch"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 747 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 748 | } |
| 749 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 750 | unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 751 | |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 752 | BranchProbability ExitProbability = |
| 753 | BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx); |
| 754 | |
Sanjoy Das | bb96979 | 2016-07-22 00:40:56 +0000 | [diff] [blame] | 755 | if (!SkipProfitabilityChecks && |
| 756 | ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) { |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 757 | FailureReason = "short running loop, not profitable"; |
| 758 | return None; |
| 759 | } |
| 760 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 761 | ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition()); |
| 762 | if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) { |
| 763 | FailureReason = "latch terminator branch not conditional on integral icmp"; |
| 764 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 765 | } |
| 766 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 767 | const SCEV *LatchCount = SE.getExitCount(&L, Latch); |
| 768 | if (isa<SCEVCouldNotCompute>(LatchCount)) { |
| 769 | FailureReason = "could not compute latch count"; |
| 770 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 771 | } |
| 772 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 773 | ICmpInst::Predicate Pred = ICI->getPredicate(); |
| 774 | Value *LeftValue = ICI->getOperand(0); |
| 775 | const SCEV *LeftSCEV = SE.getSCEV(LeftValue); |
| 776 | IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType()); |
| 777 | |
| 778 | Value *RightValue = ICI->getOperand(1); |
| 779 | const SCEV *RightSCEV = SE.getSCEV(RightValue); |
| 780 | |
| 781 | // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence. |
| 782 | if (!isa<SCEVAddRecExpr>(LeftSCEV)) { |
| 783 | if (isa<SCEVAddRecExpr>(RightSCEV)) { |
| 784 | std::swap(LeftSCEV, RightSCEV); |
| 785 | std::swap(LeftValue, RightValue); |
| 786 | Pred = ICmpInst::getSwappedPredicate(Pred); |
| 787 | } else { |
| 788 | FailureReason = "no add recurrences in the icmp"; |
| 789 | return None; |
| 790 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 791 | } |
| 792 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 793 | auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) { |
| 794 | if (AR->getNoWrapFlags(SCEV::FlagNSW)) |
| 795 | return true; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 796 | |
| 797 | IntegerType *Ty = cast<IntegerType>(AR->getType()); |
| 798 | IntegerType *WideTy = |
| 799 | IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2); |
| 800 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 801 | const SCEVAddRecExpr *ExtendAfterOp = |
| 802 | dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); |
| 803 | if (ExtendAfterOp) { |
| 804 | const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy); |
| 805 | const SCEV *ExtendedStep = |
| 806 | SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy); |
| 807 | |
| 808 | bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart && |
| 809 | ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep; |
| 810 | |
| 811 | if (NoSignedWrap) |
| 812 | return true; |
| 813 | } |
| 814 | |
| 815 | // We may have proved this when computing the sign extension above. |
| 816 | return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap; |
| 817 | }; |
| 818 | |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 819 | // Here we check whether the suggested AddRec is an induction variable that |
| 820 | // can be handled (i.e. with known constant step), and if yes, calculate its |
| 821 | // step and identify whether it is increasing or decreasing. |
| 822 | auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing, |
| 823 | ConstantInt *&StepCI) { |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 824 | if (!AR->isAffine()) |
| 825 | return false; |
| 826 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 827 | // Currently we only work with induction variables that have been proved to |
| 828 | // not wrap. This restriction can potentially be lifted in the future. |
| 829 | |
Sanjoy Das | 45dc94a | 2015-03-24 19:29:22 +0000 | [diff] [blame] | 830 | if (!HasNoSignedWrap(AR)) |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 831 | return false; |
| 832 | |
| 833 | if (const SCEVConstant *StepExpr = |
| 834 | dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) { |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 835 | StepCI = StepExpr->getValue(); |
Max Kazantsev | 85da754 | 2017-08-01 06:27:51 +0000 | [diff] [blame] | 836 | assert(!StepCI->isZero() && "Zero step?"); |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 837 | IsIncreasing = !StepCI->isNegative(); |
| 838 | return true; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 839 | } |
| 840 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 841 | return false; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 842 | }; |
| 843 | |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 844 | // `ICI` is interpreted as taking the backedge if the *next* value of the |
| 845 | // induction variable satisfies some constraint. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 846 | |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 847 | const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 848 | bool IsIncreasing = false; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 849 | bool IsSignedPredicate = true; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 850 | ConstantInt *StepCI; |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 851 | if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 852 | FailureReason = "LHS in icmp not induction variable"; |
| 853 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 854 | } |
| 855 | |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 856 | const SCEV *StartNext = IndVarBase->getStart(); |
| 857 | const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE)); |
| 858 | const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend); |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 859 | const SCEV *Step = SE.getSCEV(StepCI); |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 860 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 861 | ConstantInt *One = ConstantInt::get(IndVarTy, 1); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 862 | if (IsIncreasing) { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 863 | bool DecreasedRightValueByOne = false; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 864 | if (StepCI->isOne()) { |
| 865 | // Try to turn eq/ne predicates to those we can work with. |
| 866 | if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) |
| 867 | // while (++i != len) { while (++i < len) { |
| 868 | // ... ---> ... |
| 869 | // } } |
| 870 | // If both parts are known non-negative, it is profitable to use |
| 871 | // unsigned comparison in increasing loop. This allows us to make the |
| 872 | // comparison check against "RightSCEV + 1" more optimistic. |
| 873 | if (SE.isKnownNonNegative(IndVarStart) && |
| 874 | SE.isKnownNonNegative(RightSCEV)) |
| 875 | Pred = ICmpInst::ICMP_ULT; |
| 876 | else |
| 877 | Pred = ICmpInst::ICMP_SLT; |
| 878 | else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 && |
| 879 | !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) { |
| 880 | // while (true) { while (true) { |
| 881 | // if (++i == len) ---> if (++i > len - 1) |
| 882 | // break; break; |
| 883 | // ... ... |
| 884 | // } } |
| 885 | // TODO: Insert ICMP_UGT if both are non-negative? |
| 886 | Pred = ICmpInst::ICMP_SGT; |
| 887 | RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())); |
| 888 | DecreasedRightValueByOne = true; |
| 889 | } |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 890 | } |
| 891 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 892 | bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); |
| 893 | bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 894 | bool FoundExpectedPred = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 895 | (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 896 | |
| 897 | if (!FoundExpectedPred) { |
| 898 | FailureReason = "expected icmp slt semantically, found something else"; |
| 899 | return None; |
| 900 | } |
| 901 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 902 | IsSignedPredicate = |
| 903 | Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT; |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 904 | |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 905 | if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { |
| 906 | FailureReason = "unsigned latch conditions are explicitly prohibited"; |
| 907 | return None; |
| 908 | } |
| 909 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 910 | // The predicate that we need to check that the induction variable lies |
| 911 | // within bounds. |
| 912 | ICmpInst::Predicate BoundPred = |
| 913 | IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT; |
| 914 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 915 | if (LatchBrExitIdx == 0) { |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 916 | const SCEV *StepMinusOne = SE.getMinusSCEV(Step, |
| 917 | SE.getOne(Step->getType())); |
| 918 | if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 919 | // TODO: this restriction is easily removable -- we just have to |
| 920 | // remember that the icmp was an slt and not an sle. |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 921 | FailureReason = "limit may overflow when coercing le to lt"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 922 | return None; |
| 923 | } |
| 924 | |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 925 | if (!SE.isLoopEntryGuardedByCond( |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 926 | &L, BoundPred, IndVarStart, |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 927 | SE.getAddExpr(RightSCEV, Step))) { |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 928 | FailureReason = "Induction variable start not bounded by upper limit"; |
| 929 | return None; |
| 930 | } |
| 931 | |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 932 | // We need to increase the right value unless we have already decreased |
| 933 | // it virtually when we replaced EQ with SGT. |
| 934 | if (!DecreasedRightValueByOne) { |
| 935 | IRBuilder<> B(Preheader->getTerminator()); |
| 936 | RightValue = B.CreateAdd(RightValue, One); |
| 937 | } |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 938 | } else { |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 939 | if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) { |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 940 | FailureReason = "Induction variable start not bounded by upper limit"; |
| 941 | return None; |
| 942 | } |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 943 | assert(!DecreasedRightValueByOne && |
| 944 | "Right value can be decreased only for LatchBrExitIdx == 0!"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 945 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 946 | } else { |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 947 | bool IncreasedRightValueByOne = false; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 948 | if (StepCI->isMinusOne()) { |
| 949 | // Try to turn eq/ne predicates to those we can work with. |
| 950 | if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1) |
| 951 | // while (--i != len) { while (--i > len) { |
| 952 | // ... ---> ... |
| 953 | // } } |
| 954 | // We intentionally don't turn the predicate into UGT even if we know |
| 955 | // that both operands are non-negative, because it will only pessimize |
| 956 | // our check against "RightSCEV - 1". |
| 957 | Pred = ICmpInst::ICMP_SGT; |
| 958 | else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 && |
| 959 | !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) { |
| 960 | // while (true) { while (true) { |
| 961 | // if (--i == len) ---> if (--i < len + 1) |
| 962 | // break; break; |
| 963 | // ... ... |
| 964 | // } } |
| 965 | // TODO: Insert ICMP_ULT if both are non-negative? |
| 966 | Pred = ICmpInst::ICMP_SLT; |
| 967 | RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType())); |
| 968 | IncreasedRightValueByOne = true; |
| 969 | } |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 970 | } |
| 971 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 972 | bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT); |
| 973 | bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT); |
| 974 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 975 | bool FoundExpectedPred = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 976 | (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 977 | |
| 978 | if (!FoundExpectedPred) { |
| 979 | FailureReason = "expected icmp sgt semantically, found something else"; |
| 980 | return None; |
| 981 | } |
| 982 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 983 | IsSignedPredicate = |
| 984 | Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT; |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 985 | |
Max Kazantsev | 8aacef6 | 2017-10-04 06:53:22 +0000 | [diff] [blame] | 986 | if (!IsSignedPredicate && !AllowUnsignedLatchCondition) { |
| 987 | FailureReason = "unsigned latch conditions are explicitly prohibited"; |
| 988 | return None; |
| 989 | } |
| 990 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 991 | // The predicate that we need to check that the induction variable lies |
| 992 | // within bounds. |
| 993 | ICmpInst::Predicate BoundPred = |
| 994 | IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT; |
| 995 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 996 | if (LatchBrExitIdx == 0) { |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 997 | const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType())); |
| 998 | if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 999 | // TODO: this restriction is easily removable -- we just have to |
| 1000 | // remember that the icmp was an sgt and not an sge. |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1001 | FailureReason = "limit may overflow when coercing ge to gt"; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1002 | return None; |
| 1003 | } |
| 1004 | |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 1005 | if (!SE.isLoopEntryGuardedByCond( |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1006 | &L, BoundPred, IndVarStart, |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 1007 | SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) { |
| 1008 | FailureReason = "Induction variable start not bounded by lower limit"; |
| 1009 | return None; |
| 1010 | } |
| 1011 | |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 1012 | // We need to decrease the right value unless we have already increased |
| 1013 | // it virtually when we replaced EQ with SLT. |
| 1014 | if (!IncreasedRightValueByOne) { |
| 1015 | IRBuilder<> B(Preheader->getTerminator()); |
| 1016 | RightValue = B.CreateSub(RightValue, One); |
| 1017 | } |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 1018 | } else { |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1019 | if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) { |
Sanjoy Das | ec89213 | 2017-02-07 23:59:07 +0000 | [diff] [blame] | 1020 | FailureReason = "Induction variable start not bounded by lower limit"; |
| 1021 | return None; |
| 1022 | } |
Max Kazantsev | 2c627a9 | 2017-07-18 04:53:48 +0000 | [diff] [blame] | 1023 | assert(!IncreasedRightValueByOne && |
| 1024 | "Right value can be increased only for LatchBrExitIdx == 0!"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1025 | } |
| 1026 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1027 | BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx); |
| 1028 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1029 | assert(SE.getLoopDisposition(LatchCount, &L) == |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1030 | ScalarEvolution::LoopInvariant && |
| 1031 | "loop variant exit count doesn't make sense!"); |
| 1032 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1033 | assert(!L.contains(LatchExit) && "expected an exit block!"); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1034 | const DataLayout &DL = Preheader->getModule()->getDataLayout(); |
| 1035 | Value *IndVarStartV = |
| 1036 | SCEVExpander(SE, DL, "irce") |
Sanjoy Das | 81c00fe | 2016-06-23 18:03:26 +0000 | [diff] [blame] | 1037 | .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1038 | IndVarStartV->setName("indvar.start"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1039 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1040 | LoopStructure Result; |
| 1041 | |
| 1042 | Result.Tag = "main"; |
| 1043 | Result.Header = Header; |
| 1044 | Result.Latch = Latch; |
| 1045 | Result.LatchBr = LatchBr; |
| 1046 | Result.LatchExit = LatchExit; |
| 1047 | Result.LatchBrExitIdx = LatchBrExitIdx; |
| 1048 | Result.IndVarStart = IndVarStartV; |
Max Kazantsev | 2f6ae28 | 2017-08-04 07:01:04 +0000 | [diff] [blame] | 1049 | Result.IndVarStep = StepCI; |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1050 | Result.IndVarBase = LeftValue; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1051 | Result.IndVarIncreasing = IsIncreasing; |
| 1052 | Result.LoopExitAt = RightValue; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1053 | Result.IsSignedPredicate = IsSignedPredicate; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1054 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1055 | FailureReason = nullptr; |
| 1056 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1057 | return Result; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1058 | } |
| 1059 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1060 | Optional<LoopConstrainer::SubRanges> |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1061 | LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1062 | IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType()); |
| 1063 | |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1064 | if (Range.getType() != Ty) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1065 | return None; |
| 1066 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1067 | LoopConstrainer::SubRanges Result; |
| 1068 | |
| 1069 | // I think we can be more aggressive here and make this nuw / nsw if the |
| 1070 | // addition that feeds into the icmp for the latch's terminating branch is nuw |
| 1071 | // / nsw. In any case, a wrapping 2's complement addition is safe. |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1072 | const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart); |
| 1073 | const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1074 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1075 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1076 | |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1077 | // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or |
| 1078 | // [Smallest, GreatestSeen] is the range of values the induction variable |
| 1079 | // takes. |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1080 | |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1081 | const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1082 | |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1083 | const SCEV *One = SE.getOne(Ty); |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1084 | if (Increasing) { |
| 1085 | Smallest = Start; |
| 1086 | Greatest = End; |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1087 | // No overflow, because the range [Smallest, GreatestSeen] is not empty. |
| 1088 | GreatestSeen = SE.getMinusSCEV(End, One); |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1089 | } else { |
| 1090 | // These two computations may sign-overflow. Here is why that is okay: |
| 1091 | // |
| 1092 | // We know that the induction variable does not sign-overflow on any |
| 1093 | // iteration except the last one, and it starts at `Start` and ends at |
| 1094 | // `End`, decrementing by one every time. |
| 1095 | // |
| 1096 | // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the |
| 1097 | // induction variable is decreasing we know that that the smallest value |
| 1098 | // the loop body is actually executed with is `INT_SMIN` == `Smallest`. |
| 1099 | // |
| 1100 | // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In |
| 1101 | // that case, `Clamp` will always return `Smallest` and |
| 1102 | // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`) |
| 1103 | // will be an empty range. Returning an empty range is always safe. |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1104 | |
Max Kazantsev | 6c466a3 | 2017-06-28 04:57:45 +0000 | [diff] [blame] | 1105 | Smallest = SE.getAddExpr(End, One); |
| 1106 | Greatest = SE.getAddExpr(Start, One); |
Max Kazantsev | f80ffa1 | 2017-07-14 06:35:03 +0000 | [diff] [blame] | 1107 | GreatestSeen = Start; |
Sanjoy Das | 7a0b7f5 | 2015-03-17 00:42:16 +0000 | [diff] [blame] | 1108 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1109 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1110 | auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) { |
Max Kazantsev | 6f5229d7 | 2017-11-01 13:21:56 +0000 | [diff] [blame] | 1111 | return IsSignedPredicate |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1112 | ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S)) |
| 1113 | : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S)); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1114 | }; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1115 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1116 | // In some cases we can prove that we don't need a pre or post loop. |
| 1117 | ICmpInst::Predicate PredLE = |
| 1118 | IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; |
| 1119 | ICmpInst::Predicate PredLT = |
| 1120 | IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1121 | |
| 1122 | bool ProvablyNoPreloop = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1123 | SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1124 | if (!ProvablyNoPreloop) |
| 1125 | Result.LowLimit = Clamp(Range.getBegin()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1126 | |
| 1127 | bool ProvablyNoPostLoop = |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1128 | SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1129 | if (!ProvablyNoPostLoop) |
| 1130 | Result.HighLimit = Clamp(Range.getEnd()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1131 | |
| 1132 | return Result; |
| 1133 | } |
| 1134 | |
| 1135 | void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result, |
| 1136 | const char *Tag) const { |
| 1137 | for (BasicBlock *BB : OriginalLoop.getBlocks()) { |
| 1138 | BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F); |
| 1139 | Result.Blocks.push_back(Clone); |
| 1140 | Result.Map[BB] = Clone; |
| 1141 | } |
| 1142 | |
| 1143 | auto GetClonedValue = [&Result](Value *V) { |
| 1144 | assert(V && "null values not in domain!"); |
| 1145 | auto It = Result.Map.find(V); |
| 1146 | if (It == Result.Map.end()) |
| 1147 | return V; |
| 1148 | return static_cast<Value *>(It->second); |
| 1149 | }; |
| 1150 | |
Sanjoy Das | 7a18a23 | 2016-08-14 01:04:36 +0000 | [diff] [blame] | 1151 | auto *ClonedLatch = |
| 1152 | cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch())); |
| 1153 | ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag, |
| 1154 | MDNode::get(Ctx, {})); |
| 1155 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1156 | Result.Structure = MainLoopStructure.map(GetClonedValue); |
| 1157 | Result.Structure.Tag = Tag; |
| 1158 | |
| 1159 | for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) { |
| 1160 | BasicBlock *ClonedBB = Result.Blocks[i]; |
| 1161 | BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i]; |
| 1162 | |
| 1163 | assert(Result.Map[OriginalBB] == ClonedBB && "invariant!"); |
| 1164 | |
| 1165 | for (Instruction &I : *ClonedBB) |
| 1166 | RemapInstruction(&I, Result.Map, |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 1167 | RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1168 | |
| 1169 | // Exit blocks will now have one more predecessor and their PHI nodes need |
| 1170 | // to be edited to reflect that. No phi nodes need to be introduced because |
| 1171 | // the loop is in LCSSA. |
| 1172 | |
Sanjoy Das | d1d62a1 | 2016-08-13 22:00:09 +0000 | [diff] [blame] | 1173 | for (auto *SBB : successors(OriginalBB)) { |
| 1174 | if (OriginalLoop.contains(SBB)) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1175 | continue; // not an exit block |
| 1176 | |
Sanjoy Das | d1d62a1 | 2016-08-13 22:00:09 +0000 | [diff] [blame] | 1177 | for (Instruction &I : *SBB) { |
Sanjoy Das | f2b7baf | 2016-08-13 22:00:12 +0000 | [diff] [blame] | 1178 | auto *PN = dyn_cast<PHINode>(&I); |
| 1179 | if (!PN) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1180 | break; |
| 1181 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1182 | Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB); |
| 1183 | PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB); |
| 1184 | } |
| 1185 | } |
| 1186 | } |
| 1187 | } |
| 1188 | |
| 1189 | LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1190 | const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1191 | BasicBlock *ContinuationBlock) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1192 | // We start with a loop with a single latch: |
| 1193 | // |
| 1194 | // +--------------------+ |
| 1195 | // | | |
| 1196 | // | preheader | |
| 1197 | // | | |
| 1198 | // +--------+-----------+ |
| 1199 | // | ----------------\ |
| 1200 | // | / | |
| 1201 | // +--------v----v------+ | |
| 1202 | // | | | |
| 1203 | // | header | | |
| 1204 | // | | | |
| 1205 | // +--------------------+ | |
| 1206 | // | |
| 1207 | // ..... | |
| 1208 | // | |
| 1209 | // +--------------------+ | |
| 1210 | // | | | |
| 1211 | // | latch >----------/ |
| 1212 | // | | |
| 1213 | // +-------v------------+ |
| 1214 | // | |
| 1215 | // | |
| 1216 | // | +--------------------+ |
| 1217 | // | | | |
| 1218 | // +---> original exit | |
| 1219 | // | | |
| 1220 | // +--------------------+ |
| 1221 | // |
| 1222 | // We change the control flow to look like |
| 1223 | // |
| 1224 | // |
| 1225 | // +--------------------+ |
| 1226 | // | | |
| 1227 | // | preheader >-------------------------+ |
| 1228 | // | | | |
| 1229 | // +--------v-----------+ | |
| 1230 | // | /-------------+ | |
| 1231 | // | / | | |
| 1232 | // +--------v--v--------+ | | |
| 1233 | // | | | | |
| 1234 | // | header | | +--------+ | |
| 1235 | // | | | | | | |
| 1236 | // +--------------------+ | | +-----v-----v-----------+ |
| 1237 | // | | | | |
| 1238 | // | | | .pseudo.exit | |
| 1239 | // | | | | |
| 1240 | // | | +-----------v-----------+ |
| 1241 | // | | | |
| 1242 | // ..... | | | |
| 1243 | // | | +--------v-------------+ |
| 1244 | // +--------------------+ | | | | |
| 1245 | // | | | | | ContinuationBlock | |
| 1246 | // | latch >------+ | | | |
| 1247 | // | | | +----------------------+ |
| 1248 | // +---------v----------+ | |
| 1249 | // | | |
| 1250 | // | | |
| 1251 | // | +---------------^-----+ |
| 1252 | // | | | |
| 1253 | // +-----> .exit.selector | |
| 1254 | // | | |
| 1255 | // +----------v----------+ |
| 1256 | // | |
| 1257 | // +--------------------+ | |
| 1258 | // | | | |
| 1259 | // | original exit <----+ |
| 1260 | // | | |
| 1261 | // +--------------------+ |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1262 | |
| 1263 | RewrittenRangeInfo RRI; |
| 1264 | |
Duncan P. N. Exon Smith | 3bcaa81 | 2016-08-17 01:16:17 +0000 | [diff] [blame] | 1265 | BasicBlock *BBInsertLocation = LS.Latch->getNextNode(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1266 | RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector", |
Duncan P. N. Exon Smith | 3bcaa81 | 2016-08-17 01:16:17 +0000 | [diff] [blame] | 1267 | &F, BBInsertLocation); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1268 | RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F, |
Duncan P. N. Exon Smith | 3bcaa81 | 2016-08-17 01:16:17 +0000 | [diff] [blame] | 1269 | BBInsertLocation); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1270 | |
Sanjoy Das | 81c00fe | 2016-06-23 18:03:26 +0000 | [diff] [blame] | 1271 | BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1272 | bool Increasing = LS.IndVarIncreasing; |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1273 | bool IsSignedPredicate = LS.IsSignedPredicate; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1274 | |
| 1275 | IRBuilder<> B(PreheaderJump); |
| 1276 | |
| 1277 | // EnterLoopCond - is it okay to start executing this `LS'? |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1278 | Value *EnterLoopCond = nullptr; |
| 1279 | if (Increasing) |
| 1280 | EnterLoopCond = IsSignedPredicate |
| 1281 | ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt) |
| 1282 | : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt); |
| 1283 | else |
| 1284 | EnterLoopCond = IsSignedPredicate |
| 1285 | ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt) |
| 1286 | : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1287 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1288 | B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit); |
| 1289 | PreheaderJump->eraseFromParent(); |
| 1290 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1291 | LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1292 | B.SetInsertPoint(LS.LatchBr); |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1293 | Value *TakeBackedgeLoopCond = nullptr; |
| 1294 | if (Increasing) |
| 1295 | TakeBackedgeLoopCond = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1296 | ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt) |
| 1297 | : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt); |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1298 | else |
| 1299 | TakeBackedgeLoopCond = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1300 | ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt) |
| 1301 | : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1302 | Value *CondForBranch = LS.LatchBrExitIdx == 1 |
| 1303 | ? TakeBackedgeLoopCond |
| 1304 | : B.CreateNot(TakeBackedgeLoopCond); |
| 1305 | |
| 1306 | LS.LatchBr->setCondition(CondForBranch); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1307 | |
| 1308 | B.SetInsertPoint(RRI.ExitSelector); |
| 1309 | |
| 1310 | // IterationsLeft - are there any more iterations left, given the original |
| 1311 | // upper bound on the induction variable? If not, we branch to the "real" |
| 1312 | // exit. |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1313 | Value *IterationsLeft = nullptr; |
| 1314 | if (Increasing) |
| 1315 | IterationsLeft = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1316 | ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt) |
| 1317 | : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt); |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1318 | else |
| 1319 | IterationsLeft = IsSignedPredicate |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1320 | ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt) |
| 1321 | : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1322 | B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit); |
| 1323 | |
| 1324 | BranchInst *BranchToContinuation = |
| 1325 | BranchInst::Create(ContinuationBlock, RRI.PseudoExit); |
| 1326 | |
| 1327 | // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of |
| 1328 | // each of the PHI nodes in the loop header. This feeds into the initial |
| 1329 | // value of the same PHI nodes if/when we continue execution. |
| 1330 | for (Instruction &I : *LS.Header) { |
Sanjoy Das | f2b7baf | 2016-08-13 22:00:12 +0000 | [diff] [blame] | 1331 | auto *PN = dyn_cast<PHINode>(&I); |
| 1332 | if (!PN) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1333 | break; |
| 1334 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1335 | PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy", |
| 1336 | BranchToContinuation); |
| 1337 | |
| 1338 | NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader); |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1339 | NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch), |
| 1340 | RRI.ExitSelector); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1341 | RRI.PHIValuesAtPseudoExit.push_back(NewPHI); |
| 1342 | } |
| 1343 | |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1344 | RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end", |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1345 | BranchToContinuation); |
| 1346 | RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader); |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1347 | RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1348 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1349 | // The latch exit now has a branch from `RRI.ExitSelector' instead of |
| 1350 | // `LS.Latch'. The PHI nodes need to be updated to reflect that. |
| 1351 | for (Instruction &I : *LS.LatchExit) { |
| 1352 | if (PHINode *PN = dyn_cast<PHINode>(&I)) |
| 1353 | replacePHIBlock(PN, LS.Latch, RRI.ExitSelector); |
| 1354 | else |
| 1355 | break; |
| 1356 | } |
| 1357 | |
| 1358 | return RRI; |
| 1359 | } |
| 1360 | |
| 1361 | void LoopConstrainer::rewriteIncomingValuesForPHIs( |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1362 | LoopStructure &LS, BasicBlock *ContinuationBlock, |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1363 | const LoopConstrainer::RewrittenRangeInfo &RRI) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1364 | unsigned PHIIndex = 0; |
| 1365 | for (Instruction &I : *LS.Header) { |
Sanjoy Das | f2b7baf | 2016-08-13 22:00:12 +0000 | [diff] [blame] | 1366 | auto *PN = dyn_cast<PHINode>(&I); |
| 1367 | if (!PN) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1368 | break; |
| 1369 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1370 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) |
| 1371 | if (PN->getIncomingBlock(i) == ContinuationBlock) |
| 1372 | PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]); |
| 1373 | } |
| 1374 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1375 | LS.IndVarStart = RRI.IndVarEnd; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1376 | } |
| 1377 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1378 | BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS, |
| 1379 | BasicBlock *OldPreheader, |
| 1380 | const char *Tag) const { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1381 | BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header); |
| 1382 | BranchInst::Create(LS.Header, Preheader); |
| 1383 | |
| 1384 | for (Instruction &I : *LS.Header) { |
Sanjoy Das | f2b7baf | 2016-08-13 22:00:12 +0000 | [diff] [blame] | 1385 | auto *PN = dyn_cast<PHINode>(&I); |
| 1386 | if (!PN) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1387 | break; |
| 1388 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1389 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) |
| 1390 | replacePHIBlock(PN, OldPreheader, Preheader); |
| 1391 | } |
| 1392 | |
| 1393 | return Preheader; |
| 1394 | } |
| 1395 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1396 | void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) { |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1397 | Loop *ParentLoop = OriginalLoop.getParentLoop(); |
| 1398 | if (!ParentLoop) |
| 1399 | return; |
| 1400 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1401 | for (BasicBlock *BB : BBs) |
Sanjoy Das | 83a7285 | 2016-08-02 19:32:01 +0000 | [diff] [blame] | 1402 | ParentLoop->addBasicBlockToLoop(BB, LI); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1403 | } |
| 1404 | |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1405 | Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent, |
| 1406 | ValueToValueMapTy &VM) { |
Sanjoy Das | def1729 | 2017-09-28 02:45:42 +0000 | [diff] [blame] | 1407 | Loop &New = *LI.AllocateLoop(); |
Chandler Carruth | 29c22d2 | 2017-05-25 03:01:31 +0000 | [diff] [blame] | 1408 | if (Parent) |
| 1409 | Parent->addChildLoop(&New); |
| 1410 | else |
| 1411 | LI.addTopLevelLoop(&New); |
| 1412 | LPM.addLoop(New); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1413 | |
| 1414 | // Add all of the blocks in Original to the new loop. |
| 1415 | for (auto *BB : Original->blocks()) |
| 1416 | if (LI.getLoopFor(BB) == Original) |
| 1417 | New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI); |
| 1418 | |
| 1419 | // Add all of the subloops to the new loop. |
| 1420 | for (Loop *SubLoop : *Original) |
| 1421 | createClonedLoopStructure(SubLoop, &New, VM); |
| 1422 | |
| 1423 | return &New; |
| 1424 | } |
| 1425 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1426 | bool LoopConstrainer::run() { |
| 1427 | BasicBlock *Preheader = nullptr; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1428 | LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch); |
| 1429 | Preheader = OriginalLoop.getLoopPreheader(); |
| 1430 | assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr && |
| 1431 | "preconditions!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1432 | |
| 1433 | OriginalPreheader = Preheader; |
| 1434 | MainLoopPreheader = Preheader; |
| 1435 | |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1436 | bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate; |
| 1437 | Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1438 | if (!MaybeSR.hasValue()) { |
| 1439 | DEBUG(dbgs() << "irce: could not compute subranges\n"); |
| 1440 | return false; |
| 1441 | } |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1442 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1443 | SubRanges SR = MaybeSR.getValue(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1444 | bool Increasing = MainLoopStructure.IndVarIncreasing; |
| 1445 | IntegerType *IVTy = |
Max Kazantsev | a22742b | 2017-08-31 05:58:15 +0000 | [diff] [blame] | 1446 | cast<IntegerType>(MainLoopStructure.IndVarBase->getType()); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1447 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1448 | SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1449 | Instruction *InsertPt = OriginalPreheader->getTerminator(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1450 | |
| 1451 | // It would have been better to make `PreLoop' and `PostLoop' |
| 1452 | // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy |
| 1453 | // constructor. |
| 1454 | ClonedLoop PreLoop, PostLoop; |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1455 | bool NeedsPreLoop = |
| 1456 | Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue(); |
| 1457 | bool NeedsPostLoop = |
| 1458 | Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue(); |
| 1459 | |
| 1460 | Value *ExitPreLoopAt = nullptr; |
| 1461 | Value *ExitMainLoopAt = nullptr; |
| 1462 | const SCEVConstant *MinusOneS = |
| 1463 | cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */)); |
| 1464 | |
| 1465 | if (NeedsPreLoop) { |
| 1466 | const SCEV *ExitPreLoopAtSCEV = nullptr; |
| 1467 | |
| 1468 | if (Increasing) |
| 1469 | ExitPreLoopAtSCEV = *SR.LowLimit; |
| 1470 | else { |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1471 | if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1472 | DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1473 | << "preloop exit limit. HighLimit = " << *(*SR.HighLimit) |
| 1474 | << "\n"); |
| 1475 | return false; |
| 1476 | } |
| 1477 | ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS); |
| 1478 | } |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1479 | |
Max Kazantsev | b1b8aff | 2017-11-16 06:06:27 +0000 | [diff] [blame] | 1480 | if (!isSafeToExpandAt(ExitPreLoopAtSCEV, InsertPt, SE)) { |
| 1481 | DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" |
| 1482 | << " preloop exit limit " << *ExitPreLoopAtSCEV |
| 1483 | << " at block " << InsertPt->getParent()->getName() << "\n"); |
| 1484 | return false; |
| 1485 | } |
| 1486 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1487 | ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt); |
| 1488 | ExitPreLoopAt->setName("exit.preloop.at"); |
| 1489 | } |
| 1490 | |
| 1491 | if (NeedsPostLoop) { |
| 1492 | const SCEV *ExitMainLoopAtSCEV = nullptr; |
| 1493 | |
| 1494 | if (Increasing) |
| 1495 | ExitMainLoopAtSCEV = *SR.HighLimit; |
| 1496 | else { |
Max Kazantsev | 07da1ab | 2017-08-04 05:40:20 +0000 | [diff] [blame] | 1497 | if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) { |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1498 | DEBUG(dbgs() << "irce: could not prove no-overflow when computing " |
| 1499 | << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit) |
| 1500 | << "\n"); |
| 1501 | return false; |
| 1502 | } |
| 1503 | ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS); |
| 1504 | } |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1505 | |
Max Kazantsev | b1b8aff | 2017-11-16 06:06:27 +0000 | [diff] [blame] | 1506 | if (!isSafeToExpandAt(ExitMainLoopAtSCEV, InsertPt, SE)) { |
| 1507 | DEBUG(dbgs() << "irce: could not prove that it is safe to expand the" |
| 1508 | << " main loop exit limit " << *ExitMainLoopAtSCEV |
| 1509 | << " at block " << InsertPt->getParent()->getName() << "\n"); |
| 1510 | return false; |
| 1511 | } |
| 1512 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1513 | ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt); |
| 1514 | ExitMainLoopAt->setName("exit.mainloop.at"); |
| 1515 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1516 | |
| 1517 | // We clone these ahead of time so that we don't have to deal with changing |
| 1518 | // and temporarily invalid IR as we transform the loops. |
| 1519 | if (NeedsPreLoop) |
| 1520 | cloneLoop(PreLoop, "preloop"); |
| 1521 | if (NeedsPostLoop) |
| 1522 | cloneLoop(PostLoop, "postloop"); |
| 1523 | |
| 1524 | RewrittenRangeInfo PreLoopRRI; |
| 1525 | |
| 1526 | if (NeedsPreLoop) { |
| 1527 | Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header, |
| 1528 | PreLoop.Structure.Header); |
| 1529 | |
| 1530 | MainLoopPreheader = |
| 1531 | createPreheader(MainLoopStructure, Preheader, "mainloop"); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1532 | PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader, |
| 1533 | ExitPreLoopAt, MainLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1534 | rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader, |
| 1535 | PreLoopRRI); |
| 1536 | } |
| 1537 | |
| 1538 | BasicBlock *PostLoopPreheader = nullptr; |
| 1539 | RewrittenRangeInfo PostLoopRRI; |
| 1540 | |
| 1541 | if (NeedsPostLoop) { |
| 1542 | PostLoopPreheader = |
| 1543 | createPreheader(PostLoop.Structure, Preheader, "postloop"); |
| 1544 | PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader, |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1545 | ExitMainLoopAt, PostLoopPreheader); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1546 | rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader, |
| 1547 | PostLoopRRI); |
| 1548 | } |
| 1549 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1550 | BasicBlock *NewMainLoopPreheader = |
| 1551 | MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr; |
| 1552 | BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit, |
| 1553 | PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit, |
| 1554 | PostLoopRRI.ExitSelector, NewMainLoopPreheader}; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1555 | |
| 1556 | // Some of the above may be nullptr, filter them out before passing to |
| 1557 | // addToParentLoopIfNeeded. |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1558 | auto NewBlocksEnd = |
| 1559 | std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1560 | |
Benjamin Kramer | 39f76ac | 2015-02-06 14:43:49 +0000 | [diff] [blame] | 1561 | addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd)); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1562 | |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 1563 | DT.recalculate(F); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1564 | |
Anna Thomas | 7218032 | 2017-06-06 14:54:01 +0000 | [diff] [blame] | 1565 | // We need to first add all the pre and post loop blocks into the loop |
| 1566 | // structures (as part of createClonedLoopStructure), and then update the |
| 1567 | // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating |
| 1568 | // LI when LoopSimplifyForm is generated. |
| 1569 | Loop *PreL = nullptr, *PostL = nullptr; |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1570 | if (!PreLoop.Blocks.empty()) { |
Anna Thomas | 7218032 | 2017-06-06 14:54:01 +0000 | [diff] [blame] | 1571 | PreL = createClonedLoopStructure( |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1572 | &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1573 | } |
| 1574 | |
| 1575 | if (!PostLoop.Blocks.empty()) { |
Anna Thomas | 7218032 | 2017-06-06 14:54:01 +0000 | [diff] [blame] | 1576 | PostL = createClonedLoopStructure( |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1577 | &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1578 | } |
| 1579 | |
Anna Thomas | 7218032 | 2017-06-06 14:54:01 +0000 | [diff] [blame] | 1580 | // This function canonicalizes the loop into Loop-Simplify and LCSSA forms. |
| 1581 | auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) { |
| 1582 | formLCSSARecursively(*L, DT, &LI, &SE); |
| 1583 | simplifyLoop(L, &DT, &LI, &SE, nullptr, true); |
| 1584 | // Pre/post loops are slow paths, we do not need to perform any loop |
| 1585 | // optimizations on them. |
| 1586 | if (!IsOriginalLoop) |
| 1587 | DisableAllLoopOptsOnLoop(*L); |
| 1588 | }; |
| 1589 | if (PreL) |
| 1590 | CanonicalizeLoop(PreL, false); |
| 1591 | if (PostL) |
| 1592 | CanonicalizeLoop(PostL, false); |
| 1593 | CanonicalizeLoop(&OriginalLoop, true); |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 1594 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1595 | return true; |
| 1596 | } |
| 1597 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1598 | /// Computes and returns a range of values for the induction variable (IndVar) |
| 1599 | /// in which the range check can be safely elided. If it cannot compute such a |
| 1600 | /// range, returns None. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1601 | Optional<InductiveRangeCheck::Range> |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1602 | InductiveRangeCheck::computeSafeIterationSpace( |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1603 | ScalarEvolution &SE, const SCEVAddRecExpr *IndVar, |
| 1604 | bool IsLatchSigned) const { |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1605 | // IndVar is of the form "A + B * I" (where "I" is the canonical induction |
| 1606 | // variable, that may or may not exist as a real llvm::Value in the loop) and |
| 1607 | // this inductive range check is a range check on the "C + D * I" ("C" is |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 1608 | // getBegin() and "D" is getStep()). We rewrite the value being range |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1609 | // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA". |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1610 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1611 | // The actual inequalities we solve are of the form |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1612 | // |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1613 | // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1) |
| 1614 | // |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1615 | // Here L stands for upper limit of the safe iteration space. |
| 1616 | // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid |
| 1617 | // overflows when calculating (0 - M) and (L - M) we, depending on type of |
| 1618 | // IV's iteration space, limit the calculations by borders of the iteration |
| 1619 | // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0. |
| 1620 | // If we figured out that "anything greater than (-M) is safe", we strengthen |
| 1621 | // this to "everything greater than 0 is safe", assuming that values between |
| 1622 | // -M and 0 just do not exist in unsigned iteration space, and we don't want |
| 1623 | // to deal with overflown values. |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1624 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1625 | if (!IndVar->isAffine()) |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1626 | return None; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1627 | |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1628 | const SCEV *A = IndVar->getStart(); |
| 1629 | const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE)); |
| 1630 | if (!B) |
| 1631 | return None; |
Max Kazantsev | e4c220e | 2017-08-01 06:49:29 +0000 | [diff] [blame] | 1632 | assert(!B->isZero() && "Recurrence with zero step?"); |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1633 | |
Max Kazantsev | 84286ce | 2017-10-31 06:19:05 +0000 | [diff] [blame] | 1634 | const SCEV *C = getBegin(); |
| 1635 | const SCEVConstant *D = dyn_cast<SCEVConstant>(getStep()); |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1636 | if (D != B) |
| 1637 | return None; |
| 1638 | |
Max Kazantsev | 9505470 | 2017-08-04 07:41:24 +0000 | [diff] [blame] | 1639 | assert(!D->getValue()->isZero() && "Recurrence with zero step?"); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1640 | unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth(); |
| 1641 | const SCEV *SIntMax = SE.getConstant(APInt::getSignedMaxValue(BitWidth)); |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1642 | |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1643 | // Substract Y from X so that it does not go through border of the IV |
| 1644 | // iteration space. Mathematically, it is equivalent to: |
| 1645 | // |
| 1646 | // ClampedSubstract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1] |
| 1647 | // |
| 1648 | // In [1], 'X - Y' is a mathematical substraction (result is not bounded to |
| 1649 | // any width of bit grid). But after we take min/max, the result is |
| 1650 | // guaranteed to be within [INT_MIN, INT_MAX]. |
| 1651 | // |
| 1652 | // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min |
| 1653 | // values, depending on type of latch condition that defines IV iteration |
| 1654 | // space. |
| 1655 | auto ClampedSubstract = [&](const SCEV *X, const SCEV *Y) { |
| 1656 | assert(SE.isKnownNonNegative(X) && |
| 1657 | "We can only substract from values in [0; SINT_MAX]!"); |
| 1658 | if (IsLatchSigned) { |
| 1659 | // X is a number from signed range, Y is interpreted as signed. |
| 1660 | // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only |
| 1661 | // thing we should care about is that we didn't cross SINT_MAX. |
| 1662 | // So, if Y is positive, we substract Y safely. |
| 1663 | // Rule 1: Y > 0 ---> Y. |
| 1664 | // If 0 <= -Y <= (SINT_MAX - X), we substract Y safely. |
| 1665 | // Rule 2: Y >=s (X - SINT_MAX) ---> Y. |
| 1666 | // If 0 <= (SINT_MAX - X) < -Y, we can only substract (X - SINT_MAX). |
| 1667 | // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX). |
| 1668 | // It gives us smax(Y, X - SINT_MAX) to substract in all cases. |
| 1669 | const SCEV *XMinusSIntMax = SE.getMinusSCEV(X, SIntMax); |
Max Kazantsev | 716e647 | 2017-11-23 06:14:39 +0000 | [diff] [blame] | 1670 | return SE.getMinusSCEV(X, SE.getSMaxExpr(Y, XMinusSIntMax), |
| 1671 | SCEV::FlagNSW); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1672 | } else |
| 1673 | // X is a number from unsigned range, Y is interpreted as signed. |
| 1674 | // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only |
| 1675 | // thing we should care about is that we didn't cross zero. |
| 1676 | // So, if Y is negative, we substract Y safely. |
| 1677 | // Rule 1: Y <s 0 ---> Y. |
| 1678 | // If 0 <= Y <= X, we substract Y safely. |
| 1679 | // Rule 2: Y <=s X ---> Y. |
| 1680 | // If 0 <= X < Y, we should stop at 0 and can only substract X. |
| 1681 | // Rule 3: Y >s X ---> X. |
| 1682 | // It gives us smin(X, Y) to substract in all cases. |
Max Kazantsev | 716e647 | 2017-11-23 06:14:39 +0000 | [diff] [blame] | 1683 | return SE.getMinusSCEV(X, SE.getSMinExpr(X, Y), SCEV::FlagNUW); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1684 | }; |
Sanjoy Das | 95c476d | 2015-02-21 22:20:22 +0000 | [diff] [blame] | 1685 | const SCEV *M = SE.getMinusSCEV(C, A); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1686 | const SCEV *Zero = SE.getZero(M->getType()); |
| 1687 | const SCEV *Begin = ClampedSubstract(Zero, M); |
| 1688 | const SCEV *L = nullptr; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1689 | |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 1690 | // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L". |
| 1691 | // We can potentially do much better here. |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1692 | if (const SCEV *EndLimit = getEnd()) |
| 1693 | L = EndLimit; |
Max Kazantsev | 390fc57 | 2017-10-30 09:35:16 +0000 | [diff] [blame] | 1694 | else { |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 1695 | assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!"); |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1696 | L = SIntMax; |
Sanjoy Das | e2cde6f | 2015-03-17 00:42:13 +0000 | [diff] [blame] | 1697 | } |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1698 | const SCEV *End = ClampedSubstract(L, M); |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1699 | return InductiveRangeCheck::Range(Begin, End); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1700 | } |
| 1701 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1702 | static Optional<InductiveRangeCheck::Range> |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 1703 | IntersectSignedRange(ScalarEvolution &SE, |
| 1704 | const Optional<InductiveRangeCheck::Range> &R1, |
| 1705 | const InductiveRangeCheck::Range &R2) { |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1706 | if (R2.isEmpty(SE, /* IsSigned */ true)) |
Max Kazantsev | 25d8655 | 2017-10-11 06:53:07 +0000 | [diff] [blame] | 1707 | return None; |
Max Kazantsev | 3612d4b | 2017-10-19 05:33:28 +0000 | [diff] [blame] | 1708 | if (!R1.hasValue()) |
| 1709 | return R2; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1710 | auto &R1Value = R1.getValue(); |
Max Kazantsev | 3612d4b | 2017-10-19 05:33:28 +0000 | [diff] [blame] | 1711 | // We never return empty ranges from this function, and R1 is supposed to be |
| 1712 | // a result of intersection. Thus, R1 is never empty. |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1713 | assert(!R1Value.isEmpty(SE, /* IsSigned */ true) && |
| 1714 | "We should never have empty R1!"); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1715 | |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1716 | // TODO: we could widen the smaller range and have this work; but for now we |
| 1717 | // bail out to keep things simple. |
Sanjoy Das | 351db05 | 2015-01-22 09:32:02 +0000 | [diff] [blame] | 1718 | if (R1Value.getType() != R2.getType()) |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1719 | return None; |
| 1720 | |
Sanjoy Das | 7fc60da | 2015-02-21 22:07:32 +0000 | [diff] [blame] | 1721 | const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin()); |
| 1722 | const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd()); |
| 1723 | |
Max Kazantsev | 25d8655 | 2017-10-11 06:53:07 +0000 | [diff] [blame] | 1724 | // If the resulting range is empty, just return None. |
| 1725 | auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1726 | if (Ret.isEmpty(SE, /* IsSigned */ true)) |
Max Kazantsev | 25d8655 | 2017-10-11 06:53:07 +0000 | [diff] [blame] | 1727 | return None; |
| 1728 | return Ret; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1729 | } |
| 1730 | |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 1731 | static Optional<InductiveRangeCheck::Range> |
| 1732 | IntersectUnsignedRange(ScalarEvolution &SE, |
| 1733 | const Optional<InductiveRangeCheck::Range> &R1, |
| 1734 | const InductiveRangeCheck::Range &R2) { |
| 1735 | if (R2.isEmpty(SE, /* IsSigned */ false)) |
| 1736 | return None; |
| 1737 | if (!R1.hasValue()) |
| 1738 | return R2; |
| 1739 | auto &R1Value = R1.getValue(); |
| 1740 | // We never return empty ranges from this function, and R1 is supposed to be |
| 1741 | // a result of intersection. Thus, R1 is never empty. |
| 1742 | assert(!R1Value.isEmpty(SE, /* IsSigned */ false) && |
| 1743 | "We should never have empty R1!"); |
| 1744 | |
| 1745 | // TODO: we could widen the smaller range and have this work; but for now we |
| 1746 | // bail out to keep things simple. |
| 1747 | if (R1Value.getType() != R2.getType()) |
| 1748 | return None; |
| 1749 | |
| 1750 | const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin()); |
| 1751 | const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd()); |
| 1752 | |
| 1753 | // If the resulting range is empty, just return None. |
| 1754 | auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd); |
| 1755 | if (Ret.isEmpty(SE, /* IsSigned */ false)) |
| 1756 | return None; |
| 1757 | return Ret; |
| 1758 | } |
| 1759 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1760 | bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) { |
Andrew Kaylor | 50271f7 | 2016-05-03 22:32:30 +0000 | [diff] [blame] | 1761 | if (skipLoop(L)) |
| 1762 | return false; |
| 1763 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1764 | if (L->getBlocks().size() >= LoopSizeCutoff) { |
| 1765 | DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";); |
| 1766 | return false; |
| 1767 | } |
| 1768 | |
| 1769 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 1770 | if (!Preheader) { |
| 1771 | DEBUG(dbgs() << "irce: loop has no preheader, leaving\n"); |
| 1772 | return false; |
| 1773 | } |
| 1774 | |
| 1775 | LLVMContext &Context = Preheader->getContext(); |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1776 | SmallVector<InductiveRangeCheck, 16> RangeChecks; |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1777 | ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Cong Hou | ab23bfb | 2015-07-15 22:48:29 +0000 | [diff] [blame] | 1778 | BranchProbabilityInfo &BPI = |
| 1779 | getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1780 | |
| 1781 | for (auto BBI : L->getBlocks()) |
| 1782 | if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator())) |
Sanjoy Das | a099268 | 2016-05-26 00:09:02 +0000 | [diff] [blame] | 1783 | InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI, |
| 1784 | RangeChecks); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1785 | |
| 1786 | if (RangeChecks.empty()) |
| 1787 | return false; |
| 1788 | |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1789 | auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) { |
| 1790 | OS << "irce: looking at loop "; L->print(OS); |
| 1791 | OS << "irce: loop has " << RangeChecks.size() |
| 1792 | << " inductive range checks: \n"; |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1793 | for (InductiveRangeCheck &IRC : RangeChecks) |
| 1794 | IRC.print(OS); |
Sanjoy Das | 9c1bfae | 2015-03-17 01:40:22 +0000 | [diff] [blame] | 1795 | }; |
| 1796 | |
| 1797 | DEBUG(PrintRecognizedRangeChecks(dbgs())); |
| 1798 | |
| 1799 | if (PrintRangeChecks) |
| 1800 | PrintRecognizedRangeChecks(errs()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1801 | |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1802 | const char *FailureReason = nullptr; |
| 1803 | Optional<LoopStructure> MaybeLoopStructure = |
Sanjoy Das | e91665d | 2015-02-26 08:56:04 +0000 | [diff] [blame] | 1804 | LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1805 | if (!MaybeLoopStructure.hasValue()) { |
| 1806 | DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason |
| 1807 | << "\n";); |
| 1808 | return false; |
| 1809 | } |
| 1810 | LoopStructure LS = MaybeLoopStructure.getValue(); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1811 | const SCEVAddRecExpr *IndVar = |
Serguei Katkov | 675e304 | 2017-09-21 04:50:41 +0000 | [diff] [blame] | 1812 | cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep))); |
Sanjoy Das | e75ed92 | 2015-02-26 08:19:31 +0000 | [diff] [blame] | 1813 | |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1814 | Optional<InductiveRangeCheck::Range> SafeIterRange; |
| 1815 | Instruction *ExprInsertPt = Preheader->getTerminator(); |
| 1816 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1817 | SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate; |
Max Kazantsev | 9ac7021 | 2017-10-25 06:47:39 +0000 | [diff] [blame] | 1818 | // Basing on the type of latch predicate, we interpret the IV iteration range |
| 1819 | // as signed or unsigned range. We use different min/max functions (signed or |
| 1820 | // unsigned) when intersecting this range with safe iteration ranges implied |
| 1821 | // by range checks. |
| 1822 | auto IntersectRange = |
| 1823 | LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange; |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1824 | |
| 1825 | IRBuilder<> B(ExprInsertPt); |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1826 | for (InductiveRangeCheck &IRC : RangeChecks) { |
Max Kazantsev | 2684678 | 2017-11-20 06:07:57 +0000 | [diff] [blame] | 1827 | auto Result = IRC.computeSafeIterationSpace(SE, IndVar, |
| 1828 | LS.IsSignedPredicate); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1829 | if (Result.hasValue()) { |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1830 | auto MaybeSafeIterRange = |
Sanjoy Das | 5977673 | 2016-05-21 02:31:51 +0000 | [diff] [blame] | 1831 | IntersectRange(SE, SafeIterRange, Result.getValue()); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1832 | if (MaybeSafeIterRange.hasValue()) { |
Max Kazantsev | 4332a94 | 2017-10-25 06:10:02 +0000 | [diff] [blame] | 1833 | assert( |
| 1834 | !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) && |
| 1835 | "We should never return empty ranges!"); |
Sanjoy Das | d1fb13c | 2015-01-22 08:29:18 +0000 | [diff] [blame] | 1836 | RangeChecksToEliminate.push_back(IRC); |
| 1837 | SafeIterRange = MaybeSafeIterRange.getValue(); |
| 1838 | } |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1839 | } |
| 1840 | } |
| 1841 | |
| 1842 | if (!SafeIterRange.hasValue()) |
| 1843 | return false; |
| 1844 | |
Sanjoy Das | f45e03e | 2016-08-02 19:31:54 +0000 | [diff] [blame] | 1845 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Sanjoy Das | 2143447 | 2016-08-14 01:04:46 +0000 | [diff] [blame] | 1846 | LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM, |
| 1847 | LS, SE, DT, SafeIterRange.getValue()); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1848 | bool Changed = LC.run(); |
| 1849 | |
| 1850 | if (Changed) { |
| 1851 | auto PrintConstrainedLoopInfo = [L]() { |
| 1852 | dbgs() << "irce: in function "; |
| 1853 | dbgs() << L->getHeader()->getParent()->getName() << ": "; |
| 1854 | dbgs() << "constrained "; |
| 1855 | L->print(dbgs()); |
| 1856 | }; |
| 1857 | |
| 1858 | DEBUG(PrintConstrainedLoopInfo()); |
| 1859 | |
| 1860 | if (PrintChangedLoops) |
| 1861 | PrintConstrainedLoopInfo(); |
| 1862 | |
| 1863 | // Optimize away the now-redundant range checks. |
| 1864 | |
Sanjoy Das | c5b1169 | 2016-05-21 02:52:13 +0000 | [diff] [blame] | 1865 | for (InductiveRangeCheck &IRC : RangeChecksToEliminate) { |
| 1866 | ConstantInt *FoldedRangeCheck = IRC.getPassingDirection() |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1867 | ? ConstantInt::getTrue(Context) |
| 1868 | : ConstantInt::getFalse(Context); |
Sanjoy Das | aa83c47 | 2016-05-23 22:16:45 +0000 | [diff] [blame] | 1869 | IRC.getCheckUse()->set(FoldedRangeCheck); |
Sanjoy Das | a1837a3 | 2015-01-16 01:03:22 +0000 | [diff] [blame] | 1870 | } |
| 1871 | } |
| 1872 | |
| 1873 | return Changed; |
| 1874 | } |
| 1875 | |
| 1876 | Pass *llvm::createInductiveRangeCheckEliminationPass() { |
| 1877 | return new InductiveRangeCheckElimination; |
| 1878 | } |