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