LoopInterchange.cpp 68 KB

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