Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1 | //===-- LoopReroll.cpp - Loop rerolling pass ------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass implements a simple loop reroller. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 14 | #include "llvm/Transforms/Scalar.h" |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/MapVector.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/STLExtras.h" |
Elena Demikhovsky | 9914dbd | 2016-02-22 09:38:28 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/BitVector.h" |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/AliasAnalysis.h" |
| 21 | #include "llvm/Analysis/AliasSetTracker.h" |
| 22 | #include "llvm/Analysis/LoopPass.h" |
| 23 | #include "llvm/Analysis/ScalarEvolution.h" |
| 24 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
| 25 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ValueTracking.h" |
| 28 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Dominators.h" |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 30 | #include "llvm/IR/IntrinsicInst.h" |
| 31 | #include "llvm/Support/CommandLine.h" |
| 32 | #include "llvm/Support/Debug.h" |
| 33 | #include "llvm/Support/raw_ostream.h" |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 34 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 35 | #include "llvm/Transforms/Utils/Local.h" |
| 36 | #include "llvm/Transforms/Utils/LoopUtils.h" |
| 37 | |
| 38 | using namespace llvm; |
| 39 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 40 | #define DEBUG_TYPE "loop-reroll" |
| 41 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 42 | STATISTIC(NumRerolledLoops, "Number of rerolled loops"); |
| 43 | |
| 44 | static cl::opt<unsigned> |
| 45 | MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden, |
| 46 | cl::desc("The maximum increment for loop rerolling")); |
| 47 | |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 48 | static cl::opt<unsigned> |
| 49 | NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400), |
| 50 | cl::Hidden, |
| 51 | cl::desc("The maximum number of failures to tolerate" |
| 52 | " during fuzzy matching. (default: 400)")); |
| 53 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 54 | // This loop re-rolling transformation aims to transform loops like this: |
| 55 | // |
| 56 | // int foo(int a); |
| 57 | // void bar(int *x) { |
| 58 | // for (int i = 0; i < 500; i += 3) { |
| 59 | // foo(i); |
| 60 | // foo(i+1); |
| 61 | // foo(i+2); |
| 62 | // } |
| 63 | // } |
| 64 | // |
| 65 | // into a loop like this: |
| 66 | // |
| 67 | // void bar(int *x) { |
| 68 | // for (int i = 0; i < 500; ++i) |
| 69 | // foo(i); |
| 70 | // } |
| 71 | // |
| 72 | // It does this by looking for loops that, besides the latch code, are composed |
| 73 | // of isomorphic DAGs of instructions, with each DAG rooted at some increment |
| 74 | // to the induction variable, and where each DAG is isomorphic to the DAG |
| 75 | // rooted at the induction variable (excepting the sub-DAGs which root the |
| 76 | // other induction-variable increments). In other words, we're looking for loop |
| 77 | // bodies of the form: |
| 78 | // |
| 79 | // %iv = phi [ (preheader, ...), (body, %iv.next) ] |
| 80 | // f(%iv) |
| 81 | // %iv.1 = add %iv, 1 <-- a root increment |
| 82 | // f(%iv.1) |
| 83 | // %iv.2 = add %iv, 2 <-- a root increment |
| 84 | // f(%iv.2) |
| 85 | // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment |
| 86 | // f(%iv.scale_m_1) |
| 87 | // ... |
| 88 | // %iv.next = add %iv, scale |
| 89 | // %cmp = icmp(%iv, ...) |
| 90 | // br %cmp, header, exit |
| 91 | // |
| 92 | // where each f(i) is a set of instructions that, collectively, are a function |
| 93 | // only of i (and other loop-invariant values). |
| 94 | // |
| 95 | // As a special case, we can also reroll loops like this: |
| 96 | // |
| 97 | // int foo(int); |
| 98 | // void bar(int *x) { |
| 99 | // for (int i = 0; i < 500; ++i) { |
| 100 | // x[3*i] = foo(0); |
| 101 | // x[3*i+1] = foo(0); |
| 102 | // x[3*i+2] = foo(0); |
| 103 | // } |
| 104 | // } |
| 105 | // |
| 106 | // into this: |
| 107 | // |
| 108 | // void bar(int *x) { |
| 109 | // for (int i = 0; i < 1500; ++i) |
| 110 | // x[i] = foo(0); |
| 111 | // } |
| 112 | // |
| 113 | // in which case, we're looking for inputs like this: |
| 114 | // |
| 115 | // %iv = phi [ (preheader, ...), (body, %iv.next) ] |
| 116 | // %scaled.iv = mul %iv, scale |
| 117 | // f(%scaled.iv) |
| 118 | // %scaled.iv.1 = add %scaled.iv, 1 |
| 119 | // f(%scaled.iv.1) |
| 120 | // %scaled.iv.2 = add %scaled.iv, 2 |
| 121 | // f(%scaled.iv.2) |
| 122 | // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1 |
| 123 | // f(%scaled.iv.scale_m_1) |
| 124 | // ... |
| 125 | // %iv.next = add %iv, 1 |
| 126 | // %cmp = icmp(%iv, ...) |
| 127 | // br %cmp, header, exit |
| 128 | |
| 129 | namespace { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 130 | enum IterationLimits { |
Elena Demikhovsky | 9914dbd | 2016-02-22 09:38:28 +0000 | [diff] [blame] | 131 | /// The maximum number of iterations that we'll try and reroll. |
| 132 | IL_MaxRerollIterations = 32, |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 133 | /// The bitvector index used by loop induction variables and other |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 134 | /// instructions that belong to all iterations. |
| 135 | IL_All, |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 136 | IL_End |
| 137 | }; |
| 138 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 139 | class LoopReroll : public LoopPass { |
| 140 | public: |
| 141 | static char ID; // Pass ID, replacement for typeid |
| 142 | LoopReroll() : LoopPass(ID) { |
| 143 | initializeLoopRerollPass(*PassRegistry::getPassRegistry()); |
| 144 | } |
| 145 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 146 | bool runOnLoop(Loop *L, LPPassManager &LPM) override; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 147 | |
Craig Topper | 3e4c697 | 2014-03-05 09:10:37 +0000 | [diff] [blame] | 148 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 149 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 150 | getLoopAnalysisUsage(AU); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 151 | } |
| 152 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 153 | protected: |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 154 | AliasAnalysis *AA; |
| 155 | LoopInfo *LI; |
| 156 | ScalarEvolution *SE; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 157 | TargetLibraryInfo *TLI; |
| 158 | DominatorTree *DT; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 159 | bool PreserveLCSSA; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 160 | |
| 161 | typedef SmallVector<Instruction *, 16> SmallInstructionVector; |
| 162 | typedef SmallSet<Instruction *, 16> SmallInstructionSet; |
| 163 | |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 164 | // Map between induction variable and its increment |
| 165 | DenseMap<Instruction *, int64_t> IVToIncMap; |
| 166 | |
| 167 | // A chain of isomorphic instructions, identified by a single-use PHI |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 168 | // representing a reduction. Only the last value may be used outside the |
| 169 | // loop. |
| 170 | struct SimpleLoopReduction { |
| 171 | SimpleLoopReduction(Instruction *P, Loop *L) |
| 172 | : Valid(false), Instructions(1, P) { |
| 173 | assert(isa<PHINode>(P) && "First reduction instruction must be a PHI"); |
| 174 | add(L); |
| 175 | } |
| 176 | |
| 177 | bool valid() const { |
| 178 | return Valid; |
| 179 | } |
| 180 | |
| 181 | Instruction *getPHI() const { |
| 182 | assert(Valid && "Using invalid reduction"); |
| 183 | return Instructions.front(); |
| 184 | } |
| 185 | |
| 186 | Instruction *getReducedValue() const { |
| 187 | assert(Valid && "Using invalid reduction"); |
| 188 | return Instructions.back(); |
| 189 | } |
| 190 | |
| 191 | Instruction *get(size_t i) const { |
| 192 | assert(Valid && "Using invalid reduction"); |
| 193 | return Instructions[i+1]; |
| 194 | } |
| 195 | |
| 196 | Instruction *operator [] (size_t i) const { return get(i); } |
| 197 | |
| 198 | // The size, ignoring the initial PHI. |
| 199 | size_t size() const { |
| 200 | assert(Valid && "Using invalid reduction"); |
| 201 | return Instructions.size()-1; |
| 202 | } |
| 203 | |
| 204 | typedef SmallInstructionVector::iterator iterator; |
| 205 | typedef SmallInstructionVector::const_iterator const_iterator; |
| 206 | |
| 207 | iterator begin() { |
| 208 | assert(Valid && "Using invalid reduction"); |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 209 | return std::next(Instructions.begin()); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 210 | } |
| 211 | |
| 212 | const_iterator begin() const { |
| 213 | assert(Valid && "Using invalid reduction"); |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 214 | return std::next(Instructions.begin()); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 215 | } |
| 216 | |
| 217 | iterator end() { return Instructions.end(); } |
| 218 | const_iterator end() const { return Instructions.end(); } |
| 219 | |
| 220 | protected: |
| 221 | bool Valid; |
| 222 | SmallInstructionVector Instructions; |
| 223 | |
| 224 | void add(Loop *L); |
| 225 | }; |
| 226 | |
| 227 | // The set of all reductions, and state tracking of possible reductions |
| 228 | // during loop instruction processing. |
| 229 | struct ReductionTracker { |
| 230 | typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector; |
| 231 | |
| 232 | // Add a new possible reduction. |
NAKAMURA Takumi | d0e13af | 2014-10-28 11:54:52 +0000 | [diff] [blame] | 233 | void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); } |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 234 | |
| 235 | // Setup to track possible reductions corresponding to the provided |
| 236 | // rerolling scale. Only reductions with a number of non-PHI instructions |
| 237 | // that is divisible by the scale are considered. Three instructions sets |
| 238 | // are filled in: |
| 239 | // - A set of all possible instructions in eligible reductions. |
| 240 | // - A set of all PHIs in eligible reductions |
NAKAMURA Takumi | d0e13af | 2014-10-28 11:54:52 +0000 | [diff] [blame] | 241 | // - A set of all reduced values (last instructions) in eligible |
| 242 | // reductions. |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 243 | void restrictToScale(uint64_t Scale, |
| 244 | SmallInstructionSet &PossibleRedSet, |
| 245 | SmallInstructionSet &PossibleRedPHISet, |
| 246 | SmallInstructionSet &PossibleRedLastSet) { |
| 247 | PossibleRedIdx.clear(); |
| 248 | PossibleRedIter.clear(); |
| 249 | Reds.clear(); |
| 250 | |
| 251 | for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i) |
| 252 | if (PossibleReds[i].size() % Scale == 0) { |
| 253 | PossibleRedLastSet.insert(PossibleReds[i].getReducedValue()); |
| 254 | PossibleRedPHISet.insert(PossibleReds[i].getPHI()); |
NAKAMURA Takumi | 335a7bc | 2014-10-28 11:53:30 +0000 | [diff] [blame] | 255 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 256 | PossibleRedSet.insert(PossibleReds[i].getPHI()); |
| 257 | PossibleRedIdx[PossibleReds[i].getPHI()] = i; |
NAKAMURA Takumi | 5af50a5 | 2014-10-28 11:54:05 +0000 | [diff] [blame] | 258 | for (Instruction *J : PossibleReds[i]) { |
| 259 | PossibleRedSet.insert(J); |
| 260 | PossibleRedIdx[J] = i; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 261 | } |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // The functions below are used while processing the loop instructions. |
| 266 | |
| 267 | // Are the two instructions both from reductions, and furthermore, from |
| 268 | // the same reduction? |
| 269 | bool isPairInSame(Instruction *J1, Instruction *J2) { |
| 270 | DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1); |
| 271 | if (J1I != PossibleRedIdx.end()) { |
| 272 | DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2); |
| 273 | if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second) |
| 274 | return true; |
| 275 | } |
| 276 | |
| 277 | return false; |
| 278 | } |
| 279 | |
| 280 | // The two provided instructions, the first from the base iteration, and |
| 281 | // the second from iteration i, form a matched pair. If these are part of |
| 282 | // a reduction, record that fact. |
| 283 | void recordPair(Instruction *J1, Instruction *J2, unsigned i) { |
| 284 | if (PossibleRedIdx.count(J1)) { |
| 285 | assert(PossibleRedIdx.count(J2) && |
| 286 | "Recording reduction vs. non-reduction instruction?"); |
| 287 | |
| 288 | PossibleRedIter[J1] = 0; |
| 289 | PossibleRedIter[J2] = i; |
| 290 | |
| 291 | int Idx = PossibleRedIdx[J1]; |
| 292 | assert(Idx == PossibleRedIdx[J2] && |
| 293 | "Recording pair from different reductions?"); |
Hal Finkel | 67107ea | 2013-11-17 01:21:54 +0000 | [diff] [blame] | 294 | Reds.insert(Idx); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 295 | } |
| 296 | } |
| 297 | |
| 298 | // The functions below can be called after we've finished processing all |
| 299 | // instructions in the loop, and we know which reductions were selected. |
| 300 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 301 | bool validateSelected(); |
| 302 | void replaceSelected(); |
| 303 | |
| 304 | protected: |
| 305 | // The vector of all possible reductions (for any scale). |
| 306 | SmallReductionVector PossibleReds; |
| 307 | |
| 308 | DenseMap<Instruction *, int> PossibleRedIdx; |
| 309 | DenseMap<Instruction *, int> PossibleRedIter; |
| 310 | DenseSet<int> Reds; |
| 311 | }; |
| 312 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 313 | // A DAGRootSet models an induction variable being used in a rerollable |
| 314 | // loop. For example, |
| 315 | // |
| 316 | // x[i*3+0] = y1 |
| 317 | // x[i*3+1] = y2 |
| 318 | // x[i*3+2] = y3 |
| 319 | // |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 320 | // Base instruction -> i*3 |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 321 | // +---+----+ |
| 322 | // / | \ |
| 323 | // ST[y1] +1 +2 <-- Roots |
| 324 | // | | |
| 325 | // ST[y2] ST[y3] |
| 326 | // |
| 327 | // There may be multiple DAGRoots, for example: |
| 328 | // |
| 329 | // x[i*2+0] = ... (1) |
| 330 | // x[i*2+1] = ... (1) |
| 331 | // x[i*2+4] = ... (2) |
| 332 | // x[i*2+5] = ... (2) |
| 333 | // x[(i+1234)*2+5678] = ... (3) |
| 334 | // x[(i+1234)*2+5679] = ... (3) |
| 335 | // |
| 336 | // The loop will be rerolled by adding a new loop induction variable, |
| 337 | // one for the Base instruction in each DAGRootSet. |
| 338 | // |
| 339 | struct DAGRootSet { |
| 340 | Instruction *BaseInst; |
| 341 | SmallInstructionVector Roots; |
| 342 | // The instructions between IV and BaseInst (but not including BaseInst). |
| 343 | SmallInstructionSet SubsumedInsts; |
| 344 | }; |
| 345 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 346 | // The set of all DAG roots, and state tracking of all roots |
| 347 | // for a particular induction variable. |
| 348 | struct DAGRootTracker { |
| 349 | DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV, |
| 350 | ScalarEvolution *SE, AliasAnalysis *AA, |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 351 | TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI, |
| 352 | bool PreserveLCSSA, |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 353 | DenseMap<Instruction *, int64_t> &IncrMap) |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 354 | : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI), |
| 355 | PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap) {} |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 356 | |
| 357 | /// Stage 1: Find all the DAG roots for the induction variable. |
| 358 | bool findRoots(); |
| 359 | /// Stage 2: Validate if the found roots are valid. |
| 360 | bool validate(ReductionTracker &Reductions); |
| 361 | /// Stage 3: Assuming validate() returned true, perform the |
| 362 | /// replacement. |
| 363 | /// @param IterCount The maximum iteration count of L. |
| 364 | void replace(const SCEV *IterCount); |
| 365 | |
| 366 | protected: |
Elena Demikhovsky | 9914dbd | 2016-02-22 09:38:28 +0000 | [diff] [blame] | 367 | typedef MapVector<Instruction*, BitVector> UsesTy; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 368 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 369 | bool findRootsRecursive(Instruction *IVU, |
| 370 | SmallInstructionSet SubsumedInsts); |
| 371 | bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts); |
| 372 | bool collectPossibleRoots(Instruction *Base, |
| 373 | std::map<int64_t,Instruction*> &Roots); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 374 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 375 | bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 376 | void collectInLoopUserSet(const SmallInstructionVector &Roots, |
| 377 | const SmallInstructionSet &Exclude, |
| 378 | const SmallInstructionSet &Final, |
| 379 | DenseSet<Instruction *> &Users); |
| 380 | void collectInLoopUserSet(Instruction *Root, |
| 381 | const SmallInstructionSet &Exclude, |
| 382 | const SmallInstructionSet &Final, |
| 383 | DenseSet<Instruction *> &Users); |
| 384 | |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 385 | UsesTy::iterator nextInstr(int Val, UsesTy &In, |
| 386 | const SmallInstructionSet &Exclude, |
| 387 | UsesTy::iterator *StartI=nullptr); |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 388 | bool isBaseInst(Instruction *I); |
| 389 | bool isRootInst(Instruction *I); |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 390 | bool instrDependsOn(Instruction *I, |
| 391 | UsesTy::iterator Start, |
| 392 | UsesTy::iterator End); |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 393 | void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 394 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 395 | LoopReroll *Parent; |
| 396 | |
| 397 | // Members of Parent, replicated here for brevity. |
| 398 | Loop *L; |
| 399 | ScalarEvolution *SE; |
| 400 | AliasAnalysis *AA; |
| 401 | TargetLibraryInfo *TLI; |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 402 | DominatorTree *DT; |
| 403 | LoopInfo *LI; |
| 404 | bool PreserveLCSSA; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 405 | |
| 406 | // The loop induction variable. |
| 407 | Instruction *IV; |
| 408 | // Loop step amount. |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 409 | int64_t Inc; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 410 | // Loop reroll count; if Inc == 1, this records the scaling applied |
| 411 | // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ; |
| 412 | // If Inc is not 1, Scale = Inc. |
| 413 | uint64_t Scale; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 414 | // The roots themselves. |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 415 | SmallVector<DAGRootSet,16> RootSets; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 416 | // All increment instructions for IV. |
| 417 | SmallInstructionVector LoopIncs; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 418 | // Map of all instructions in the loop (in order) to the iterations |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 419 | // they are used in (or specially, IL_All for instructions |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 420 | // used in the loop increment mechanism). |
| 421 | UsesTy Uses; |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 422 | // Map between induction variable and its increment |
| 423 | DenseMap<Instruction *, int64_t> &IVToIncMap; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 424 | }; |
| 425 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 426 | void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs); |
| 427 | void collectPossibleReductions(Loop *L, |
| 428 | ReductionTracker &Reductions); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 429 | bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount, |
| 430 | ReductionTracker &Reductions); |
| 431 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 432 | } |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 433 | |
| 434 | char LoopReroll::ID = 0; |
| 435 | INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 436 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 437 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 438 | INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false) |
| 439 | |
| 440 | Pass *llvm::createLoopRerollPass() { |
| 441 | return new LoopReroll; |
| 442 | } |
| 443 | |
| 444 | // Returns true if the provided instruction is used outside the given loop. |
| 445 | // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in |
| 446 | // non-loop blocks to be outside the loop. |
| 447 | static bool hasUsesOutsideLoop(Instruction *I, Loop *L) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 448 | for (User *U : I->users()) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 449 | if (!L->contains(cast<Instruction>(U))) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 450 | return true; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 451 | } |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 452 | return false; |
| 453 | } |
| 454 | |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 455 | static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE, |
| 456 | const SCEV *SCEVExpr, |
| 457 | Instruction &IV) { |
| 458 | const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr); |
| 459 | |
| 460 | // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)), |
| 461 | // Return c1. |
| 462 | if (!MulSCEV && IV.getType()->isPointerTy()) |
| 463 | if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) { |
| 464 | const PointerType *PTy = cast<PointerType>(IV.getType()); |
| 465 | Type *ElTy = PTy->getElementType(); |
| 466 | const SCEV *SizeOfExpr = |
| 467 | SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy); |
| 468 | if (IncSCEV->getValue()->getValue().isNegative()) { |
| 469 | const SCEV *NewSCEV = |
| 470 | SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr); |
| 471 | return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV)); |
| 472 | } else { |
| 473 | return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr)); |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | if (!MulSCEV) |
| 478 | return nullptr; |
| 479 | |
| 480 | // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant, |
| 481 | // Return c. |
| 482 | const SCEVConstant *CIncSCEV = nullptr; |
| 483 | for (const SCEV *Operand : MulSCEV->operands()) { |
| 484 | if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) { |
| 485 | CIncSCEV = Constant; |
| 486 | } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) { |
| 487 | Type *AllocTy; |
| 488 | if (!Unknown->isSizeOf(AllocTy)) |
| 489 | break; |
| 490 | } else { |
| 491 | return nullptr; |
| 492 | } |
| 493 | } |
| 494 | return CIncSCEV; |
| 495 | } |
| 496 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 497 | // Collect the list of loop induction variables with respect to which it might |
| 498 | // be possible to reroll the loop. |
| 499 | void LoopReroll::collectPossibleIVs(Loop *L, |
| 500 | SmallInstructionVector &PossibleIVs) { |
| 501 | BasicBlock *Header = L->getHeader(); |
| 502 | for (BasicBlock::iterator I = Header->begin(), |
| 503 | IE = Header->getFirstInsertionPt(); I != IE; ++I) { |
| 504 | if (!isa<PHINode>(I)) |
| 505 | continue; |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 506 | if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy()) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 507 | continue; |
| 508 | |
| 509 | if (const SCEVAddRecExpr *PHISCEV = |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 510 | dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) { |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 511 | if (PHISCEV->getLoop() != L) |
| 512 | continue; |
| 513 | if (!PHISCEV->isAffine()) |
| 514 | continue; |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 515 | const SCEVConstant *IncSCEV = nullptr; |
| 516 | if (I->getType()->isPointerTy()) |
| 517 | IncSCEV = |
| 518 | getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I); |
| 519 | else |
| 520 | IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE)); |
| 521 | if (IncSCEV) { |
| 522 | const APInt &AInt = IncSCEV->getValue()->getValue().abs(); |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 523 | if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc)) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 524 | continue; |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 525 | IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue(); |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 526 | DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV |
| 527 | << "\n"); |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 528 | PossibleIVs.push_back(&*I); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 529 | } |
| 530 | } |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | // Add the remainder of the reduction-variable chain to the instruction vector |
| 535 | // (the initial PHINode has already been added). If successful, the object is |
| 536 | // marked as valid. |
| 537 | void LoopReroll::SimpleLoopReduction::add(Loop *L) { |
| 538 | assert(!Valid && "Cannot add to an already-valid chain"); |
| 539 | |
| 540 | // The reduction variable must be a chain of single-use instructions |
| 541 | // (including the PHI), except for the last value (which is used by the PHI |
| 542 | // and also outside the loop). |
| 543 | Instruction *C = Instructions.front(); |
James Molloy | 4c7deb2 | 2015-02-16 17:01:52 +0000 | [diff] [blame] | 544 | if (C->user_empty()) |
| 545 | return; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 546 | |
| 547 | do { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 548 | C = cast<Instruction>(*C->user_begin()); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 549 | if (C->hasOneUse()) { |
| 550 | if (!C->isBinaryOp()) |
| 551 | return; |
| 552 | |
| 553 | if (!(isa<PHINode>(Instructions.back()) || |
| 554 | C->isSameOperationAs(Instructions.back()))) |
| 555 | return; |
| 556 | |
| 557 | Instructions.push_back(C); |
| 558 | } |
| 559 | } while (C->hasOneUse()); |
| 560 | |
| 561 | if (Instructions.size() < 2 || |
| 562 | !C->isSameOperationAs(Instructions.back()) || |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 563 | C->use_empty()) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 564 | return; |
| 565 | |
| 566 | // C is now the (potential) last instruction in the reduction chain. |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 567 | for (User *U : C->users()) { |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 568 | // The only in-loop user can be the initial PHI. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 569 | if (L->contains(cast<Instruction>(U))) |
| 570 | if (cast<Instruction>(U) != Instructions.front()) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 571 | return; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 572 | } |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 573 | |
| 574 | Instructions.push_back(C); |
| 575 | Valid = true; |
| 576 | } |
| 577 | |
| 578 | // Collect the vector of possible reduction variables. |
| 579 | void LoopReroll::collectPossibleReductions(Loop *L, |
| 580 | ReductionTracker &Reductions) { |
| 581 | BasicBlock *Header = L->getHeader(); |
| 582 | for (BasicBlock::iterator I = Header->begin(), |
| 583 | IE = Header->getFirstInsertionPt(); I != IE; ++I) { |
| 584 | if (!isa<PHINode>(I)) |
| 585 | continue; |
| 586 | if (!I->getType()->isSingleValueType()) |
| 587 | continue; |
| 588 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 589 | SimpleLoopReduction SLR(&*I, L); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 590 | if (!SLR.valid()) |
| 591 | continue; |
| 592 | |
| 593 | DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " << |
| 594 | SLR.size() << " chained instructions)\n"); |
| 595 | Reductions.addSLR(SLR); |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | // Collect the set of all users of the provided root instruction. This set of |
| 600 | // users contains not only the direct users of the root instruction, but also |
| 601 | // all users of those users, and so on. There are two exceptions: |
| 602 | // |
| 603 | // 1. Instructions in the set of excluded instructions are never added to the |
| 604 | // use set (even if they are users). This is used, for example, to exclude |
| 605 | // including root increments in the use set of the primary IV. |
| 606 | // |
| 607 | // 2. Instructions in the set of final instructions are added to the use set |
| 608 | // if they are users, but their users are not added. This is used, for |
| 609 | // example, to prevent a reduction update from forcing all later reduction |
| 610 | // updates into the use set. |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 611 | void LoopReroll::DAGRootTracker::collectInLoopUserSet( |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 612 | Instruction *Root, const SmallInstructionSet &Exclude, |
| 613 | const SmallInstructionSet &Final, |
| 614 | DenseSet<Instruction *> &Users) { |
| 615 | SmallInstructionVector Queue(1, Root); |
| 616 | while (!Queue.empty()) { |
| 617 | Instruction *I = Queue.pop_back_val(); |
| 618 | if (!Users.insert(I).second) |
| 619 | continue; |
| 620 | |
| 621 | if (!Final.count(I)) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 622 | for (Use &U : I->uses()) { |
| 623 | Instruction *User = cast<Instruction>(U.getUser()); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 624 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
| 625 | // Ignore "wrap-around" uses to PHIs of this loop's header. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 626 | if (PN->getIncomingBlock(U) == L->getHeader()) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 627 | continue; |
| 628 | } |
NAKAMURA Takumi | 335a7bc | 2014-10-28 11:53:30 +0000 | [diff] [blame] | 629 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 630 | if (L->contains(User) && !Exclude.count(User)) { |
| 631 | Queue.push_back(User); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | // We also want to collect single-user "feeder" values. |
| 636 | for (User::op_iterator OI = I->op_begin(), |
| 637 | OIE = I->op_end(); OI != OIE; ++OI) { |
| 638 | if (Instruction *Op = dyn_cast<Instruction>(*OI)) |
| 639 | if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) && |
| 640 | !Final.count(Op)) |
| 641 | Queue.push_back(Op); |
| 642 | } |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | // Collect all of the users of all of the provided root instructions (combined |
| 647 | // into a single set). |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 648 | void LoopReroll::DAGRootTracker::collectInLoopUserSet( |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 649 | const SmallInstructionVector &Roots, |
| 650 | const SmallInstructionSet &Exclude, |
| 651 | const SmallInstructionSet &Final, |
| 652 | DenseSet<Instruction *> &Users) { |
| 653 | for (SmallInstructionVector::const_iterator I = Roots.begin(), |
| 654 | IE = Roots.end(); I != IE; ++I) |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 655 | collectInLoopUserSet(*I, Exclude, Final, Users); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 656 | } |
| 657 | |
| 658 | static bool isSimpleLoadStore(Instruction *I) { |
| 659 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) |
| 660 | return LI->isSimple(); |
| 661 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) |
| 662 | return SI->isSimple(); |
| 663 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) |
| 664 | return !MI->isVolatile(); |
| 665 | return false; |
| 666 | } |
| 667 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 668 | /// Return true if IVU is a "simple" arithmetic operation. |
| 669 | /// This is used for narrowing the search space for DAGRoots; only arithmetic |
| 670 | /// and GEPs can be part of a DAGRoot. |
| 671 | static bool isSimpleArithmeticOp(User *IVU) { |
| 672 | if (Instruction *I = dyn_cast<Instruction>(IVU)) { |
| 673 | switch (I->getOpcode()) { |
| 674 | default: return false; |
| 675 | case Instruction::Add: |
| 676 | case Instruction::Sub: |
| 677 | case Instruction::Mul: |
| 678 | case Instruction::Shl: |
| 679 | case Instruction::AShr: |
| 680 | case Instruction::LShr: |
| 681 | case Instruction::GetElementPtr: |
| 682 | case Instruction::Trunc: |
| 683 | case Instruction::ZExt: |
| 684 | case Instruction::SExt: |
| 685 | return true; |
| 686 | } |
| 687 | } |
| 688 | return false; |
| 689 | } |
| 690 | |
| 691 | static bool isLoopIncrement(User *U, Instruction *IV) { |
| 692 | BinaryOperator *BO = dyn_cast<BinaryOperator>(U); |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 693 | |
| 694 | if ((BO && BO->getOpcode() != Instruction::Add) || |
| 695 | (!BO && !isa<GetElementPtrInst>(U))) |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 696 | return false; |
| 697 | |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 698 | for (auto *UU : U->users()) { |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 699 | PHINode *PN = dyn_cast<PHINode>(UU); |
| 700 | if (PN && PN == IV) |
| 701 | return true; |
| 702 | } |
| 703 | return false; |
| 704 | } |
| 705 | |
| 706 | bool LoopReroll::DAGRootTracker:: |
| 707 | collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) { |
| 708 | SmallInstructionVector BaseUsers; |
| 709 | |
| 710 | for (auto *I : Base->users()) { |
| 711 | ConstantInt *CI = nullptr; |
| 712 | |
| 713 | if (isLoopIncrement(I, IV)) { |
| 714 | LoopIncs.push_back(cast<Instruction>(I)); |
| 715 | continue; |
| 716 | } |
| 717 | |
| 718 | // The root nodes must be either GEPs, ORs or ADDs. |
| 719 | if (auto *BO = dyn_cast<BinaryOperator>(I)) { |
| 720 | if (BO->getOpcode() == Instruction::Add || |
| 721 | BO->getOpcode() == Instruction::Or) |
| 722 | CI = dyn_cast<ConstantInt>(BO->getOperand(1)); |
| 723 | } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { |
| 724 | Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1); |
| 725 | CI = dyn_cast<ConstantInt>(LastOperand); |
| 726 | } |
| 727 | |
| 728 | if (!CI) { |
| 729 | if (Instruction *II = dyn_cast<Instruction>(I)) { |
| 730 | BaseUsers.push_back(II); |
| 731 | continue; |
| 732 | } else { |
| 733 | DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n"); |
| 734 | return false; |
| 735 | } |
| 736 | } |
| 737 | |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 738 | int64_t V = std::abs(CI->getValue().getSExtValue()); |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 739 | if (Roots.find(V) != Roots.end()) |
| 740 | // No duplicates, please. |
| 741 | return false; |
| 742 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 743 | Roots[V] = cast<Instruction>(I); |
| 744 | } |
| 745 | |
| 746 | if (Roots.empty()) |
| 747 | return false; |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 748 | |
| 749 | // If we found non-loop-inc, non-root users of Base, assume they are |
| 750 | // for the zeroth root index. This is because "add %a, 0" gets optimized |
| 751 | // away. |
James Molloy | e32d806 | 2015-02-16 17:02:00 +0000 | [diff] [blame] | 752 | if (BaseUsers.size()) { |
| 753 | if (Roots.find(0) != Roots.end()) { |
| 754 | DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n"); |
| 755 | return false; |
| 756 | } |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 757 | Roots[0] = Base; |
James Molloy | e32d806 | 2015-02-16 17:02:00 +0000 | [diff] [blame] | 758 | } |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 759 | |
| 760 | // Calculate the number of users of the base, or lowest indexed, iteration. |
| 761 | unsigned NumBaseUses = BaseUsers.size(); |
| 762 | if (NumBaseUses == 0) |
| 763 | NumBaseUses = Roots.begin()->second->getNumUses(); |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 764 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 765 | // Check that every node has the same number of users. |
| 766 | for (auto &KV : Roots) { |
| 767 | if (KV.first == 0) |
| 768 | continue; |
| 769 | if (KV.second->getNumUses() != NumBaseUses) { |
| 770 | DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: " |
| 771 | << "#Base=" << NumBaseUses << ", #Root=" << |
| 772 | KV.second->getNumUses() << "\n"); |
| 773 | return false; |
| 774 | } |
| 775 | } |
| 776 | |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 777 | return true; |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 778 | } |
| 779 | |
| 780 | bool LoopReroll::DAGRootTracker:: |
| 781 | findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) { |
| 782 | // Does the user look like it could be part of a root set? |
| 783 | // All its users must be simple arithmetic ops. |
| 784 | if (I->getNumUses() > IL_MaxRerollIterations) |
| 785 | return false; |
| 786 | |
| 787 | if ((I->getOpcode() == Instruction::Mul || |
| 788 | I->getOpcode() == Instruction::PHI) && |
| 789 | I != IV && |
| 790 | findRootsBase(I, SubsumedInsts)) |
| 791 | return true; |
| 792 | |
| 793 | SubsumedInsts.insert(I); |
| 794 | |
| 795 | for (User *V : I->users()) { |
| 796 | Instruction *I = dyn_cast<Instruction>(V); |
| 797 | if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end()) |
| 798 | continue; |
| 799 | |
| 800 | if (!I || !isSimpleArithmeticOp(I) || |
| 801 | !findRootsRecursive(I, SubsumedInsts)) |
| 802 | return false; |
| 803 | } |
| 804 | return true; |
| 805 | } |
| 806 | |
| 807 | bool LoopReroll::DAGRootTracker:: |
| 808 | findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) { |
| 809 | |
| 810 | // The base instruction needs to be a multiply so |
| 811 | // that we can erase it. |
| 812 | if (IVU->getOpcode() != Instruction::Mul && |
| 813 | IVU->getOpcode() != Instruction::PHI) |
| 814 | return false; |
| 815 | |
| 816 | std::map<int64_t, Instruction*> V; |
| 817 | if (!collectPossibleRoots(IVU, V)) |
| 818 | return false; |
| 819 | |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 820 | // If we didn't get a root for index zero, then IVU must be |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 821 | // subsumed. |
| 822 | if (V.find(0) == V.end()) |
| 823 | SubsumedInsts.insert(IVU); |
| 824 | |
| 825 | // Partition the vector into monotonically increasing indexes. |
| 826 | DAGRootSet DRS; |
| 827 | DRS.BaseInst = nullptr; |
| 828 | |
| 829 | for (auto &KV : V) { |
| 830 | if (!DRS.BaseInst) { |
| 831 | DRS.BaseInst = KV.second; |
| 832 | DRS.SubsumedInsts = SubsumedInsts; |
| 833 | } else if (DRS.Roots.empty()) { |
| 834 | DRS.Roots.push_back(KV.second); |
| 835 | } else if (V.find(KV.first - 1) != V.end()) { |
| 836 | DRS.Roots.push_back(KV.second); |
| 837 | } else { |
| 838 | // Linear sequence terminated. |
| 839 | RootSets.push_back(DRS); |
| 840 | DRS.BaseInst = KV.second; |
| 841 | DRS.SubsumedInsts = SubsumedInsts; |
| 842 | DRS.Roots.clear(); |
| 843 | } |
| 844 | } |
| 845 | RootSets.push_back(DRS); |
| 846 | |
| 847 | return true; |
| 848 | } |
| 849 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 850 | bool LoopReroll::DAGRootTracker::findRoots() { |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 851 | Inc = IVToIncMap[IV]; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 852 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 853 | assert(RootSets.empty() && "Unclean state!"); |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 854 | if (std::abs(Inc) == 1) { |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 855 | for (auto *IVU : IV->users()) { |
| 856 | if (isLoopIncrement(IVU, IV)) |
| 857 | LoopIncs.push_back(cast<Instruction>(IVU)); |
| 858 | } |
| 859 | if (!findRootsRecursive(IV, SmallInstructionSet())) |
| 860 | return false; |
| 861 | LoopIncs.push_back(IV); |
| 862 | } else { |
| 863 | if (!findRootsBase(IV, SmallInstructionSet())) |
| 864 | return false; |
| 865 | } |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 866 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 867 | // Ensure all sets have the same size. |
| 868 | if (RootSets.empty()) { |
| 869 | DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n"); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 870 | return false; |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 871 | } |
| 872 | for (auto &V : RootSets) { |
| 873 | if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) { |
| 874 | DEBUG(dbgs() |
| 875 | << "LRR: Aborting because not all root sets have the same size\n"); |
| 876 | return false; |
| 877 | } |
| 878 | } |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 879 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 880 | // And ensure all loop iterations are consecutive. We rely on std::map |
| 881 | // providing ordered traversal. |
| 882 | for (auto &V : RootSets) { |
| 883 | const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst)); |
| 884 | if (!ADR) |
| 885 | return false; |
| 886 | |
| 887 | // Consider a DAGRootSet with N-1 roots (so N different values including |
| 888 | // BaseInst). |
| 889 | // Define d = Roots[0] - BaseInst, which should be the same as |
| 890 | // Roots[I] - Roots[I-1] for all I in [1..N). |
| 891 | // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the |
| 892 | // loop iteration J. |
| 893 | // |
| 894 | // Now, For the loop iterations to be consecutive: |
| 895 | // D = d * N |
| 896 | |
| 897 | unsigned N = V.Roots.size() + 1; |
| 898 | const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR); |
| 899 | const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N); |
| 900 | if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) { |
| 901 | DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n"); |
| 902 | return false; |
| 903 | } |
| 904 | } |
| 905 | Scale = RootSets[0].Roots.size() + 1; |
| 906 | |
| 907 | if (Scale > IL_MaxRerollIterations) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 908 | DEBUG(dbgs() << "LRR: Aborting - too many iterations found. " |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 909 | << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 910 | << "\n"); |
| 911 | return false; |
| 912 | } |
| 913 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 914 | DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n"); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 915 | |
| 916 | return true; |
| 917 | } |
| 918 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 919 | bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) { |
| 920 | // Populate the MapVector with all instructions in the block, in order first, |
| 921 | // so we can iterate over the contents later in perfect order. |
| 922 | for (auto &I : *L->getHeader()) { |
| 923 | Uses[&I].resize(IL_End); |
| 924 | } |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 925 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 926 | SmallInstructionSet Exclude; |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 927 | for (auto &DRS : RootSets) { |
| 928 | Exclude.insert(DRS.Roots.begin(), DRS.Roots.end()); |
| 929 | Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end()); |
| 930 | Exclude.insert(DRS.BaseInst); |
| 931 | } |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 932 | Exclude.insert(LoopIncs.begin(), LoopIncs.end()); |
| 933 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 934 | for (auto &DRS : RootSets) { |
| 935 | DenseSet<Instruction*> VBase; |
| 936 | collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase); |
| 937 | for (auto *I : VBase) { |
| 938 | Uses[I].set(0); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 939 | } |
| 940 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 941 | unsigned Idx = 1; |
| 942 | for (auto *Root : DRS.Roots) { |
| 943 | DenseSet<Instruction*> V; |
| 944 | collectInLoopUserSet(Root, Exclude, PossibleRedSet, V); |
| 945 | |
| 946 | // While we're here, check the use sets are the same size. |
| 947 | if (V.size() != VBase.size()) { |
| 948 | DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n"); |
| 949 | return false; |
| 950 | } |
| 951 | |
| 952 | for (auto *I : V) { |
| 953 | Uses[I].set(Idx); |
| 954 | } |
| 955 | ++Idx; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 956 | } |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 957 | |
| 958 | // Make sure our subsumed instructions are remembered too. |
| 959 | for (auto *I : DRS.SubsumedInsts) { |
| 960 | Uses[I].set(IL_All); |
| 961 | } |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 962 | } |
| 963 | |
| 964 | // Make sure the loop increments are also accounted for. |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 965 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 966 | Exclude.clear(); |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 967 | for (auto &DRS : RootSets) { |
| 968 | Exclude.insert(DRS.Roots.begin(), DRS.Roots.end()); |
| 969 | Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end()); |
| 970 | Exclude.insert(DRS.BaseInst); |
| 971 | } |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 972 | |
| 973 | DenseSet<Instruction*> V; |
| 974 | collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V); |
| 975 | for (auto *I : V) { |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 976 | Uses[I].set(IL_All); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 977 | } |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 978 | |
| 979 | return true; |
| 980 | |
| 981 | } |
| 982 | |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 983 | /// Get the next instruction in "In" that is a member of set Val. |
| 984 | /// Start searching from StartI, and do not return anything in Exclude. |
| 985 | /// If StartI is not given, start from In.begin(). |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 986 | LoopReroll::DAGRootTracker::UsesTy::iterator |
| 987 | LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In, |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 988 | const SmallInstructionSet &Exclude, |
| 989 | UsesTy::iterator *StartI) { |
| 990 | UsesTy::iterator I = StartI ? *StartI : In.begin(); |
| 991 | while (I != In.end() && (I->second.test(Val) == 0 || |
| 992 | Exclude.count(I->first) != 0)) |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 993 | ++I; |
| 994 | return I; |
| 995 | } |
| 996 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 997 | bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) { |
| 998 | for (auto &DRS : RootSets) { |
| 999 | if (DRS.BaseInst == I) |
| 1000 | return true; |
| 1001 | } |
| 1002 | return false; |
| 1003 | } |
| 1004 | |
| 1005 | bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) { |
| 1006 | for (auto &DRS : RootSets) { |
| 1007 | if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end()) |
| 1008 | return true; |
| 1009 | } |
| 1010 | return false; |
| 1011 | } |
| 1012 | |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1013 | /// Return true if instruction I depends on any instruction between |
| 1014 | /// Start and End. |
| 1015 | bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I, |
| 1016 | UsesTy::iterator Start, |
| 1017 | UsesTy::iterator End) { |
| 1018 | for (auto *U : I->users()) { |
| 1019 | for (auto It = Start; It != End; ++It) |
| 1020 | if (U == It->first) |
| 1021 | return true; |
| 1022 | } |
| 1023 | return false; |
| 1024 | } |
| 1025 | |
Weiming Zhao | 310770a | 2015-09-28 17:03:23 +0000 | [diff] [blame] | 1026 | static bool isIgnorableInst(const Instruction *I) { |
| 1027 | if (isa<DbgInfoIntrinsic>(I)) |
| 1028 | return true; |
| 1029 | const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I); |
| 1030 | if (!II) |
| 1031 | return false; |
| 1032 | switch (II->getIntrinsicID()) { |
| 1033 | default: |
| 1034 | return false; |
| 1035 | case llvm::Intrinsic::annotation: |
| 1036 | case Intrinsic::ptr_annotation: |
| 1037 | case Intrinsic::var_annotation: |
| 1038 | // TODO: the following intrinsics may also be whitelisted: |
| 1039 | // lifetime_start, lifetime_end, invariant_start, invariant_end |
| 1040 | return true; |
| 1041 | } |
| 1042 | return false; |
| 1043 | } |
| 1044 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1045 | bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1046 | // We now need to check for equivalence of the use graph of each root with |
| 1047 | // that of the primary induction variable (excluding the roots). Our goal |
| 1048 | // here is not to solve the full graph isomorphism problem, but rather to |
| 1049 | // catch common cases without a lot of work. As a result, we will assume |
| 1050 | // that the relative order of the instructions in each unrolled iteration |
| 1051 | // is the same (although we will not make an assumption about how the |
| 1052 | // different iterations are intermixed). Note that while the order must be |
| 1053 | // the same, the instructions may not be in the same basic block. |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1054 | |
| 1055 | // An array of just the possible reductions for this scale factor. When we |
| 1056 | // collect the set of all users of some root instructions, these reduction |
| 1057 | // instructions are treated as 'final' (their uses are not considered). |
| 1058 | // This is important because we don't want the root use set to search down |
| 1059 | // the reduction chain. |
| 1060 | SmallInstructionSet PossibleRedSet; |
| 1061 | SmallInstructionSet PossibleRedLastSet; |
| 1062 | SmallInstructionSet PossibleRedPHISet; |
| 1063 | Reductions.restrictToScale(Scale, PossibleRedSet, |
| 1064 | PossibleRedPHISet, PossibleRedLastSet); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1065 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1066 | // Populate "Uses" with where each instruction is used. |
| 1067 | if (!collectUsedInstructions(PossibleRedSet)) |
| 1068 | return false; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1069 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1070 | // Make sure we mark the reduction PHIs as used in all iterations. |
| 1071 | for (auto *I : PossibleRedPHISet) { |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1072 | Uses[I].set(IL_All); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1073 | } |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1074 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1075 | // Make sure all instructions in the loop are in one and only one |
| 1076 | // set. |
| 1077 | for (auto &KV : Uses) { |
Weiming Zhao | 310770a | 2015-09-28 17:03:23 +0000 | [diff] [blame] | 1078 | if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1079 | DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: " |
| 1080 | << *KV.first << " (#uses=" << KV.second.count() << ")\n"); |
| 1081 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1082 | } |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1083 | } |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1084 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1085 | DEBUG( |
| 1086 | for (auto &KV : Uses) { |
| 1087 | dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n"; |
| 1088 | } |
| 1089 | ); |
| 1090 | |
| 1091 | for (unsigned Iter = 1; Iter < Scale; ++Iter) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1092 | // In addition to regular aliasing information, we need to look for |
| 1093 | // instructions from later (future) iterations that have side effects |
| 1094 | // preventing us from reordering them past other instructions with side |
| 1095 | // effects. |
| 1096 | bool FutureSideEffects = false; |
| 1097 | AliasSetTracker AST(*AA); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1098 | // The map between instructions in f(%iv.(i+1)) and f(%iv). |
| 1099 | DenseMap<Value *, Value *> BaseMap; |
| 1100 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1101 | // Compare iteration Iter to the base. |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1102 | SmallInstructionSet Visited; |
| 1103 | auto BaseIt = nextInstr(0, Uses, Visited); |
| 1104 | auto RootIt = nextInstr(Iter, Uses, Visited); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1105 | auto LastRootIt = Uses.begin(); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1106 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1107 | while (BaseIt != Uses.end() && RootIt != Uses.end()) { |
| 1108 | Instruction *BaseInst = BaseIt->first; |
| 1109 | Instruction *RootInst = RootIt->first; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1110 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1111 | // Skip over the IV or root instructions; only match their users. |
| 1112 | bool Continue = false; |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1113 | if (isBaseInst(BaseInst)) { |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1114 | Visited.insert(BaseInst); |
| 1115 | BaseIt = nextInstr(0, Uses, Visited); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1116 | Continue = true; |
| 1117 | } |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1118 | if (isRootInst(RootInst)) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1119 | LastRootIt = RootIt; |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1120 | Visited.insert(RootInst); |
| 1121 | RootIt = nextInstr(Iter, Uses, Visited); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1122 | Continue = true; |
| 1123 | } |
| 1124 | if (Continue) continue; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1125 | |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1126 | if (!BaseInst->isSameOperationAs(RootInst)) { |
| 1127 | // Last chance saloon. We don't try and solve the full isomorphism |
| 1128 | // problem, but try and at least catch the case where two instructions |
| 1129 | // *of different types* are round the wrong way. We won't be able to |
| 1130 | // efficiently tell, given two ADD instructions, which way around we |
| 1131 | // should match them, but given an ADD and a SUB, we can at least infer |
| 1132 | // which one is which. |
| 1133 | // |
| 1134 | // This should allow us to deal with a greater subset of the isomorphism |
| 1135 | // problem. It does however change a linear algorithm into a quadratic |
| 1136 | // one, so limit the number of probes we do. |
| 1137 | auto TryIt = RootIt; |
| 1138 | unsigned N = NumToleratedFailedMatches; |
| 1139 | while (TryIt != Uses.end() && |
| 1140 | !BaseInst->isSameOperationAs(TryIt->first) && |
| 1141 | N--) { |
| 1142 | ++TryIt; |
| 1143 | TryIt = nextInstr(Iter, Uses, Visited, &TryIt); |
| 1144 | } |
| 1145 | |
| 1146 | if (TryIt == Uses.end() || TryIt == RootIt || |
| 1147 | instrDependsOn(TryIt->first, RootIt, TryIt)) { |
| 1148 | DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << |
| 1149 | " vs. " << *RootInst << "\n"); |
| 1150 | return false; |
| 1151 | } |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 1152 | |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1153 | RootIt = TryIt; |
| 1154 | RootInst = TryIt->first; |
| 1155 | } |
| 1156 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1157 | // All instructions between the last root and this root |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 1158 | // may belong to some other iteration. If they belong to a |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1159 | // future iteration, then they're dangerous to alias with. |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 1160 | // |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1161 | // Note that because we allow a limited amount of flexibility in the order |
| 1162 | // that we visit nodes, LastRootIt might be *before* RootIt, in which |
| 1163 | // case we've already checked this set of instructions so we shouldn't |
| 1164 | // do anything. |
| 1165 | for (; LastRootIt < RootIt; ++LastRootIt) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1166 | Instruction *I = LastRootIt->first; |
| 1167 | if (LastRootIt->second.find_first() < (int)Iter) |
| 1168 | continue; |
| 1169 | if (I->mayWriteToMemory()) |
| 1170 | AST.add(I); |
| 1171 | // Note: This is specifically guarded by a check on isa<PHINode>, |
| 1172 | // which while a valid (somewhat arbitrary) micro-optimization, is |
| 1173 | // needed because otherwise isSafeToSpeculativelyExecute returns |
| 1174 | // false on PHI nodes. |
| 1175 | if (!isa<PHINode>(I) && !isSimpleLoadStore(I) && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1176 | !isSafeToSpeculativelyExecute(I)) |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1177 | // Intervening instructions cause side effects. |
| 1178 | FutureSideEffects = true; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1179 | } |
| 1180 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1181 | // Make sure that this instruction, which is in the use set of this |
| 1182 | // root instruction, does not also belong to the base set or the set of |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1183 | // some other root instruction. |
| 1184 | if (RootIt->second.count() > 1) { |
| 1185 | DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << |
| 1186 | " vs. " << *RootInst << " (prev. case overlap)\n"); |
| 1187 | return false; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1188 | } |
| 1189 | |
| 1190 | // Make sure that we don't alias with any instruction in the alias set |
| 1191 | // tracker. If we do, then we depend on a future iteration, and we |
| 1192 | // can't reroll. |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1193 | if (RootInst->mayReadFromMemory()) |
| 1194 | for (auto &K : AST) { |
| 1195 | if (K.aliasesUnknownInst(RootInst, *AA)) { |
| 1196 | DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << |
| 1197 | " vs. " << *RootInst << " (depends on future store)\n"); |
| 1198 | return false; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1199 | } |
| 1200 | } |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1201 | |
| 1202 | // If we've past an instruction from a future iteration that may have |
| 1203 | // side effects, and this instruction might also, then we can't reorder |
| 1204 | // them, and this matching fails. As an exception, we allow the alias |
| 1205 | // set tracker to handle regular (simple) load/store dependencies. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1206 | if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) && |
| 1207 | !isSafeToSpeculativelyExecute(BaseInst)) || |
| 1208 | (!isSimpleLoadStore(RootInst) && |
| 1209 | !isSafeToSpeculativelyExecute(RootInst)))) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1210 | DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << |
| 1211 | " vs. " << *RootInst << |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1212 | " (side effects prevent reordering)\n"); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1213 | return false; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1214 | } |
| 1215 | |
| 1216 | // For instructions that are part of a reduction, if the operation is |
| 1217 | // associative, then don't bother matching the operands (because we |
| 1218 | // already know that the instructions are isomorphic, and the order |
| 1219 | // within the iteration does not matter). For non-associative reductions, |
| 1220 | // we do need to match the operands, because we need to reject |
| 1221 | // out-of-order instructions within an iteration! |
| 1222 | // For example (assume floating-point addition), we need to reject this: |
| 1223 | // x += a[i]; x += b[i]; |
| 1224 | // x += a[i+1]; x += b[i+1]; |
| 1225 | // x += b[i+2]; x += a[i+2]; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1226 | bool InReduction = Reductions.isPairInSame(BaseInst, RootInst); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1227 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1228 | if (!(InReduction && BaseInst->isAssociative())) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1229 | bool Swapped = false, SomeOpMatched = false; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1230 | for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) { |
| 1231 | Value *Op2 = RootInst->getOperand(j); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1232 | |
| 1233 | // If this is part of a reduction (and the operation is not |
| 1234 | // associatve), then we match all operands, but not those that are |
| 1235 | // part of the reduction. |
| 1236 | if (InReduction) |
| 1237 | if (Instruction *Op2I = dyn_cast<Instruction>(Op2)) |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1238 | if (Reductions.isPairInSame(RootInst, Op2I)) |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1239 | continue; |
| 1240 | |
| 1241 | DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2); |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1242 | if (BMI != BaseMap.end()) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1243 | Op2 = BMI->second; |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1244 | } else { |
| 1245 | for (auto &DRS : RootSets) { |
| 1246 | if (DRS.Roots[Iter-1] == (Instruction*) Op2) { |
| 1247 | Op2 = DRS.BaseInst; |
| 1248 | break; |
| 1249 | } |
| 1250 | } |
| 1251 | } |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1252 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1253 | if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1254 | // If we've not already decided to swap the matched operands, and |
| 1255 | // we've not already matched our first operand (note that we could |
| 1256 | // have skipped matching the first operand because it is part of a |
| 1257 | // reduction above), and the instruction is commutative, then try |
| 1258 | // the swapped match. |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1259 | if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched && |
| 1260 | BaseInst->getOperand(!j) == Op2) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1261 | Swapped = true; |
| 1262 | } else { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1263 | DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst |
| 1264 | << " vs. " << *RootInst << " (operand " << j << ")\n"); |
| 1265 | return false; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | SomeOpMatched = true; |
| 1270 | } |
| 1271 | } |
| 1272 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1273 | if ((!PossibleRedLastSet.count(BaseInst) && |
| 1274 | hasUsesOutsideLoop(BaseInst, L)) || |
| 1275 | (!PossibleRedLastSet.count(RootInst) && |
| 1276 | hasUsesOutsideLoop(RootInst, L))) { |
| 1277 | DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst << |
| 1278 | " vs. " << *RootInst << " (uses outside loop)\n"); |
| 1279 | return false; |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1280 | } |
| 1281 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1282 | Reductions.recordPair(BaseInst, RootInst, Iter); |
| 1283 | BaseMap.insert(std::make_pair(RootInst, BaseInst)); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1284 | |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1285 | LastRootIt = RootIt; |
James Molloy | e805ad9 | 2015-02-12 15:54:14 +0000 | [diff] [blame] | 1286 | Visited.insert(BaseInst); |
| 1287 | Visited.insert(RootInst); |
| 1288 | BaseIt = nextInstr(0, Uses, Visited); |
| 1289 | RootIt = nextInstr(Iter, Uses, Visited); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1290 | } |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1291 | assert (BaseIt == Uses.end() && RootIt == Uses.end() && |
| 1292 | "Mismatched set sizes!"); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1293 | } |
| 1294 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1295 | DEBUG(dbgs() << "LRR: Matched all iteration increments for " << |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1296 | *IV << "\n"); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1297 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1298 | return true; |
| 1299 | } |
| 1300 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1301 | void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) { |
| 1302 | BasicBlock *Header = L->getHeader(); |
| 1303 | // Remove instructions associated with non-base iterations. |
| 1304 | for (BasicBlock::reverse_iterator J = Header->rbegin(); |
| 1305 | J != Header->rend();) { |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1306 | unsigned I = Uses[&*J].find_first(); |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1307 | if (I > 0 && I < IL_All) { |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1308 | Instruction *D = &*J; |
| 1309 | DEBUG(dbgs() << "LRR: removing: " << *D << "\n"); |
| 1310 | D->eraseFromParent(); |
| 1311 | continue; |
| 1312 | } |
| 1313 | |
| 1314 | ++J; |
| 1315 | } |
| 1316 | |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1317 | // We need to create a new induction variable for each different BaseInst. |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 1318 | for (auto &DRS : RootSets) |
James Molloy | f147359 | 2015-02-11 09:19:47 +0000 | [diff] [blame] | 1319 | // Insert the new induction variable. |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 1320 | replaceIV(DRS.BaseInst, IV, IterCount); |
Lawrence Hu | b917cd9 | 2016-01-25 19:36:30 +0000 | [diff] [blame] | 1321 | |
| 1322 | SimplifyInstructionsInBlock(Header, TLI); |
| 1323 | DeleteDeadPHIs(Header, TLI); |
Lawrence Hu | 84b6195 | 2016-01-25 18:53:39 +0000 | [diff] [blame] | 1324 | } |
| 1325 | |
Lawrence Hu | d3d5106 | 2016-01-25 19:43:45 +0000 | [diff] [blame] | 1326 | void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst, |
| 1327 | Instruction *InstIV, |
| 1328 | const SCEV *IterCount) { |
| 1329 | BasicBlock *Header = L->getHeader(); |
| 1330 | int64_t Inc = IVToIncMap[InstIV]; |
| 1331 | bool Negative = Inc < 0; |
| 1332 | |
| 1333 | const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst)); |
| 1334 | const SCEV *Start = RealIVSCEV->getStart(); |
| 1335 | |
| 1336 | const SCEV *SizeOfExpr = nullptr; |
| 1337 | const SCEV *IncrExpr = |
| 1338 | SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1); |
| 1339 | if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) { |
| 1340 | Type *ElTy = PTy->getElementType(); |
| 1341 | SizeOfExpr = |
| 1342 | SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy); |
| 1343 | IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr); |
| 1344 | } |
| 1345 | const SCEV *NewIVSCEV = |
| 1346 | SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap); |
| 1347 | |
| 1348 | { // Limit the lifetime of SCEVExpander. |
| 1349 | const DataLayout &DL = Header->getModule()->getDataLayout(); |
| 1350 | SCEVExpander Expander(*SE, DL, "reroll"); |
| 1351 | Value *NewIV = |
| 1352 | Expander.expandCodeFor(NewIVSCEV, InstIV->getType(), &Header->front()); |
| 1353 | |
| 1354 | for (auto &KV : Uses) |
| 1355 | if (KV.second.find_first() == 0) |
| 1356 | KV.first->replaceUsesOfWith(Inst, NewIV); |
| 1357 | |
| 1358 | if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) { |
| 1359 | // FIXME: Why do we need this check? |
| 1360 | if (Uses[BI].find_first() == IL_All) { |
| 1361 | const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE); |
| 1362 | |
| 1363 | // Iteration count SCEV minus or plus 1 |
| 1364 | const SCEV *MinusPlus1SCEV = |
| 1365 | SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1); |
| 1366 | if (Inst->getType()->isPointerTy()) { |
| 1367 | assert(SizeOfExpr && "SizeOfExpr is not initialized"); |
| 1368 | MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr); |
| 1369 | } |
| 1370 | |
| 1371 | const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV); |
| 1372 | // Iteration count minus 1 |
| 1373 | Value *ICMinusPlus1 = nullptr; |
| 1374 | if (isa<SCEVConstant>(ICMinusPlus1SCEV)) { |
| 1375 | ICMinusPlus1 = |
| 1376 | Expander.expandCodeFor(ICMinusPlus1SCEV, NewIV->getType(), BI); |
| 1377 | } else { |
| 1378 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 1379 | if (!Preheader) |
| 1380 | Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA); |
| 1381 | ICMinusPlus1 = Expander.expandCodeFor( |
| 1382 | ICMinusPlus1SCEV, NewIV->getType(), Preheader->getTerminator()); |
| 1383 | } |
| 1384 | |
| 1385 | Value *Cond = |
| 1386 | new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond"); |
| 1387 | BI->setCondition(Cond); |
| 1388 | |
| 1389 | if (BI->getSuccessor(1) != Header) |
| 1390 | BI->swapSuccessors(); |
| 1391 | } |
| 1392 | } |
| 1393 | } |
| 1394 | } |
| 1395 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1396 | // Validate the selected reductions. All iterations must have an isomorphic |
| 1397 | // part of the reduction chain and, for non-associative reductions, the chain |
| 1398 | // entries must appear in order. |
| 1399 | bool LoopReroll::ReductionTracker::validateSelected() { |
| 1400 | // For a non-associative reduction, the chain entries must appear in order. |
| 1401 | for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end(); |
| 1402 | RI != RIE; ++RI) { |
| 1403 | int i = *RI; |
| 1404 | int PrevIter = 0, BaseCount = 0, Count = 0; |
NAKAMURA Takumi | 5af50a5 | 2014-10-28 11:54:05 +0000 | [diff] [blame] | 1405 | for (Instruction *J : PossibleReds[i]) { |
| 1406 | // Note that all instructions in the chain must have been found because |
| 1407 | // all instructions in the function must have been assigned to some |
| 1408 | // iteration. |
| 1409 | int Iter = PossibleRedIter[J]; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1410 | if (Iter != PrevIter && Iter != PrevIter + 1 && |
| 1411 | !PossibleReds[i].getReducedValue()->isAssociative()) { |
| 1412 | DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " << |
NAKAMURA Takumi | 5af50a5 | 2014-10-28 11:54:05 +0000 | [diff] [blame] | 1413 | J << "\n"); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1414 | return false; |
| 1415 | } |
| 1416 | |
| 1417 | if (Iter != PrevIter) { |
| 1418 | if (Count != BaseCount) { |
| 1419 | DEBUG(dbgs() << "LRR: Iteration " << PrevIter << |
| 1420 | " reduction use count " << Count << |
| 1421 | " is not equal to the base use count " << |
| 1422 | BaseCount << "\n"); |
| 1423 | return false; |
| 1424 | } |
| 1425 | |
| 1426 | Count = 0; |
| 1427 | } |
| 1428 | |
| 1429 | ++Count; |
| 1430 | if (Iter == 0) |
| 1431 | ++BaseCount; |
| 1432 | |
| 1433 | PrevIter = Iter; |
| 1434 | } |
| 1435 | } |
| 1436 | |
| 1437 | return true; |
| 1438 | } |
| 1439 | |
| 1440 | // For all selected reductions, remove all parts except those in the first |
| 1441 | // iteration (and the PHI). Replace outside uses of the reduced value with uses |
| 1442 | // of the first-iteration reduced value (in other words, reroll the selected |
| 1443 | // reductions). |
| 1444 | void LoopReroll::ReductionTracker::replaceSelected() { |
| 1445 | // Fixup reductions to refer to the last instruction associated with the |
| 1446 | // first iteration (not the last). |
| 1447 | for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end(); |
| 1448 | RI != RIE; ++RI) { |
| 1449 | int i = *RI; |
| 1450 | int j = 0; |
| 1451 | for (int e = PossibleReds[i].size(); j != e; ++j) |
| 1452 | if (PossibleRedIter[PossibleReds[i][j]] != 0) { |
| 1453 | --j; |
| 1454 | break; |
| 1455 | } |
| 1456 | |
| 1457 | // Replace users with the new end-of-chain value. |
| 1458 | SmallInstructionVector Users; |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1459 | for (User *U : PossibleReds[i].getReducedValue()->users()) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1460 | Users.push_back(cast<Instruction>(U)); |
James Molloy | 64419d4 | 2015-01-29 21:52:03 +0000 | [diff] [blame] | 1461 | } |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1462 | |
| 1463 | for (SmallInstructionVector::iterator J = Users.begin(), |
| 1464 | JE = Users.end(); J != JE; ++J) |
| 1465 | (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(), |
| 1466 | PossibleReds[i][j]); |
| 1467 | } |
| 1468 | } |
| 1469 | |
| 1470 | // Reroll the provided loop with respect to the provided induction variable. |
| 1471 | // Generally, we're looking for a loop like this: |
| 1472 | // |
| 1473 | // %iv = phi [ (preheader, ...), (body, %iv.next) ] |
| 1474 | // f(%iv) |
| 1475 | // %iv.1 = add %iv, 1 <-- a root increment |
| 1476 | // f(%iv.1) |
| 1477 | // %iv.2 = add %iv, 2 <-- a root increment |
| 1478 | // f(%iv.2) |
| 1479 | // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment |
| 1480 | // f(%iv.scale_m_1) |
| 1481 | // ... |
| 1482 | // %iv.next = add %iv, scale |
| 1483 | // %cmp = icmp(%iv, ...) |
| 1484 | // br %cmp, header, exit |
| 1485 | // |
| 1486 | // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of |
| 1487 | // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can |
| 1488 | // be intermixed with eachother. The restriction imposed by this algorithm is |
| 1489 | // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1), |
| 1490 | // etc. be the same. |
| 1491 | // |
| 1492 | // First, we collect the use set of %iv, excluding the other increment roots. |
| 1493 | // This gives us f(%iv). Then we iterate over the loop instructions (scale-1) |
| 1494 | // times, having collected the use set of f(%iv.(i+1)), during which we: |
| 1495 | // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to |
| 1496 | // the next unmatched instruction in f(%iv.(i+1)). |
| 1497 | // - Ensure that both matched instructions don't have any external users |
| 1498 | // (with the exception of last-in-chain reduction instructions). |
| 1499 | // - Track the (aliasing) write set, and other side effects, of all |
| 1500 | // instructions that belong to future iterations that come before the matched |
| 1501 | // instructions. If the matched instructions read from that write set, then |
| 1502 | // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in |
| 1503 | // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly, |
| 1504 | // if any of these future instructions had side effects (could not be |
| 1505 | // speculatively executed), and so do the matched instructions, when we |
| 1506 | // cannot reorder those side-effect-producing instructions, and rerolling |
| 1507 | // fails. |
| 1508 | // |
| 1509 | // Finally, we make sure that all loop instructions are either loop increment |
| 1510 | // roots, belong to simple latch code, parts of validated reductions, part of |
| 1511 | // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions |
| 1512 | // have been validated), then we reroll the loop. |
| 1513 | bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header, |
| 1514 | const SCEV *IterCount, |
| 1515 | ReductionTracker &Reductions) { |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 1516 | DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA, |
| 1517 | IVToIncMap); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1518 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1519 | if (!DAGRoots.findRoots()) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1520 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1521 | DEBUG(dbgs() << "LRR: Found all root induction increments for: " << |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1522 | *IV << "\n"); |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 1523 | |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1524 | if (!DAGRoots.validate(Reductions)) |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1525 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1526 | if (!Reductions.validateSelected()) |
| 1527 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1528 | // At this point, we've validated the rerolling, and we're committed to |
| 1529 | // making changes! |
| 1530 | |
| 1531 | Reductions.replaceSelected(); |
James Molloy | 5f255eb | 2015-01-29 13:48:05 +0000 | [diff] [blame] | 1532 | DAGRoots.replace(IterCount); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1533 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1534 | ++NumRerolledLoops; |
| 1535 | return true; |
| 1536 | } |
| 1537 | |
| 1538 | bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) { |
Paul Robinson | af4e64d | 2014-02-06 00:07:05 +0000 | [diff] [blame] | 1539 | if (skipOptnoneFunction(L)) |
| 1540 | return false; |
| 1541 | |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 1542 | AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); |
Chandler Carruth | 4f8f307 | 2015-01-17 14:16:18 +0000 | [diff] [blame] | 1543 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Chandler Carruth | 2f1fd16 | 2015-08-17 02:08:17 +0000 | [diff] [blame] | 1544 | SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 1545 | TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 1546 | DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
Justin Bogner | 843fb20 | 2015-12-15 19:40:57 +0000 | [diff] [blame] | 1547 | PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1548 | |
| 1549 | BasicBlock *Header = L->getHeader(); |
| 1550 | DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << |
| 1551 | "] Loop %" << Header->getName() << " (" << |
| 1552 | L->getNumBlocks() << " block(s))\n"); |
| 1553 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1554 | // For now, we'll handle only single BB loops. |
| 1555 | if (L->getNumBlocks() > 1) |
Zinovy Nis | 07ac2bd | 2016-03-22 13:50:57 +0000 | [diff] [blame^] | 1556 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1557 | |
| 1558 | if (!SE->hasLoopInvariantBackedgeTakenCount(L)) |
Zinovy Nis | 07ac2bd | 2016-03-22 13:50:57 +0000 | [diff] [blame^] | 1559 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1560 | |
| 1561 | const SCEV *LIBETC = SE->getBackedgeTakenCount(L); |
Sanjoy Das | 2aacc0e | 2015-09-23 01:59:04 +0000 | [diff] [blame] | 1562 | const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType())); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1563 | DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n"); |
| 1564 | |
| 1565 | // First, we need to find the induction variable with respect to which we can |
| 1566 | // reroll (there may be several possible options). |
| 1567 | SmallInstructionVector PossibleIVs; |
Lawrence Hu | dc8a83b | 2015-07-24 22:01:49 +0000 | [diff] [blame] | 1568 | IVToIncMap.clear(); |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1569 | collectPossibleIVs(L, PossibleIVs); |
| 1570 | |
| 1571 | if (PossibleIVs.empty()) { |
| 1572 | DEBUG(dbgs() << "LRR: No possible IVs found\n"); |
Zinovy Nis | 07ac2bd | 2016-03-22 13:50:57 +0000 | [diff] [blame^] | 1573 | return false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1574 | } |
| 1575 | |
| 1576 | ReductionTracker Reductions; |
| 1577 | collectPossibleReductions(L, Reductions); |
Zinovy Nis | 07ac2bd | 2016-03-22 13:50:57 +0000 | [diff] [blame^] | 1578 | bool Changed = false; |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1579 | |
| 1580 | // For each possible IV, collect the associated possible set of 'root' nodes |
| 1581 | // (i+1, i+2, etc.). |
| 1582 | for (SmallInstructionVector::iterator I = PossibleIVs.begin(), |
| 1583 | IE = PossibleIVs.end(); I != IE; ++I) |
| 1584 | if (reroll(*I, L, Header, IterCount, Reductions)) { |
| 1585 | Changed = true; |
| 1586 | break; |
| 1587 | } |
| 1588 | |
Zinovy Nis | 07ac2bd | 2016-03-22 13:50:57 +0000 | [diff] [blame^] | 1589 | // Trip count of L has changed so SE must be re-evaluated. |
| 1590 | if (Changed) |
| 1591 | SE->forgetLoop(L); |
| 1592 | |
Hal Finkel | bf45efd | 2013-11-16 23:59:05 +0000 | [diff] [blame] | 1593 | return Changed; |
| 1594 | } |