blob: f007d6855a4be13bf5c2245a147f90fbf3417e99 [file] [log] [blame]
Hal Finkelbf45efd2013-11-16 23:59:05 +00001//===-- 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 Finkelbf45efd2013-11-16 23:59:05 +000014#include "llvm/Transforms/Scalar.h"
James Molloy64419d42015-01-29 21:52:03 +000015#include "llvm/ADT/MapVector.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000016#include "llvm/ADT/STLExtras.h"
James Molloy64419d42015-01-29 21:52:03 +000017#include "llvm/ADT/SmallBitVector.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000018#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000020#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 Kramer799003b2015-03-23 19:32:43 +000026#include "llvm/Analysis/TargetLibraryInfo.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000027#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000029#include "llvm/IR/Dominators.h"
Hal Finkelbf45efd2013-11-16 23:59:05 +000030#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 Finkelbf45efd2013-11-16 23:59:05 +000034#include "llvm/Transforms/Utils/BasicBlockUtils.h"
35#include "llvm/Transforms/Utils/Local.h"
36#include "llvm/Transforms/Utils/LoopUtils.h"
37
38using namespace llvm;
39
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "loop-reroll"
41
Hal Finkelbf45efd2013-11-16 23:59:05 +000042STATISTIC(NumRerolledLoops, "Number of rerolled loops");
43
44static cl::opt<unsigned>
45MaxInc("max-reroll-increment", cl::init(2048), cl::Hidden,
46 cl::desc("The maximum increment for loop rerolling"));
47
James Molloye805ad92015-02-12 15:54:14 +000048static cl::opt<unsigned>
49NumToleratedFailedMatches("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 Finkelbf45efd2013-11-16 23:59:05 +000054// 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
129namespace {
James Molloy64419d42015-01-29 21:52:03 +0000130 enum IterationLimits {
131 /// The maximum number of iterations that we'll try and reroll. This
132 /// has to be less than 25 in order to fit into a SmallBitVector.
133 IL_MaxRerollIterations = 16,
134 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000135 /// instructions that belong to all iterations.
136 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000137 IL_End
138 };
139
Hal Finkelbf45efd2013-11-16 23:59:05 +0000140 class LoopReroll : public LoopPass {
141 public:
142 static char ID; // Pass ID, replacement for typeid
143 LoopReroll() : LoopPass(ID) {
144 initializeLoopRerollPass(*PassRegistry::getPassRegistry());
145 }
146
Craig Topper3e4c6972014-03-05 09:10:37 +0000147 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000148
Craig Topper3e4c6972014-03-05 09:10:37 +0000149 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth7b560d42015-09-09 17:55:00 +0000150 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000151 AU.addRequired<LoopInfoWrapperPass>();
152 AU.addPreserved<LoopInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000153 AU.addRequired<DominatorTreeWrapperPass>();
154 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000155 AU.addRequired<ScalarEvolutionWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000156 AU.addRequired<TargetLibraryInfoWrapperPass>();
Hal Finkelbf45efd2013-11-16 23:59:05 +0000157 }
158
James Molloy64419d42015-01-29 21:52:03 +0000159 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000160 AliasAnalysis *AA;
161 LoopInfo *LI;
162 ScalarEvolution *SE;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000163 TargetLibraryInfo *TLI;
164 DominatorTree *DT;
165
166 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
167 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
168
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000169 // Map between induction variable and its increment
170 DenseMap<Instruction *, int64_t> IVToIncMap;
171
172 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000173 // representing a reduction. Only the last value may be used outside the
174 // loop.
175 struct SimpleLoopReduction {
176 SimpleLoopReduction(Instruction *P, Loop *L)
177 : Valid(false), Instructions(1, P) {
178 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
179 add(L);
180 }
181
182 bool valid() const {
183 return Valid;
184 }
185
186 Instruction *getPHI() const {
187 assert(Valid && "Using invalid reduction");
188 return Instructions.front();
189 }
190
191 Instruction *getReducedValue() const {
192 assert(Valid && "Using invalid reduction");
193 return Instructions.back();
194 }
195
196 Instruction *get(size_t i) const {
197 assert(Valid && "Using invalid reduction");
198 return Instructions[i+1];
199 }
200
201 Instruction *operator [] (size_t i) const { return get(i); }
202
203 // The size, ignoring the initial PHI.
204 size_t size() const {
205 assert(Valid && "Using invalid reduction");
206 return Instructions.size()-1;
207 }
208
209 typedef SmallInstructionVector::iterator iterator;
210 typedef SmallInstructionVector::const_iterator const_iterator;
211
212 iterator begin() {
213 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000214 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000215 }
216
217 const_iterator begin() const {
218 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000219 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000220 }
221
222 iterator end() { return Instructions.end(); }
223 const_iterator end() const { return Instructions.end(); }
224
225 protected:
226 bool Valid;
227 SmallInstructionVector Instructions;
228
229 void add(Loop *L);
230 };
231
232 // The set of all reductions, and state tracking of possible reductions
233 // during loop instruction processing.
234 struct ReductionTracker {
235 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
236
237 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000238 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000239
240 // Setup to track possible reductions corresponding to the provided
241 // rerolling scale. Only reductions with a number of non-PHI instructions
242 // that is divisible by the scale are considered. Three instructions sets
243 // are filled in:
244 // - A set of all possible instructions in eligible reductions.
245 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000246 // - A set of all reduced values (last instructions) in eligible
247 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000248 void restrictToScale(uint64_t Scale,
249 SmallInstructionSet &PossibleRedSet,
250 SmallInstructionSet &PossibleRedPHISet,
251 SmallInstructionSet &PossibleRedLastSet) {
252 PossibleRedIdx.clear();
253 PossibleRedIter.clear();
254 Reds.clear();
255
256 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
257 if (PossibleReds[i].size() % Scale == 0) {
258 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
259 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000260
Hal Finkelbf45efd2013-11-16 23:59:05 +0000261 PossibleRedSet.insert(PossibleReds[i].getPHI());
262 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000263 for (Instruction *J : PossibleReds[i]) {
264 PossibleRedSet.insert(J);
265 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000266 }
267 }
268 }
269
270 // The functions below are used while processing the loop instructions.
271
272 // Are the two instructions both from reductions, and furthermore, from
273 // the same reduction?
274 bool isPairInSame(Instruction *J1, Instruction *J2) {
275 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
276 if (J1I != PossibleRedIdx.end()) {
277 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
278 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
279 return true;
280 }
281
282 return false;
283 }
284
285 // The two provided instructions, the first from the base iteration, and
286 // the second from iteration i, form a matched pair. If these are part of
287 // a reduction, record that fact.
288 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
289 if (PossibleRedIdx.count(J1)) {
290 assert(PossibleRedIdx.count(J2) &&
291 "Recording reduction vs. non-reduction instruction?");
292
293 PossibleRedIter[J1] = 0;
294 PossibleRedIter[J2] = i;
295
296 int Idx = PossibleRedIdx[J1];
297 assert(Idx == PossibleRedIdx[J2] &&
298 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000299 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000300 }
301 }
302
303 // The functions below can be called after we've finished processing all
304 // instructions in the loop, and we know which reductions were selected.
305
306 // Is the provided instruction the PHI of a reduction selected for
307 // rerolling?
308 bool isSelectedPHI(Instruction *J) {
309 if (!isa<PHINode>(J))
310 return false;
311
312 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
313 RI != RIE; ++RI) {
314 int i = *RI;
315 if (cast<Instruction>(J) == PossibleReds[i].getPHI())
316 return true;
317 }
318
319 return false;
320 }
321
322 bool validateSelected();
323 void replaceSelected();
324
325 protected:
326 // The vector of all possible reductions (for any scale).
327 SmallReductionVector PossibleReds;
328
329 DenseMap<Instruction *, int> PossibleRedIdx;
330 DenseMap<Instruction *, int> PossibleRedIter;
331 DenseSet<int> Reds;
332 };
333
James Molloyf1473592015-02-11 09:19:47 +0000334 // A DAGRootSet models an induction variable being used in a rerollable
335 // loop. For example,
336 //
337 // x[i*3+0] = y1
338 // x[i*3+1] = y2
339 // x[i*3+2] = y3
340 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000341 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000342 // +---+----+
343 // / | \
344 // ST[y1] +1 +2 <-- Roots
345 // | |
346 // ST[y2] ST[y3]
347 //
348 // There may be multiple DAGRoots, for example:
349 //
350 // x[i*2+0] = ... (1)
351 // x[i*2+1] = ... (1)
352 // x[i*2+4] = ... (2)
353 // x[i*2+5] = ... (2)
354 // x[(i+1234)*2+5678] = ... (3)
355 // x[(i+1234)*2+5679] = ... (3)
356 //
357 // The loop will be rerolled by adding a new loop induction variable,
358 // one for the Base instruction in each DAGRootSet.
359 //
360 struct DAGRootSet {
361 Instruction *BaseInst;
362 SmallInstructionVector Roots;
363 // The instructions between IV and BaseInst (but not including BaseInst).
364 SmallInstructionSet SubsumedInsts;
365 };
366
James Molloy5f255eb2015-01-29 13:48:05 +0000367 // The set of all DAG roots, and state tracking of all roots
368 // for a particular induction variable.
369 struct DAGRootTracker {
370 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
371 ScalarEvolution *SE, AliasAnalysis *AA,
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000372 TargetLibraryInfo *TLI,
373 DenseMap<Instruction *, int64_t> &IncrMap)
374 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), IV(IV),
375 IVToIncMap(IncrMap) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000376
377 /// Stage 1: Find all the DAG roots for the induction variable.
378 bool findRoots();
379 /// Stage 2: Validate if the found roots are valid.
380 bool validate(ReductionTracker &Reductions);
381 /// Stage 3: Assuming validate() returned true, perform the
382 /// replacement.
383 /// @param IterCount The maximum iteration count of L.
384 void replace(const SCEV *IterCount);
385
386 protected:
James Molloy64419d42015-01-29 21:52:03 +0000387 typedef MapVector<Instruction*, SmallBitVector> UsesTy;
388
James Molloyf1473592015-02-11 09:19:47 +0000389 bool findRootsRecursive(Instruction *IVU,
390 SmallInstructionSet SubsumedInsts);
391 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
392 bool collectPossibleRoots(Instruction *Base,
393 std::map<int64_t,Instruction*> &Roots);
James Molloy5f255eb2015-01-29 13:48:05 +0000394
James Molloy64419d42015-01-29 21:52:03 +0000395 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000396 void collectInLoopUserSet(const SmallInstructionVector &Roots,
397 const SmallInstructionSet &Exclude,
398 const SmallInstructionSet &Final,
399 DenseSet<Instruction *> &Users);
400 void collectInLoopUserSet(Instruction *Root,
401 const SmallInstructionSet &Exclude,
402 const SmallInstructionSet &Final,
403 DenseSet<Instruction *> &Users);
404
James Molloye805ad92015-02-12 15:54:14 +0000405 UsesTy::iterator nextInstr(int Val, UsesTy &In,
406 const SmallInstructionSet &Exclude,
407 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000408 bool isBaseInst(Instruction *I);
409 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000410 bool instrDependsOn(Instruction *I,
411 UsesTy::iterator Start,
412 UsesTy::iterator End);
James Molloy64419d42015-01-29 21:52:03 +0000413
James Molloy5f255eb2015-01-29 13:48:05 +0000414 LoopReroll *Parent;
415
416 // Members of Parent, replicated here for brevity.
417 Loop *L;
418 ScalarEvolution *SE;
419 AliasAnalysis *AA;
420 TargetLibraryInfo *TLI;
James Molloy5f255eb2015-01-29 13:48:05 +0000421
422 // The loop induction variable.
423 Instruction *IV;
424 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000425 int64_t Inc;
James Molloy5f255eb2015-01-29 13:48:05 +0000426 // Loop reroll count; if Inc == 1, this records the scaling applied
427 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
428 // If Inc is not 1, Scale = Inc.
429 uint64_t Scale;
James Molloy5f255eb2015-01-29 13:48:05 +0000430 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000431 SmallVector<DAGRootSet,16> RootSets;
James Molloy5f255eb2015-01-29 13:48:05 +0000432 // All increment instructions for IV.
433 SmallInstructionVector LoopIncs;
James Molloy64419d42015-01-29 21:52:03 +0000434 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000435 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000436 // used in the loop increment mechanism).
437 UsesTy Uses;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000438 // Map between induction variable and its increment
439 DenseMap<Instruction *, int64_t> &IVToIncMap;
James Molloy5f255eb2015-01-29 13:48:05 +0000440 };
441
Hal Finkelbf45efd2013-11-16 23:59:05 +0000442 void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
443 void collectPossibleReductions(Loop *L,
444 ReductionTracker &Reductions);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000445 bool reroll(Instruction *IV, Loop *L, BasicBlock *Header, const SCEV *IterCount,
446 ReductionTracker &Reductions);
447 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000448}
Hal Finkelbf45efd2013-11-16 23:59:05 +0000449
450char LoopReroll::ID = 0;
451INITIALIZE_PASS_BEGIN(LoopReroll, "loop-reroll", "Reroll loops", false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000452INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000453INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000454INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000455INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000456INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000457INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
458
459Pass *llvm::createLoopRerollPass() {
460 return new LoopReroll;
461}
462
463// Returns true if the provided instruction is used outside the given loop.
464// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
465// non-loop blocks to be outside the loop.
466static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000467 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000468 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000469 return true;
James Molloy64419d42015-01-29 21:52:03 +0000470 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000471 return false;
472}
473
474// Collect the list of loop induction variables with respect to which it might
475// be possible to reroll the loop.
476void LoopReroll::collectPossibleIVs(Loop *L,
477 SmallInstructionVector &PossibleIVs) {
478 BasicBlock *Header = L->getHeader();
479 for (BasicBlock::iterator I = Header->begin(),
480 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
481 if (!isa<PHINode>(I))
482 continue;
483 if (!I->getType()->isIntegerTy())
484 continue;
485
486 if (const SCEVAddRecExpr *PHISCEV =
487 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(I))) {
488 if (PHISCEV->getLoop() != L)
489 continue;
490 if (!PHISCEV->isAffine())
491 continue;
492 if (const SCEVConstant *IncSCEV =
493 dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE))) {
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000494 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
495 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000496 continue;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000497 IVToIncMap[I] = IncSCEV->getValue()->getSExtValue();
498 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
499 << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +0000500 PossibleIVs.push_back(I);
501 }
502 }
503 }
504}
505
506// Add the remainder of the reduction-variable chain to the instruction vector
507// (the initial PHINode has already been added). If successful, the object is
508// marked as valid.
509void LoopReroll::SimpleLoopReduction::add(Loop *L) {
510 assert(!Valid && "Cannot add to an already-valid chain");
511
512 // The reduction variable must be a chain of single-use instructions
513 // (including the PHI), except for the last value (which is used by the PHI
514 // and also outside the loop).
515 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000516 if (C->user_empty())
517 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000518
519 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000520 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000521 if (C->hasOneUse()) {
522 if (!C->isBinaryOp())
523 return;
524
525 if (!(isa<PHINode>(Instructions.back()) ||
526 C->isSameOperationAs(Instructions.back())))
527 return;
528
529 Instructions.push_back(C);
530 }
531 } while (C->hasOneUse());
532
533 if (Instructions.size() < 2 ||
534 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000535 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000536 return;
537
538 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000539 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000540 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000541 if (L->contains(cast<Instruction>(U)))
542 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000543 return;
James Molloy64419d42015-01-29 21:52:03 +0000544 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000545
546 Instructions.push_back(C);
547 Valid = true;
548}
549
550// Collect the vector of possible reduction variables.
551void LoopReroll::collectPossibleReductions(Loop *L,
552 ReductionTracker &Reductions) {
553 BasicBlock *Header = L->getHeader();
554 for (BasicBlock::iterator I = Header->begin(),
555 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
556 if (!isa<PHINode>(I))
557 continue;
558 if (!I->getType()->isSingleValueType())
559 continue;
560
561 SimpleLoopReduction SLR(I, L);
562 if (!SLR.valid())
563 continue;
564
565 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
566 SLR.size() << " chained instructions)\n");
567 Reductions.addSLR(SLR);
568 }
569}
570
571// Collect the set of all users of the provided root instruction. This set of
572// users contains not only the direct users of the root instruction, but also
573// all users of those users, and so on. There are two exceptions:
574//
575// 1. Instructions in the set of excluded instructions are never added to the
576// use set (even if they are users). This is used, for example, to exclude
577// including root increments in the use set of the primary IV.
578//
579// 2. Instructions in the set of final instructions are added to the use set
580// if they are users, but their users are not added. This is used, for
581// example, to prevent a reduction update from forcing all later reduction
582// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000583void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000584 Instruction *Root, const SmallInstructionSet &Exclude,
585 const SmallInstructionSet &Final,
586 DenseSet<Instruction *> &Users) {
587 SmallInstructionVector Queue(1, Root);
588 while (!Queue.empty()) {
589 Instruction *I = Queue.pop_back_val();
590 if (!Users.insert(I).second)
591 continue;
592
593 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000594 for (Use &U : I->uses()) {
595 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000596 if (PHINode *PN = dyn_cast<PHINode>(User)) {
597 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000598 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000599 continue;
600 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000601
Hal Finkelbf45efd2013-11-16 23:59:05 +0000602 if (L->contains(User) && !Exclude.count(User)) {
603 Queue.push_back(User);
604 }
605 }
606
607 // We also want to collect single-user "feeder" values.
608 for (User::op_iterator OI = I->op_begin(),
609 OIE = I->op_end(); OI != OIE; ++OI) {
610 if (Instruction *Op = dyn_cast<Instruction>(*OI))
611 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
612 !Final.count(Op))
613 Queue.push_back(Op);
614 }
615 }
616}
617
618// Collect all of the users of all of the provided root instructions (combined
619// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000620void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000621 const SmallInstructionVector &Roots,
622 const SmallInstructionSet &Exclude,
623 const SmallInstructionSet &Final,
624 DenseSet<Instruction *> &Users) {
625 for (SmallInstructionVector::const_iterator I = Roots.begin(),
626 IE = Roots.end(); I != IE; ++I)
James Molloy5f255eb2015-01-29 13:48:05 +0000627 collectInLoopUserSet(*I, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000628}
629
630static bool isSimpleLoadStore(Instruction *I) {
631 if (LoadInst *LI = dyn_cast<LoadInst>(I))
632 return LI->isSimple();
633 if (StoreInst *SI = dyn_cast<StoreInst>(I))
634 return SI->isSimple();
635 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
636 return !MI->isVolatile();
637 return false;
638}
639
James Molloyf1473592015-02-11 09:19:47 +0000640/// Return true if IVU is a "simple" arithmetic operation.
641/// This is used for narrowing the search space for DAGRoots; only arithmetic
642/// and GEPs can be part of a DAGRoot.
643static bool isSimpleArithmeticOp(User *IVU) {
644 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
645 switch (I->getOpcode()) {
646 default: return false;
647 case Instruction::Add:
648 case Instruction::Sub:
649 case Instruction::Mul:
650 case Instruction::Shl:
651 case Instruction::AShr:
652 case Instruction::LShr:
653 case Instruction::GetElementPtr:
654 case Instruction::Trunc:
655 case Instruction::ZExt:
656 case Instruction::SExt:
657 return true;
658 }
659 }
660 return false;
661}
662
663static bool isLoopIncrement(User *U, Instruction *IV) {
664 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
665 if (!BO || BO->getOpcode() != Instruction::Add)
666 return false;
667
668 for (auto *UU : BO->users()) {
669 PHINode *PN = dyn_cast<PHINode>(UU);
670 if (PN && PN == IV)
671 return true;
672 }
673 return false;
674}
675
676bool LoopReroll::DAGRootTracker::
677collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
678 SmallInstructionVector BaseUsers;
679
680 for (auto *I : Base->users()) {
681 ConstantInt *CI = nullptr;
682
683 if (isLoopIncrement(I, IV)) {
684 LoopIncs.push_back(cast<Instruction>(I));
685 continue;
686 }
687
688 // The root nodes must be either GEPs, ORs or ADDs.
689 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
690 if (BO->getOpcode() == Instruction::Add ||
691 BO->getOpcode() == Instruction::Or)
692 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
693 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
694 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
695 CI = dyn_cast<ConstantInt>(LastOperand);
696 }
697
698 if (!CI) {
699 if (Instruction *II = dyn_cast<Instruction>(I)) {
700 BaseUsers.push_back(II);
701 continue;
702 } else {
703 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
704 return false;
705 }
706 }
707
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000708 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000709 if (Roots.find(V) != Roots.end())
710 // No duplicates, please.
711 return false;
712
James Molloyf1473592015-02-11 09:19:47 +0000713 Roots[V] = cast<Instruction>(I);
714 }
715
716 if (Roots.empty())
717 return false;
James Molloyf1473592015-02-11 09:19:47 +0000718
719 // If we found non-loop-inc, non-root users of Base, assume they are
720 // for the zeroth root index. This is because "add %a, 0" gets optimized
721 // away.
James Molloye32d8062015-02-16 17:02:00 +0000722 if (BaseUsers.size()) {
723 if (Roots.find(0) != Roots.end()) {
724 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
725 return false;
726 }
James Molloyf1473592015-02-11 09:19:47 +0000727 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000728 }
James Molloyf1473592015-02-11 09:19:47 +0000729
730 // Calculate the number of users of the base, or lowest indexed, iteration.
731 unsigned NumBaseUses = BaseUsers.size();
732 if (NumBaseUses == 0)
733 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000734
James Molloyf1473592015-02-11 09:19:47 +0000735 // Check that every node has the same number of users.
736 for (auto &KV : Roots) {
737 if (KV.first == 0)
738 continue;
739 if (KV.second->getNumUses() != NumBaseUses) {
740 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
741 << "#Base=" << NumBaseUses << ", #Root=" <<
742 KV.second->getNumUses() << "\n");
743 return false;
744 }
745 }
746
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000747 return true;
James Molloyf1473592015-02-11 09:19:47 +0000748}
749
750bool LoopReroll::DAGRootTracker::
751findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
752 // Does the user look like it could be part of a root set?
753 // All its users must be simple arithmetic ops.
754 if (I->getNumUses() > IL_MaxRerollIterations)
755 return false;
756
757 if ((I->getOpcode() == Instruction::Mul ||
758 I->getOpcode() == Instruction::PHI) &&
759 I != IV &&
760 findRootsBase(I, SubsumedInsts))
761 return true;
762
763 SubsumedInsts.insert(I);
764
765 for (User *V : I->users()) {
766 Instruction *I = dyn_cast<Instruction>(V);
767 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
768 continue;
769
770 if (!I || !isSimpleArithmeticOp(I) ||
771 !findRootsRecursive(I, SubsumedInsts))
772 return false;
773 }
774 return true;
775}
776
777bool LoopReroll::DAGRootTracker::
778findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
779
780 // The base instruction needs to be a multiply so
781 // that we can erase it.
782 if (IVU->getOpcode() != Instruction::Mul &&
783 IVU->getOpcode() != Instruction::PHI)
784 return false;
785
786 std::map<int64_t, Instruction*> V;
787 if (!collectPossibleRoots(IVU, V))
788 return false;
789
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000790 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000791 // subsumed.
792 if (V.find(0) == V.end())
793 SubsumedInsts.insert(IVU);
794
795 // Partition the vector into monotonically increasing indexes.
796 DAGRootSet DRS;
797 DRS.BaseInst = nullptr;
798
799 for (auto &KV : V) {
800 if (!DRS.BaseInst) {
801 DRS.BaseInst = KV.second;
802 DRS.SubsumedInsts = SubsumedInsts;
803 } else if (DRS.Roots.empty()) {
804 DRS.Roots.push_back(KV.second);
805 } else if (V.find(KV.first - 1) != V.end()) {
806 DRS.Roots.push_back(KV.second);
807 } else {
808 // Linear sequence terminated.
809 RootSets.push_back(DRS);
810 DRS.BaseInst = KV.second;
811 DRS.SubsumedInsts = SubsumedInsts;
812 DRS.Roots.clear();
813 }
814 }
815 RootSets.push_back(DRS);
816
817 return true;
818}
819
James Molloy5f255eb2015-01-29 13:48:05 +0000820bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000821 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +0000822
James Molloyf1473592015-02-11 09:19:47 +0000823 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000824 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +0000825 for (auto *IVU : IV->users()) {
826 if (isLoopIncrement(IVU, IV))
827 LoopIncs.push_back(cast<Instruction>(IVU));
828 }
829 if (!findRootsRecursive(IV, SmallInstructionSet()))
830 return false;
831 LoopIncs.push_back(IV);
832 } else {
833 if (!findRootsBase(IV, SmallInstructionSet()))
834 return false;
835 }
James Molloy5f255eb2015-01-29 13:48:05 +0000836
James Molloyf1473592015-02-11 09:19:47 +0000837 // Ensure all sets have the same size.
838 if (RootSets.empty()) {
839 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000840 return false;
James Molloyf1473592015-02-11 09:19:47 +0000841 }
842 for (auto &V : RootSets) {
843 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
844 DEBUG(dbgs()
845 << "LRR: Aborting because not all root sets have the same size\n");
846 return false;
847 }
848 }
James Molloy5f255eb2015-01-29 13:48:05 +0000849
James Molloyf1473592015-02-11 09:19:47 +0000850 // And ensure all loop iterations are consecutive. We rely on std::map
851 // providing ordered traversal.
852 for (auto &V : RootSets) {
853 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
854 if (!ADR)
855 return false;
856
857 // Consider a DAGRootSet with N-1 roots (so N different values including
858 // BaseInst).
859 // Define d = Roots[0] - BaseInst, which should be the same as
860 // Roots[I] - Roots[I-1] for all I in [1..N).
861 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
862 // loop iteration J.
863 //
864 // Now, For the loop iterations to be consecutive:
865 // D = d * N
866
867 unsigned N = V.Roots.size() + 1;
868 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
869 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
870 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
871 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
872 return false;
873 }
874 }
875 Scale = RootSets[0].Roots.size() + 1;
876
877 if (Scale > IL_MaxRerollIterations) {
James Molloy64419d42015-01-29 21:52:03 +0000878 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
James Molloyf1473592015-02-11 09:19:47 +0000879 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
James Molloy64419d42015-01-29 21:52:03 +0000880 << "\n");
881 return false;
882 }
883
James Molloyf1473592015-02-11 09:19:47 +0000884 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000885
886 return true;
887}
888
James Molloy64419d42015-01-29 21:52:03 +0000889bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
890 // Populate the MapVector with all instructions in the block, in order first,
891 // so we can iterate over the contents later in perfect order.
892 for (auto &I : *L->getHeader()) {
893 Uses[&I].resize(IL_End);
894 }
James Molloy5f255eb2015-01-29 13:48:05 +0000895
James Molloy64419d42015-01-29 21:52:03 +0000896 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +0000897 for (auto &DRS : RootSets) {
898 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
899 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
900 Exclude.insert(DRS.BaseInst);
901 }
James Molloy64419d42015-01-29 21:52:03 +0000902 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
903
James Molloyf1473592015-02-11 09:19:47 +0000904 for (auto &DRS : RootSets) {
905 DenseSet<Instruction*> VBase;
906 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
907 for (auto *I : VBase) {
908 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +0000909 }
910
James Molloyf1473592015-02-11 09:19:47 +0000911 unsigned Idx = 1;
912 for (auto *Root : DRS.Roots) {
913 DenseSet<Instruction*> V;
914 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
915
916 // While we're here, check the use sets are the same size.
917 if (V.size() != VBase.size()) {
918 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
919 return false;
920 }
921
922 for (auto *I : V) {
923 Uses[I].set(Idx);
924 }
925 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +0000926 }
James Molloyf1473592015-02-11 09:19:47 +0000927
928 // Make sure our subsumed instructions are remembered too.
929 for (auto *I : DRS.SubsumedInsts) {
930 Uses[I].set(IL_All);
931 }
James Molloy64419d42015-01-29 21:52:03 +0000932 }
933
934 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +0000935
James Molloy64419d42015-01-29 21:52:03 +0000936 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +0000937 for (auto &DRS : RootSets) {
938 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
939 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
940 Exclude.insert(DRS.BaseInst);
941 }
James Molloy64419d42015-01-29 21:52:03 +0000942
943 DenseSet<Instruction*> V;
944 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
945 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +0000946 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +0000947 }
James Molloy64419d42015-01-29 21:52:03 +0000948
949 return true;
950
951}
952
James Molloye805ad92015-02-12 15:54:14 +0000953/// Get the next instruction in "In" that is a member of set Val.
954/// Start searching from StartI, and do not return anything in Exclude.
955/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +0000956LoopReroll::DAGRootTracker::UsesTy::iterator
957LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +0000958 const SmallInstructionSet &Exclude,
959 UsesTy::iterator *StartI) {
960 UsesTy::iterator I = StartI ? *StartI : In.begin();
961 while (I != In.end() && (I->second.test(Val) == 0 ||
962 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +0000963 ++I;
964 return I;
965}
966
James Molloyf1473592015-02-11 09:19:47 +0000967bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
968 for (auto &DRS : RootSets) {
969 if (DRS.BaseInst == I)
970 return true;
971 }
972 return false;
973}
974
975bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
976 for (auto &DRS : RootSets) {
977 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
978 return true;
979 }
980 return false;
981}
982
James Molloye805ad92015-02-12 15:54:14 +0000983/// Return true if instruction I depends on any instruction between
984/// Start and End.
985bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
986 UsesTy::iterator Start,
987 UsesTy::iterator End) {
988 for (auto *U : I->users()) {
989 for (auto It = Start; It != End; ++It)
990 if (U == It->first)
991 return true;
992 }
993 return false;
994}
995
James Molloy64419d42015-01-29 21:52:03 +0000996bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +0000997 // We now need to check for equivalence of the use graph of each root with
998 // that of the primary induction variable (excluding the roots). Our goal
999 // here is not to solve the full graph isomorphism problem, but rather to
1000 // catch common cases without a lot of work. As a result, we will assume
1001 // that the relative order of the instructions in each unrolled iteration
1002 // is the same (although we will not make an assumption about how the
1003 // different iterations are intermixed). Note that while the order must be
1004 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001005
1006 // An array of just the possible reductions for this scale factor. When we
1007 // collect the set of all users of some root instructions, these reduction
1008 // instructions are treated as 'final' (their uses are not considered).
1009 // This is important because we don't want the root use set to search down
1010 // the reduction chain.
1011 SmallInstructionSet PossibleRedSet;
1012 SmallInstructionSet PossibleRedLastSet;
1013 SmallInstructionSet PossibleRedPHISet;
1014 Reductions.restrictToScale(Scale, PossibleRedSet,
1015 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001016
James Molloy64419d42015-01-29 21:52:03 +00001017 // Populate "Uses" with where each instruction is used.
1018 if (!collectUsedInstructions(PossibleRedSet))
1019 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001020
James Molloy64419d42015-01-29 21:52:03 +00001021 // Make sure we mark the reduction PHIs as used in all iterations.
1022 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001023 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001024 }
James Molloy5f255eb2015-01-29 13:48:05 +00001025
James Molloy64419d42015-01-29 21:52:03 +00001026 // Make sure all instructions in the loop are in one and only one
1027 // set.
1028 for (auto &KV : Uses) {
1029 if (KV.second.count() != 1) {
1030 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1031 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1032 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001033 }
James Molloy64419d42015-01-29 21:52:03 +00001034 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001035
James Molloy64419d42015-01-29 21:52:03 +00001036 DEBUG(
1037 for (auto &KV : Uses) {
1038 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1039 }
1040 );
1041
1042 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001043 // In addition to regular aliasing information, we need to look for
1044 // instructions from later (future) iterations that have side effects
1045 // preventing us from reordering them past other instructions with side
1046 // effects.
1047 bool FutureSideEffects = false;
1048 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001049 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1050 DenseMap<Value *, Value *> BaseMap;
1051
James Molloy64419d42015-01-29 21:52:03 +00001052 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001053 SmallInstructionSet Visited;
1054 auto BaseIt = nextInstr(0, Uses, Visited);
1055 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001056 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001057
James Molloy64419d42015-01-29 21:52:03 +00001058 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1059 Instruction *BaseInst = BaseIt->first;
1060 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001061
James Molloy64419d42015-01-29 21:52:03 +00001062 // Skip over the IV or root instructions; only match their users.
1063 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001064 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001065 Visited.insert(BaseInst);
1066 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001067 Continue = true;
1068 }
James Molloyf1473592015-02-11 09:19:47 +00001069 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001070 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001071 Visited.insert(RootInst);
1072 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001073 Continue = true;
1074 }
1075 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001076
James Molloye805ad92015-02-12 15:54:14 +00001077 if (!BaseInst->isSameOperationAs(RootInst)) {
1078 // Last chance saloon. We don't try and solve the full isomorphism
1079 // problem, but try and at least catch the case where two instructions
1080 // *of different types* are round the wrong way. We won't be able to
1081 // efficiently tell, given two ADD instructions, which way around we
1082 // should match them, but given an ADD and a SUB, we can at least infer
1083 // which one is which.
1084 //
1085 // This should allow us to deal with a greater subset of the isomorphism
1086 // problem. It does however change a linear algorithm into a quadratic
1087 // one, so limit the number of probes we do.
1088 auto TryIt = RootIt;
1089 unsigned N = NumToleratedFailedMatches;
1090 while (TryIt != Uses.end() &&
1091 !BaseInst->isSameOperationAs(TryIt->first) &&
1092 N--) {
1093 ++TryIt;
1094 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1095 }
1096
1097 if (TryIt == Uses.end() || TryIt == RootIt ||
1098 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1099 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1100 " vs. " << *RootInst << "\n");
1101 return false;
1102 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001103
James Molloye805ad92015-02-12 15:54:14 +00001104 RootIt = TryIt;
1105 RootInst = TryIt->first;
1106 }
1107
James Molloy64419d42015-01-29 21:52:03 +00001108 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001109 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001110 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001111 //
James Molloye805ad92015-02-12 15:54:14 +00001112 // Note that because we allow a limited amount of flexibility in the order
1113 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1114 // case we've already checked this set of instructions so we shouldn't
1115 // do anything.
1116 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001117 Instruction *I = LastRootIt->first;
1118 if (LastRootIt->second.find_first() < (int)Iter)
1119 continue;
1120 if (I->mayWriteToMemory())
1121 AST.add(I);
1122 // Note: This is specifically guarded by a check on isa<PHINode>,
1123 // which while a valid (somewhat arbitrary) micro-optimization, is
1124 // needed because otherwise isSafeToSpeculativelyExecute returns
1125 // false on PHI nodes.
1126 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001127 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001128 // Intervening instructions cause side effects.
1129 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001130 }
1131
James Molloy5f255eb2015-01-29 13:48:05 +00001132 // Make sure that this instruction, which is in the use set of this
1133 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001134 // some other root instruction.
1135 if (RootIt->second.count() > 1) {
1136 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1137 " vs. " << *RootInst << " (prev. case overlap)\n");
1138 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001139 }
1140
1141 // Make sure that we don't alias with any instruction in the alias set
1142 // tracker. If we do, then we depend on a future iteration, and we
1143 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001144 if (RootInst->mayReadFromMemory())
1145 for (auto &K : AST) {
1146 if (K.aliasesUnknownInst(RootInst, *AA)) {
1147 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1148 " vs. " << *RootInst << " (depends on future store)\n");
1149 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001150 }
1151 }
James Molloy5f255eb2015-01-29 13:48:05 +00001152
1153 // If we've past an instruction from a future iteration that may have
1154 // side effects, and this instruction might also, then we can't reorder
1155 // them, and this matching fails. As an exception, we allow the alias
1156 // set tracker to handle regular (simple) load/store dependencies.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001157 if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1158 !isSafeToSpeculativelyExecute(BaseInst)) ||
1159 (!isSimpleLoadStore(RootInst) &&
1160 !isSafeToSpeculativelyExecute(RootInst)))) {
James Molloy64419d42015-01-29 21:52:03 +00001161 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1162 " vs. " << *RootInst <<
James Molloy5f255eb2015-01-29 13:48:05 +00001163 " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001164 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001165 }
1166
1167 // For instructions that are part of a reduction, if the operation is
1168 // associative, then don't bother matching the operands (because we
1169 // already know that the instructions are isomorphic, and the order
1170 // within the iteration does not matter). For non-associative reductions,
1171 // we do need to match the operands, because we need to reject
1172 // out-of-order instructions within an iteration!
1173 // For example (assume floating-point addition), we need to reject this:
1174 // x += a[i]; x += b[i];
1175 // x += a[i+1]; x += b[i+1];
1176 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001177 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001178
James Molloy64419d42015-01-29 21:52:03 +00001179 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001180 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001181 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1182 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001183
1184 // If this is part of a reduction (and the operation is not
1185 // associatve), then we match all operands, but not those that are
1186 // part of the reduction.
1187 if (InReduction)
1188 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001189 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001190 continue;
1191
1192 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001193 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001194 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001195 } else {
1196 for (auto &DRS : RootSets) {
1197 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1198 Op2 = DRS.BaseInst;
1199 break;
1200 }
1201 }
1202 }
James Molloy5f255eb2015-01-29 13:48:05 +00001203
James Molloy64419d42015-01-29 21:52:03 +00001204 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001205 // If we've not already decided to swap the matched operands, and
1206 // we've not already matched our first operand (note that we could
1207 // have skipped matching the first operand because it is part of a
1208 // reduction above), and the instruction is commutative, then try
1209 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001210 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1211 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001212 Swapped = true;
1213 } else {
James Molloy64419d42015-01-29 21:52:03 +00001214 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1215 << " vs. " << *RootInst << " (operand " << j << ")\n");
1216 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001217 }
1218 }
1219
1220 SomeOpMatched = true;
1221 }
1222 }
1223
James Molloy64419d42015-01-29 21:52:03 +00001224 if ((!PossibleRedLastSet.count(BaseInst) &&
1225 hasUsesOutsideLoop(BaseInst, L)) ||
1226 (!PossibleRedLastSet.count(RootInst) &&
1227 hasUsesOutsideLoop(RootInst, L))) {
1228 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1229 " vs. " << *RootInst << " (uses outside loop)\n");
1230 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001231 }
1232
James Molloy64419d42015-01-29 21:52:03 +00001233 Reductions.recordPair(BaseInst, RootInst, Iter);
1234 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001235
James Molloy64419d42015-01-29 21:52:03 +00001236 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001237 Visited.insert(BaseInst);
1238 Visited.insert(RootInst);
1239 BaseIt = nextInstr(0, Uses, Visited);
1240 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001241 }
James Molloy64419d42015-01-29 21:52:03 +00001242 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1243 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001244 }
1245
James Molloy5f255eb2015-01-29 13:48:05 +00001246 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
James Molloyf1473592015-02-11 09:19:47 +00001247 *IV << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001248
Hal Finkelbf45efd2013-11-16 23:59:05 +00001249 return true;
1250}
1251
James Molloy5f255eb2015-01-29 13:48:05 +00001252void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1253 BasicBlock *Header = L->getHeader();
1254 // Remove instructions associated with non-base iterations.
1255 for (BasicBlock::reverse_iterator J = Header->rbegin();
1256 J != Header->rend();) {
James Molloy64419d42015-01-29 21:52:03 +00001257 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001258 if (I > 0 && I < IL_All) {
James Molloy5f255eb2015-01-29 13:48:05 +00001259 Instruction *D = &*J;
1260 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1261 D->eraseFromParent();
1262 continue;
1263 }
1264
1265 ++J;
1266 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001267 bool Negative = IVToIncMap[IV] < 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001268 const DataLayout &DL = Header->getModule()->getDataLayout();
James Molloy5f255eb2015-01-29 13:48:05 +00001269
James Molloyf1473592015-02-11 09:19:47 +00001270 // We need to create a new induction variable for each different BaseInst.
1271 for (auto &DRS : RootSets) {
1272 // Insert the new induction variable.
1273 const SCEVAddRecExpr *RealIVSCEV =
1274 cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
1275 const SCEV *Start = RealIVSCEV->getStart();
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001276 const SCEVAddRecExpr *H = cast<SCEVAddRecExpr>(SE->getAddRecExpr(
1277 Start, SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1), L,
1278 SCEV::FlagAnyWrap));
James Molloyf1473592015-02-11 09:19:47 +00001279 { // Limit the lifetime of SCEVExpander.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001280 SCEVExpander Expander(*SE, DL, "reroll");
James Molloyf1473592015-02-11 09:19:47 +00001281 Value *NewIV = Expander.expandCodeFor(H, IV->getType(), Header->begin());
James Molloy5f255eb2015-01-29 13:48:05 +00001282
James Molloyf1473592015-02-11 09:19:47 +00001283 for (auto &KV : Uses) {
1284 if (KV.second.find_first() == 0)
1285 KV.first->replaceUsesOfWith(DRS.BaseInst, NewIV);
1286 }
James Molloy5f255eb2015-01-29 13:48:05 +00001287
James Molloyf1473592015-02-11 09:19:47 +00001288 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1289 // FIXME: Why do we need this check?
1290 if (Uses[BI].find_first() == IL_All) {
1291 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
James Molloy5f255eb2015-01-29 13:48:05 +00001292
James Molloyf1473592015-02-11 09:19:47 +00001293 // Iteration count SCEV minus 1
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001294 const SCEV *ICMinus1SCEV = SE->getMinusSCEV(
1295 ICSCEV, SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1));
James Molloy5f255eb2015-01-29 13:48:05 +00001296
James Molloyf1473592015-02-11 09:19:47 +00001297 Value *ICMinus1; // Iteration count minus 1
1298 if (isa<SCEVConstant>(ICMinus1SCEV)) {
1299 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(), BI);
1300 } else {
1301 BasicBlock *Preheader = L->getLoopPreheader();
1302 if (!Preheader)
1303 Preheader = InsertPreheaderForLoop(L, Parent);
James Molloy5f255eb2015-01-29 13:48:05 +00001304
James Molloyf1473592015-02-11 09:19:47 +00001305 ICMinus1 = Expander.expandCodeFor(ICMinus1SCEV, NewIV->getType(),
1306 Preheader->getTerminator());
1307 }
1308
1309 Value *Cond =
James Molloy5f255eb2015-01-29 13:48:05 +00001310 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinus1, "exitcond");
James Molloyf1473592015-02-11 09:19:47 +00001311 BI->setCondition(Cond);
James Molloy5f255eb2015-01-29 13:48:05 +00001312
James Molloyf1473592015-02-11 09:19:47 +00001313 if (BI->getSuccessor(1) != Header)
1314 BI->swapSuccessors();
1315 }
James Molloy5f255eb2015-01-29 13:48:05 +00001316 }
1317 }
1318 }
1319
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001320 SimplifyInstructionsInBlock(Header, TLI);
James Molloy5f255eb2015-01-29 13:48:05 +00001321 DeleteDeadPHIs(Header, TLI);
1322}
1323
Hal Finkelbf45efd2013-11-16 23:59:05 +00001324// Validate the selected reductions. All iterations must have an isomorphic
1325// part of the reduction chain and, for non-associative reductions, the chain
1326// entries must appear in order.
1327bool LoopReroll::ReductionTracker::validateSelected() {
1328 // For a non-associative reduction, the chain entries must appear in order.
1329 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1330 RI != RIE; ++RI) {
1331 int i = *RI;
1332 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001333 for (Instruction *J : PossibleReds[i]) {
1334 // Note that all instructions in the chain must have been found because
1335 // all instructions in the function must have been assigned to some
1336 // iteration.
1337 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001338 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1339 !PossibleReds[i].getReducedValue()->isAssociative()) {
1340 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001341 J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001342 return false;
1343 }
1344
1345 if (Iter != PrevIter) {
1346 if (Count != BaseCount) {
1347 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1348 " reduction use count " << Count <<
1349 " is not equal to the base use count " <<
1350 BaseCount << "\n");
1351 return false;
1352 }
1353
1354 Count = 0;
1355 }
1356
1357 ++Count;
1358 if (Iter == 0)
1359 ++BaseCount;
1360
1361 PrevIter = Iter;
1362 }
1363 }
1364
1365 return true;
1366}
1367
1368// For all selected reductions, remove all parts except those in the first
1369// iteration (and the PHI). Replace outside uses of the reduced value with uses
1370// of the first-iteration reduced value (in other words, reroll the selected
1371// reductions).
1372void LoopReroll::ReductionTracker::replaceSelected() {
1373 // Fixup reductions to refer to the last instruction associated with the
1374 // first iteration (not the last).
1375 for (DenseSet<int>::iterator RI = Reds.begin(), RIE = Reds.end();
1376 RI != RIE; ++RI) {
1377 int i = *RI;
1378 int j = 0;
1379 for (int e = PossibleReds[i].size(); j != e; ++j)
1380 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1381 --j;
1382 break;
1383 }
1384
1385 // Replace users with the new end-of-chain value.
1386 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001387 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001388 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001389 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001390
1391 for (SmallInstructionVector::iterator J = Users.begin(),
1392 JE = Users.end(); J != JE; ++J)
1393 (*J)->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
1394 PossibleReds[i][j]);
1395 }
1396}
1397
1398// Reroll the provided loop with respect to the provided induction variable.
1399// Generally, we're looking for a loop like this:
1400//
1401// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1402// f(%iv)
1403// %iv.1 = add %iv, 1 <-- a root increment
1404// f(%iv.1)
1405// %iv.2 = add %iv, 2 <-- a root increment
1406// f(%iv.2)
1407// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1408// f(%iv.scale_m_1)
1409// ...
1410// %iv.next = add %iv, scale
1411// %cmp = icmp(%iv, ...)
1412// br %cmp, header, exit
1413//
1414// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1415// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1416// be intermixed with eachother. The restriction imposed by this algorithm is
1417// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1418// etc. be the same.
1419//
1420// First, we collect the use set of %iv, excluding the other increment roots.
1421// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1422// times, having collected the use set of f(%iv.(i+1)), during which we:
1423// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1424// the next unmatched instruction in f(%iv.(i+1)).
1425// - Ensure that both matched instructions don't have any external users
1426// (with the exception of last-in-chain reduction instructions).
1427// - Track the (aliasing) write set, and other side effects, of all
1428// instructions that belong to future iterations that come before the matched
1429// instructions. If the matched instructions read from that write set, then
1430// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1431// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1432// if any of these future instructions had side effects (could not be
1433// speculatively executed), and so do the matched instructions, when we
1434// cannot reorder those side-effect-producing instructions, and rerolling
1435// fails.
1436//
1437// Finally, we make sure that all loop instructions are either loop increment
1438// roots, belong to simple latch code, parts of validated reductions, part of
1439// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1440// have been validated), then we reroll the loop.
1441bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1442 const SCEV *IterCount,
1443 ReductionTracker &Reductions) {
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001444 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, IVToIncMap);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001445
James Molloy5f255eb2015-01-29 13:48:05 +00001446 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001447 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001448 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
James Molloy5f255eb2015-01-29 13:48:05 +00001449 *IV << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001450
James Molloy5f255eb2015-01-29 13:48:05 +00001451 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001452 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001453 if (!Reductions.validateSelected())
1454 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001455 // At this point, we've validated the rerolling, and we're committed to
1456 // making changes!
1457
1458 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001459 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001460
Hal Finkelbf45efd2013-11-16 23:59:05 +00001461 ++NumRerolledLoops;
1462 return true;
1463}
1464
1465bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001466 if (skipOptnoneFunction(L))
1467 return false;
1468
Chandler Carruth7b560d42015-09-09 17:55:00 +00001469 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001470 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001471 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001472 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001473 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Hal Finkelbf45efd2013-11-16 23:59:05 +00001474
1475 BasicBlock *Header = L->getHeader();
1476 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1477 "] Loop %" << Header->getName() << " (" <<
1478 L->getNumBlocks() << " block(s))\n");
1479
1480 bool Changed = false;
1481
1482 // For now, we'll handle only single BB loops.
1483 if (L->getNumBlocks() > 1)
1484 return Changed;
1485
1486 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
1487 return Changed;
1488
1489 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001490 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
Hal Finkelbf45efd2013-11-16 23:59:05 +00001491 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1492
1493 // First, we need to find the induction variable with respect to which we can
1494 // reroll (there may be several possible options).
1495 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001496 IVToIncMap.clear();
Hal Finkelbf45efd2013-11-16 23:59:05 +00001497 collectPossibleIVs(L, PossibleIVs);
1498
1499 if (PossibleIVs.empty()) {
1500 DEBUG(dbgs() << "LRR: No possible IVs found\n");
1501 return Changed;
1502 }
1503
1504 ReductionTracker Reductions;
1505 collectPossibleReductions(L, Reductions);
1506
1507 // For each possible IV, collect the associated possible set of 'root' nodes
1508 // (i+1, i+2, etc.).
1509 for (SmallInstructionVector::iterator I = PossibleIVs.begin(),
1510 IE = PossibleIVs.end(); I != IE; ++I)
1511 if (reroll(*I, L, Header, IterCount, Reductions)) {
1512 Changed = true;
1513 break;
1514 }
1515
1516 return Changed;
1517}