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