LoopInterchange.cpp 65 KB

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