1 //===- LoopInterchange.cpp - Loop interchange 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 handles loop interchange transform. 10 // This pass interchanges loops to provide a more cache-friendly memory access 11 // patterns. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Analysis/DependenceAnalysis.h" 20 #include "llvm/Analysis/LoopInfo.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/Analysis/ScalarEvolution.h" 24 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/InstrTypes.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/User.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/InitializePasses.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Transforms/Scalar.h" 44 #include "llvm/Transforms/Utils.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include "llvm/Transforms/Utils/LoopUtils.h" 47 #include <cassert> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "loop-interchange" 54 55 STATISTIC(LoopsInterchanged, "Number of loops interchanged"); 56 57 static cl::opt<int> LoopInterchangeCostThreshold( 58 "loop-interchange-threshold", cl::init(0), cl::Hidden, 59 cl::desc("Interchange if you gain more than this number")); 60 61 namespace { 62 63 using LoopVector = SmallVector<Loop *, 8>; 64 65 // TODO: Check if we can use a sparse matrix here. 66 using CharMatrix = std::vector<std::vector<char>>; 67 68 } // end anonymous namespace 69 70 // Maximum number of dependencies that can be handled in the dependency matrix. 71 static const unsigned MaxMemInstrCount = 100; 72 73 // Maximum loop depth supported. 74 static const unsigned MaxLoopNestDepth = 10; 75 76 #ifdef DUMP_DEP_MATRICIES 77 static void printDepMatrix(CharMatrix &DepMatrix) { 78 for (auto &Row : DepMatrix) { 79 for (auto D : Row) 80 LLVM_DEBUG(dbgs() << D << " "); 81 LLVM_DEBUG(dbgs() << "\n"); 82 } 83 } 84 #endif 85 86 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, 87 Loop *L, DependenceInfo *DI) { 88 using ValueVector = SmallVector<Value *, 16>; 89 90 ValueVector MemInstr; 91 92 // For each block. 93 for (BasicBlock *BB : L->blocks()) { 94 // Scan the BB and collect legal loads and stores. 95 for (Instruction &I : *BB) { 96 if (!isa<Instruction>(I)) 97 return false; 98 if (auto *Ld = dyn_cast<LoadInst>(&I)) { 99 if (!Ld->isSimple()) 100 return false; 101 MemInstr.push_back(&I); 102 } else if (auto *St = dyn_cast<StoreInst>(&I)) { 103 if (!St->isSimple()) 104 return false; 105 MemInstr.push_back(&I); 106 } 107 } 108 } 109 110 LLVM_DEBUG(dbgs() << "Found " << MemInstr.size() 111 << " Loads and Stores to analyze\n"); 112 113 ValueVector::iterator I, IE, J, JE; 114 115 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { 116 for (J = I, JE = MemInstr.end(); J != JE; ++J) { 117 std::vector<char> Dep; 118 Instruction *Src = cast<Instruction>(*I); 119 Instruction *Dst = cast<Instruction>(*J); 120 if (Src == Dst) 121 continue; 122 // Ignore Input dependencies. 123 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) 124 continue; 125 // Track Output, Flow, and Anti dependencies. 126 if (auto D = DI->depends(Src, Dst, true)) { 127 assert(D->isOrdered() && "Expected an output, flow or anti dep."); 128 LLVM_DEBUG(StringRef DepType = 129 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; 130 dbgs() << "Found " << DepType 131 << " dependency between Src and Dst\n" 132 << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); 133 unsigned Levels = D->getLevels(); 134 char Direction; 135 for (unsigned II = 1; II <= Levels; ++II) { 136 const SCEV *Distance = D->getDistance(II); 137 const SCEVConstant *SCEVConst = 138 dyn_cast_or_null<SCEVConstant>(Distance); 139 if (SCEVConst) { 140 const ConstantInt *CI = SCEVConst->getValue(); 141 if (CI->isNegative()) 142 Direction = '<'; 143 else if (CI->isZero()) 144 Direction = '='; 145 else 146 Direction = '>'; 147 Dep.push_back(Direction); 148 } else if (D->isScalar(II)) { 149 Direction = 'S'; 150 Dep.push_back(Direction); 151 } else { 152 unsigned Dir = D->getDirection(II); 153 if (Dir == Dependence::DVEntry::LT || 154 Dir == Dependence::DVEntry::LE) 155 Direction = '<'; 156 else if (Dir == Dependence::DVEntry::GT || 157 Dir == Dependence::DVEntry::GE) 158 Direction = '>'; 159 else if (Dir == Dependence::DVEntry::EQ) 160 Direction = '='; 161 else 162 Direction = '*'; 163 Dep.push_back(Direction); 164 } 165 } 166 while (Dep.size() != Level) { 167 Dep.push_back('I'); 168 } 169 170 DepMatrix.push_back(Dep); 171 if (DepMatrix.size() > MaxMemInstrCount) { 172 LLVM_DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount 173 << " dependencies inside loop\n"); 174 return false; 175 } 176 } 177 } 178 } 179 180 return true; 181 } 182 183 // A loop is moved from index 'from' to an index 'to'. Update the Dependence 184 // matrix by exchanging the two columns. 185 static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, 186 unsigned ToIndx) { 187 unsigned numRows = DepMatrix.size(); 188 for (unsigned i = 0; i < numRows; ++i) { 189 char TmpVal = DepMatrix[i][ToIndx]; 190 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; 191 DepMatrix[i][FromIndx] = TmpVal; 192 } 193 } 194 195 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is 196 // '>' 197 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, 198 unsigned Column) { 199 for (unsigned i = 0; i <= Column; ++i) { 200 if (DepMatrix[Row][i] == '<') 201 return false; 202 if (DepMatrix[Row][i] == '>') 203 return true; 204 } 205 // All dependencies were '=','S' or 'I' 206 return false; 207 } 208 209 // Checks if no dependence exist in the dependency matrix in Row before Column. 210 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, 211 unsigned Column) { 212 for (unsigned i = 0; i < Column; ++i) { 213 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' && 214 DepMatrix[Row][i] != 'I') 215 return false; 216 } 217 return true; 218 } 219 220 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, 221 unsigned OuterLoopId, char InnerDep, 222 char OuterDep) { 223 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) 224 return false; 225 226 if (InnerDep == OuterDep) 227 return true; 228 229 // It is legal to interchange if and only if after interchange no row has a 230 // '>' direction as the leftmost non-'='. 231 232 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') 233 return true; 234 235 if (InnerDep == '<') 236 return true; 237 238 if (InnerDep == '>') { 239 // If OuterLoopId represents outermost loop then interchanging will make the 240 // 1st dependency as '>' 241 if (OuterLoopId == 0) 242 return false; 243 244 // If all dependencies before OuterloopId are '=','S'or 'I'. Then 245 // interchanging will result in this row having an outermost non '=' 246 // dependency of '>' 247 if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) 248 return true; 249 } 250 251 return false; 252 } 253 254 // Checks if it is legal to interchange 2 loops. 255 // [Theorem] A permutation of the loops in a perfect nest is legal if and only 256 // if the direction matrix, after the same permutation is applied to its 257 // columns, has no ">" direction as the leftmost non-"=" direction in any row. 258 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, 259 unsigned InnerLoopId, 260 unsigned OuterLoopId) { 261 unsigned NumRows = DepMatrix.size(); 262 // For each row check if it is valid to interchange. 263 for (unsigned Row = 0; Row < NumRows; ++Row) { 264 char InnerDep = DepMatrix[Row][InnerLoopId]; 265 char OuterDep = DepMatrix[Row][OuterLoopId]; 266 if (InnerDep == '*' || OuterDep == '*') 267 return false; 268 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) 269 return false; 270 } 271 return true; 272 } 273 274 static LoopVector populateWorklist(Loop &L) { 275 LLVM_DEBUG(dbgs() << "Calling populateWorklist on Func: " 276 << L.getHeader()->getParent()->getName() << " Loop: %" 277 << L.getHeader()->getName() << '\n'); 278 LoopVector LoopList; 279 Loop *CurrentLoop = &L; 280 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 281 while (!Vec->empty()) { 282 // The current loop has multiple subloops in it hence it is not tightly 283 // nested. 284 // Discard all loops above it added into Worklist. 285 if (Vec->size() != 1) 286 return {}; 287 288 LoopList.push_back(CurrentLoop); 289 CurrentLoop = Vec->front(); 290 Vec = &CurrentLoop->getSubLoops(); 291 } 292 LoopList.push_back(CurrentLoop); 293 return LoopList; 294 } 295 296 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { 297 PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); 298 if (InnerIndexVar) 299 return InnerIndexVar; 300 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) 301 return nullptr; 302 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 303 PHINode *PhiVar = cast<PHINode>(I); 304 Type *PhiTy = PhiVar->getType(); 305 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 306 !PhiTy->isPointerTy()) 307 return nullptr; 308 const SCEVAddRecExpr *AddRec = 309 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); 310 if (!AddRec || !AddRec->isAffine()) 311 continue; 312 const SCEV *Step = AddRec->getStepRecurrence(*SE); 313 if (!isa<SCEVConstant>(Step)) 314 continue; 315 // Found the induction variable. 316 // FIXME: Handle loops with more than one induction variable. Note that, 317 // currently, legality makes sure we have only one induction variable. 318 return PhiVar; 319 } 320 return nullptr; 321 } 322 323 namespace { 324 325 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 326 class LoopInterchangeLegality { 327 public: 328 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 329 OptimizationRemarkEmitter *ORE) 330 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 331 332 /// Check if the loops can be interchanged. 333 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 334 CharMatrix &DepMatrix); 335 336 /// Check if the loop structure is understood. We do not handle triangular 337 /// loops for now. 338 bool isLoopStructureUnderstood(PHINode *InnerInductionVar); 339 340 bool currentLimitations(); 341 342 const SmallPtrSetImpl<PHINode *> &getOuterInnerReductions() const { 343 return OuterInnerReductions; 344 } 345 346 private: 347 bool tightlyNested(Loop *Outer, Loop *Inner); 348 bool containsUnsafeInstructions(BasicBlock *BB); 349 350 /// Discover induction and reduction PHIs in the header of \p L. Induction 351 /// PHIs are added to \p Inductions, reductions are added to 352 /// OuterInnerReductions. When the outer loop is passed, the inner loop needs 353 /// to be passed as \p InnerLoop. 354 bool findInductionAndReductions(Loop *L, 355 SmallVector<PHINode *, 8> &Inductions, 356 Loop *InnerLoop); 357 358 Loop *OuterLoop; 359 Loop *InnerLoop; 360 361 ScalarEvolution *SE; 362 363 /// Interface to emit optimization remarks. 364 OptimizationRemarkEmitter *ORE; 365 366 /// Set of reduction PHIs taking part of a reduction across the inner and 367 /// outer loop. 368 SmallPtrSet<PHINode *, 4> OuterInnerReductions; 369 }; 370 371 /// LoopInterchangeProfitability checks if it is profitable to interchange the 372 /// loop. 373 class LoopInterchangeProfitability { 374 public: 375 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 376 OptimizationRemarkEmitter *ORE) 377 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 378 379 /// Check if the loop interchange is profitable. 380 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 381 CharMatrix &DepMatrix); 382 383 private: 384 int getInstrOrderCost(); 385 386 Loop *OuterLoop; 387 Loop *InnerLoop; 388 389 /// Scev analysis. 390 ScalarEvolution *SE; 391 392 /// Interface to emit optimization remarks. 393 OptimizationRemarkEmitter *ORE; 394 }; 395 396 /// LoopInterchangeTransform interchanges the loop. 397 class LoopInterchangeTransform { 398 public: 399 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 400 LoopInfo *LI, DominatorTree *DT, 401 BasicBlock *LoopNestExit, 402 const LoopInterchangeLegality &LIL) 403 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 404 LoopExit(LoopNestExit), LIL(LIL) {} 405 406 /// Interchange OuterLoop and InnerLoop. 407 bool transform(); 408 void restructureLoops(Loop *NewInner, Loop *NewOuter, 409 BasicBlock *OrigInnerPreHeader, 410 BasicBlock *OrigOuterPreHeader); 411 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 412 413 private: 414 bool adjustLoopLinks(); 415 void adjustLoopPreheaders(); 416 bool adjustLoopBranches(); 417 418 Loop *OuterLoop; 419 Loop *InnerLoop; 420 421 /// Scev analysis. 422 ScalarEvolution *SE; 423 424 LoopInfo *LI; 425 DominatorTree *DT; 426 BasicBlock *LoopExit; 427 428 const LoopInterchangeLegality &LIL; 429 }; 430 431 // Main LoopInterchange Pass. 432 struct LoopInterchange : public LoopPass { 433 static char ID; 434 ScalarEvolution *SE = nullptr; 435 LoopInfo *LI = nullptr; 436 DependenceInfo *DI = nullptr; 437 DominatorTree *DT = nullptr; 438 439 /// Interface to emit optimization remarks. 440 OptimizationRemarkEmitter *ORE; 441 442 LoopInterchange() : LoopPass(ID) { 443 initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); 444 } 445 446 void getAnalysisUsage(AnalysisUsage &AU) const override { 447 AU.addRequired<DependenceAnalysisWrapperPass>(); 448 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 449 450 getLoopAnalysisUsage(AU); 451 } 452 453 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 454 if (skipLoop(L) || L->getParentLoop()) 455 return false; 456 457 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 458 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 459 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 460 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 461 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 462 463 return processLoopList(populateWorklist(*L)); 464 } 465 466 bool isComputableLoopNest(LoopVector LoopList) { 467 for (Loop *L : LoopList) { 468 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 469 if (ExitCountOuter == SE->getCouldNotCompute()) { 470 LLVM_DEBUG(dbgs() << "Couldn't compute backedge count\n"); 471 return false; 472 } 473 if (L->getNumBackEdges() != 1) { 474 LLVM_DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 475 return false; 476 } 477 if (!L->getExitingBlock()) { 478 LLVM_DEBUG(dbgs() << "Loop doesn't have unique exit block\n"); 479 return false; 480 } 481 } 482 return true; 483 } 484 485 unsigned selectLoopForInterchange(const LoopVector &LoopList) { 486 // TODO: Add a better heuristic to select the loop to be interchanged based 487 // on the dependence matrix. Currently we select the innermost loop. 488 return LoopList.size() - 1; 489 } 490 491 bool processLoopList(LoopVector LoopList) { 492 bool Changed = false; 493 unsigned LoopNestDepth = LoopList.size(); 494 if (LoopNestDepth < 2) { 495 LLVM_DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 496 return false; 497 } 498 if (LoopNestDepth > MaxLoopNestDepth) { 499 LLVM_DEBUG(dbgs() << "Cannot handle loops of depth greater than " 500 << MaxLoopNestDepth << "\n"); 501 return false; 502 } 503 if (!isComputableLoopNest(LoopList)) { 504 LLVM_DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); 505 return false; 506 } 507 508 LLVM_DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth 509 << "\n"); 510 511 CharMatrix DependencyMatrix; 512 Loop *OuterMostLoop = *(LoopList.begin()); 513 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, 514 OuterMostLoop, DI)) { 515 LLVM_DEBUG(dbgs() << "Populating dependency matrix failed\n"); 516 return false; 517 } 518 #ifdef DUMP_DEP_MATRICIES 519 LLVM_DEBUG(dbgs() << "Dependence before interchange\n"); 520 printDepMatrix(DependencyMatrix); 521 #endif 522 523 // Get the Outermost loop exit. 524 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock(); 525 if (!LoopNestExit) { 526 LLVM_DEBUG(dbgs() << "OuterMostLoop needs an unique exit block"); 527 return false; 528 } 529 530 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 531 // Move the selected loop outwards to the best possible position. 532 for (unsigned i = SelecLoopId; i > 0; i--) { 533 bool Interchanged = 534 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); 535 if (!Interchanged) 536 return Changed; 537 // Loops interchanged reflect the same in LoopList 538 std::swap(LoopList[i - 1], LoopList[i]); 539 540 // Update the DependencyMatrix 541 interChangeDependencies(DependencyMatrix, i, i - 1); 542 #ifdef DUMP_DEP_MATRICIES 543 LLVM_DEBUG(dbgs() << "Dependence after interchange\n"); 544 printDepMatrix(DependencyMatrix); 545 #endif 546 Changed |= Interchanged; 547 } 548 return Changed; 549 } 550 551 bool processLoop(LoopVector LoopList, unsigned InnerLoopId, 552 unsigned OuterLoopId, BasicBlock *LoopNestExit, 553 std::vector<std::vector<char>> &DependencyMatrix) { 554 LLVM_DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId 555 << " and OuterLoopId = " << OuterLoopId << "\n"); 556 Loop *InnerLoop = LoopList[InnerLoopId]; 557 Loop *OuterLoop = LoopList[OuterLoopId]; 558 559 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, ORE); 560 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 561 LLVM_DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n"); 562 return false; 563 } 564 LLVM_DEBUG(dbgs() << "Loops are legal to interchange\n"); 565 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE); 566 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 567 LLVM_DEBUG(dbgs() << "Interchanging loops not profitable.\n"); 568 return false; 569 } 570 571 ORE->emit([&]() { 572 return OptimizationRemark(DEBUG_TYPE, "Interchanged", 573 InnerLoop->getStartLoc(), 574 InnerLoop->getHeader()) 575 << "Loop interchanged with enclosing loop."; 576 }); 577 578 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, LoopNestExit, 579 LIL); 580 LIT.transform(); 581 LLVM_DEBUG(dbgs() << "Loops interchanged.\n"); 582 LoopsInterchanged++; 583 return true; 584 } 585 }; 586 587 } // end anonymous namespace 588 589 bool LoopInterchangeLegality::containsUnsafeInstructions(BasicBlock *BB) { 590 return any_of(*BB, [](const Instruction &I) { 591 return I.mayHaveSideEffects() || I.mayReadFromMemory(); 592 }); 593 } 594 595 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 596 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 597 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 598 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 599 600 LLVM_DEBUG(dbgs() << "Checking if loops are tightly nested\n"); 601 602 // A perfectly nested loop will not have any branch in between the outer and 603 // inner block i.e. outer header will branch to either inner preheader and 604 // outerloop latch. 605 BranchInst *OuterLoopHeaderBI = 606 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 607 if (!OuterLoopHeaderBI) 608 return false; 609 610 for (BasicBlock *Succ : successors(OuterLoopHeaderBI)) 611 if (Succ != InnerLoopPreHeader && Succ != InnerLoop->getHeader() && 612 Succ != OuterLoopLatch) 613 return false; 614 615 LLVM_DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n"); 616 // We do not have any basic block in between now make sure the outer header 617 // and outer loop latch doesn't contain any unsafe instructions. 618 if (containsUnsafeInstructions(OuterLoopHeader) || 619 containsUnsafeInstructions(OuterLoopLatch)) 620 return false; 621 622 LLVM_DEBUG(dbgs() << "Loops are perfectly nested\n"); 623 // We have a perfect loop nest. 624 return true; 625 } 626 627 bool LoopInterchangeLegality::isLoopStructureUnderstood( 628 PHINode *InnerInduction) { 629 unsigned Num = InnerInduction->getNumOperands(); 630 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 631 for (unsigned i = 0; i < Num; ++i) { 632 Value *Val = InnerInduction->getOperand(i); 633 if (isa<Constant>(Val)) 634 continue; 635 Instruction *I = dyn_cast<Instruction>(Val); 636 if (!I) 637 return false; 638 // TODO: Handle triangular loops. 639 // e.g. for(int i=0;i<N;i++) 640 // for(int j=i;j<N;j++) 641 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 642 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 643 InnerLoopPreheader && 644 !OuterLoop->isLoopInvariant(I)) { 645 return false; 646 } 647 } 648 return true; 649 } 650 651 // If SV is a LCSSA PHI node with a single incoming value, return the incoming 652 // value. 653 static Value *followLCSSA(Value *SV) { 654 PHINode *PHI = dyn_cast<PHINode>(SV); 655 if (!PHI) 656 return SV; 657 658 if (PHI->getNumIncomingValues() != 1) 659 return SV; 660 return followLCSSA(PHI->getIncomingValue(0)); 661 } 662 663 // Check V's users to see if it is involved in a reduction in L. 664 static PHINode *findInnerReductionPhi(Loop *L, Value *V) { 665 for (Value *User : V->users()) { 666 if (PHINode *PHI = dyn_cast<PHINode>(User)) { 667 if (PHI->getNumIncomingValues() == 1) 668 continue; 669 RecurrenceDescriptor RD; 670 if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) 671 return PHI; 672 return nullptr; 673 } 674 } 675 676 return nullptr; 677 } 678 679 bool LoopInterchangeLegality::findInductionAndReductions( 680 Loop *L, SmallVector<PHINode *, 8> &Inductions, Loop *InnerLoop) { 681 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 682 return false; 683 for (PHINode &PHI : L->getHeader()->phis()) { 684 RecurrenceDescriptor RD; 685 InductionDescriptor ID; 686 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) 687 Inductions.push_back(&PHI); 688 else { 689 // PHIs in inner loops need to be part of a reduction in the outer loop, 690 // discovered when checking the PHIs of the outer loop earlier. 691 if (!InnerLoop) { 692 if (OuterInnerReductions.find(&PHI) == OuterInnerReductions.end()) { 693 LLVM_DEBUG(dbgs() << "Inner loop PHI is not part of reductions " 694 "across the outer loop.\n"); 695 return false; 696 } 697 } else { 698 assert(PHI.getNumIncomingValues() == 2 && 699 "Phis in loop header should have exactly 2 incoming values"); 700 // Check if we have a PHI node in the outer loop that has a reduction 701 // result from the inner loop as an incoming value. 702 Value *V = followLCSSA(PHI.getIncomingValueForBlock(L->getLoopLatch())); 703 PHINode *InnerRedPhi = findInnerReductionPhi(InnerLoop, V); 704 if (!InnerRedPhi || 705 !llvm::any_of(InnerRedPhi->incoming_values(), 706 [&PHI](Value *V) { return V == &PHI; })) { 707 LLVM_DEBUG( 708 dbgs() 709 << "Failed to recognize PHI as an induction or reduction.\n"); 710 return false; 711 } 712 OuterInnerReductions.insert(&PHI); 713 OuterInnerReductions.insert(InnerRedPhi); 714 } 715 } 716 } 717 return true; 718 } 719 720 static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { 721 for (PHINode &PHI : Block->phis()) { 722 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 723 if (PHI.getNumIncomingValues() > 1) 724 return false; 725 Instruction *Ins = dyn_cast<Instruction>(PHI.getIncomingValue(0)); 726 if (!Ins) 727 return false; 728 // Incoming value for lcssa phi's in outer loop exit can only be inner loop 729 // exits lcssa phi else it would not be tightly nested. 730 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) 731 return false; 732 } 733 return true; 734 } 735 736 // This function indicates the current limitations in the transform as a result 737 // of which we do not proceed. 738 bool LoopInterchangeLegality::currentLimitations() { 739 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 740 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 741 742 // transform currently expects the loop latches to also be the exiting 743 // blocks. 744 if (InnerLoop->getExitingBlock() != InnerLoopLatch || 745 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() || 746 !isa<BranchInst>(InnerLoopLatch->getTerminator()) || 747 !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) { 748 LLVM_DEBUG( 749 dbgs() << "Loops where the latch is not the exiting block are not" 750 << " supported currently.\n"); 751 ORE->emit([&]() { 752 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch", 753 OuterLoop->getStartLoc(), 754 OuterLoop->getHeader()) 755 << "Loops where the latch is not the exiting block cannot be" 756 " interchange currently."; 757 }); 758 return true; 759 } 760 761 PHINode *InnerInductionVar; 762 SmallVector<PHINode *, 8> Inductions; 763 if (!findInductionAndReductions(OuterLoop, Inductions, InnerLoop)) { 764 LLVM_DEBUG( 765 dbgs() << "Only outer loops with induction or reduction PHI nodes " 766 << "are supported currently.\n"); 767 ORE->emit([&]() { 768 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter", 769 OuterLoop->getStartLoc(), 770 OuterLoop->getHeader()) 771 << "Only outer loops with induction or reduction PHI nodes can be" 772 " interchanged currently."; 773 }); 774 return true; 775 } 776 777 // TODO: Currently we handle only loops with 1 induction variable. 778 if (Inductions.size() != 1) { 779 LLVM_DEBUG(dbgs() << "Loops with more than 1 induction variables are not " 780 << "supported currently.\n"); 781 ORE->emit([&]() { 782 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter", 783 OuterLoop->getStartLoc(), 784 OuterLoop->getHeader()) 785 << "Only outer loops with 1 induction variable can be " 786 "interchanged currently."; 787 }); 788 return true; 789 } 790 791 Inductions.clear(); 792 if (!findInductionAndReductions(InnerLoop, Inductions, nullptr)) { 793 LLVM_DEBUG( 794 dbgs() << "Only inner loops with induction or reduction PHI nodes " 795 << "are supported currently.\n"); 796 ORE->emit([&]() { 797 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner", 798 InnerLoop->getStartLoc(), 799 InnerLoop->getHeader()) 800 << "Only inner loops with induction or reduction PHI nodes can be" 801 " interchange currently."; 802 }); 803 return true; 804 } 805 806 // TODO: Currently we handle only loops with 1 induction variable. 807 if (Inductions.size() != 1) { 808 LLVM_DEBUG( 809 dbgs() << "We currently only support loops with 1 induction variable." 810 << "Failed to interchange due to current limitation\n"); 811 ORE->emit([&]() { 812 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner", 813 InnerLoop->getStartLoc(), 814 InnerLoop->getHeader()) 815 << "Only inner loops with 1 induction variable can be " 816 "interchanged currently."; 817 }); 818 return true; 819 } 820 InnerInductionVar = Inductions.pop_back_val(); 821 822 // TODO: Triangular loops are not handled for now. 823 if (!isLoopStructureUnderstood(InnerInductionVar)) { 824 LLVM_DEBUG(dbgs() << "Loop structure not understood by pass\n"); 825 ORE->emit([&]() { 826 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner", 827 InnerLoop->getStartLoc(), 828 InnerLoop->getHeader()) 829 << "Inner loop structure not understood currently."; 830 }); 831 return true; 832 } 833 834 // TODO: We only handle LCSSA PHI's corresponding to reduction for now. 835 BasicBlock *InnerExit = InnerLoop->getExitBlock(); 836 if (!containsSafePHI(InnerExit, false)) { 837 LLVM_DEBUG( 838 dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n"); 839 ORE->emit([&]() { 840 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner", 841 InnerLoop->getStartLoc(), 842 InnerLoop->getHeader()) 843 << "Only inner loops with LCSSA PHIs can be interchange " 844 "currently."; 845 }); 846 return true; 847 } 848 849 // TODO: Current limitation: Since we split the inner loop latch at the point 850 // were induction variable is incremented (induction.next); We cannot have 851 // more than 1 user of induction.next since it would result in broken code 852 // after split. 853 // e.g. 854 // for(i=0;i<N;i++) { 855 // for(j = 0;j<M;j++) { 856 // A[j+1][i+2] = A[j][i]+k; 857 // } 858 // } 859 Instruction *InnerIndexVarInc = nullptr; 860 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) 861 InnerIndexVarInc = 862 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); 863 else 864 InnerIndexVarInc = 865 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); 866 867 if (!InnerIndexVarInc) { 868 LLVM_DEBUG( 869 dbgs() << "Did not find an instruction to increment the induction " 870 << "variable.\n"); 871 ORE->emit([&]() { 872 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner", 873 InnerLoop->getStartLoc(), 874 InnerLoop->getHeader()) 875 << "The inner loop does not increment the induction variable."; 876 }); 877 return true; 878 } 879 880 // Since we split the inner loop latch on this induction variable. Make sure 881 // we do not have any instruction between the induction variable and branch 882 // instruction. 883 884 bool FoundInduction = false; 885 for (const Instruction &I : 886 llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) { 887 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) || 888 isa<ZExtInst>(I)) 889 continue; 890 891 // We found an instruction. If this is not induction variable then it is not 892 // safe to split this loop latch. 893 if (!I.isIdenticalTo(InnerIndexVarInc)) { 894 LLVM_DEBUG(dbgs() << "Found unsupported instructions between induction " 895 << "variable increment and branch.\n"); 896 ORE->emit([&]() { 897 return OptimizationRemarkMissed( 898 DEBUG_TYPE, "UnsupportedInsBetweenInduction", 899 InnerLoop->getStartLoc(), InnerLoop->getHeader()) 900 << "Found unsupported instruction between induction variable " 901 "increment and branch."; 902 }); 903 return true; 904 } 905 906 FoundInduction = true; 907 break; 908 } 909 // The loop latch ended and we didn't find the induction variable return as 910 // current limitation. 911 if (!FoundInduction) { 912 LLVM_DEBUG(dbgs() << "Did not find the induction variable.\n"); 913 ORE->emit([&]() { 914 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable", 915 InnerLoop->getStartLoc(), 916 InnerLoop->getHeader()) 917 << "Did not find the induction variable."; 918 }); 919 return true; 920 } 921 return false; 922 } 923 924 // We currently support LCSSA PHI nodes in the outer loop exit, if their 925 // incoming values do not come from the outer loop latch or if the 926 // outer loop latch has a single predecessor. In that case, the value will 927 // be available if both the inner and outer loop conditions are true, which 928 // will still be true after interchanging. If we have multiple predecessor, 929 // that may not be the case, e.g. because the outer loop latch may be executed 930 // if the inner loop is not executed. 931 static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { 932 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock(); 933 for (PHINode &PHI : LoopNestExit->phis()) { 934 // FIXME: We currently are not able to detect floating point reductions 935 // and have to use floating point PHIs as a proxy to prevent 936 // interchanging in the presence of floating point reductions. 937 if (PHI.getType()->isFloatingPointTy()) 938 return false; 939 for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) { 940 Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i)); 941 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch()) 942 continue; 943 944 // The incoming value is defined in the outer loop latch. Currently we 945 // only support that in case the outer loop latch has a single predecessor. 946 // This guarantees that the outer loop latch is executed if and only if 947 // the inner loop is executed (because tightlyNested() guarantees that the 948 // outer loop header only branches to the inner loop or the outer loop 949 // latch). 950 // FIXME: We could weaken this logic and allow multiple predecessors, 951 // if the values are produced outside the loop latch. We would need 952 // additional logic to update the PHI nodes in the exit block as 953 // well. 954 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr) 955 return false; 956 } 957 } 958 return true; 959 } 960 961 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 962 unsigned OuterLoopId, 963 CharMatrix &DepMatrix) { 964 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 965 LLVM_DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 966 << " and OuterLoopId = " << OuterLoopId 967 << " due to dependence\n"); 968 ORE->emit([&]() { 969 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence", 970 InnerLoop->getStartLoc(), 971 InnerLoop->getHeader()) 972 << "Cannot interchange loops due to dependences."; 973 }); 974 return false; 975 } 976 // Check if outer and inner loop contain legal instructions only. 977 for (auto *BB : OuterLoop->blocks()) 978 for (Instruction &I : BB->instructionsWithoutDebug()) 979 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 980 // readnone functions do not prevent interchanging. 981 if (CI->doesNotReadMemory()) 982 continue; 983 LLVM_DEBUG( 984 dbgs() << "Loops with call instructions cannot be interchanged " 985 << "safely."); 986 ORE->emit([&]() { 987 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst", 988 CI->getDebugLoc(), 989 CI->getParent()) 990 << "Cannot interchange loops due to call instruction."; 991 }); 992 993 return false; 994 } 995 996 // TODO: The loops could not be interchanged due to current limitations in the 997 // transform module. 998 if (currentLimitations()) { 999 LLVM_DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 1000 return false; 1001 } 1002 1003 // Check if the loops are tightly nested. 1004 if (!tightlyNested(OuterLoop, InnerLoop)) { 1005 LLVM_DEBUG(dbgs() << "Loops not tightly nested\n"); 1006 ORE->emit([&]() { 1007 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested", 1008 InnerLoop->getStartLoc(), 1009 InnerLoop->getHeader()) 1010 << "Cannot interchange loops because they are not tightly " 1011 "nested."; 1012 }); 1013 return false; 1014 } 1015 1016 if (!areLoopExitPHIsSupported(OuterLoop, InnerLoop)) { 1017 LLVM_DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n"); 1018 ORE->emit([&]() { 1019 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", 1020 OuterLoop->getStartLoc(), 1021 OuterLoop->getHeader()) 1022 << "Found unsupported PHI node in loop exit."; 1023 }); 1024 return false; 1025 } 1026 1027 return true; 1028 } 1029 1030 int LoopInterchangeProfitability::getInstrOrderCost() { 1031 unsigned GoodOrder, BadOrder; 1032 BadOrder = GoodOrder = 0; 1033 for (BasicBlock *BB : InnerLoop->blocks()) { 1034 for (Instruction &Ins : *BB) { 1035 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 1036 unsigned NumOp = GEP->getNumOperands(); 1037 bool FoundInnerInduction = false; 1038 bool FoundOuterInduction = false; 1039 for (unsigned i = 0; i < NumOp; ++i) { 1040 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 1041 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 1042 if (!AR) 1043 continue; 1044 1045 // If we find the inner induction after an outer induction e.g. 1046 // for(int i=0;i<N;i++) 1047 // for(int j=0;j<N;j++) 1048 // A[i][j] = A[i-1][j-1]+k; 1049 // then it is a good order. 1050 if (AR->getLoop() == InnerLoop) { 1051 // We found an InnerLoop induction after OuterLoop induction. It is 1052 // a good order. 1053 FoundInnerInduction = true; 1054 if (FoundOuterInduction) { 1055 GoodOrder++; 1056 break; 1057 } 1058 } 1059 // If we find the outer induction after an inner induction e.g. 1060 // for(int i=0;i<N;i++) 1061 // for(int j=0;j<N;j++) 1062 // A[j][i] = A[j-1][i-1]+k; 1063 // then it is a bad order. 1064 if (AR->getLoop() == OuterLoop) { 1065 // We found an OuterLoop induction after InnerLoop induction. It is 1066 // a bad order. 1067 FoundOuterInduction = true; 1068 if (FoundInnerInduction) { 1069 BadOrder++; 1070 break; 1071 } 1072 } 1073 } 1074 } 1075 } 1076 } 1077 return GoodOrder - BadOrder; 1078 } 1079 1080 static bool isProfitableForVectorization(unsigned InnerLoopId, 1081 unsigned OuterLoopId, 1082 CharMatrix &DepMatrix) { 1083 // TODO: Improve this heuristic to catch more cases. 1084 // If the inner loop is loop independent or doesn't carry any dependency it is 1085 // profitable to move this to outer position. 1086 for (auto &Row : DepMatrix) { 1087 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I') 1088 return false; 1089 // TODO: We need to improve this heuristic. 1090 if (Row[OuterLoopId] != '=') 1091 return false; 1092 } 1093 // If outer loop has dependence and inner loop is loop independent then it is 1094 // profitable to interchange to enable parallelism. 1095 // If there are no dependences, interchanging will not improve anything. 1096 return !DepMatrix.empty(); 1097 } 1098 1099 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 1100 unsigned OuterLoopId, 1101 CharMatrix &DepMatrix) { 1102 // TODO: Add better profitability checks. 1103 // e.g 1104 // 1) Construct dependency matrix and move the one with no loop carried dep 1105 // inside to enable vectorization. 1106 1107 // This is rough cost estimation algorithm. It counts the good and bad order 1108 // of induction variables in the instruction and allows reordering if number 1109 // of bad orders is more than good. 1110 int Cost = getInstrOrderCost(); 1111 LLVM_DEBUG(dbgs() << "Cost = " << Cost << "\n"); 1112 if (Cost < -LoopInterchangeCostThreshold) 1113 return true; 1114 1115 // It is not profitable as per current cache profitability model. But check if 1116 // we can move this loop outside to improve parallelism. 1117 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix)) 1118 return true; 1119 1120 ORE->emit([&]() { 1121 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable", 1122 InnerLoop->getStartLoc(), 1123 InnerLoop->getHeader()) 1124 << "Interchanging loops is too costly (cost=" 1125 << ore::NV("Cost", Cost) << ", threshold=" 1126 << ore::NV("Threshold", LoopInterchangeCostThreshold) 1127 << ") and it does not improve parallelism."; 1128 }); 1129 return false; 1130 } 1131 1132 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 1133 Loop *InnerLoop) { 1134 for (Loop *L : *OuterLoop) 1135 if (L == InnerLoop) { 1136 OuterLoop->removeChildLoop(L); 1137 return; 1138 } 1139 llvm_unreachable("Couldn't find loop"); 1140 } 1141 1142 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the 1143 /// new inner and outer loop after interchanging: NewInner is the original 1144 /// outer loop and NewOuter is the original inner loop. 1145 /// 1146 /// Before interchanging, we have the following structure 1147 /// Outer preheader 1148 // Outer header 1149 // Inner preheader 1150 // Inner header 1151 // Inner body 1152 // Inner latch 1153 // outer bbs 1154 // Outer latch 1155 // 1156 // After interchanging: 1157 // Inner preheader 1158 // Inner header 1159 // Outer preheader 1160 // Outer header 1161 // Inner body 1162 // outer bbs 1163 // Outer latch 1164 // Inner latch 1165 void LoopInterchangeTransform::restructureLoops( 1166 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader, 1167 BasicBlock *OrigOuterPreHeader) { 1168 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1169 // The original inner loop preheader moves from the new inner loop to 1170 // the parent loop, if there is one. 1171 NewInner->removeBlockFromLoop(OrigInnerPreHeader); 1172 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent); 1173 1174 // Switch the loop levels. 1175 if (OuterLoopParent) { 1176 // Remove the loop from its parent loop. 1177 removeChildLoop(OuterLoopParent, NewInner); 1178 removeChildLoop(NewInner, NewOuter); 1179 OuterLoopParent->addChildLoop(NewOuter); 1180 } else { 1181 removeChildLoop(NewInner, NewOuter); 1182 LI->changeTopLevelLoop(NewInner, NewOuter); 1183 } 1184 while (!NewOuter->empty()) 1185 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin())); 1186 NewOuter->addChildLoop(NewInner); 1187 1188 // BBs from the original inner loop. 1189 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks()); 1190 1191 // Add BBs from the original outer loop to the original inner loop (excluding 1192 // BBs already in inner loop) 1193 for (BasicBlock *BB : NewInner->blocks()) 1194 if (LI->getLoopFor(BB) == NewInner) 1195 NewOuter->addBlockEntry(BB); 1196 1197 // Now remove inner loop header and latch from the new inner loop and move 1198 // other BBs (the loop body) to the new inner loop. 1199 BasicBlock *OuterHeader = NewOuter->getHeader(); 1200 BasicBlock *OuterLatch = NewOuter->getLoopLatch(); 1201 for (BasicBlock *BB : OrigInnerBBs) { 1202 // Nothing will change for BBs in child loops. 1203 if (LI->getLoopFor(BB) != NewOuter) 1204 continue; 1205 // Remove the new outer loop header and latch from the new inner loop. 1206 if (BB == OuterHeader || BB == OuterLatch) 1207 NewInner->removeBlockFromLoop(BB); 1208 else 1209 LI->changeLoopFor(BB, NewInner); 1210 } 1211 1212 // The preheader of the original outer loop becomes part of the new 1213 // outer loop. 1214 NewOuter->addBlockEntry(OrigOuterPreHeader); 1215 LI->changeLoopFor(OrigOuterPreHeader, NewOuter); 1216 1217 // Tell SE that we move the loops around. 1218 SE->forgetLoop(NewOuter); 1219 SE->forgetLoop(NewInner); 1220 } 1221 1222 bool LoopInterchangeTransform::transform() { 1223 bool Transformed = false; 1224 Instruction *InnerIndexVar; 1225 1226 if (InnerLoop->getSubLoops().empty()) { 1227 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1228 LLVM_DEBUG(dbgs() << "Splitting the inner loop latch\n"); 1229 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); 1230 if (!InductionPHI) { 1231 LLVM_DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1232 return false; 1233 } 1234 1235 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1236 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); 1237 else 1238 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); 1239 1240 // Ensure that InductionPHI is the first Phi node. 1241 if (&InductionPHI->getParent()->front() != InductionPHI) 1242 InductionPHI->moveBefore(&InductionPHI->getParent()->front()); 1243 1244 // Create a new latch block for the inner loop. We split at the 1245 // current latch's terminator and then move the condition and all 1246 // operands that are not either loop-invariant or the induction PHI into the 1247 // new latch block. 1248 BasicBlock *NewLatch = 1249 SplitBlock(InnerLoop->getLoopLatch(), 1250 InnerLoop->getLoopLatch()->getTerminator(), DT, LI); 1251 1252 SmallSetVector<Instruction *, 4> WorkList; 1253 unsigned i = 0; 1254 auto MoveInstructions = [&i, &WorkList, this, InductionPHI, NewLatch]() { 1255 for (; i < WorkList.size(); i++) { 1256 // Duplicate instruction and move it the new latch. Update uses that 1257 // have been moved. 1258 Instruction *NewI = WorkList[i]->clone(); 1259 NewI->insertBefore(NewLatch->getFirstNonPHI()); 1260 assert(!NewI->mayHaveSideEffects() && 1261 "Moving instructions with side-effects may change behavior of " 1262 "the loop nest!"); 1263 for (auto UI = WorkList[i]->use_begin(), UE = WorkList[i]->use_end(); 1264 UI != UE;) { 1265 Use &U = *UI++; 1266 Instruction *UserI = cast<Instruction>(U.getUser()); 1267 if (!InnerLoop->contains(UserI->getParent()) || 1268 UserI->getParent() == NewLatch || UserI == InductionPHI) 1269 U.set(NewI); 1270 } 1271 // Add operands of moved instruction to the worklist, except if they are 1272 // outside the inner loop or are the induction PHI. 1273 for (Value *Op : WorkList[i]->operands()) { 1274 Instruction *OpI = dyn_cast<Instruction>(Op); 1275 if (!OpI || 1276 this->LI->getLoopFor(OpI->getParent()) != this->InnerLoop || 1277 OpI == InductionPHI) 1278 continue; 1279 WorkList.insert(OpI); 1280 } 1281 } 1282 }; 1283 1284 // FIXME: Should we interchange when we have a constant condition? 1285 Instruction *CondI = dyn_cast<Instruction>( 1286 cast<BranchInst>(InnerLoop->getLoopLatch()->getTerminator()) 1287 ->getCondition()); 1288 if (CondI) 1289 WorkList.insert(CondI); 1290 MoveInstructions(); 1291 WorkList.insert(cast<Instruction>(InnerIndexVar)); 1292 MoveInstructions(); 1293 1294 // Splits the inner loops phi nodes out into a separate basic block. 1295 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1296 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1297 LLVM_DEBUG(dbgs() << "splitting InnerLoopHeader done\n"); 1298 } 1299 1300 Transformed |= adjustLoopLinks(); 1301 if (!Transformed) { 1302 LLVM_DEBUG(dbgs() << "adjustLoopLinks failed\n"); 1303 return false; 1304 } 1305 1306 return true; 1307 } 1308 1309 /// \brief Move all instructions except the terminator from FromBB right before 1310 /// InsertBefore 1311 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1312 auto &ToList = InsertBefore->getParent()->getInstList(); 1313 auto &FromList = FromBB->getInstList(); 1314 1315 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1316 FromBB->getTerminator()->getIterator()); 1317 } 1318 1319 // Update BI to jump to NewBB instead of OldBB. Records updates to the 1320 // dominator tree in DTUpdates. If \p MustUpdateOnce is true, assert that 1321 // \p OldBB is exactly once in BI's successor list. 1322 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, 1323 BasicBlock *NewBB, 1324 std::vector<DominatorTree::UpdateType> &DTUpdates, 1325 bool MustUpdateOnce = true) { 1326 assert((!MustUpdateOnce || 1327 llvm::count_if(successors(BI), 1328 [OldBB](BasicBlock *BB) { 1329 return BB == OldBB; 1330 }) == 1) && "BI must jump to OldBB exactly once."); 1331 bool Changed = false; 1332 for (Use &Op : BI->operands()) 1333 if (Op == OldBB) { 1334 Op.set(NewBB); 1335 Changed = true; 1336 } 1337 1338 if (Changed) { 1339 DTUpdates.push_back( 1340 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB}); 1341 DTUpdates.push_back( 1342 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB}); 1343 } 1344 assert(Changed && "Expected a successor to be updated"); 1345 } 1346 1347 // Move Lcssa PHIs to the right place. 1348 static void moveLCSSAPhis(BasicBlock *InnerExit, BasicBlock *InnerHeader, 1349 BasicBlock *InnerLatch, BasicBlock *OuterHeader, 1350 BasicBlock *OuterLatch, BasicBlock *OuterExit, 1351 Loop *InnerLoop, LoopInfo *LI) { 1352 1353 // Deal with LCSSA PHI nodes in the exit block of the inner loop, that are 1354 // defined either in the header or latch. Those blocks will become header and 1355 // latch of the new outer loop, and the only possible users can PHI nodes 1356 // in the exit block of the loop nest or the outer loop header (reduction 1357 // PHIs, in that case, the incoming value must be defined in the inner loop 1358 // header). We can just substitute the user with the incoming value and remove 1359 // the PHI. 1360 for (PHINode &P : make_early_inc_range(InnerExit->phis())) { 1361 assert(P.getNumIncomingValues() == 1 && 1362 "Only loops with a single exit are supported!"); 1363 1364 // Incoming values are guaranteed be instructions currently. 1365 auto IncI = cast<Instruction>(P.getIncomingValueForBlock(InnerLatch)); 1366 // Skip phis with incoming values from the inner loop body, excluding the 1367 // header and latch. 1368 if (IncI->getParent() != InnerLatch && IncI->getParent() != InnerHeader) 1369 continue; 1370 1371 assert(all_of(P.users(), 1372 [OuterHeader, OuterExit, IncI, InnerHeader](User *U) { 1373 return (cast<PHINode>(U)->getParent() == OuterHeader && 1374 IncI->getParent() == InnerHeader) || 1375 cast<PHINode>(U)->getParent() == OuterExit; 1376 }) && 1377 "Can only replace phis iff the uses are in the loop nest exit or " 1378 "the incoming value is defined in the inner header (it will " 1379 "dominate all loop blocks after interchanging)"); 1380 P.replaceAllUsesWith(IncI); 1381 P.eraseFromParent(); 1382 } 1383 1384 SmallVector<PHINode *, 8> LcssaInnerExit; 1385 for (PHINode &P : InnerExit->phis()) 1386 LcssaInnerExit.push_back(&P); 1387 1388 SmallVector<PHINode *, 8> LcssaInnerLatch; 1389 for (PHINode &P : InnerLatch->phis()) 1390 LcssaInnerLatch.push_back(&P); 1391 1392 // Lcssa PHIs for values used outside the inner loop are in InnerExit. 1393 // If a PHI node has users outside of InnerExit, it has a use outside the 1394 // interchanged loop and we have to preserve it. We move these to 1395 // InnerLatch, which will become the new exit block for the innermost 1396 // loop after interchanging. 1397 for (PHINode *P : LcssaInnerExit) 1398 P->moveBefore(InnerLatch->getFirstNonPHI()); 1399 1400 // If the inner loop latch contains LCSSA PHIs, those come from a child loop 1401 // and we have to move them to the new inner latch. 1402 for (PHINode *P : LcssaInnerLatch) 1403 P->moveBefore(InnerExit->getFirstNonPHI()); 1404 1405 // Deal with LCSSA PHI nodes in the loop nest exit block. For PHIs that have 1406 // incoming values defined in the outer loop, we have to add a new PHI 1407 // in the inner loop latch, which became the exit block of the outer loop, 1408 // after interchanging. 1409 if (OuterExit) { 1410 for (PHINode &P : OuterExit->phis()) { 1411 if (P.getNumIncomingValues() != 1) 1412 continue; 1413 // Skip Phis with incoming values defined in the inner loop. Those should 1414 // already have been updated. 1415 auto I = dyn_cast<Instruction>(P.getIncomingValue(0)); 1416 if (!I || LI->getLoopFor(I->getParent()) == InnerLoop) 1417 continue; 1418 1419 PHINode *NewPhi = dyn_cast<PHINode>(P.clone()); 1420 NewPhi->setIncomingValue(0, P.getIncomingValue(0)); 1421 NewPhi->setIncomingBlock(0, OuterLatch); 1422 NewPhi->insertBefore(InnerLatch->getFirstNonPHI()); 1423 P.setIncomingValue(0, NewPhi); 1424 } 1425 } 1426 1427 // Now adjust the incoming blocks for the LCSSA PHIs. 1428 // For PHIs moved from Inner's exit block, we need to replace Inner's latch 1429 // with the new latch. 1430 InnerLatch->replacePhiUsesWith(InnerLatch, OuterLatch); 1431 } 1432 1433 bool LoopInterchangeTransform::adjustLoopBranches() { 1434 LLVM_DEBUG(dbgs() << "adjustLoopBranches called\n"); 1435 std::vector<DominatorTree::UpdateType> DTUpdates; 1436 1437 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1438 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1439 1440 assert(OuterLoopPreHeader != OuterLoop->getHeader() && 1441 InnerLoopPreHeader != InnerLoop->getHeader() && OuterLoopPreHeader && 1442 InnerLoopPreHeader && "Guaranteed by loop-simplify form"); 1443 // Ensure that both preheaders do not contain PHI nodes and have single 1444 // predecessors. This allows us to move them easily. We use 1445 // InsertPreHeaderForLoop to create an 'extra' preheader, if the existing 1446 // preheaders do not satisfy those conditions. 1447 if (isa<PHINode>(OuterLoopPreHeader->begin()) || 1448 !OuterLoopPreHeader->getUniquePredecessor()) 1449 OuterLoopPreHeader = 1450 InsertPreheaderForLoop(OuterLoop, DT, LI, nullptr, true); 1451 if (InnerLoopPreHeader == OuterLoop->getHeader()) 1452 InnerLoopPreHeader = 1453 InsertPreheaderForLoop(InnerLoop, DT, LI, nullptr, true); 1454 1455 // Adjust the loop preheader 1456 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1457 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1458 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1459 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1460 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1461 BasicBlock *InnerLoopLatchPredecessor = 1462 InnerLoopLatch->getUniquePredecessor(); 1463 BasicBlock *InnerLoopLatchSuccessor; 1464 BasicBlock *OuterLoopLatchSuccessor; 1465 1466 BranchInst *OuterLoopLatchBI = 1467 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1468 BranchInst *InnerLoopLatchBI = 1469 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1470 BranchInst *OuterLoopHeaderBI = 1471 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1472 BranchInst *InnerLoopHeaderBI = 1473 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1474 1475 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1476 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1477 !InnerLoopHeaderBI) 1478 return false; 1479 1480 BranchInst *InnerLoopLatchPredecessorBI = 1481 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1482 BranchInst *OuterLoopPredecessorBI = 1483 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1484 1485 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1486 return false; 1487 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1488 if (!InnerLoopHeaderSuccessor) 1489 return false; 1490 1491 // Adjust Loop Preheader and headers. 1492 // The branches in the outer loop predecessor and the outer loop header can 1493 // be unconditional branches or conditional branches with duplicates. Consider 1494 // this when updating the successors. 1495 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader, 1496 InnerLoopPreHeader, DTUpdates, /*MustUpdateOnce=*/false); 1497 // The outer loop header might or might not branch to the outer latch. 1498 // We are guaranteed to branch to the inner loop preheader. 1499 if (std::find(succ_begin(OuterLoopHeaderBI), succ_end(OuterLoopHeaderBI), 1500 OuterLoopLatch) != succ_end(OuterLoopHeaderBI)) 1501 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates, 1502 /*MustUpdateOnce=*/false); 1503 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader, 1504 InnerLoopHeaderSuccessor, DTUpdates, 1505 /*MustUpdateOnce=*/false); 1506 1507 // Adjust reduction PHI's now that the incoming block has changed. 1508 InnerLoopHeaderSuccessor->replacePhiUsesWith(InnerLoopHeader, 1509 OuterLoopHeader); 1510 1511 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor, 1512 OuterLoopPreHeader, DTUpdates); 1513 1514 // -------------Adjust loop latches----------- 1515 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1516 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1517 else 1518 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1519 1520 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch, 1521 InnerLoopLatchSuccessor, DTUpdates); 1522 1523 1524 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1525 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1526 else 1527 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1528 1529 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor, 1530 OuterLoopLatchSuccessor, DTUpdates); 1531 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch, 1532 DTUpdates); 1533 1534 DT->applyUpdates(DTUpdates); 1535 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader, 1536 OuterLoopPreHeader); 1537 1538 moveLCSSAPhis(InnerLoopLatchSuccessor, InnerLoopHeader, InnerLoopLatch, 1539 OuterLoopHeader, OuterLoopLatch, InnerLoop->getExitBlock(), 1540 InnerLoop, LI); 1541 // For PHIs in the exit block of the outer loop, outer's latch has been 1542 // replaced by Inners'. 1543 OuterLoopLatchSuccessor->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); 1544 1545 // Now update the reduction PHIs in the inner and outer loop headers. 1546 SmallVector<PHINode *, 4> InnerLoopPHIs, OuterLoopPHIs; 1547 for (PHINode &PHI : drop_begin(InnerLoopHeader->phis(), 1)) 1548 InnerLoopPHIs.push_back(cast<PHINode>(&PHI)); 1549 for (PHINode &PHI : drop_begin(OuterLoopHeader->phis(), 1)) 1550 OuterLoopPHIs.push_back(cast<PHINode>(&PHI)); 1551 1552 auto &OuterInnerReductions = LIL.getOuterInnerReductions(); 1553 (void)OuterInnerReductions; 1554 1555 // Now move the remaining reduction PHIs from outer to inner loop header and 1556 // vice versa. The PHI nodes must be part of a reduction across the inner and 1557 // outer loop and all the remains to do is and updating the incoming blocks. 1558 for (PHINode *PHI : OuterLoopPHIs) { 1559 PHI->moveBefore(InnerLoopHeader->getFirstNonPHI()); 1560 assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() && 1561 "Expected a reduction PHI node"); 1562 } 1563 for (PHINode *PHI : InnerLoopPHIs) { 1564 PHI->moveBefore(OuterLoopHeader->getFirstNonPHI()); 1565 assert(OuterInnerReductions.find(PHI) != OuterInnerReductions.end() && 1566 "Expected a reduction PHI node"); 1567 } 1568 1569 // Update the incoming blocks for moved PHI nodes. 1570 OuterLoopHeader->replacePhiUsesWith(InnerLoopPreHeader, OuterLoopPreHeader); 1571 OuterLoopHeader->replacePhiUsesWith(InnerLoopLatch, OuterLoopLatch); 1572 InnerLoopHeader->replacePhiUsesWith(OuterLoopPreHeader, InnerLoopPreHeader); 1573 InnerLoopHeader->replacePhiUsesWith(OuterLoopLatch, InnerLoopLatch); 1574 1575 return true; 1576 } 1577 1578 void LoopInterchangeTransform::adjustLoopPreheaders() { 1579 // We have interchanged the preheaders so we need to interchange the data in 1580 // the preheader as well. 1581 // This is because the content of inner preheader was previously executed 1582 // inside the outer loop. 1583 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1584 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1585 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1586 BranchInst *InnerTermBI = 1587 cast<BranchInst>(InnerLoopPreHeader->getTerminator()); 1588 1589 // These instructions should now be executed inside the loop. 1590 // Move instruction into a new block after outer header. 1591 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); 1592 // These instructions were not executed previously in the loop so move them to 1593 // the older inner loop preheader. 1594 moveBBContents(OuterLoopPreHeader, InnerTermBI); 1595 } 1596 1597 bool LoopInterchangeTransform::adjustLoopLinks() { 1598 // Adjust all branches in the inner and outer loop. 1599 bool Changed = adjustLoopBranches(); 1600 if (Changed) 1601 adjustLoopPreheaders(); 1602 return Changed; 1603 } 1604 1605 char LoopInterchange::ID = 0; 1606 1607 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", 1608 "Interchanges loops for cache reuse", false, false) 1609 INITIALIZE_PASS_DEPENDENCY(LoopPass) 1610 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1611 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 1612 1613 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", 1614 "Interchanges loops for cache reuse", false, false) 1615 1616 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } 1617