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