blob: d2f1b66076a6ceba5fe7b60d0d074c8919e6cb85 [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"
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +000017#include "llvm/ADT/BitVector.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 {
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000131 /// The maximum number of iterations that we'll try and reroll.
132 IL_MaxRerollIterations = 32,
James Molloy64419d42015-01-29 21:52:03 +0000133 /// The bitvector index used by loop induction variables and other
James Molloyf1473592015-02-11 09:19:47 +0000134 /// instructions that belong to all iterations.
135 IL_All,
James Molloy64419d42015-01-29 21:52:03 +0000136 IL_End
137 };
138
Hal Finkelbf45efd2013-11-16 23:59:05 +0000139 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 Topper3e4c6972014-03-05 09:10:37 +0000146 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000147
Craig Topper3e4c6972014-03-05 09:10:37 +0000148 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000149 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000150 getLoopAnalysisUsage(AU);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000151 }
152
James Molloy64419d42015-01-29 21:52:03 +0000153 protected:
Hal Finkelbf45efd2013-11-16 23:59:05 +0000154 AliasAnalysis *AA;
155 LoopInfo *LI;
156 ScalarEvolution *SE;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000157 TargetLibraryInfo *TLI;
158 DominatorTree *DT;
Justin Bogner843fb202015-12-15 19:40:57 +0000159 bool PreserveLCSSA;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000160
161 typedef SmallVector<Instruction *, 16> SmallInstructionVector;
162 typedef SmallSet<Instruction *, 16> SmallInstructionSet;
163
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000164 // Map between induction variable and its increment
165 DenseMap<Instruction *, int64_t> IVToIncMap;
Lawrence Hu1befea22016-04-30 00:51:22 +0000166 // For loop with multiple induction variable, remember the one used only to
167 // control the loop.
168 Instruction *LoopControlIV;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000169
170 // A chain of isomorphic instructions, identified by a single-use PHI
Hal Finkelbf45efd2013-11-16 23:59:05 +0000171 // representing a reduction. Only the last value may be used outside the
172 // loop.
173 struct SimpleLoopReduction {
174 SimpleLoopReduction(Instruction *P, Loop *L)
175 : Valid(false), Instructions(1, P) {
176 assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
177 add(L);
178 }
179
180 bool valid() const {
181 return Valid;
182 }
183
184 Instruction *getPHI() const {
185 assert(Valid && "Using invalid reduction");
186 return Instructions.front();
187 }
188
189 Instruction *getReducedValue() const {
190 assert(Valid && "Using invalid reduction");
191 return Instructions.back();
192 }
193
194 Instruction *get(size_t i) const {
195 assert(Valid && "Using invalid reduction");
196 return Instructions[i+1];
197 }
198
199 Instruction *operator [] (size_t i) const { return get(i); }
200
201 // The size, ignoring the initial PHI.
202 size_t size() const {
203 assert(Valid && "Using invalid reduction");
204 return Instructions.size()-1;
205 }
206
207 typedef SmallInstructionVector::iterator iterator;
208 typedef SmallInstructionVector::const_iterator const_iterator;
209
210 iterator begin() {
211 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000212 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000213 }
214
215 const_iterator begin() const {
216 assert(Valid && "Using invalid reduction");
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000217 return std::next(Instructions.begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000218 }
219
220 iterator end() { return Instructions.end(); }
221 const_iterator end() const { return Instructions.end(); }
222
223 protected:
224 bool Valid;
225 SmallInstructionVector Instructions;
226
227 void add(Loop *L);
228 };
229
230 // The set of all reductions, and state tracking of possible reductions
231 // during loop instruction processing.
232 struct ReductionTracker {
233 typedef SmallVector<SimpleLoopReduction, 16> SmallReductionVector;
234
235 // Add a new possible reduction.
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000236 void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000237
238 // Setup to track possible reductions corresponding to the provided
239 // rerolling scale. Only reductions with a number of non-PHI instructions
240 // that is divisible by the scale are considered. Three instructions sets
241 // are filled in:
242 // - A set of all possible instructions in eligible reductions.
243 // - A set of all PHIs in eligible reductions
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +0000244 // - A set of all reduced values (last instructions) in eligible
245 // reductions.
Hal Finkelbf45efd2013-11-16 23:59:05 +0000246 void restrictToScale(uint64_t Scale,
247 SmallInstructionSet &PossibleRedSet,
248 SmallInstructionSet &PossibleRedPHISet,
249 SmallInstructionSet &PossibleRedLastSet) {
250 PossibleRedIdx.clear();
251 PossibleRedIter.clear();
252 Reds.clear();
253
254 for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
255 if (PossibleReds[i].size() % Scale == 0) {
256 PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
257 PossibleRedPHISet.insert(PossibleReds[i].getPHI());
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000258
Hal Finkelbf45efd2013-11-16 23:59:05 +0000259 PossibleRedSet.insert(PossibleReds[i].getPHI());
260 PossibleRedIdx[PossibleReds[i].getPHI()] = i;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +0000261 for (Instruction *J : PossibleReds[i]) {
262 PossibleRedSet.insert(J);
263 PossibleRedIdx[J] = i;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000264 }
265 }
266 }
267
268 // The functions below are used while processing the loop instructions.
269
270 // Are the two instructions both from reductions, and furthermore, from
271 // the same reduction?
272 bool isPairInSame(Instruction *J1, Instruction *J2) {
273 DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
274 if (J1I != PossibleRedIdx.end()) {
275 DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
276 if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
277 return true;
278 }
279
280 return false;
281 }
282
283 // The two provided instructions, the first from the base iteration, and
284 // the second from iteration i, form a matched pair. If these are part of
285 // a reduction, record that fact.
286 void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
287 if (PossibleRedIdx.count(J1)) {
288 assert(PossibleRedIdx.count(J2) &&
289 "Recording reduction vs. non-reduction instruction?");
290
291 PossibleRedIter[J1] = 0;
292 PossibleRedIter[J2] = i;
293
294 int Idx = PossibleRedIdx[J1];
295 assert(Idx == PossibleRedIdx[J2] &&
296 "Recording pair from different reductions?");
Hal Finkel67107ea2013-11-17 01:21:54 +0000297 Reds.insert(Idx);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000298 }
299 }
300
301 // The functions below can be called after we've finished processing all
302 // instructions in the loop, and we know which reductions were selected.
303
Hal Finkelbf45efd2013-11-16 23:59:05 +0000304 bool validateSelected();
305 void replaceSelected();
306
307 protected:
308 // The vector of all possible reductions (for any scale).
309 SmallReductionVector PossibleReds;
310
311 DenseMap<Instruction *, int> PossibleRedIdx;
312 DenseMap<Instruction *, int> PossibleRedIter;
313 DenseSet<int> Reds;
314 };
315
James Molloyf1473592015-02-11 09:19:47 +0000316 // A DAGRootSet models an induction variable being used in a rerollable
317 // loop. For example,
318 //
319 // x[i*3+0] = y1
320 // x[i*3+1] = y2
321 // x[i*3+2] = y3
322 //
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000323 // Base instruction -> i*3
James Molloyf1473592015-02-11 09:19:47 +0000324 // +---+----+
325 // / | \
326 // ST[y1] +1 +2 <-- Roots
327 // | |
328 // ST[y2] ST[y3]
329 //
330 // There may be multiple DAGRoots, for example:
331 //
332 // x[i*2+0] = ... (1)
333 // x[i*2+1] = ... (1)
334 // x[i*2+4] = ... (2)
335 // x[i*2+5] = ... (2)
336 // x[(i+1234)*2+5678] = ... (3)
337 // x[(i+1234)*2+5679] = ... (3)
338 //
339 // The loop will be rerolled by adding a new loop induction variable,
340 // one for the Base instruction in each DAGRootSet.
341 //
342 struct DAGRootSet {
343 Instruction *BaseInst;
344 SmallInstructionVector Roots;
345 // The instructions between IV and BaseInst (but not including BaseInst).
346 SmallInstructionSet SubsumedInsts;
347 };
348
James Molloy5f255eb2015-01-29 13:48:05 +0000349 // The set of all DAG roots, and state tracking of all roots
350 // for a particular induction variable.
351 struct DAGRootTracker {
352 DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
353 ScalarEvolution *SE, AliasAnalysis *AA,
Justin Bogner843fb202015-12-15 19:40:57 +0000354 TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
355 bool PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +0000356 DenseMap<Instruction *, int64_t> &IncrMap,
357 Instruction *LoopCtrlIV)
Justin Bogner843fb202015-12-15 19:40:57 +0000358 : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
Lawrence Hu1befea22016-04-30 00:51:22 +0000359 PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
360 LoopControlIV(LoopCtrlIV) {}
James Molloy5f255eb2015-01-29 13:48:05 +0000361
362 /// Stage 1: Find all the DAG roots for the induction variable.
363 bool findRoots();
364 /// Stage 2: Validate if the found roots are valid.
365 bool validate(ReductionTracker &Reductions);
366 /// Stage 3: Assuming validate() returned true, perform the
367 /// replacement.
368 /// @param IterCount The maximum iteration count of L.
369 void replace(const SCEV *IterCount);
370
371 protected:
Elena Demikhovsky9914dbd2016-02-22 09:38:28 +0000372 typedef MapVector<Instruction*, BitVector> UsesTy;
James Molloy64419d42015-01-29 21:52:03 +0000373
James Molloyf1473592015-02-11 09:19:47 +0000374 bool findRootsRecursive(Instruction *IVU,
375 SmallInstructionSet SubsumedInsts);
376 bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
377 bool collectPossibleRoots(Instruction *Base,
378 std::map<int64_t,Instruction*> &Roots);
James Molloy5f255eb2015-01-29 13:48:05 +0000379
James Molloy64419d42015-01-29 21:52:03 +0000380 bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
James Molloy5f255eb2015-01-29 13:48:05 +0000381 void collectInLoopUserSet(const SmallInstructionVector &Roots,
382 const SmallInstructionSet &Exclude,
383 const SmallInstructionSet &Final,
384 DenseSet<Instruction *> &Users);
385 void collectInLoopUserSet(Instruction *Root,
386 const SmallInstructionSet &Exclude,
387 const SmallInstructionSet &Final,
388 DenseSet<Instruction *> &Users);
389
James Molloye805ad92015-02-12 15:54:14 +0000390 UsesTy::iterator nextInstr(int Val, UsesTy &In,
391 const SmallInstructionSet &Exclude,
392 UsesTy::iterator *StartI=nullptr);
James Molloyf1473592015-02-11 09:19:47 +0000393 bool isBaseInst(Instruction *I);
394 bool isRootInst(Instruction *I);
James Molloye805ad92015-02-12 15:54:14 +0000395 bool instrDependsOn(Instruction *I,
396 UsesTy::iterator Start,
397 UsesTy::iterator End);
Lawrence Hud3d51062016-01-25 19:43:45 +0000398 void replaceIV(Instruction *Inst, Instruction *IV, const SCEV *IterCount);
Lawrence Hu1befea22016-04-30 00:51:22 +0000399 void updateNonLoopCtrlIncr();
James Molloy64419d42015-01-29 21:52:03 +0000400
James Molloy5f255eb2015-01-29 13:48:05 +0000401 LoopReroll *Parent;
402
403 // Members of Parent, replicated here for brevity.
404 Loop *L;
405 ScalarEvolution *SE;
406 AliasAnalysis *AA;
407 TargetLibraryInfo *TLI;
Justin Bogner843fb202015-12-15 19:40:57 +0000408 DominatorTree *DT;
409 LoopInfo *LI;
410 bool PreserveLCSSA;
James Molloy5f255eb2015-01-29 13:48:05 +0000411
412 // The loop induction variable.
413 Instruction *IV;
414 // Loop step amount.
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000415 int64_t Inc;
James Molloy5f255eb2015-01-29 13:48:05 +0000416 // Loop reroll count; if Inc == 1, this records the scaling applied
417 // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
418 // If Inc is not 1, Scale = Inc.
419 uint64_t Scale;
James Molloy5f255eb2015-01-29 13:48:05 +0000420 // The roots themselves.
James Molloyf1473592015-02-11 09:19:47 +0000421 SmallVector<DAGRootSet,16> RootSets;
James Molloy5f255eb2015-01-29 13:48:05 +0000422 // All increment instructions for IV.
423 SmallInstructionVector LoopIncs;
James Molloy64419d42015-01-29 21:52:03 +0000424 // Map of all instructions in the loop (in order) to the iterations
James Molloyf1473592015-02-11 09:19:47 +0000425 // they are used in (or specially, IL_All for instructions
James Molloy64419d42015-01-29 21:52:03 +0000426 // used in the loop increment mechanism).
427 UsesTy Uses;
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000428 // Map between induction variable and its increment
429 DenseMap<Instruction *, int64_t> &IVToIncMap;
Lawrence Hu1befea22016-04-30 00:51:22 +0000430 Instruction *LoopControlIV;
James Molloy5f255eb2015-01-29 13:48:05 +0000431 };
432
Lawrence Hu1befea22016-04-30 00:51:22 +0000433 // Check if it is a compare-like instruction whose user is a branch
434 bool isCompareUsedByBranch(Instruction *I) {
435 auto *TI = I->getParent()->getTerminator();
436 if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
437 return false;
438 return I->hasOneUse() && TI->getOperand(0) == I;
439 };
440
441 bool isLoopControlIV(Loop *L, Instruction *IV);
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 Carruth31088a92016-02-19 10:45:18 +0000452INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000453INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Hal Finkelbf45efd2013-11-16 23:59:05 +0000454INITIALIZE_PASS_END(LoopReroll, "loop-reroll", "Reroll loops", false, false)
455
456Pass *llvm::createLoopRerollPass() {
457 return new LoopReroll;
458}
459
460// Returns true if the provided instruction is used outside the given loop.
461// This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
462// non-loop blocks to be outside the loop.
463static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
James Molloy64419d42015-01-29 21:52:03 +0000464 for (User *U : I->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000465 if (!L->contains(cast<Instruction>(U)))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000466 return true;
James Molloy64419d42015-01-29 21:52:03 +0000467 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000468 return false;
469}
470
Lawrence Hud3d51062016-01-25 19:43:45 +0000471static const SCEVConstant *getIncrmentFactorSCEV(ScalarEvolution *SE,
472 const SCEV *SCEVExpr,
473 Instruction &IV) {
474 const SCEVMulExpr *MulSCEV = dyn_cast<SCEVMulExpr>(SCEVExpr);
475
476 // If StepRecurrence of a SCEVExpr is a constant (c1 * c2, c2 = sizeof(ptr)),
477 // Return c1.
478 if (!MulSCEV && IV.getType()->isPointerTy())
479 if (const SCEVConstant *IncSCEV = dyn_cast<SCEVConstant>(SCEVExpr)) {
480 const PointerType *PTy = cast<PointerType>(IV.getType());
481 Type *ElTy = PTy->getElementType();
482 const SCEV *SizeOfExpr =
483 SE->getSizeOfExpr(SE->getEffectiveSCEVType(IV.getType()), ElTy);
484 if (IncSCEV->getValue()->getValue().isNegative()) {
485 const SCEV *NewSCEV =
486 SE->getUDivExpr(SE->getNegativeSCEV(SCEVExpr), SizeOfExpr);
487 return dyn_cast<SCEVConstant>(SE->getNegativeSCEV(NewSCEV));
488 } else {
489 return dyn_cast<SCEVConstant>(SE->getUDivExpr(SCEVExpr, SizeOfExpr));
490 }
491 }
492
493 if (!MulSCEV)
494 return nullptr;
495
496 // If StepRecurrence of a SCEVExpr is a c * sizeof(x), where c is constant,
497 // Return c.
498 const SCEVConstant *CIncSCEV = nullptr;
499 for (const SCEV *Operand : MulSCEV->operands()) {
500 if (const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Operand)) {
501 CIncSCEV = Constant;
502 } else if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Operand)) {
503 Type *AllocTy;
504 if (!Unknown->isSizeOf(AllocTy))
505 break;
506 } else {
507 return nullptr;
508 }
509 }
510 return CIncSCEV;
511}
512
Lawrence Hu1befea22016-04-30 00:51:22 +0000513// Check if an IV is only used to control the loop. There are two cases:
514// 1. It only has one use which is loop increment, and the increment is only
Lawrence Hue58a8142016-05-10 21:16:49 +0000515// used by comparison and the PHI (could has sext with nsw in between), and the
516// comparison is only used by branch.
Lawrence Hu1befea22016-04-30 00:51:22 +0000517// 2. It is used by loop increment and the comparison, the loop increment is
518// only used by the PHI, and the comparison is used only by the branch.
519bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
Lawrence Hu1befea22016-04-30 00:51:22 +0000520 unsigned IVUses = IV->getNumUses();
521 if (IVUses != 2 && IVUses != 1)
522 return false;
523
524 for (auto *User : IV->users()) {
525 int32_t IncOrCmpUses = User->getNumUses();
526 bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
527
528 // User can only have one or two uses.
529 if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
530 return false;
531
532 // Case 1
533 if (IVUses == 1) {
534 // The only user must be the loop increment.
535 // The loop increment must have two uses.
536 if (IsCompInst || IncOrCmpUses != 2)
537 return false;
538 }
539
540 // Case 2
541 if (IVUses == 2 && IncOrCmpUses != 1)
542 return false;
543
544 // The users of the IV must be a binary operation or a comparison
545 if (auto *BO = dyn_cast<BinaryOperator>(User)) {
546 if (BO->getOpcode() == Instruction::Add) {
547 // Loop Increment
548 // User of Loop Increment should be either PHI or CMP
549 for (auto *UU : User->users()) {
550 if (PHINode *PN = dyn_cast<PHINode>(UU)) {
551 if (PN != IV)
552 return false;
553 }
Lawrence Hue58a8142016-05-10 21:16:49 +0000554 // Must be a CMP or an ext (of a value with nsw) then CMP
555 else {
556 Instruction *UUser = dyn_cast<Instruction>(UU);
557 // Skip SExt if we are extending an nsw value
558 // TODO: Allow ZExt too
559 if (BO->hasNoSignedWrap() && UUser && UUser->getNumUses() == 1 &&
560 isa<SExtInst>(UUser))
561 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
562 if (!isCompareUsedByBranch(UUser))
563 return false;
564 }
Lawrence Hu1befea22016-04-30 00:51:22 +0000565 }
566 } else
567 return false;
568 // Compare : can only have one use, and must be branch
569 } else if (!IsCompInst)
570 return false;
571 }
572 return true;
573}
574
Hal Finkelbf45efd2013-11-16 23:59:05 +0000575// Collect the list of loop induction variables with respect to which it might
576// be possible to reroll the loop.
577void LoopReroll::collectPossibleIVs(Loop *L,
578 SmallInstructionVector &PossibleIVs) {
579 BasicBlock *Header = L->getHeader();
580 for (BasicBlock::iterator I = Header->begin(),
581 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
582 if (!isa<PHINode>(I))
583 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000584 if (!I->getType()->isIntegerTy() && !I->getType()->isPointerTy())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000585 continue;
586
587 if (const SCEVAddRecExpr *PHISCEV =
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000588 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&*I))) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000589 if (PHISCEV->getLoop() != L)
590 continue;
591 if (!PHISCEV->isAffine())
592 continue;
Lawrence Hud3d51062016-01-25 19:43:45 +0000593 const SCEVConstant *IncSCEV = nullptr;
594 if (I->getType()->isPointerTy())
595 IncSCEV =
596 getIncrmentFactorSCEV(SE, PHISCEV->getStepRecurrence(*SE), *I);
597 else
598 IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
599 if (IncSCEV) {
600 const APInt &AInt = IncSCEV->getValue()->getValue().abs();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000601 if (IncSCEV->getValue()->isZero() || AInt.uge(MaxInc))
Hal Finkelbf45efd2013-11-16 23:59:05 +0000602 continue;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000603 IVToIncMap[&*I] = IncSCEV->getValue()->getSExtValue();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000604 DEBUG(dbgs() << "LRR: Possible IV: " << *I << " = " << *PHISCEV
605 << "\n");
Lawrence Hu1befea22016-04-30 00:51:22 +0000606
607 if (isLoopControlIV(L, &*I)) {
608 assert(!LoopControlIV && "Found two loop control only IV");
609 LoopControlIV = &(*I);
610 DEBUG(dbgs() << "LRR: Possible loop control only IV: " << *I << " = "
611 << *PHISCEV << "\n");
612 } else
613 PossibleIVs.push_back(&*I);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000614 }
615 }
616 }
617}
618
619// Add the remainder of the reduction-variable chain to the instruction vector
620// (the initial PHINode has already been added). If successful, the object is
621// marked as valid.
622void LoopReroll::SimpleLoopReduction::add(Loop *L) {
623 assert(!Valid && "Cannot add to an already-valid chain");
624
625 // The reduction variable must be a chain of single-use instructions
626 // (including the PHI), except for the last value (which is used by the PHI
627 // and also outside the loop).
628 Instruction *C = Instructions.front();
James Molloy4c7deb22015-02-16 17:01:52 +0000629 if (C->user_empty())
630 return;
Hal Finkelbf45efd2013-11-16 23:59:05 +0000631
632 do {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000633 C = cast<Instruction>(*C->user_begin());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000634 if (C->hasOneUse()) {
635 if (!C->isBinaryOp())
636 return;
637
638 if (!(isa<PHINode>(Instructions.back()) ||
639 C->isSameOperationAs(Instructions.back())))
640 return;
641
642 Instructions.push_back(C);
643 }
644 } while (C->hasOneUse());
645
646 if (Instructions.size() < 2 ||
647 !C->isSameOperationAs(Instructions.back()) ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000648 C->use_empty())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000649 return;
650
651 // C is now the (potential) last instruction in the reduction chain.
James Molloy64419d42015-01-29 21:52:03 +0000652 for (User *U : C->users()) {
Hal Finkelbf45efd2013-11-16 23:59:05 +0000653 // The only in-loop user can be the initial PHI.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000654 if (L->contains(cast<Instruction>(U)))
655 if (cast<Instruction>(U) != Instructions.front())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000656 return;
James Molloy64419d42015-01-29 21:52:03 +0000657 }
Hal Finkelbf45efd2013-11-16 23:59:05 +0000658
659 Instructions.push_back(C);
660 Valid = true;
661}
662
663// Collect the vector of possible reduction variables.
664void LoopReroll::collectPossibleReductions(Loop *L,
665 ReductionTracker &Reductions) {
666 BasicBlock *Header = L->getHeader();
667 for (BasicBlock::iterator I = Header->begin(),
668 IE = Header->getFirstInsertionPt(); I != IE; ++I) {
669 if (!isa<PHINode>(I))
670 continue;
671 if (!I->getType()->isSingleValueType())
672 continue;
673
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000674 SimpleLoopReduction SLR(&*I, L);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000675 if (!SLR.valid())
676 continue;
677
678 DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with " <<
679 SLR.size() << " chained instructions)\n");
680 Reductions.addSLR(SLR);
681 }
682}
683
684// Collect the set of all users of the provided root instruction. This set of
685// users contains not only the direct users of the root instruction, but also
686// all users of those users, and so on. There are two exceptions:
687//
688// 1. Instructions in the set of excluded instructions are never added to the
689// use set (even if they are users). This is used, for example, to exclude
690// including root increments in the use set of the primary IV.
691//
692// 2. Instructions in the set of final instructions are added to the use set
693// if they are users, but their users are not added. This is used, for
694// example, to prevent a reduction update from forcing all later reduction
695// updates into the use set.
James Molloy5f255eb2015-01-29 13:48:05 +0000696void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000697 Instruction *Root, const SmallInstructionSet &Exclude,
698 const SmallInstructionSet &Final,
699 DenseSet<Instruction *> &Users) {
700 SmallInstructionVector Queue(1, Root);
701 while (!Queue.empty()) {
702 Instruction *I = Queue.pop_back_val();
703 if (!Users.insert(I).second)
704 continue;
705
706 if (!Final.count(I))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000707 for (Use &U : I->uses()) {
708 Instruction *User = cast<Instruction>(U.getUser());
Hal Finkelbf45efd2013-11-16 23:59:05 +0000709 if (PHINode *PN = dyn_cast<PHINode>(User)) {
710 // Ignore "wrap-around" uses to PHIs of this loop's header.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000711 if (PN->getIncomingBlock(U) == L->getHeader())
Hal Finkelbf45efd2013-11-16 23:59:05 +0000712 continue;
713 }
NAKAMURA Takumi335a7bc2014-10-28 11:53:30 +0000714
Hal Finkelbf45efd2013-11-16 23:59:05 +0000715 if (L->contains(User) && !Exclude.count(User)) {
716 Queue.push_back(User);
717 }
718 }
719
720 // We also want to collect single-user "feeder" values.
721 for (User::op_iterator OI = I->op_begin(),
722 OIE = I->op_end(); OI != OIE; ++OI) {
723 if (Instruction *Op = dyn_cast<Instruction>(*OI))
724 if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
725 !Final.count(Op))
726 Queue.push_back(Op);
727 }
728 }
729}
730
731// Collect all of the users of all of the provided root instructions (combined
732// into a single set).
James Molloy5f255eb2015-01-29 13:48:05 +0000733void LoopReroll::DAGRootTracker::collectInLoopUserSet(
Hal Finkelbf45efd2013-11-16 23:59:05 +0000734 const SmallInstructionVector &Roots,
735 const SmallInstructionSet &Exclude,
736 const SmallInstructionSet &Final,
737 DenseSet<Instruction *> &Users) {
Benjamin Kramer135f7352016-06-26 12:28:59 +0000738 for (Instruction *Root : Roots)
739 collectInLoopUserSet(Root, Exclude, Final, Users);
Hal Finkelbf45efd2013-11-16 23:59:05 +0000740}
741
742static bool isSimpleLoadStore(Instruction *I) {
743 if (LoadInst *LI = dyn_cast<LoadInst>(I))
744 return LI->isSimple();
745 if (StoreInst *SI = dyn_cast<StoreInst>(I))
746 return SI->isSimple();
747 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
748 return !MI->isVolatile();
749 return false;
750}
751
James Molloyf1473592015-02-11 09:19:47 +0000752/// Return true if IVU is a "simple" arithmetic operation.
753/// This is used for narrowing the search space for DAGRoots; only arithmetic
754/// and GEPs can be part of a DAGRoot.
755static bool isSimpleArithmeticOp(User *IVU) {
756 if (Instruction *I = dyn_cast<Instruction>(IVU)) {
757 switch (I->getOpcode()) {
758 default: return false;
759 case Instruction::Add:
760 case Instruction::Sub:
761 case Instruction::Mul:
762 case Instruction::Shl:
763 case Instruction::AShr:
764 case Instruction::LShr:
765 case Instruction::GetElementPtr:
766 case Instruction::Trunc:
767 case Instruction::ZExt:
768 case Instruction::SExt:
769 return true;
770 }
771 }
772 return false;
773}
774
775static bool isLoopIncrement(User *U, Instruction *IV) {
776 BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
Lawrence Hud3d51062016-01-25 19:43:45 +0000777
778 if ((BO && BO->getOpcode() != Instruction::Add) ||
779 (!BO && !isa<GetElementPtrInst>(U)))
James Molloyf1473592015-02-11 09:19:47 +0000780 return false;
781
Lawrence Hud3d51062016-01-25 19:43:45 +0000782 for (auto *UU : U->users()) {
James Molloyf1473592015-02-11 09:19:47 +0000783 PHINode *PN = dyn_cast<PHINode>(UU);
784 if (PN && PN == IV)
785 return true;
786 }
787 return false;
788}
789
790bool LoopReroll::DAGRootTracker::
791collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
792 SmallInstructionVector BaseUsers;
793
794 for (auto *I : Base->users()) {
795 ConstantInt *CI = nullptr;
796
797 if (isLoopIncrement(I, IV)) {
798 LoopIncs.push_back(cast<Instruction>(I));
799 continue;
800 }
801
802 // The root nodes must be either GEPs, ORs or ADDs.
803 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
804 if (BO->getOpcode() == Instruction::Add ||
805 BO->getOpcode() == Instruction::Or)
806 CI = dyn_cast<ConstantInt>(BO->getOperand(1));
807 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
808 Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
809 CI = dyn_cast<ConstantInt>(LastOperand);
810 }
811
812 if (!CI) {
813 if (Instruction *II = dyn_cast<Instruction>(I)) {
814 BaseUsers.push_back(II);
815 continue;
816 } else {
817 DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I << "\n");
818 return false;
819 }
820 }
821
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000822 int64_t V = std::abs(CI->getValue().getSExtValue());
James Molloyf1473592015-02-11 09:19:47 +0000823 if (Roots.find(V) != Roots.end())
824 // No duplicates, please.
825 return false;
826
James Molloyf1473592015-02-11 09:19:47 +0000827 Roots[V] = cast<Instruction>(I);
828 }
829
830 if (Roots.empty())
831 return false;
James Molloyf1473592015-02-11 09:19:47 +0000832
833 // If we found non-loop-inc, non-root users of Base, assume they are
834 // for the zeroth root index. This is because "add %a, 0" gets optimized
835 // away.
James Molloye32d8062015-02-16 17:02:00 +0000836 if (BaseUsers.size()) {
837 if (Roots.find(0) != Roots.end()) {
838 DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
839 return false;
840 }
James Molloyf1473592015-02-11 09:19:47 +0000841 Roots[0] = Base;
James Molloye32d8062015-02-16 17:02:00 +0000842 }
James Molloyf1473592015-02-11 09:19:47 +0000843
844 // Calculate the number of users of the base, or lowest indexed, iteration.
845 unsigned NumBaseUses = BaseUsers.size();
846 if (NumBaseUses == 0)
847 NumBaseUses = Roots.begin()->second->getNumUses();
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000848
James Molloyf1473592015-02-11 09:19:47 +0000849 // Check that every node has the same number of users.
850 for (auto &KV : Roots) {
851 if (KV.first == 0)
852 continue;
853 if (KV.second->getNumUses() != NumBaseUses) {
854 DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
855 << "#Base=" << NumBaseUses << ", #Root=" <<
856 KV.second->getNumUses() << "\n");
857 return false;
858 }
859 }
860
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000861 return true;
James Molloyf1473592015-02-11 09:19:47 +0000862}
863
864bool LoopReroll::DAGRootTracker::
865findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
866 // Does the user look like it could be part of a root set?
867 // All its users must be simple arithmetic ops.
868 if (I->getNumUses() > IL_MaxRerollIterations)
869 return false;
870
871 if ((I->getOpcode() == Instruction::Mul ||
872 I->getOpcode() == Instruction::PHI) &&
873 I != IV &&
874 findRootsBase(I, SubsumedInsts))
875 return true;
876
877 SubsumedInsts.insert(I);
878
879 for (User *V : I->users()) {
880 Instruction *I = dyn_cast<Instruction>(V);
881 if (std::find(LoopIncs.begin(), LoopIncs.end(), I) != LoopIncs.end())
882 continue;
883
884 if (!I || !isSimpleArithmeticOp(I) ||
885 !findRootsRecursive(I, SubsumedInsts))
886 return false;
887 }
888 return true;
889}
890
891bool LoopReroll::DAGRootTracker::
892findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
893
894 // The base instruction needs to be a multiply so
895 // that we can erase it.
896 if (IVU->getOpcode() != Instruction::Mul &&
897 IVU->getOpcode() != Instruction::PHI)
898 return false;
899
900 std::map<int64_t, Instruction*> V;
901 if (!collectPossibleRoots(IVU, V))
902 return false;
903
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000904 // If we didn't get a root for index zero, then IVU must be
James Molloyf1473592015-02-11 09:19:47 +0000905 // subsumed.
906 if (V.find(0) == V.end())
907 SubsumedInsts.insert(IVU);
908
909 // Partition the vector into monotonically increasing indexes.
910 DAGRootSet DRS;
911 DRS.BaseInst = nullptr;
912
913 for (auto &KV : V) {
914 if (!DRS.BaseInst) {
915 DRS.BaseInst = KV.second;
916 DRS.SubsumedInsts = SubsumedInsts;
917 } else if (DRS.Roots.empty()) {
918 DRS.Roots.push_back(KV.second);
919 } else if (V.find(KV.first - 1) != V.end()) {
920 DRS.Roots.push_back(KV.second);
921 } else {
922 // Linear sequence terminated.
923 RootSets.push_back(DRS);
924 DRS.BaseInst = KV.second;
925 DRS.SubsumedInsts = SubsumedInsts;
926 DRS.Roots.clear();
927 }
928 }
929 RootSets.push_back(DRS);
930
931 return true;
932}
933
James Molloy5f255eb2015-01-29 13:48:05 +0000934bool LoopReroll::DAGRootTracker::findRoots() {
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000935 Inc = IVToIncMap[IV];
James Molloy5f255eb2015-01-29 13:48:05 +0000936
James Molloyf1473592015-02-11 09:19:47 +0000937 assert(RootSets.empty() && "Unclean state!");
Lawrence Hudc8a83b2015-07-24 22:01:49 +0000938 if (std::abs(Inc) == 1) {
James Molloyf1473592015-02-11 09:19:47 +0000939 for (auto *IVU : IV->users()) {
940 if (isLoopIncrement(IVU, IV))
941 LoopIncs.push_back(cast<Instruction>(IVU));
942 }
943 if (!findRootsRecursive(IV, SmallInstructionSet()))
944 return false;
945 LoopIncs.push_back(IV);
946 } else {
947 if (!findRootsBase(IV, SmallInstructionSet()))
948 return false;
949 }
James Molloy5f255eb2015-01-29 13:48:05 +0000950
James Molloyf1473592015-02-11 09:19:47 +0000951 // Ensure all sets have the same size.
952 if (RootSets.empty()) {
953 DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000954 return false;
James Molloyf1473592015-02-11 09:19:47 +0000955 }
956 for (auto &V : RootSets) {
957 if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
958 DEBUG(dbgs()
959 << "LRR: Aborting because not all root sets have the same size\n");
960 return false;
961 }
962 }
James Molloy5f255eb2015-01-29 13:48:05 +0000963
James Molloyf1473592015-02-11 09:19:47 +0000964 // And ensure all loop iterations are consecutive. We rely on std::map
965 // providing ordered traversal.
966 for (auto &V : RootSets) {
967 const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(V.BaseInst));
968 if (!ADR)
969 return false;
970
971 // Consider a DAGRootSet with N-1 roots (so N different values including
972 // BaseInst).
973 // Define d = Roots[0] - BaseInst, which should be the same as
974 // Roots[I] - Roots[I-1] for all I in [1..N).
975 // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
976 // loop iteration J.
977 //
978 // Now, For the loop iterations to be consecutive:
979 // D = d * N
980
981 unsigned N = V.Roots.size() + 1;
982 const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(V.Roots[0]), ADR);
983 const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
984 if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV)) {
985 DEBUG(dbgs() << "LRR: Aborting because iterations are not consecutive\n");
986 return false;
987 }
988 }
989 Scale = RootSets[0].Roots.size() + 1;
990
991 if (Scale > IL_MaxRerollIterations) {
James Molloy64419d42015-01-29 21:52:03 +0000992 DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
James Molloyf1473592015-02-11 09:19:47 +0000993 << "#Found=" << Scale << ", #Max=" << IL_MaxRerollIterations
James Molloy64419d42015-01-29 21:52:03 +0000994 << "\n");
995 return false;
996 }
997
James Molloyf1473592015-02-11 09:19:47 +0000998 DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +0000999
1000 return true;
1001}
1002
James Molloy64419d42015-01-29 21:52:03 +00001003bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
1004 // Populate the MapVector with all instructions in the block, in order first,
1005 // so we can iterate over the contents later in perfect order.
1006 for (auto &I : *L->getHeader()) {
1007 Uses[&I].resize(IL_End);
1008 }
James Molloy5f255eb2015-01-29 13:48:05 +00001009
James Molloy64419d42015-01-29 21:52:03 +00001010 SmallInstructionSet Exclude;
James Molloyf1473592015-02-11 09:19:47 +00001011 for (auto &DRS : RootSets) {
1012 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1013 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1014 Exclude.insert(DRS.BaseInst);
1015 }
James Molloy64419d42015-01-29 21:52:03 +00001016 Exclude.insert(LoopIncs.begin(), LoopIncs.end());
1017
James Molloyf1473592015-02-11 09:19:47 +00001018 for (auto &DRS : RootSets) {
1019 DenseSet<Instruction*> VBase;
1020 collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
1021 for (auto *I : VBase) {
1022 Uses[I].set(0);
James Molloy64419d42015-01-29 21:52:03 +00001023 }
1024
James Molloyf1473592015-02-11 09:19:47 +00001025 unsigned Idx = 1;
1026 for (auto *Root : DRS.Roots) {
1027 DenseSet<Instruction*> V;
1028 collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
1029
1030 // While we're here, check the use sets are the same size.
1031 if (V.size() != VBase.size()) {
1032 DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
1033 return false;
1034 }
1035
1036 for (auto *I : V) {
1037 Uses[I].set(Idx);
1038 }
1039 ++Idx;
James Molloy64419d42015-01-29 21:52:03 +00001040 }
James Molloyf1473592015-02-11 09:19:47 +00001041
1042 // Make sure our subsumed instructions are remembered too.
1043 for (auto *I : DRS.SubsumedInsts) {
1044 Uses[I].set(IL_All);
1045 }
James Molloy64419d42015-01-29 21:52:03 +00001046 }
1047
1048 // Make sure the loop increments are also accounted for.
James Molloyf1473592015-02-11 09:19:47 +00001049
James Molloy64419d42015-01-29 21:52:03 +00001050 Exclude.clear();
James Molloyf1473592015-02-11 09:19:47 +00001051 for (auto &DRS : RootSets) {
1052 Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
1053 Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
1054 Exclude.insert(DRS.BaseInst);
1055 }
James Molloy64419d42015-01-29 21:52:03 +00001056
1057 DenseSet<Instruction*> V;
1058 collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
1059 for (auto *I : V) {
James Molloyf1473592015-02-11 09:19:47 +00001060 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001061 }
James Molloy64419d42015-01-29 21:52:03 +00001062
1063 return true;
1064
1065}
1066
James Molloye805ad92015-02-12 15:54:14 +00001067/// Get the next instruction in "In" that is a member of set Val.
1068/// Start searching from StartI, and do not return anything in Exclude.
1069/// If StartI is not given, start from In.begin().
James Molloy64419d42015-01-29 21:52:03 +00001070LoopReroll::DAGRootTracker::UsesTy::iterator
1071LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
James Molloye805ad92015-02-12 15:54:14 +00001072 const SmallInstructionSet &Exclude,
1073 UsesTy::iterator *StartI) {
1074 UsesTy::iterator I = StartI ? *StartI : In.begin();
1075 while (I != In.end() && (I->second.test(Val) == 0 ||
1076 Exclude.count(I->first) != 0))
James Molloy64419d42015-01-29 21:52:03 +00001077 ++I;
1078 return I;
1079}
1080
James Molloyf1473592015-02-11 09:19:47 +00001081bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
1082 for (auto &DRS : RootSets) {
1083 if (DRS.BaseInst == I)
1084 return true;
1085 }
1086 return false;
1087}
1088
1089bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
1090 for (auto &DRS : RootSets) {
1091 if (std::find(DRS.Roots.begin(), DRS.Roots.end(), I) != DRS.Roots.end())
1092 return true;
1093 }
1094 return false;
1095}
1096
James Molloye805ad92015-02-12 15:54:14 +00001097/// Return true if instruction I depends on any instruction between
1098/// Start and End.
1099bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
1100 UsesTy::iterator Start,
1101 UsesTy::iterator End) {
1102 for (auto *U : I->users()) {
1103 for (auto It = Start; It != End; ++It)
1104 if (U == It->first)
1105 return true;
1106 }
1107 return false;
1108}
1109
Weiming Zhao310770a2015-09-28 17:03:23 +00001110static bool isIgnorableInst(const Instruction *I) {
1111 if (isa<DbgInfoIntrinsic>(I))
1112 return true;
1113 const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
1114 if (!II)
1115 return false;
1116 switch (II->getIntrinsicID()) {
1117 default:
1118 return false;
1119 case llvm::Intrinsic::annotation:
1120 case Intrinsic::ptr_annotation:
1121 case Intrinsic::var_annotation:
1122 // TODO: the following intrinsics may also be whitelisted:
1123 // lifetime_start, lifetime_end, invariant_start, invariant_end
1124 return true;
1125 }
1126 return false;
1127}
1128
James Molloy64419d42015-01-29 21:52:03 +00001129bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
James Molloy5f255eb2015-01-29 13:48:05 +00001130 // We now need to check for equivalence of the use graph of each root with
1131 // that of the primary induction variable (excluding the roots). Our goal
1132 // here is not to solve the full graph isomorphism problem, but rather to
1133 // catch common cases without a lot of work. As a result, we will assume
1134 // that the relative order of the instructions in each unrolled iteration
1135 // is the same (although we will not make an assumption about how the
1136 // different iterations are intermixed). Note that while the order must be
1137 // the same, the instructions may not be in the same basic block.
James Molloy5f255eb2015-01-29 13:48:05 +00001138
1139 // An array of just the possible reductions for this scale factor. When we
1140 // collect the set of all users of some root instructions, these reduction
1141 // instructions are treated as 'final' (their uses are not considered).
1142 // This is important because we don't want the root use set to search down
1143 // the reduction chain.
1144 SmallInstructionSet PossibleRedSet;
1145 SmallInstructionSet PossibleRedLastSet;
1146 SmallInstructionSet PossibleRedPHISet;
1147 Reductions.restrictToScale(Scale, PossibleRedSet,
1148 PossibleRedPHISet, PossibleRedLastSet);
James Molloy5f255eb2015-01-29 13:48:05 +00001149
James Molloy64419d42015-01-29 21:52:03 +00001150 // Populate "Uses" with where each instruction is used.
1151 if (!collectUsedInstructions(PossibleRedSet))
1152 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001153
James Molloy64419d42015-01-29 21:52:03 +00001154 // Make sure we mark the reduction PHIs as used in all iterations.
1155 for (auto *I : PossibleRedPHISet) {
James Molloyf1473592015-02-11 09:19:47 +00001156 Uses[I].set(IL_All);
James Molloy64419d42015-01-29 21:52:03 +00001157 }
James Molloy5f255eb2015-01-29 13:48:05 +00001158
Lawrence Hu1befea22016-04-30 00:51:22 +00001159 // Make sure we mark loop-control-only PHIs as used in all iterations. See
1160 // comment above LoopReroll::isLoopControlIV for more information.
1161 BasicBlock *Header = L->getHeader();
1162 if (LoopControlIV && LoopControlIV != IV) {
1163 for (auto *U : LoopControlIV->users()) {
1164 Instruction *IVUser = dyn_cast<Instruction>(U);
1165 // IVUser could be loop increment or compare
1166 Uses[IVUser].set(IL_All);
1167 for (auto *UU : IVUser->users()) {
1168 Instruction *UUser = dyn_cast<Instruction>(UU);
1169 // UUser could be compare, PHI or branch
1170 Uses[UUser].set(IL_All);
Lawrence Hue58a8142016-05-10 21:16:49 +00001171 // Skip SExt
1172 if (isa<SExtInst>(UUser)) {
1173 UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
1174 Uses[UUser].set(IL_All);
1175 }
Lawrence Hu1befea22016-04-30 00:51:22 +00001176 // Is UUser a compare instruction?
1177 if (UU->hasOneUse()) {
1178 Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
1179 if (BI == cast<BranchInst>(Header->getTerminator()))
1180 Uses[BI].set(IL_All);
1181 }
1182 }
1183 }
1184 }
1185
James Molloy64419d42015-01-29 21:52:03 +00001186 // Make sure all instructions in the loop are in one and only one
1187 // set.
1188 for (auto &KV : Uses) {
Weiming Zhao310770a2015-09-28 17:03:23 +00001189 if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
James Molloy64419d42015-01-29 21:52:03 +00001190 DEBUG(dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
1191 << *KV.first << " (#uses=" << KV.second.count() << ")\n");
1192 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001193 }
James Molloy64419d42015-01-29 21:52:03 +00001194 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001195
James Molloy64419d42015-01-29 21:52:03 +00001196 DEBUG(
1197 for (auto &KV : Uses) {
1198 dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
1199 }
1200 );
1201
1202 for (unsigned Iter = 1; Iter < Scale; ++Iter) {
James Molloy5f255eb2015-01-29 13:48:05 +00001203 // In addition to regular aliasing information, we need to look for
1204 // instructions from later (future) iterations that have side effects
1205 // preventing us from reordering them past other instructions with side
1206 // effects.
1207 bool FutureSideEffects = false;
1208 AliasSetTracker AST(*AA);
James Molloy5f255eb2015-01-29 13:48:05 +00001209 // The map between instructions in f(%iv.(i+1)) and f(%iv).
1210 DenseMap<Value *, Value *> BaseMap;
1211
James Molloy64419d42015-01-29 21:52:03 +00001212 // Compare iteration Iter to the base.
James Molloye805ad92015-02-12 15:54:14 +00001213 SmallInstructionSet Visited;
1214 auto BaseIt = nextInstr(0, Uses, Visited);
1215 auto RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001216 auto LastRootIt = Uses.begin();
James Molloy5f255eb2015-01-29 13:48:05 +00001217
James Molloy64419d42015-01-29 21:52:03 +00001218 while (BaseIt != Uses.end() && RootIt != Uses.end()) {
1219 Instruction *BaseInst = BaseIt->first;
1220 Instruction *RootInst = RootIt->first;
James Molloy5f255eb2015-01-29 13:48:05 +00001221
James Molloy64419d42015-01-29 21:52:03 +00001222 // Skip over the IV or root instructions; only match their users.
1223 bool Continue = false;
James Molloyf1473592015-02-11 09:19:47 +00001224 if (isBaseInst(BaseInst)) {
James Molloye805ad92015-02-12 15:54:14 +00001225 Visited.insert(BaseInst);
1226 BaseIt = nextInstr(0, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001227 Continue = true;
1228 }
James Molloyf1473592015-02-11 09:19:47 +00001229 if (isRootInst(RootInst)) {
James Molloy64419d42015-01-29 21:52:03 +00001230 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001231 Visited.insert(RootInst);
1232 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy64419d42015-01-29 21:52:03 +00001233 Continue = true;
1234 }
1235 if (Continue) continue;
James Molloy5f255eb2015-01-29 13:48:05 +00001236
James Molloye805ad92015-02-12 15:54:14 +00001237 if (!BaseInst->isSameOperationAs(RootInst)) {
1238 // Last chance saloon. We don't try and solve the full isomorphism
1239 // problem, but try and at least catch the case where two instructions
1240 // *of different types* are round the wrong way. We won't be able to
1241 // efficiently tell, given two ADD instructions, which way around we
1242 // should match them, but given an ADD and a SUB, we can at least infer
1243 // which one is which.
1244 //
1245 // This should allow us to deal with a greater subset of the isomorphism
1246 // problem. It does however change a linear algorithm into a quadratic
1247 // one, so limit the number of probes we do.
1248 auto TryIt = RootIt;
1249 unsigned N = NumToleratedFailedMatches;
1250 while (TryIt != Uses.end() &&
1251 !BaseInst->isSameOperationAs(TryIt->first) &&
1252 N--) {
1253 ++TryIt;
1254 TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
1255 }
1256
1257 if (TryIt == Uses.end() || TryIt == RootIt ||
1258 instrDependsOn(TryIt->first, RootIt, TryIt)) {
1259 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1260 " vs. " << *RootInst << "\n");
1261 return false;
1262 }
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001263
James Molloye805ad92015-02-12 15:54:14 +00001264 RootIt = TryIt;
1265 RootInst = TryIt->first;
1266 }
1267
James Molloy64419d42015-01-29 21:52:03 +00001268 // All instructions between the last root and this root
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001269 // may belong to some other iteration. If they belong to a
James Molloy64419d42015-01-29 21:52:03 +00001270 // future iteration, then they're dangerous to alias with.
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001271 //
James Molloye805ad92015-02-12 15:54:14 +00001272 // Note that because we allow a limited amount of flexibility in the order
1273 // that we visit nodes, LastRootIt might be *before* RootIt, in which
1274 // case we've already checked this set of instructions so we shouldn't
1275 // do anything.
1276 for (; LastRootIt < RootIt; ++LastRootIt) {
James Molloy64419d42015-01-29 21:52:03 +00001277 Instruction *I = LastRootIt->first;
1278 if (LastRootIt->second.find_first() < (int)Iter)
1279 continue;
1280 if (I->mayWriteToMemory())
1281 AST.add(I);
1282 // Note: This is specifically guarded by a check on isa<PHINode>,
1283 // which while a valid (somewhat arbitrary) micro-optimization, is
1284 // needed because otherwise isSafeToSpeculativelyExecute returns
1285 // false on PHI nodes.
1286 if (!isa<PHINode>(I) && !isSimpleLoadStore(I) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001287 !isSafeToSpeculativelyExecute(I))
James Molloy64419d42015-01-29 21:52:03 +00001288 // Intervening instructions cause side effects.
1289 FutureSideEffects = true;
James Molloy5f255eb2015-01-29 13:48:05 +00001290 }
1291
James Molloy5f255eb2015-01-29 13:48:05 +00001292 // Make sure that this instruction, which is in the use set of this
1293 // root instruction, does not also belong to the base set or the set of
James Molloy64419d42015-01-29 21:52:03 +00001294 // some other root instruction.
1295 if (RootIt->second.count() > 1) {
1296 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1297 " vs. " << *RootInst << " (prev. case overlap)\n");
1298 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001299 }
1300
1301 // Make sure that we don't alias with any instruction in the alias set
1302 // tracker. If we do, then we depend on a future iteration, and we
1303 // can't reroll.
James Molloy64419d42015-01-29 21:52:03 +00001304 if (RootInst->mayReadFromMemory())
1305 for (auto &K : AST) {
1306 if (K.aliasesUnknownInst(RootInst, *AA)) {
1307 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1308 " vs. " << *RootInst << " (depends on future store)\n");
1309 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001310 }
1311 }
James Molloy5f255eb2015-01-29 13:48:05 +00001312
1313 // If we've past an instruction from a future iteration that may have
1314 // side effects, and this instruction might also, then we can't reorder
1315 // them, and this matching fails. As an exception, we allow the alias
1316 // set tracker to handle regular (simple) load/store dependencies.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001317 if (FutureSideEffects && ((!isSimpleLoadStore(BaseInst) &&
1318 !isSafeToSpeculativelyExecute(BaseInst)) ||
1319 (!isSimpleLoadStore(RootInst) &&
1320 !isSafeToSpeculativelyExecute(RootInst)))) {
James Molloy64419d42015-01-29 21:52:03 +00001321 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1322 " vs. " << *RootInst <<
James Molloy5f255eb2015-01-29 13:48:05 +00001323 " (side effects prevent reordering)\n");
James Molloy64419d42015-01-29 21:52:03 +00001324 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001325 }
1326
1327 // For instructions that are part of a reduction, if the operation is
1328 // associative, then don't bother matching the operands (because we
1329 // already know that the instructions are isomorphic, and the order
1330 // within the iteration does not matter). For non-associative reductions,
1331 // we do need to match the operands, because we need to reject
1332 // out-of-order instructions within an iteration!
1333 // For example (assume floating-point addition), we need to reject this:
1334 // x += a[i]; x += b[i];
1335 // x += a[i+1]; x += b[i+1];
1336 // x += b[i+2]; x += a[i+2];
James Molloy64419d42015-01-29 21:52:03 +00001337 bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
James Molloy5f255eb2015-01-29 13:48:05 +00001338
James Molloy64419d42015-01-29 21:52:03 +00001339 if (!(InReduction && BaseInst->isAssociative())) {
James Molloy5f255eb2015-01-29 13:48:05 +00001340 bool Swapped = false, SomeOpMatched = false;
James Molloy64419d42015-01-29 21:52:03 +00001341 for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
1342 Value *Op2 = RootInst->getOperand(j);
James Molloy5f255eb2015-01-29 13:48:05 +00001343
1344 // If this is part of a reduction (and the operation is not
1345 // associatve), then we match all operands, but not those that are
1346 // part of the reduction.
1347 if (InReduction)
1348 if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
James Molloy64419d42015-01-29 21:52:03 +00001349 if (Reductions.isPairInSame(RootInst, Op2I))
James Molloy5f255eb2015-01-29 13:48:05 +00001350 continue;
1351
1352 DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
James Molloyf1473592015-02-11 09:19:47 +00001353 if (BMI != BaseMap.end()) {
James Molloy5f255eb2015-01-29 13:48:05 +00001354 Op2 = BMI->second;
James Molloyf1473592015-02-11 09:19:47 +00001355 } else {
1356 for (auto &DRS : RootSets) {
1357 if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
1358 Op2 = DRS.BaseInst;
1359 break;
1360 }
1361 }
1362 }
James Molloy5f255eb2015-01-29 13:48:05 +00001363
James Molloy64419d42015-01-29 21:52:03 +00001364 if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001365 // If we've not already decided to swap the matched operands, and
1366 // we've not already matched our first operand (note that we could
1367 // have skipped matching the first operand because it is part of a
1368 // reduction above), and the instruction is commutative, then try
1369 // the swapped match.
James Molloy64419d42015-01-29 21:52:03 +00001370 if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
1371 BaseInst->getOperand(!j) == Op2) {
James Molloy5f255eb2015-01-29 13:48:05 +00001372 Swapped = true;
1373 } else {
James Molloy64419d42015-01-29 21:52:03 +00001374 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
1375 << " vs. " << *RootInst << " (operand " << j << ")\n");
1376 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001377 }
1378 }
1379
1380 SomeOpMatched = true;
1381 }
1382 }
1383
James Molloy64419d42015-01-29 21:52:03 +00001384 if ((!PossibleRedLastSet.count(BaseInst) &&
1385 hasUsesOutsideLoop(BaseInst, L)) ||
1386 (!PossibleRedLastSet.count(RootInst) &&
1387 hasUsesOutsideLoop(RootInst, L))) {
1388 DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst <<
1389 " vs. " << *RootInst << " (uses outside loop)\n");
1390 return false;
James Molloy5f255eb2015-01-29 13:48:05 +00001391 }
1392
James Molloy64419d42015-01-29 21:52:03 +00001393 Reductions.recordPair(BaseInst, RootInst, Iter);
1394 BaseMap.insert(std::make_pair(RootInst, BaseInst));
James Molloy5f255eb2015-01-29 13:48:05 +00001395
James Molloy64419d42015-01-29 21:52:03 +00001396 LastRootIt = RootIt;
James Molloye805ad92015-02-12 15:54:14 +00001397 Visited.insert(BaseInst);
1398 Visited.insert(RootInst);
1399 BaseIt = nextInstr(0, Uses, Visited);
1400 RootIt = nextInstr(Iter, Uses, Visited);
James Molloy5f255eb2015-01-29 13:48:05 +00001401 }
James Molloy64419d42015-01-29 21:52:03 +00001402 assert (BaseIt == Uses.end() && RootIt == Uses.end() &&
1403 "Mismatched set sizes!");
James Molloy5f255eb2015-01-29 13:48:05 +00001404 }
1405
James Molloy5f255eb2015-01-29 13:48:05 +00001406 DEBUG(dbgs() << "LRR: Matched all iteration increments for " <<
James Molloyf1473592015-02-11 09:19:47 +00001407 *IV << "\n");
James Molloy5f255eb2015-01-29 13:48:05 +00001408
Hal Finkelbf45efd2013-11-16 23:59:05 +00001409 return true;
1410}
1411
James Molloy5f255eb2015-01-29 13:48:05 +00001412void LoopReroll::DAGRootTracker::replace(const SCEV *IterCount) {
1413 BasicBlock *Header = L->getHeader();
1414 // Remove instructions associated with non-base iterations.
1415 for (BasicBlock::reverse_iterator J = Header->rbegin();
1416 J != Header->rend();) {
James Molloy64419d42015-01-29 21:52:03 +00001417 unsigned I = Uses[&*J].find_first();
James Molloyf1473592015-02-11 09:19:47 +00001418 if (I > 0 && I < IL_All) {
James Molloy5f255eb2015-01-29 13:48:05 +00001419 Instruction *D = &*J;
1420 DEBUG(dbgs() << "LRR: removing: " << *D << "\n");
1421 D->eraseFromParent();
1422 continue;
1423 }
1424
1425 ++J;
1426 }
1427
Lawrence Hu1befea22016-04-30 00:51:22 +00001428 bool HasTwoIVs = LoopControlIV && LoopControlIV != IV;
1429
1430 if (HasTwoIVs) {
1431 updateNonLoopCtrlIncr();
1432 replaceIV(LoopControlIV, LoopControlIV, IterCount);
1433 } else
1434 // We need to create a new induction variable for each different BaseInst.
1435 for (auto &DRS : RootSets)
1436 // Insert the new induction variable.
1437 replaceIV(DRS.BaseInst, IV, IterCount);
Lawrence Hub917cd92016-01-25 19:36:30 +00001438
1439 SimplifyInstructionsInBlock(Header, TLI);
1440 DeleteDeadPHIs(Header, TLI);
Lawrence Hu84b61952016-01-25 18:53:39 +00001441}
1442
Lawrence Hu1befea22016-04-30 00:51:22 +00001443// For non-loop-control IVs, we only need to update the last increment
1444// with right amount, then we are done.
1445void LoopReroll::DAGRootTracker::updateNonLoopCtrlIncr() {
1446 const SCEV *NewInc = nullptr;
1447 for (auto *LoopInc : LoopIncs) {
1448 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LoopInc);
1449 const SCEVConstant *COp = nullptr;
1450 if (GEP && LoopInc->getOperand(0)->getType()->isPointerTy()) {
1451 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1452 } else {
1453 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(0)));
1454 if (!COp)
1455 COp = dyn_cast<SCEVConstant>(SE->getSCEV(LoopInc->getOperand(1)));
1456 }
1457
1458 assert(COp && "Didn't find constant operand of LoopInc!\n");
1459
1460 const APInt &AInt = COp->getValue()->getValue();
1461 const SCEV *ScaleSCEV = SE->getConstant(COp->getType(), Scale);
1462 if (AInt.isNegative()) {
1463 NewInc = SE->getNegativeSCEV(COp);
1464 NewInc = SE->getUDivExpr(NewInc, ScaleSCEV);
1465 NewInc = SE->getNegativeSCEV(NewInc);
1466 } else
1467 NewInc = SE->getUDivExpr(COp, ScaleSCEV);
1468
1469 LoopInc->setOperand(1, dyn_cast<SCEVConstant>(NewInc)->getValue());
1470 }
1471}
1472
Lawrence Hud3d51062016-01-25 19:43:45 +00001473void LoopReroll::DAGRootTracker::replaceIV(Instruction *Inst,
1474 Instruction *InstIV,
1475 const SCEV *IterCount) {
1476 BasicBlock *Header = L->getHeader();
1477 int64_t Inc = IVToIncMap[InstIV];
Lawrence Hu1befea22016-04-30 00:51:22 +00001478 bool NeedNewIV = InstIV == LoopControlIV;
1479 bool Negative = !NeedNewIV && Inc < 0;
Lawrence Hud3d51062016-01-25 19:43:45 +00001480
1481 const SCEVAddRecExpr *RealIVSCEV = cast<SCEVAddRecExpr>(SE->getSCEV(Inst));
1482 const SCEV *Start = RealIVSCEV->getStart();
1483
Lawrence Hu1befea22016-04-30 00:51:22 +00001484 if (NeedNewIV)
1485 Start = SE->getConstant(Start->getType(), 0);
1486
Lawrence Hud3d51062016-01-25 19:43:45 +00001487 const SCEV *SizeOfExpr = nullptr;
1488 const SCEV *IncrExpr =
1489 SE->getConstant(RealIVSCEV->getType(), Negative ? -1 : 1);
1490 if (auto *PTy = dyn_cast<PointerType>(Inst->getType())) {
1491 Type *ElTy = PTy->getElementType();
1492 SizeOfExpr =
1493 SE->getSizeOfExpr(SE->getEffectiveSCEVType(Inst->getType()), ElTy);
1494 IncrExpr = SE->getMulExpr(IncrExpr, SizeOfExpr);
1495 }
1496 const SCEV *NewIVSCEV =
1497 SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
1498
1499 { // Limit the lifetime of SCEVExpander.
1500 const DataLayout &DL = Header->getModule()->getDataLayout();
1501 SCEVExpander Expander(*SE, DL, "reroll");
1502 Value *NewIV =
1503 Expander.expandCodeFor(NewIVSCEV, InstIV->getType(), &Header->front());
1504
1505 for (auto &KV : Uses)
1506 if (KV.second.find_first() == 0)
1507 KV.first->replaceUsesOfWith(Inst, NewIV);
1508
1509 if (BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator())) {
1510 // FIXME: Why do we need this check?
1511 if (Uses[BI].find_first() == IL_All) {
1512 const SCEV *ICSCEV = RealIVSCEV->evaluateAtIteration(IterCount, *SE);
1513
Lawrence Hu1befea22016-04-30 00:51:22 +00001514 if (NeedNewIV)
1515 ICSCEV = SE->getMulExpr(IterCount,
1516 SE->getConstant(IterCount->getType(), Scale));
Lawrence Hu1befea22016-04-30 00:51:22 +00001517
Lawrence Hud3d51062016-01-25 19:43:45 +00001518 // Iteration count SCEV minus or plus 1
1519 const SCEV *MinusPlus1SCEV =
1520 SE->getConstant(ICSCEV->getType(), Negative ? -1 : 1);
1521 if (Inst->getType()->isPointerTy()) {
1522 assert(SizeOfExpr && "SizeOfExpr is not initialized");
1523 MinusPlus1SCEV = SE->getMulExpr(MinusPlus1SCEV, SizeOfExpr);
1524 }
1525
1526 const SCEV *ICMinusPlus1SCEV = SE->getMinusSCEV(ICSCEV, MinusPlus1SCEV);
1527 // Iteration count minus 1
Lawrence Hue58a8142016-05-10 21:16:49 +00001528 Instruction *InsertPtr = nullptr;
Lawrence Hud3d51062016-01-25 19:43:45 +00001529 if (isa<SCEVConstant>(ICMinusPlus1SCEV)) {
Lawrence Hue58a8142016-05-10 21:16:49 +00001530 InsertPtr = BI;
Lawrence Hud3d51062016-01-25 19:43:45 +00001531 } else {
1532 BasicBlock *Preheader = L->getLoopPreheader();
1533 if (!Preheader)
1534 Preheader = InsertPreheaderForLoop(L, DT, LI, PreserveLCSSA);
Lawrence Hue58a8142016-05-10 21:16:49 +00001535 InsertPtr = Preheader->getTerminator();
Lawrence Hud3d51062016-01-25 19:43:45 +00001536 }
1537
Lawrence Hue58a8142016-05-10 21:16:49 +00001538 if (!isa<PointerType>(NewIV->getType()) && NeedNewIV &&
1539 (SE->getTypeSizeInBits(NewIV->getType()) <
1540 SE->getTypeSizeInBits(ICMinusPlus1SCEV->getType()))) {
1541 IRBuilder<> Builder(BI);
1542 Builder.SetCurrentDebugLocation(BI->getDebugLoc());
1543 NewIV = Builder.CreateSExt(NewIV, ICMinusPlus1SCEV->getType());
1544 }
1545 Value *ICMinusPlus1 = Expander.expandCodeFor(
1546 ICMinusPlus1SCEV, NewIV->getType(), InsertPtr);
1547
Lawrence Hud3d51062016-01-25 19:43:45 +00001548 Value *Cond =
1549 new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, ICMinusPlus1, "exitcond");
1550 BI->setCondition(Cond);
1551
1552 if (BI->getSuccessor(1) != Header)
1553 BI->swapSuccessors();
1554 }
1555 }
1556 }
1557}
1558
Hal Finkelbf45efd2013-11-16 23:59:05 +00001559// Validate the selected reductions. All iterations must have an isomorphic
1560// part of the reduction chain and, for non-associative reductions, the chain
1561// entries must appear in order.
1562bool LoopReroll::ReductionTracker::validateSelected() {
1563 // For a non-associative reduction, the chain entries must appear in order.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001564 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001565 int PrevIter = 0, BaseCount = 0, Count = 0;
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001566 for (Instruction *J : PossibleReds[i]) {
1567 // Note that all instructions in the chain must have been found because
1568 // all instructions in the function must have been assigned to some
1569 // iteration.
1570 int Iter = PossibleRedIter[J];
Hal Finkelbf45efd2013-11-16 23:59:05 +00001571 if (Iter != PrevIter && Iter != PrevIter + 1 &&
1572 !PossibleReds[i].getReducedValue()->isAssociative()) {
1573 DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: " <<
NAKAMURA Takumi5af50a52014-10-28 11:54:05 +00001574 J << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001575 return false;
1576 }
1577
1578 if (Iter != PrevIter) {
1579 if (Count != BaseCount) {
1580 DEBUG(dbgs() << "LRR: Iteration " << PrevIter <<
1581 " reduction use count " << Count <<
1582 " is not equal to the base use count " <<
1583 BaseCount << "\n");
1584 return false;
1585 }
1586
1587 Count = 0;
1588 }
1589
1590 ++Count;
1591 if (Iter == 0)
1592 ++BaseCount;
1593
1594 PrevIter = Iter;
1595 }
1596 }
1597
1598 return true;
1599}
1600
1601// For all selected reductions, remove all parts except those in the first
1602// iteration (and the PHI). Replace outside uses of the reduced value with uses
1603// of the first-iteration reduced value (in other words, reroll the selected
1604// reductions).
1605void LoopReroll::ReductionTracker::replaceSelected() {
1606 // Fixup reductions to refer to the last instruction associated with the
1607 // first iteration (not the last).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001608 for (int i : Reds) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001609 int j = 0;
1610 for (int e = PossibleReds[i].size(); j != e; ++j)
1611 if (PossibleRedIter[PossibleReds[i][j]] != 0) {
1612 --j;
1613 break;
1614 }
1615
1616 // Replace users with the new end-of-chain value.
1617 SmallInstructionVector Users;
James Molloy64419d42015-01-29 21:52:03 +00001618 for (User *U : PossibleReds[i].getReducedValue()->users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001619 Users.push_back(cast<Instruction>(U));
James Molloy64419d42015-01-29 21:52:03 +00001620 }
Hal Finkelbf45efd2013-11-16 23:59:05 +00001621
Benjamin Kramer135f7352016-06-26 12:28:59 +00001622 for (Instruction *User : Users)
1623 User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
Hal Finkelbf45efd2013-11-16 23:59:05 +00001624 PossibleReds[i][j]);
1625 }
1626}
1627
1628// Reroll the provided loop with respect to the provided induction variable.
1629// Generally, we're looking for a loop like this:
1630//
1631// %iv = phi [ (preheader, ...), (body, %iv.next) ]
1632// f(%iv)
1633// %iv.1 = add %iv, 1 <-- a root increment
1634// f(%iv.1)
1635// %iv.2 = add %iv, 2 <-- a root increment
1636// f(%iv.2)
1637// %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
1638// f(%iv.scale_m_1)
1639// ...
1640// %iv.next = add %iv, scale
1641// %cmp = icmp(%iv, ...)
1642// br %cmp, header, exit
1643//
1644// Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
1645// instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
1646// be intermixed with eachother. The restriction imposed by this algorithm is
1647// that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
1648// etc. be the same.
1649//
1650// First, we collect the use set of %iv, excluding the other increment roots.
1651// This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
1652// times, having collected the use set of f(%iv.(i+1)), during which we:
1653// - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
1654// the next unmatched instruction in f(%iv.(i+1)).
1655// - Ensure that both matched instructions don't have any external users
1656// (with the exception of last-in-chain reduction instructions).
1657// - Track the (aliasing) write set, and other side effects, of all
1658// instructions that belong to future iterations that come before the matched
1659// instructions. If the matched instructions read from that write set, then
1660// f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
1661// f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
1662// if any of these future instructions had side effects (could not be
1663// speculatively executed), and so do the matched instructions, when we
1664// cannot reorder those side-effect-producing instructions, and rerolling
1665// fails.
1666//
1667// Finally, we make sure that all loop instructions are either loop increment
1668// roots, belong to simple latch code, parts of validated reductions, part of
1669// f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
1670// have been validated), then we reroll the loop.
1671bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
1672 const SCEV *IterCount,
1673 ReductionTracker &Reductions) {
Justin Bogner843fb202015-12-15 19:40:57 +00001674 DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
Lawrence Hu1befea22016-04-30 00:51:22 +00001675 IVToIncMap, LoopControlIV);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001676
James Molloy5f255eb2015-01-29 13:48:05 +00001677 if (!DAGRoots.findRoots())
Hal Finkelbf45efd2013-11-16 23:59:05 +00001678 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001679 DEBUG(dbgs() << "LRR: Found all root induction increments for: " <<
James Molloy5f255eb2015-01-29 13:48:05 +00001680 *IV << "\n");
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001681
James Molloy5f255eb2015-01-29 13:48:05 +00001682 if (!DAGRoots.validate(Reductions))
Hal Finkelbf45efd2013-11-16 23:59:05 +00001683 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001684 if (!Reductions.validateSelected())
1685 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001686 // At this point, we've validated the rerolling, and we're committed to
1687 // making changes!
1688
1689 Reductions.replaceSelected();
James Molloy5f255eb2015-01-29 13:48:05 +00001690 DAGRoots.replace(IterCount);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001691
Hal Finkelbf45efd2013-11-16 23:59:05 +00001692 ++NumRerolledLoops;
1693 return true;
1694}
1695
1696bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001697 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001698 return false;
1699
Chandler Carruth7b560d42015-09-09 17:55:00 +00001700 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001701 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00001702 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001703 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruth73523022014-01-13 13:07:17 +00001704 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Justin Bogner843fb202015-12-15 19:40:57 +00001705 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Hal Finkelbf45efd2013-11-16 23:59:05 +00001706
1707 BasicBlock *Header = L->getHeader();
1708 DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() <<
1709 "] Loop %" << Header->getName() << " (" <<
1710 L->getNumBlocks() << " block(s))\n");
1711
Hal Finkelbf45efd2013-11-16 23:59:05 +00001712 // For now, we'll handle only single BB loops.
1713 if (L->getNumBlocks() > 1)
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001714 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001715
1716 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001717 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001718
1719 const SCEV *LIBETC = SE->getBackedgeTakenCount(L);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001720 const SCEV *IterCount = SE->getAddExpr(LIBETC, SE->getOne(LIBETC->getType()));
Lawrence Hue58a8142016-05-10 21:16:49 +00001721 DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001722 DEBUG(dbgs() << "LRR: iteration count = " << *IterCount << "\n");
1723
1724 // First, we need to find the induction variable with respect to which we can
1725 // reroll (there may be several possible options).
1726 SmallInstructionVector PossibleIVs;
Lawrence Hudc8a83b2015-07-24 22:01:49 +00001727 IVToIncMap.clear();
Lawrence Hu1befea22016-04-30 00:51:22 +00001728 LoopControlIV = nullptr;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001729 collectPossibleIVs(L, PossibleIVs);
1730
1731 if (PossibleIVs.empty()) {
1732 DEBUG(dbgs() << "LRR: No possible IVs found\n");
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001733 return false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001734 }
1735
1736 ReductionTracker Reductions;
1737 collectPossibleReductions(L, Reductions);
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001738 bool Changed = false;
Hal Finkelbf45efd2013-11-16 23:59:05 +00001739
1740 // For each possible IV, collect the associated possible set of 'root' nodes
1741 // (i+1, i+2, etc.).
Benjamin Kramer135f7352016-06-26 12:28:59 +00001742 for (Instruction *PossibleIV : PossibleIVs)
1743 if (reroll(PossibleIV, L, Header, IterCount, Reductions)) {
Hal Finkelbf45efd2013-11-16 23:59:05 +00001744 Changed = true;
1745 break;
1746 }
Lawrence Hue58a8142016-05-10 21:16:49 +00001747 DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
Hal Finkelbf45efd2013-11-16 23:59:05 +00001748
Zinovy Nis07ac2bd2016-03-22 13:50:57 +00001749 // Trip count of L has changed so SE must be re-evaluated.
1750 if (Changed)
1751 SE->forgetLoop(L);
1752
Hal Finkelbf45efd2013-11-16 23:59:05 +00001753 return Changed;
1754}