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