ModuloSchedule.cpp 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213
  1. //===- ModuloSchedule.cpp - Software pipeline schedule expansion ----------===//
  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. #include "llvm/CodeGen/ModuloSchedule.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Analysis/MemoryLocation.h"
  11. #include "llvm/CodeGen/LiveIntervals.h"
  12. #include "llvm/CodeGen/MachineInstrBuilder.h"
  13. #include "llvm/CodeGen/MachineLoopInfo.h"
  14. #include "llvm/CodeGen/MachineRegisterInfo.h"
  15. #include "llvm/InitializePasses.h"
  16. #include "llvm/MC/MCContext.h"
  17. #include "llvm/Support/Debug.h"
  18. #include "llvm/Support/ErrorHandling.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #define DEBUG_TYPE "pipeliner"
  21. using namespace llvm;
  22. void ModuloSchedule::print(raw_ostream &OS) {
  23. for (MachineInstr *MI : ScheduledInstrs)
  24. OS << "[stage " << getStage(MI) << " @" << getCycle(MI) << "c] " << *MI;
  25. }
  26. //===----------------------------------------------------------------------===//
  27. // ModuloScheduleExpander implementation
  28. //===----------------------------------------------------------------------===//
  29. /// Return the register values for the operands of a Phi instruction.
  30. /// This function assume the instruction is a Phi.
  31. static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
  32. unsigned &InitVal, unsigned &LoopVal) {
  33. assert(Phi.isPHI() && "Expecting a Phi.");
  34. InitVal = 0;
  35. LoopVal = 0;
  36. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  37. if (Phi.getOperand(i + 1).getMBB() != Loop)
  38. InitVal = Phi.getOperand(i).getReg();
  39. else
  40. LoopVal = Phi.getOperand(i).getReg();
  41. assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
  42. }
  43. /// Return the Phi register value that comes from the incoming block.
  44. static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  45. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  46. if (Phi.getOperand(i + 1).getMBB() != LoopBB)
  47. return Phi.getOperand(i).getReg();
  48. return 0;
  49. }
  50. /// Return the Phi register value that comes the loop block.
  51. static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
  52. for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
  53. if (Phi.getOperand(i + 1).getMBB() == LoopBB)
  54. return Phi.getOperand(i).getReg();
  55. return 0;
  56. }
  57. void ModuloScheduleExpander::expand() {
  58. BB = Schedule.getLoop()->getTopBlock();
  59. Preheader = *BB->pred_begin();
  60. if (Preheader == BB)
  61. Preheader = *std::next(BB->pred_begin());
  62. // Iterate over the definitions in each instruction, and compute the
  63. // stage difference for each use. Keep the maximum value.
  64. for (MachineInstr *MI : Schedule.getInstructions()) {
  65. int DefStage = Schedule.getStage(MI);
  66. for (const MachineOperand &Op : MI->operands()) {
  67. if (!Op.isReg() || !Op.isDef())
  68. continue;
  69. Register Reg = Op.getReg();
  70. unsigned MaxDiff = 0;
  71. bool PhiIsSwapped = false;
  72. for (MachineOperand &UseOp : MRI.use_operands(Reg)) {
  73. MachineInstr *UseMI = UseOp.getParent();
  74. int UseStage = Schedule.getStage(UseMI);
  75. unsigned Diff = 0;
  76. if (UseStage != -1 && UseStage >= DefStage)
  77. Diff = UseStage - DefStage;
  78. if (MI->isPHI()) {
  79. if (isLoopCarried(*MI))
  80. ++Diff;
  81. else
  82. PhiIsSwapped = true;
  83. }
  84. MaxDiff = std::max(Diff, MaxDiff);
  85. }
  86. RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
  87. }
  88. }
  89. generatePipelinedLoop();
  90. }
  91. void ModuloScheduleExpander::generatePipelinedLoop() {
  92. LoopInfo = TII->analyzeLoopForPipelining(BB);
  93. assert(LoopInfo && "Must be able to analyze loop!");
  94. // Create a new basic block for the kernel and add it to the CFG.
  95. MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  96. unsigned MaxStageCount = Schedule.getNumStages() - 1;
  97. // Remember the registers that are used in different stages. The index is
  98. // the iteration, or stage, that the instruction is scheduled in. This is
  99. // a map between register names in the original block and the names created
  100. // in each stage of the pipelined loop.
  101. ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
  102. // The renaming destination by Phis for the registers across stages.
  103. // This map is updated during Phis generation to point to the most recent
  104. // renaming destination.
  105. ValueMapTy *VRMapPhi = new ValueMapTy[(MaxStageCount + 1) * 2];
  106. InstrMapTy InstrMap;
  107. SmallVector<MachineBasicBlock *, 4> PrologBBs;
  108. // Generate the prolog instructions that set up the pipeline.
  109. generateProlog(MaxStageCount, KernelBB, VRMap, PrologBBs);
  110. MF.insert(BB->getIterator(), KernelBB);
  111. // Rearrange the instructions to generate the new, pipelined loop,
  112. // and update register names as needed.
  113. for (MachineInstr *CI : Schedule.getInstructions()) {
  114. if (CI->isPHI())
  115. continue;
  116. unsigned StageNum = Schedule.getStage(CI);
  117. MachineInstr *NewMI = cloneInstr(CI, MaxStageCount, StageNum);
  118. updateInstruction(NewMI, false, MaxStageCount, StageNum, VRMap);
  119. KernelBB->push_back(NewMI);
  120. InstrMap[NewMI] = CI;
  121. }
  122. // Copy any terminator instructions to the new kernel, and update
  123. // names as needed.
  124. for (MachineInstr &MI : BB->terminators()) {
  125. MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
  126. updateInstruction(NewMI, false, MaxStageCount, 0, VRMap);
  127. KernelBB->push_back(NewMI);
  128. InstrMap[NewMI] = &MI;
  129. }
  130. NewKernel = KernelBB;
  131. KernelBB->transferSuccessors(BB);
  132. KernelBB->replaceSuccessor(BB, KernelBB);
  133. generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap,
  134. InstrMap, MaxStageCount, MaxStageCount, false);
  135. generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap, VRMapPhi,
  136. InstrMap, MaxStageCount, MaxStageCount, false);
  137. LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
  138. SmallVector<MachineBasicBlock *, 4> EpilogBBs;
  139. // Generate the epilog instructions to complete the pipeline.
  140. generateEpilog(MaxStageCount, KernelBB, BB, VRMap, VRMapPhi, EpilogBBs,
  141. PrologBBs);
  142. // We need this step because the register allocation doesn't handle some
  143. // situations well, so we insert copies to help out.
  144. splitLifetimes(KernelBB, EpilogBBs);
  145. // Remove dead instructions due to loop induction variables.
  146. removeDeadInstructions(KernelBB, EpilogBBs);
  147. // Add branches between prolog and epilog blocks.
  148. addBranches(*Preheader, PrologBBs, KernelBB, EpilogBBs, VRMap);
  149. delete[] VRMap;
  150. delete[] VRMapPhi;
  151. }
  152. void ModuloScheduleExpander::cleanup() {
  153. // Remove the original loop since it's no longer referenced.
  154. for (auto &I : *BB)
  155. LIS.RemoveMachineInstrFromMaps(I);
  156. BB->clear();
  157. BB->eraseFromParent();
  158. }
  159. /// Generate the pipeline prolog code.
  160. void ModuloScheduleExpander::generateProlog(unsigned LastStage,
  161. MachineBasicBlock *KernelBB,
  162. ValueMapTy *VRMap,
  163. MBBVectorTy &PrologBBs) {
  164. MachineBasicBlock *PredBB = Preheader;
  165. InstrMapTy InstrMap;
  166. // Generate a basic block for each stage, not including the last stage,
  167. // which will be generated in the kernel. Each basic block may contain
  168. // instructions from multiple stages/iterations.
  169. for (unsigned i = 0; i < LastStage; ++i) {
  170. // Create and insert the prolog basic block prior to the original loop
  171. // basic block. The original loop is removed later.
  172. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  173. PrologBBs.push_back(NewBB);
  174. MF.insert(BB->getIterator(), NewBB);
  175. NewBB->transferSuccessors(PredBB);
  176. PredBB->addSuccessor(NewBB);
  177. PredBB = NewBB;
  178. // Generate instructions for each appropriate stage. Process instructions
  179. // in original program order.
  180. for (int StageNum = i; StageNum >= 0; --StageNum) {
  181. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  182. BBE = BB->getFirstTerminator();
  183. BBI != BBE; ++BBI) {
  184. if (Schedule.getStage(&*BBI) == StageNum) {
  185. if (BBI->isPHI())
  186. continue;
  187. MachineInstr *NewMI =
  188. cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum);
  189. updateInstruction(NewMI, false, i, (unsigned)StageNum, VRMap);
  190. NewBB->push_back(NewMI);
  191. InstrMap[NewMI] = &*BBI;
  192. }
  193. }
  194. }
  195. rewritePhiValues(NewBB, i, VRMap, InstrMap);
  196. LLVM_DEBUG({
  197. dbgs() << "prolog:\n";
  198. NewBB->dump();
  199. });
  200. }
  201. PredBB->replaceSuccessor(BB, KernelBB);
  202. // Check if we need to remove the branch from the preheader to the original
  203. // loop, and replace it with a branch to the new loop.
  204. unsigned numBranches = TII->removeBranch(*Preheader);
  205. if (numBranches) {
  206. SmallVector<MachineOperand, 0> Cond;
  207. TII->insertBranch(*Preheader, PrologBBs[0], nullptr, Cond, DebugLoc());
  208. }
  209. }
  210. /// Generate the pipeline epilog code. The epilog code finishes the iterations
  211. /// that were started in either the prolog or the kernel. We create a basic
  212. /// block for each stage that needs to complete.
  213. void ModuloScheduleExpander::generateEpilog(
  214. unsigned LastStage, MachineBasicBlock *KernelBB, MachineBasicBlock *OrigBB,
  215. ValueMapTy *VRMap, ValueMapTy *VRMapPhi, MBBVectorTy &EpilogBBs,
  216. MBBVectorTy &PrologBBs) {
  217. // We need to change the branch from the kernel to the first epilog block, so
  218. // this call to analyze branch uses the kernel rather than the original BB.
  219. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  220. SmallVector<MachineOperand, 4> Cond;
  221. bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
  222. assert(!checkBranch && "generateEpilog must be able to analyze the branch");
  223. if (checkBranch)
  224. return;
  225. MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
  226. if (*LoopExitI == KernelBB)
  227. ++LoopExitI;
  228. assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
  229. MachineBasicBlock *LoopExitBB = *LoopExitI;
  230. MachineBasicBlock *PredBB = KernelBB;
  231. MachineBasicBlock *EpilogStart = LoopExitBB;
  232. InstrMapTy InstrMap;
  233. // Generate a basic block for each stage, not including the last stage,
  234. // which was generated for the kernel. Each basic block may contain
  235. // instructions from multiple stages/iterations.
  236. int EpilogStage = LastStage + 1;
  237. for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
  238. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
  239. EpilogBBs.push_back(NewBB);
  240. MF.insert(BB->getIterator(), NewBB);
  241. PredBB->replaceSuccessor(LoopExitBB, NewBB);
  242. NewBB->addSuccessor(LoopExitBB);
  243. if (EpilogStart == LoopExitBB)
  244. EpilogStart = NewBB;
  245. // Add instructions to the epilog depending on the current block.
  246. // Process instructions in original program order.
  247. for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
  248. for (auto &BBI : *BB) {
  249. if (BBI.isPHI())
  250. continue;
  251. MachineInstr *In = &BBI;
  252. if ((unsigned)Schedule.getStage(In) == StageNum) {
  253. // Instructions with memoperands in the epilog are updated with
  254. // conservative values.
  255. MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
  256. updateInstruction(NewMI, i == 1, EpilogStage, 0, VRMap);
  257. NewBB->push_back(NewMI);
  258. InstrMap[NewMI] = In;
  259. }
  260. }
  261. }
  262. generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap,
  263. InstrMap, LastStage, EpilogStage, i == 1);
  264. generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap, VRMapPhi,
  265. InstrMap, LastStage, EpilogStage, i == 1);
  266. PredBB = NewBB;
  267. LLVM_DEBUG({
  268. dbgs() << "epilog:\n";
  269. NewBB->dump();
  270. });
  271. }
  272. // Fix any Phi nodes in the loop exit block.
  273. LoopExitBB->replacePhiUsesWith(BB, PredBB);
  274. // Create a branch to the new epilog from the kernel.
  275. // Remove the original branch and add a new branch to the epilog.
  276. TII->removeBranch(*KernelBB);
  277. assert((OrigBB == TBB || OrigBB == FBB) &&
  278. "Unable to determine looping branch direction");
  279. if (OrigBB != TBB)
  280. TII->insertBranch(*KernelBB, EpilogStart, KernelBB, Cond, DebugLoc());
  281. else
  282. TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
  283. // Add a branch to the loop exit.
  284. if (EpilogBBs.size() > 0) {
  285. MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
  286. SmallVector<MachineOperand, 4> Cond1;
  287. TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
  288. }
  289. }
  290. /// Replace all uses of FromReg that appear outside the specified
  291. /// basic block with ToReg.
  292. static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
  293. MachineBasicBlock *MBB,
  294. MachineRegisterInfo &MRI,
  295. LiveIntervals &LIS) {
  296. for (MachineOperand &O :
  297. llvm::make_early_inc_range(MRI.use_operands(FromReg)))
  298. if (O.getParent()->getParent() != MBB)
  299. O.setReg(ToReg);
  300. if (!LIS.hasInterval(ToReg))
  301. LIS.createEmptyInterval(ToReg);
  302. }
  303. /// Return true if the register has a use that occurs outside the
  304. /// specified loop.
  305. static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
  306. MachineRegisterInfo &MRI) {
  307. for (const MachineOperand &MO : MRI.use_operands(Reg))
  308. if (MO.getParent()->getParent() != BB)
  309. return true;
  310. return false;
  311. }
  312. /// Generate Phis for the specific block in the generated pipelined code.
  313. /// This function looks at the Phis from the original code to guide the
  314. /// creation of new Phis.
  315. void ModuloScheduleExpander::generateExistingPhis(
  316. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  317. MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
  318. unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
  319. // Compute the stage number for the initial value of the Phi, which
  320. // comes from the prolog. The prolog to use depends on to which kernel/
  321. // epilog that we're adding the Phi.
  322. unsigned PrologStage = 0;
  323. unsigned PrevStage = 0;
  324. bool InKernel = (LastStageNum == CurStageNum);
  325. if (InKernel) {
  326. PrologStage = LastStageNum - 1;
  327. PrevStage = CurStageNum;
  328. } else {
  329. PrologStage = LastStageNum - (CurStageNum - LastStageNum);
  330. PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
  331. }
  332. for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
  333. BBE = BB->getFirstNonPHI();
  334. BBI != BBE; ++BBI) {
  335. Register Def = BBI->getOperand(0).getReg();
  336. unsigned InitVal = 0;
  337. unsigned LoopVal = 0;
  338. getPhiRegs(*BBI, BB, InitVal, LoopVal);
  339. unsigned PhiOp1 = 0;
  340. // The Phi value from the loop body typically is defined in the loop, but
  341. // not always. So, we need to check if the value is defined in the loop.
  342. unsigned PhiOp2 = LoopVal;
  343. if (VRMap[LastStageNum].count(LoopVal))
  344. PhiOp2 = VRMap[LastStageNum][LoopVal];
  345. int StageScheduled = Schedule.getStage(&*BBI);
  346. int LoopValStage = Schedule.getStage(MRI.getVRegDef(LoopVal));
  347. unsigned NumStages = getStagesForReg(Def, CurStageNum);
  348. if (NumStages == 0) {
  349. // We don't need to generate a Phi anymore, but we need to rename any uses
  350. // of the Phi value.
  351. unsigned NewReg = VRMap[PrevStage][LoopVal];
  352. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, 0, &*BBI, Def,
  353. InitVal, NewReg);
  354. if (VRMap[CurStageNum].count(LoopVal))
  355. VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
  356. }
  357. // Adjust the number of Phis needed depending on the number of prologs left,
  358. // and the distance from where the Phi is first scheduled. The number of
  359. // Phis cannot exceed the number of prolog stages. Each stage can
  360. // potentially define two values.
  361. unsigned MaxPhis = PrologStage + 2;
  362. if (!InKernel && (int)PrologStage <= LoopValStage)
  363. MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
  364. unsigned NumPhis = std::min(NumStages, MaxPhis);
  365. unsigned NewReg = 0;
  366. unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
  367. // In the epilog, we may need to look back one stage to get the correct
  368. // Phi name, because the epilog and prolog blocks execute the same stage.
  369. // The correct name is from the previous block only when the Phi has
  370. // been completely scheduled prior to the epilog, and Phi value is not
  371. // needed in multiple stages.
  372. int StageDiff = 0;
  373. if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
  374. NumPhis == 1)
  375. StageDiff = 1;
  376. // Adjust the computations below when the phi and the loop definition
  377. // are scheduled in different stages.
  378. if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
  379. StageDiff = StageScheduled - LoopValStage;
  380. for (unsigned np = 0; np < NumPhis; ++np) {
  381. // If the Phi hasn't been scheduled, then use the initial Phi operand
  382. // value. Otherwise, use the scheduled version of the instruction. This
  383. // is a little complicated when a Phi references another Phi.
  384. if (np > PrologStage || StageScheduled >= (int)LastStageNum)
  385. PhiOp1 = InitVal;
  386. // Check if the Phi has already been scheduled in a prolog stage.
  387. else if (PrologStage >= AccessStage + StageDiff + np &&
  388. VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
  389. PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
  390. // Check if the Phi has already been scheduled, but the loop instruction
  391. // is either another Phi, or doesn't occur in the loop.
  392. else if (PrologStage >= AccessStage + StageDiff + np) {
  393. // If the Phi references another Phi, we need to examine the other
  394. // Phi to get the correct value.
  395. PhiOp1 = LoopVal;
  396. MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
  397. int Indirects = 1;
  398. while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
  399. int PhiStage = Schedule.getStage(InstOp1);
  400. if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
  401. PhiOp1 = getInitPhiReg(*InstOp1, BB);
  402. else
  403. PhiOp1 = getLoopPhiReg(*InstOp1, BB);
  404. InstOp1 = MRI.getVRegDef(PhiOp1);
  405. int PhiOpStage = Schedule.getStage(InstOp1);
  406. int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
  407. if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
  408. VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
  409. PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
  410. break;
  411. }
  412. ++Indirects;
  413. }
  414. } else
  415. PhiOp1 = InitVal;
  416. // If this references a generated Phi in the kernel, get the Phi operand
  417. // from the incoming block.
  418. if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
  419. if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
  420. PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
  421. MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
  422. bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
  423. // In the epilog, a map lookup is needed to get the value from the kernel,
  424. // or previous epilog block. How is does this depends on if the
  425. // instruction is scheduled in the previous block.
  426. if (!InKernel) {
  427. int StageDiffAdj = 0;
  428. if (LoopValStage != -1 && StageScheduled > LoopValStage)
  429. StageDiffAdj = StageScheduled - LoopValStage;
  430. // Use the loop value defined in the kernel, unless the kernel
  431. // contains the last definition of the Phi.
  432. if (np == 0 && PrevStage == LastStageNum &&
  433. (StageScheduled != 0 || LoopValStage != 0) &&
  434. VRMap[PrevStage - StageDiffAdj].count(LoopVal))
  435. PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
  436. // Use the value defined by the Phi. We add one because we switch
  437. // from looking at the loop value to the Phi definition.
  438. else if (np > 0 && PrevStage == LastStageNum &&
  439. VRMap[PrevStage - np + 1].count(Def))
  440. PhiOp2 = VRMap[PrevStage - np + 1][Def];
  441. // Use the loop value defined in the kernel.
  442. else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
  443. VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
  444. PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
  445. // Use the value defined by the Phi, unless we're generating the first
  446. // epilog and the Phi refers to a Phi in a different stage.
  447. else if (VRMap[PrevStage - np].count(Def) &&
  448. (!LoopDefIsPhi || (PrevStage != LastStageNum) ||
  449. (LoopValStage == StageScheduled)))
  450. PhiOp2 = VRMap[PrevStage - np][Def];
  451. }
  452. // Check if we can reuse an existing Phi. This occurs when a Phi
  453. // references another Phi, and the other Phi is scheduled in an
  454. // earlier stage. We can try to reuse an existing Phi up until the last
  455. // stage of the current Phi.
  456. if (LoopDefIsPhi) {
  457. if (static_cast<int>(PrologStage - np) >= StageScheduled) {
  458. int LVNumStages = getStagesForPhi(LoopVal);
  459. int StageDiff = (StageScheduled - LoopValStage);
  460. LVNumStages -= StageDiff;
  461. // Make sure the loop value Phi has been processed already.
  462. if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
  463. NewReg = PhiOp2;
  464. unsigned ReuseStage = CurStageNum;
  465. if (isLoopCarried(*PhiInst))
  466. ReuseStage -= LVNumStages;
  467. // Check if the Phi to reuse has been generated yet. If not, then
  468. // there is nothing to reuse.
  469. if (VRMap[ReuseStage - np].count(LoopVal)) {
  470. NewReg = VRMap[ReuseStage - np][LoopVal];
  471. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI,
  472. Def, NewReg);
  473. // Update the map with the new Phi name.
  474. VRMap[CurStageNum - np][Def] = NewReg;
  475. PhiOp2 = NewReg;
  476. if (VRMap[LastStageNum - np - 1].count(LoopVal))
  477. PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
  478. if (IsLast && np == NumPhis - 1)
  479. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  480. continue;
  481. }
  482. }
  483. }
  484. if (InKernel && StageDiff > 0 &&
  485. VRMap[CurStageNum - StageDiff - np].count(LoopVal))
  486. PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
  487. }
  488. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  489. NewReg = MRI.createVirtualRegister(RC);
  490. MachineInstrBuilder NewPhi =
  491. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  492. TII->get(TargetOpcode::PHI), NewReg);
  493. NewPhi.addReg(PhiOp1).addMBB(BB1);
  494. NewPhi.addReg(PhiOp2).addMBB(BB2);
  495. if (np == 0)
  496. InstrMap[NewPhi] = &*BBI;
  497. // We define the Phis after creating the new pipelined code, so
  498. // we need to rename the Phi values in scheduled instructions.
  499. unsigned PrevReg = 0;
  500. if (InKernel && VRMap[PrevStage - np].count(LoopVal))
  501. PrevReg = VRMap[PrevStage - np][LoopVal];
  502. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
  503. NewReg, PrevReg);
  504. // If the Phi has been scheduled, use the new name for rewriting.
  505. if (VRMap[CurStageNum - np].count(Def)) {
  506. unsigned R = VRMap[CurStageNum - np][Def];
  507. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, R,
  508. NewReg);
  509. }
  510. // Check if we need to rename any uses that occurs after the loop. The
  511. // register to replace depends on whether the Phi is scheduled in the
  512. // epilog.
  513. if (IsLast && np == NumPhis - 1)
  514. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  515. // In the kernel, a dependent Phi uses the value from this Phi.
  516. if (InKernel)
  517. PhiOp2 = NewReg;
  518. // Update the map with the new Phi name.
  519. VRMap[CurStageNum - np][Def] = NewReg;
  520. }
  521. while (NumPhis++ < NumStages) {
  522. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, NumPhis, &*BBI, Def,
  523. NewReg, 0);
  524. }
  525. // Check if we need to rename a Phi that has been eliminated due to
  526. // scheduling.
  527. if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
  528. replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
  529. }
  530. }
  531. /// Generate Phis for the specified block in the generated pipelined code.
  532. /// These are new Phis needed because the definition is scheduled after the
  533. /// use in the pipelined sequence.
  534. void ModuloScheduleExpander::generatePhis(
  535. MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
  536. MachineBasicBlock *KernelBB, ValueMapTy *VRMap, ValueMapTy *VRMapPhi,
  537. InstrMapTy &InstrMap, unsigned LastStageNum, unsigned CurStageNum,
  538. bool IsLast) {
  539. // Compute the stage number that contains the initial Phi value, and
  540. // the Phi from the previous stage.
  541. unsigned PrologStage = 0;
  542. unsigned PrevStage = 0;
  543. unsigned StageDiff = CurStageNum - LastStageNum;
  544. bool InKernel = (StageDiff == 0);
  545. if (InKernel) {
  546. PrologStage = LastStageNum - 1;
  547. PrevStage = CurStageNum;
  548. } else {
  549. PrologStage = LastStageNum - StageDiff;
  550. PrevStage = LastStageNum + StageDiff - 1;
  551. }
  552. for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
  553. BBE = BB->instr_end();
  554. BBI != BBE; ++BBI) {
  555. for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
  556. MachineOperand &MO = BBI->getOperand(i);
  557. if (!MO.isReg() || !MO.isDef() || !MO.getReg().isVirtual())
  558. continue;
  559. int StageScheduled = Schedule.getStage(&*BBI);
  560. assert(StageScheduled != -1 && "Expecting scheduled instruction.");
  561. Register Def = MO.getReg();
  562. unsigned NumPhis = getStagesForReg(Def, CurStageNum);
  563. // An instruction scheduled in stage 0 and is used after the loop
  564. // requires a phi in the epilog for the last definition from either
  565. // the kernel or prolog.
  566. if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
  567. hasUseAfterLoop(Def, BB, MRI))
  568. NumPhis = 1;
  569. if (!InKernel && (unsigned)StageScheduled > PrologStage)
  570. continue;
  571. unsigned PhiOp2;
  572. if (InKernel) {
  573. PhiOp2 = VRMap[PrevStage][Def];
  574. if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
  575. if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
  576. PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
  577. }
  578. // The number of Phis can't exceed the number of prolog stages. The
  579. // prolog stage number is zero based.
  580. if (NumPhis > PrologStage + 1 - StageScheduled)
  581. NumPhis = PrologStage + 1 - StageScheduled;
  582. for (unsigned np = 0; np < NumPhis; ++np) {
  583. // Example for
  584. // Org:
  585. // %Org = ... (Scheduled at Stage#0, NumPhi = 2)
  586. //
  587. // Prolog0 (Stage0):
  588. // %Clone0 = ...
  589. // Prolog1 (Stage1):
  590. // %Clone1 = ...
  591. // Kernel (Stage2):
  592. // %Phi0 = Phi %Clone1, Prolog1, %Clone2, Kernel
  593. // %Phi1 = Phi %Clone0, Prolog1, %Phi0, Kernel
  594. // %Clone2 = ...
  595. // Epilog0 (Stage3):
  596. // %Phi2 = Phi %Clone1, Prolog1, %Clone2, Kernel
  597. // %Phi3 = Phi %Clone0, Prolog1, %Phi0, Kernel
  598. // Epilog1 (Stage4):
  599. // %Phi4 = Phi %Clone0, Prolog0, %Phi2, Epilog0
  600. //
  601. // VRMap = {0: %Clone0, 1: %Clone1, 2: %Clone2}
  602. // VRMapPhi (after Kernel) = {0: %Phi1, 1: %Phi0}
  603. // VRMapPhi (after Epilog0) = {0: %Phi3, 1: %Phi2}
  604. unsigned PhiOp1 = VRMap[PrologStage][Def];
  605. if (np <= PrologStage)
  606. PhiOp1 = VRMap[PrologStage - np][Def];
  607. if (!InKernel) {
  608. if (PrevStage == LastStageNum && np == 0)
  609. PhiOp2 = VRMap[LastStageNum][Def];
  610. else
  611. PhiOp2 = VRMapPhi[PrevStage - np][Def];
  612. }
  613. const TargetRegisterClass *RC = MRI.getRegClass(Def);
  614. Register NewReg = MRI.createVirtualRegister(RC);
  615. MachineInstrBuilder NewPhi =
  616. BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
  617. TII->get(TargetOpcode::PHI), NewReg);
  618. NewPhi.addReg(PhiOp1).addMBB(BB1);
  619. NewPhi.addReg(PhiOp2).addMBB(BB2);
  620. if (np == 0)
  621. InstrMap[NewPhi] = &*BBI;
  622. // Rewrite uses and update the map. The actions depend upon whether
  623. // we generating code for the kernel or epilog blocks.
  624. if (InKernel) {
  625. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp1,
  626. NewReg);
  627. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp2,
  628. NewReg);
  629. PhiOp2 = NewReg;
  630. VRMapPhi[PrevStage - np - 1][Def] = NewReg;
  631. } else {
  632. VRMapPhi[CurStageNum - np][Def] = NewReg;
  633. if (np == NumPhis - 1)
  634. rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
  635. NewReg);
  636. }
  637. if (IsLast && np == NumPhis - 1)
  638. replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
  639. }
  640. }
  641. }
  642. }
  643. /// Remove instructions that generate values with no uses.
  644. /// Typically, these are induction variable operations that generate values
  645. /// used in the loop itself. A dead instruction has a definition with
  646. /// no uses, or uses that occur in the original loop only.
  647. void ModuloScheduleExpander::removeDeadInstructions(MachineBasicBlock *KernelBB,
  648. MBBVectorTy &EpilogBBs) {
  649. // For each epilog block, check that the value defined by each instruction
  650. // is used. If not, delete it.
  651. for (MachineBasicBlock *MBB : llvm::reverse(EpilogBBs))
  652. for (MachineBasicBlock::reverse_instr_iterator MI = MBB->instr_rbegin(),
  653. ME = MBB->instr_rend();
  654. MI != ME;) {
  655. // From DeadMachineInstructionElem. Don't delete inline assembly.
  656. if (MI->isInlineAsm()) {
  657. ++MI;
  658. continue;
  659. }
  660. bool SawStore = false;
  661. // Check if it's safe to remove the instruction due to side effects.
  662. // We can, and want to, remove Phis here.
  663. if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
  664. ++MI;
  665. continue;
  666. }
  667. bool used = true;
  668. for (const MachineOperand &MO : MI->operands()) {
  669. if (!MO.isReg() || !MO.isDef())
  670. continue;
  671. Register reg = MO.getReg();
  672. // Assume physical registers are used, unless they are marked dead.
  673. if (reg.isPhysical()) {
  674. used = !MO.isDead();
  675. if (used)
  676. break;
  677. continue;
  678. }
  679. unsigned realUses = 0;
  680. for (const MachineOperand &U : MRI.use_operands(reg)) {
  681. // Check if there are any uses that occur only in the original
  682. // loop. If so, that's not a real use.
  683. if (U.getParent()->getParent() != BB) {
  684. realUses++;
  685. used = true;
  686. break;
  687. }
  688. }
  689. if (realUses > 0)
  690. break;
  691. used = false;
  692. }
  693. if (!used) {
  694. LIS.RemoveMachineInstrFromMaps(*MI);
  695. MI++->eraseFromParent();
  696. continue;
  697. }
  698. ++MI;
  699. }
  700. // In the kernel block, check if we can remove a Phi that generates a value
  701. // used in an instruction removed in the epilog block.
  702. for (MachineInstr &MI : llvm::make_early_inc_range(KernelBB->phis())) {
  703. Register reg = MI.getOperand(0).getReg();
  704. if (MRI.use_begin(reg) == MRI.use_end()) {
  705. LIS.RemoveMachineInstrFromMaps(MI);
  706. MI.eraseFromParent();
  707. }
  708. }
  709. }
  710. /// For loop carried definitions, we split the lifetime of a virtual register
  711. /// that has uses past the definition in the next iteration. A copy with a new
  712. /// virtual register is inserted before the definition, which helps with
  713. /// generating a better register assignment.
  714. ///
  715. /// v1 = phi(a, v2) v1 = phi(a, v2)
  716. /// v2 = phi(b, v3) v2 = phi(b, v3)
  717. /// v3 = .. v4 = copy v1
  718. /// .. = V1 v3 = ..
  719. /// .. = v4
  720. void ModuloScheduleExpander::splitLifetimes(MachineBasicBlock *KernelBB,
  721. MBBVectorTy &EpilogBBs) {
  722. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  723. for (auto &PHI : KernelBB->phis()) {
  724. Register Def = PHI.getOperand(0).getReg();
  725. // Check for any Phi definition that used as an operand of another Phi
  726. // in the same block.
  727. for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
  728. E = MRI.use_instr_end();
  729. I != E; ++I) {
  730. if (I->isPHI() && I->getParent() == KernelBB) {
  731. // Get the loop carried definition.
  732. unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
  733. if (!LCDef)
  734. continue;
  735. MachineInstr *MI = MRI.getVRegDef(LCDef);
  736. if (!MI || MI->getParent() != KernelBB || MI->isPHI())
  737. continue;
  738. // Search through the rest of the block looking for uses of the Phi
  739. // definition. If one occurs, then split the lifetime.
  740. unsigned SplitReg = 0;
  741. for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
  742. KernelBB->instr_end()))
  743. if (BBJ.readsRegister(Def)) {
  744. // We split the lifetime when we find the first use.
  745. if (SplitReg == 0) {
  746. SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
  747. BuildMI(*KernelBB, MI, MI->getDebugLoc(),
  748. TII->get(TargetOpcode::COPY), SplitReg)
  749. .addReg(Def);
  750. }
  751. BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
  752. }
  753. if (!SplitReg)
  754. continue;
  755. // Search through each of the epilog blocks for any uses to be renamed.
  756. for (auto &Epilog : EpilogBBs)
  757. for (auto &I : *Epilog)
  758. if (I.readsRegister(Def))
  759. I.substituteRegister(Def, SplitReg, 0, *TRI);
  760. break;
  761. }
  762. }
  763. }
  764. }
  765. /// Remove the incoming block from the Phis in a basic block.
  766. static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
  767. for (MachineInstr &MI : *BB) {
  768. if (!MI.isPHI())
  769. break;
  770. for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
  771. if (MI.getOperand(i + 1).getMBB() == Incoming) {
  772. MI.removeOperand(i + 1);
  773. MI.removeOperand(i);
  774. break;
  775. }
  776. }
  777. }
  778. /// Create branches from each prolog basic block to the appropriate epilog
  779. /// block. These edges are needed if the loop ends before reaching the
  780. /// kernel.
  781. void ModuloScheduleExpander::addBranches(MachineBasicBlock &PreheaderBB,
  782. MBBVectorTy &PrologBBs,
  783. MachineBasicBlock *KernelBB,
  784. MBBVectorTy &EpilogBBs,
  785. ValueMapTy *VRMap) {
  786. assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
  787. MachineBasicBlock *LastPro = KernelBB;
  788. MachineBasicBlock *LastEpi = KernelBB;
  789. // Start from the blocks connected to the kernel and work "out"
  790. // to the first prolog and the last epilog blocks.
  791. SmallVector<MachineInstr *, 4> PrevInsts;
  792. unsigned MaxIter = PrologBBs.size() - 1;
  793. for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
  794. // Add branches to the prolog that go to the corresponding
  795. // epilog, and the fall-thru prolog/kernel block.
  796. MachineBasicBlock *Prolog = PrologBBs[j];
  797. MachineBasicBlock *Epilog = EpilogBBs[i];
  798. SmallVector<MachineOperand, 4> Cond;
  799. std::optional<bool> StaticallyGreater =
  800. LoopInfo->createTripCountGreaterCondition(j + 1, *Prolog, Cond);
  801. unsigned numAdded = 0;
  802. if (!StaticallyGreater) {
  803. Prolog->addSuccessor(Epilog);
  804. numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
  805. } else if (*StaticallyGreater == false) {
  806. Prolog->addSuccessor(Epilog);
  807. Prolog->removeSuccessor(LastPro);
  808. LastEpi->removeSuccessor(Epilog);
  809. numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
  810. removePhis(Epilog, LastEpi);
  811. // Remove the blocks that are no longer referenced.
  812. if (LastPro != LastEpi) {
  813. LastEpi->clear();
  814. LastEpi->eraseFromParent();
  815. }
  816. if (LastPro == KernelBB) {
  817. LoopInfo->disposed();
  818. NewKernel = nullptr;
  819. }
  820. LastPro->clear();
  821. LastPro->eraseFromParent();
  822. } else {
  823. numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
  824. removePhis(Epilog, Prolog);
  825. }
  826. LastPro = Prolog;
  827. LastEpi = Epilog;
  828. for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
  829. E = Prolog->instr_rend();
  830. I != E && numAdded > 0; ++I, --numAdded)
  831. updateInstruction(&*I, false, j, 0, VRMap);
  832. }
  833. if (NewKernel) {
  834. LoopInfo->setPreheader(PrologBBs[MaxIter]);
  835. LoopInfo->adjustTripCount(-(MaxIter + 1));
  836. }
  837. }
  838. /// Return true if we can compute the amount the instruction changes
  839. /// during each iteration. Set Delta to the amount of the change.
  840. bool ModuloScheduleExpander::computeDelta(MachineInstr &MI, unsigned &Delta) {
  841. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  842. const MachineOperand *BaseOp;
  843. int64_t Offset;
  844. bool OffsetIsScalable;
  845. if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
  846. return false;
  847. // FIXME: This algorithm assumes instructions have fixed-size offsets.
  848. if (OffsetIsScalable)
  849. return false;
  850. if (!BaseOp->isReg())
  851. return false;
  852. Register BaseReg = BaseOp->getReg();
  853. MachineRegisterInfo &MRI = MF.getRegInfo();
  854. // Check if there is a Phi. If so, get the definition in the loop.
  855. MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
  856. if (BaseDef && BaseDef->isPHI()) {
  857. BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
  858. BaseDef = MRI.getVRegDef(BaseReg);
  859. }
  860. if (!BaseDef)
  861. return false;
  862. int D = 0;
  863. if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
  864. return false;
  865. Delta = D;
  866. return true;
  867. }
  868. /// Update the memory operand with a new offset when the pipeliner
  869. /// generates a new copy of the instruction that refers to a
  870. /// different memory location.
  871. void ModuloScheduleExpander::updateMemOperands(MachineInstr &NewMI,
  872. MachineInstr &OldMI,
  873. unsigned Num) {
  874. if (Num == 0)
  875. return;
  876. // If the instruction has memory operands, then adjust the offset
  877. // when the instruction appears in different stages.
  878. if (NewMI.memoperands_empty())
  879. return;
  880. SmallVector<MachineMemOperand *, 2> NewMMOs;
  881. for (MachineMemOperand *MMO : NewMI.memoperands()) {
  882. // TODO: Figure out whether isAtomic is really necessary (see D57601).
  883. if (MMO->isVolatile() || MMO->isAtomic() ||
  884. (MMO->isInvariant() && MMO->isDereferenceable()) ||
  885. (!MMO->getValue())) {
  886. NewMMOs.push_back(MMO);
  887. continue;
  888. }
  889. unsigned Delta;
  890. if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
  891. int64_t AdjOffset = Delta * Num;
  892. NewMMOs.push_back(
  893. MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
  894. } else {
  895. NewMMOs.push_back(
  896. MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
  897. }
  898. }
  899. NewMI.setMemRefs(MF, NewMMOs);
  900. }
  901. /// Clone the instruction for the new pipelined loop and update the
  902. /// memory operands, if needed.
  903. MachineInstr *ModuloScheduleExpander::cloneInstr(MachineInstr *OldMI,
  904. unsigned CurStageNum,
  905. unsigned InstStageNum) {
  906. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  907. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  908. return NewMI;
  909. }
  910. /// Clone the instruction for the new pipelined loop. If needed, this
  911. /// function updates the instruction using the values saved in the
  912. /// InstrChanges structure.
  913. MachineInstr *ModuloScheduleExpander::cloneAndChangeInstr(
  914. MachineInstr *OldMI, unsigned CurStageNum, unsigned InstStageNum) {
  915. MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
  916. auto It = InstrChanges.find(OldMI);
  917. if (It != InstrChanges.end()) {
  918. std::pair<unsigned, int64_t> RegAndOffset = It->second;
  919. unsigned BasePos, OffsetPos;
  920. if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
  921. return nullptr;
  922. int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
  923. MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
  924. if (Schedule.getStage(LoopDef) > (signed)InstStageNum)
  925. NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
  926. NewMI->getOperand(OffsetPos).setImm(NewOffset);
  927. }
  928. updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
  929. return NewMI;
  930. }
  931. /// Update the machine instruction with new virtual registers. This
  932. /// function may change the definitions and/or uses.
  933. void ModuloScheduleExpander::updateInstruction(MachineInstr *NewMI,
  934. bool LastDef,
  935. unsigned CurStageNum,
  936. unsigned InstrStageNum,
  937. ValueMapTy *VRMap) {
  938. for (MachineOperand &MO : NewMI->operands()) {
  939. if (!MO.isReg() || !MO.getReg().isVirtual())
  940. continue;
  941. Register reg = MO.getReg();
  942. if (MO.isDef()) {
  943. // Create a new virtual register for the definition.
  944. const TargetRegisterClass *RC = MRI.getRegClass(reg);
  945. Register NewReg = MRI.createVirtualRegister(RC);
  946. MO.setReg(NewReg);
  947. VRMap[CurStageNum][reg] = NewReg;
  948. if (LastDef)
  949. replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
  950. } else if (MO.isUse()) {
  951. MachineInstr *Def = MRI.getVRegDef(reg);
  952. // Compute the stage that contains the last definition for instruction.
  953. int DefStageNum = Schedule.getStage(Def);
  954. unsigned StageNum = CurStageNum;
  955. if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
  956. // Compute the difference in stages between the defintion and the use.
  957. unsigned StageDiff = (InstrStageNum - DefStageNum);
  958. // Make an adjustment to get the last definition.
  959. StageNum -= StageDiff;
  960. }
  961. if (VRMap[StageNum].count(reg))
  962. MO.setReg(VRMap[StageNum][reg]);
  963. }
  964. }
  965. }
  966. /// Return the instruction in the loop that defines the register.
  967. /// If the definition is a Phi, then follow the Phi operand to
  968. /// the instruction in the loop.
  969. MachineInstr *ModuloScheduleExpander::findDefInLoop(unsigned Reg) {
  970. SmallPtrSet<MachineInstr *, 8> Visited;
  971. MachineInstr *Def = MRI.getVRegDef(Reg);
  972. while (Def->isPHI()) {
  973. if (!Visited.insert(Def).second)
  974. break;
  975. for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
  976. if (Def->getOperand(i + 1).getMBB() == BB) {
  977. Def = MRI.getVRegDef(Def->getOperand(i).getReg());
  978. break;
  979. }
  980. }
  981. return Def;
  982. }
  983. /// Return the new name for the value from the previous stage.
  984. unsigned ModuloScheduleExpander::getPrevMapVal(
  985. unsigned StageNum, unsigned PhiStage, unsigned LoopVal, unsigned LoopStage,
  986. ValueMapTy *VRMap, MachineBasicBlock *BB) {
  987. unsigned PrevVal = 0;
  988. if (StageNum > PhiStage) {
  989. MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
  990. if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
  991. // The name is defined in the previous stage.
  992. PrevVal = VRMap[StageNum - 1][LoopVal];
  993. else if (VRMap[StageNum].count(LoopVal))
  994. // The previous name is defined in the current stage when the instruction
  995. // order is swapped.
  996. PrevVal = VRMap[StageNum][LoopVal];
  997. else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
  998. // The loop value hasn't yet been scheduled.
  999. PrevVal = LoopVal;
  1000. else if (StageNum == PhiStage + 1)
  1001. // The loop value is another phi, which has not been scheduled.
  1002. PrevVal = getInitPhiReg(*LoopInst, BB);
  1003. else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
  1004. // The loop value is another phi, which has been scheduled.
  1005. PrevVal =
  1006. getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
  1007. LoopStage, VRMap, BB);
  1008. }
  1009. return PrevVal;
  1010. }
  1011. /// Rewrite the Phi values in the specified block to use the mappings
  1012. /// from the initial operand. Once the Phi is scheduled, we switch
  1013. /// to using the loop value instead of the Phi value, so those names
  1014. /// do not need to be rewritten.
  1015. void ModuloScheduleExpander::rewritePhiValues(MachineBasicBlock *NewBB,
  1016. unsigned StageNum,
  1017. ValueMapTy *VRMap,
  1018. InstrMapTy &InstrMap) {
  1019. for (auto &PHI : BB->phis()) {
  1020. unsigned InitVal = 0;
  1021. unsigned LoopVal = 0;
  1022. getPhiRegs(PHI, BB, InitVal, LoopVal);
  1023. Register PhiDef = PHI.getOperand(0).getReg();
  1024. unsigned PhiStage = (unsigned)Schedule.getStage(MRI.getVRegDef(PhiDef));
  1025. unsigned LoopStage = (unsigned)Schedule.getStage(MRI.getVRegDef(LoopVal));
  1026. unsigned NumPhis = getStagesForPhi(PhiDef);
  1027. if (NumPhis > StageNum)
  1028. NumPhis = StageNum;
  1029. for (unsigned np = 0; np <= NumPhis; ++np) {
  1030. unsigned NewVal =
  1031. getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
  1032. if (!NewVal)
  1033. NewVal = InitVal;
  1034. rewriteScheduledInstr(NewBB, InstrMap, StageNum - np, np, &PHI, PhiDef,
  1035. NewVal);
  1036. }
  1037. }
  1038. }
  1039. /// Rewrite a previously scheduled instruction to use the register value
  1040. /// from the new instruction. Make sure the instruction occurs in the
  1041. /// basic block, and we don't change the uses in the new instruction.
  1042. void ModuloScheduleExpander::rewriteScheduledInstr(
  1043. MachineBasicBlock *BB, InstrMapTy &InstrMap, unsigned CurStageNum,
  1044. unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, unsigned NewReg,
  1045. unsigned PrevReg) {
  1046. bool InProlog = (CurStageNum < (unsigned)Schedule.getNumStages() - 1);
  1047. int StagePhi = Schedule.getStage(Phi) + PhiNum;
  1048. // Rewrite uses that have been scheduled already to use the new
  1049. // Phi register.
  1050. for (MachineOperand &UseOp :
  1051. llvm::make_early_inc_range(MRI.use_operands(OldReg))) {
  1052. MachineInstr *UseMI = UseOp.getParent();
  1053. if (UseMI->getParent() != BB)
  1054. continue;
  1055. if (UseMI->isPHI()) {
  1056. if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
  1057. continue;
  1058. if (getLoopPhiReg(*UseMI, BB) != OldReg)
  1059. continue;
  1060. }
  1061. InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
  1062. assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
  1063. MachineInstr *OrigMI = OrigInstr->second;
  1064. int StageSched = Schedule.getStage(OrigMI);
  1065. int CycleSched = Schedule.getCycle(OrigMI);
  1066. unsigned ReplaceReg = 0;
  1067. // This is the stage for the scheduled instruction.
  1068. if (StagePhi == StageSched && Phi->isPHI()) {
  1069. int CyclePhi = Schedule.getCycle(Phi);
  1070. if (PrevReg && InProlog)
  1071. ReplaceReg = PrevReg;
  1072. else if (PrevReg && !isLoopCarried(*Phi) &&
  1073. (CyclePhi <= CycleSched || OrigMI->isPHI()))
  1074. ReplaceReg = PrevReg;
  1075. else
  1076. ReplaceReg = NewReg;
  1077. }
  1078. // The scheduled instruction occurs before the scheduled Phi, and the
  1079. // Phi is not loop carried.
  1080. if (!InProlog && StagePhi + 1 == StageSched && !isLoopCarried(*Phi))
  1081. ReplaceReg = NewReg;
  1082. if (StagePhi > StageSched && Phi->isPHI())
  1083. ReplaceReg = NewReg;
  1084. if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
  1085. ReplaceReg = NewReg;
  1086. if (ReplaceReg) {
  1087. const TargetRegisterClass *NRC =
  1088. MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
  1089. if (NRC)
  1090. UseOp.setReg(ReplaceReg);
  1091. else {
  1092. Register SplitReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
  1093. BuildMI(*BB, UseMI, UseMI->getDebugLoc(), TII->get(TargetOpcode::COPY),
  1094. SplitReg)
  1095. .addReg(ReplaceReg);
  1096. UseOp.setReg(SplitReg);
  1097. }
  1098. }
  1099. }
  1100. }
  1101. bool ModuloScheduleExpander::isLoopCarried(MachineInstr &Phi) {
  1102. if (!Phi.isPHI())
  1103. return false;
  1104. int DefCycle = Schedule.getCycle(&Phi);
  1105. int DefStage = Schedule.getStage(&Phi);
  1106. unsigned InitVal = 0;
  1107. unsigned LoopVal = 0;
  1108. getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
  1109. MachineInstr *Use = MRI.getVRegDef(LoopVal);
  1110. if (!Use || Use->isPHI())
  1111. return true;
  1112. int LoopCycle = Schedule.getCycle(Use);
  1113. int LoopStage = Schedule.getStage(Use);
  1114. return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
  1115. }
  1116. //===----------------------------------------------------------------------===//
  1117. // PeelingModuloScheduleExpander implementation
  1118. //===----------------------------------------------------------------------===//
  1119. // This is a reimplementation of ModuloScheduleExpander that works by creating
  1120. // a fully correct steady-state kernel and peeling off the prolog and epilogs.
  1121. //===----------------------------------------------------------------------===//
  1122. namespace {
  1123. // Remove any dead phis in MBB. Dead phis either have only one block as input
  1124. // (in which case they are the identity) or have no uses.
  1125. void EliminateDeadPhis(MachineBasicBlock *MBB, MachineRegisterInfo &MRI,
  1126. LiveIntervals *LIS, bool KeepSingleSrcPhi = false) {
  1127. bool Changed = true;
  1128. while (Changed) {
  1129. Changed = false;
  1130. for (MachineInstr &MI : llvm::make_early_inc_range(MBB->phis())) {
  1131. assert(MI.isPHI());
  1132. if (MRI.use_empty(MI.getOperand(0).getReg())) {
  1133. if (LIS)
  1134. LIS->RemoveMachineInstrFromMaps(MI);
  1135. MI.eraseFromParent();
  1136. Changed = true;
  1137. } else if (!KeepSingleSrcPhi && MI.getNumExplicitOperands() == 3) {
  1138. const TargetRegisterClass *ConstrainRegClass =
  1139. MRI.constrainRegClass(MI.getOperand(1).getReg(),
  1140. MRI.getRegClass(MI.getOperand(0).getReg()));
  1141. assert(ConstrainRegClass &&
  1142. "Expected a valid constrained register class!");
  1143. (void)ConstrainRegClass;
  1144. MRI.replaceRegWith(MI.getOperand(0).getReg(),
  1145. MI.getOperand(1).getReg());
  1146. if (LIS)
  1147. LIS->RemoveMachineInstrFromMaps(MI);
  1148. MI.eraseFromParent();
  1149. Changed = true;
  1150. }
  1151. }
  1152. }
  1153. }
  1154. /// Rewrites the kernel block in-place to adhere to the given schedule.
  1155. /// KernelRewriter holds all of the state required to perform the rewriting.
  1156. class KernelRewriter {
  1157. ModuloSchedule &S;
  1158. MachineBasicBlock *BB;
  1159. MachineBasicBlock *PreheaderBB, *ExitBB;
  1160. MachineRegisterInfo &MRI;
  1161. const TargetInstrInfo *TII;
  1162. LiveIntervals *LIS;
  1163. // Map from register class to canonical undef register for that class.
  1164. DenseMap<const TargetRegisterClass *, Register> Undefs;
  1165. // Map from <LoopReg, InitReg> to phi register for all created phis. Note that
  1166. // this map is only used when InitReg is non-undef.
  1167. DenseMap<std::pair<unsigned, unsigned>, Register> Phis;
  1168. // Map from LoopReg to phi register where the InitReg is undef.
  1169. DenseMap<Register, Register> UndefPhis;
  1170. // Reg is used by MI. Return the new register MI should use to adhere to the
  1171. // schedule. Insert phis as necessary.
  1172. Register remapUse(Register Reg, MachineInstr &MI);
  1173. // Insert a phi that carries LoopReg from the loop body and InitReg otherwise.
  1174. // If InitReg is not given it is chosen arbitrarily. It will either be undef
  1175. // or will be chosen so as to share another phi.
  1176. Register phi(Register LoopReg, std::optional<Register> InitReg = {},
  1177. const TargetRegisterClass *RC = nullptr);
  1178. // Create an undef register of the given register class.
  1179. Register undef(const TargetRegisterClass *RC);
  1180. public:
  1181. KernelRewriter(MachineLoop &L, ModuloSchedule &S, MachineBasicBlock *LoopBB,
  1182. LiveIntervals *LIS = nullptr);
  1183. void rewrite();
  1184. };
  1185. } // namespace
  1186. KernelRewriter::KernelRewriter(MachineLoop &L, ModuloSchedule &S,
  1187. MachineBasicBlock *LoopBB, LiveIntervals *LIS)
  1188. : S(S), BB(LoopBB), PreheaderBB(L.getLoopPreheader()),
  1189. ExitBB(L.getExitBlock()), MRI(BB->getParent()->getRegInfo()),
  1190. TII(BB->getParent()->getSubtarget().getInstrInfo()), LIS(LIS) {
  1191. PreheaderBB = *BB->pred_begin();
  1192. if (PreheaderBB == BB)
  1193. PreheaderBB = *std::next(BB->pred_begin());
  1194. }
  1195. void KernelRewriter::rewrite() {
  1196. // Rearrange the loop to be in schedule order. Note that the schedule may
  1197. // contain instructions that are not owned by the loop block (InstrChanges and
  1198. // friends), so we gracefully handle unowned instructions and delete any
  1199. // instructions that weren't in the schedule.
  1200. auto InsertPt = BB->getFirstTerminator();
  1201. MachineInstr *FirstMI = nullptr;
  1202. for (MachineInstr *MI : S.getInstructions()) {
  1203. if (MI->isPHI())
  1204. continue;
  1205. if (MI->getParent())
  1206. MI->removeFromParent();
  1207. BB->insert(InsertPt, MI);
  1208. if (!FirstMI)
  1209. FirstMI = MI;
  1210. }
  1211. assert(FirstMI && "Failed to find first MI in schedule");
  1212. // At this point all of the scheduled instructions are between FirstMI
  1213. // and the end of the block. Kill from the first non-phi to FirstMI.
  1214. for (auto I = BB->getFirstNonPHI(); I != FirstMI->getIterator();) {
  1215. if (LIS)
  1216. LIS->RemoveMachineInstrFromMaps(*I);
  1217. (I++)->eraseFromParent();
  1218. }
  1219. // Now remap every instruction in the loop.
  1220. for (MachineInstr &MI : *BB) {
  1221. if (MI.isPHI() || MI.isTerminator())
  1222. continue;
  1223. for (MachineOperand &MO : MI.uses()) {
  1224. if (!MO.isReg() || MO.getReg().isPhysical() || MO.isImplicit())
  1225. continue;
  1226. Register Reg = remapUse(MO.getReg(), MI);
  1227. MO.setReg(Reg);
  1228. }
  1229. }
  1230. EliminateDeadPhis(BB, MRI, LIS);
  1231. // Ensure a phi exists for all instructions that are either referenced by
  1232. // an illegal phi or by an instruction outside the loop. This allows us to
  1233. // treat remaps of these values the same as "normal" values that come from
  1234. // loop-carried phis.
  1235. for (auto MI = BB->getFirstNonPHI(); MI != BB->end(); ++MI) {
  1236. if (MI->isPHI()) {
  1237. Register R = MI->getOperand(0).getReg();
  1238. phi(R);
  1239. continue;
  1240. }
  1241. for (MachineOperand &Def : MI->defs()) {
  1242. for (MachineInstr &MI : MRI.use_instructions(Def.getReg())) {
  1243. if (MI.getParent() != BB) {
  1244. phi(Def.getReg());
  1245. break;
  1246. }
  1247. }
  1248. }
  1249. }
  1250. }
  1251. Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) {
  1252. MachineInstr *Producer = MRI.getUniqueVRegDef(Reg);
  1253. if (!Producer)
  1254. return Reg;
  1255. int ConsumerStage = S.getStage(&MI);
  1256. if (!Producer->isPHI()) {
  1257. // Non-phi producers are simple to remap. Insert as many phis as the
  1258. // difference between the consumer and producer stages.
  1259. if (Producer->getParent() != BB)
  1260. // Producer was not inside the loop. Use the register as-is.
  1261. return Reg;
  1262. int ProducerStage = S.getStage(Producer);
  1263. assert(ConsumerStage != -1 &&
  1264. "In-loop consumer should always be scheduled!");
  1265. assert(ConsumerStage >= ProducerStage);
  1266. unsigned StageDiff = ConsumerStage - ProducerStage;
  1267. for (unsigned I = 0; I < StageDiff; ++I)
  1268. Reg = phi(Reg);
  1269. return Reg;
  1270. }
  1271. // First, dive through the phi chain to find the defaults for the generated
  1272. // phis.
  1273. SmallVector<std::optional<Register>, 4> Defaults;
  1274. Register LoopReg = Reg;
  1275. auto LoopProducer = Producer;
  1276. while (LoopProducer->isPHI() && LoopProducer->getParent() == BB) {
  1277. LoopReg = getLoopPhiReg(*LoopProducer, BB);
  1278. Defaults.emplace_back(getInitPhiReg(*LoopProducer, BB));
  1279. LoopProducer = MRI.getUniqueVRegDef(LoopReg);
  1280. assert(LoopProducer);
  1281. }
  1282. int LoopProducerStage = S.getStage(LoopProducer);
  1283. std::optional<Register> IllegalPhiDefault;
  1284. if (LoopProducerStage == -1) {
  1285. // Do nothing.
  1286. } else if (LoopProducerStage > ConsumerStage) {
  1287. // This schedule is only representable if ProducerStage == ConsumerStage+1.
  1288. // In addition, Consumer's cycle must be scheduled after Producer in the
  1289. // rescheduled loop. This is enforced by the pipeliner's ASAP and ALAP
  1290. // functions.
  1291. #ifndef NDEBUG // Silence unused variables in non-asserts mode.
  1292. int LoopProducerCycle = S.getCycle(LoopProducer);
  1293. int ConsumerCycle = S.getCycle(&MI);
  1294. #endif
  1295. assert(LoopProducerCycle <= ConsumerCycle);
  1296. assert(LoopProducerStage == ConsumerStage + 1);
  1297. // Peel off the first phi from Defaults and insert a phi between producer
  1298. // and consumer. This phi will not be at the front of the block so we
  1299. // consider it illegal. It will only exist during the rewrite process; it
  1300. // needs to exist while we peel off prologs because these could take the
  1301. // default value. After that we can replace all uses with the loop producer
  1302. // value.
  1303. IllegalPhiDefault = Defaults.front();
  1304. Defaults.erase(Defaults.begin());
  1305. } else {
  1306. assert(ConsumerStage >= LoopProducerStage);
  1307. int StageDiff = ConsumerStage - LoopProducerStage;
  1308. if (StageDiff > 0) {
  1309. LLVM_DEBUG(dbgs() << " -- padding defaults array from " << Defaults.size()
  1310. << " to " << (Defaults.size() + StageDiff) << "\n");
  1311. // If we need more phis than we have defaults for, pad out with undefs for
  1312. // the earliest phis, which are at the end of the defaults chain (the
  1313. // chain is in reverse order).
  1314. Defaults.resize(Defaults.size() + StageDiff,
  1315. Defaults.empty() ? std::optional<Register>()
  1316. : Defaults.back());
  1317. }
  1318. }
  1319. // Now we know the number of stages to jump back, insert the phi chain.
  1320. auto DefaultI = Defaults.rbegin();
  1321. while (DefaultI != Defaults.rend())
  1322. LoopReg = phi(LoopReg, *DefaultI++, MRI.getRegClass(Reg));
  1323. if (IllegalPhiDefault) {
  1324. // The consumer optionally consumes LoopProducer in the same iteration
  1325. // (because the producer is scheduled at an earlier cycle than the consumer)
  1326. // or the initial value. To facilitate this we create an illegal block here
  1327. // by embedding a phi in the middle of the block. We will fix this up
  1328. // immediately prior to pruning.
  1329. auto RC = MRI.getRegClass(Reg);
  1330. Register R = MRI.createVirtualRegister(RC);
  1331. MachineInstr *IllegalPhi =
  1332. BuildMI(*BB, MI, DebugLoc(), TII->get(TargetOpcode::PHI), R)
  1333. .addReg(*IllegalPhiDefault)
  1334. .addMBB(PreheaderBB) // Block choice is arbitrary and has no effect.
  1335. .addReg(LoopReg)
  1336. .addMBB(BB); // Block choice is arbitrary and has no effect.
  1337. // Illegal phi should belong to the producer stage so that it can be
  1338. // filtered correctly during peeling.
  1339. S.setStage(IllegalPhi, LoopProducerStage);
  1340. return R;
  1341. }
  1342. return LoopReg;
  1343. }
  1344. Register KernelRewriter::phi(Register LoopReg, std::optional<Register> InitReg,
  1345. const TargetRegisterClass *RC) {
  1346. // If the init register is not undef, try and find an existing phi.
  1347. if (InitReg) {
  1348. auto I = Phis.find({LoopReg, *InitReg});
  1349. if (I != Phis.end())
  1350. return I->second;
  1351. } else {
  1352. for (auto &KV : Phis) {
  1353. if (KV.first.first == LoopReg)
  1354. return KV.second;
  1355. }
  1356. }
  1357. // InitReg is either undef or no existing phi takes InitReg as input. Try and
  1358. // find a phi that takes undef as input.
  1359. auto I = UndefPhis.find(LoopReg);
  1360. if (I != UndefPhis.end()) {
  1361. Register R = I->second;
  1362. if (!InitReg)
  1363. // Found a phi taking undef as input, and this input is undef so return
  1364. // without any more changes.
  1365. return R;
  1366. // Found a phi taking undef as input, so rewrite it to take InitReg.
  1367. MachineInstr *MI = MRI.getVRegDef(R);
  1368. MI->getOperand(1).setReg(*InitReg);
  1369. Phis.insert({{LoopReg, *InitReg}, R});
  1370. const TargetRegisterClass *ConstrainRegClass =
  1371. MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
  1372. assert(ConstrainRegClass && "Expected a valid constrained register class!");
  1373. (void)ConstrainRegClass;
  1374. UndefPhis.erase(I);
  1375. return R;
  1376. }
  1377. // Failed to find any existing phi to reuse, so create a new one.
  1378. if (!RC)
  1379. RC = MRI.getRegClass(LoopReg);
  1380. Register R = MRI.createVirtualRegister(RC);
  1381. if (InitReg) {
  1382. const TargetRegisterClass *ConstrainRegClass =
  1383. MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
  1384. assert(ConstrainRegClass && "Expected a valid constrained register class!");
  1385. (void)ConstrainRegClass;
  1386. }
  1387. BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
  1388. .addReg(InitReg ? *InitReg : undef(RC))
  1389. .addMBB(PreheaderBB)
  1390. .addReg(LoopReg)
  1391. .addMBB(BB);
  1392. if (!InitReg)
  1393. UndefPhis[LoopReg] = R;
  1394. else
  1395. Phis[{LoopReg, *InitReg}] = R;
  1396. return R;
  1397. }
  1398. Register KernelRewriter::undef(const TargetRegisterClass *RC) {
  1399. Register &R = Undefs[RC];
  1400. if (R == 0) {
  1401. // Create an IMPLICIT_DEF that defines this register if we need it.
  1402. // All uses of this should be removed by the time we have finished unrolling
  1403. // prologs and epilogs.
  1404. R = MRI.createVirtualRegister(RC);
  1405. auto *InsertBB = &PreheaderBB->getParent()->front();
  1406. BuildMI(*InsertBB, InsertBB->getFirstTerminator(), DebugLoc(),
  1407. TII->get(TargetOpcode::IMPLICIT_DEF), R);
  1408. }
  1409. return R;
  1410. }
  1411. namespace {
  1412. /// Describes an operand in the kernel of a pipelined loop. Characteristics of
  1413. /// the operand are discovered, such as how many in-loop PHIs it has to jump
  1414. /// through and defaults for these phis.
  1415. class KernelOperandInfo {
  1416. MachineBasicBlock *BB;
  1417. MachineRegisterInfo &MRI;
  1418. SmallVector<Register, 4> PhiDefaults;
  1419. MachineOperand *Source;
  1420. MachineOperand *Target;
  1421. public:
  1422. KernelOperandInfo(MachineOperand *MO, MachineRegisterInfo &MRI,
  1423. const SmallPtrSetImpl<MachineInstr *> &IllegalPhis)
  1424. : MRI(MRI) {
  1425. Source = MO;
  1426. BB = MO->getParent()->getParent();
  1427. while (isRegInLoop(MO)) {
  1428. MachineInstr *MI = MRI.getVRegDef(MO->getReg());
  1429. if (MI->isFullCopy()) {
  1430. MO = &MI->getOperand(1);
  1431. continue;
  1432. }
  1433. if (!MI->isPHI())
  1434. break;
  1435. // If this is an illegal phi, don't count it in distance.
  1436. if (IllegalPhis.count(MI)) {
  1437. MO = &MI->getOperand(3);
  1438. continue;
  1439. }
  1440. Register Default = getInitPhiReg(*MI, BB);
  1441. MO = MI->getOperand(2).getMBB() == BB ? &MI->getOperand(1)
  1442. : &MI->getOperand(3);
  1443. PhiDefaults.push_back(Default);
  1444. }
  1445. Target = MO;
  1446. }
  1447. bool operator==(const KernelOperandInfo &Other) const {
  1448. return PhiDefaults.size() == Other.PhiDefaults.size();
  1449. }
  1450. void print(raw_ostream &OS) const {
  1451. OS << "use of " << *Source << ": distance(" << PhiDefaults.size() << ") in "
  1452. << *Source->getParent();
  1453. }
  1454. private:
  1455. bool isRegInLoop(MachineOperand *MO) {
  1456. return MO->isReg() && MO->getReg().isVirtual() &&
  1457. MRI.getVRegDef(MO->getReg())->getParent() == BB;
  1458. }
  1459. };
  1460. } // namespace
  1461. MachineBasicBlock *
  1462. PeelingModuloScheduleExpander::peelKernel(LoopPeelDirection LPD) {
  1463. MachineBasicBlock *NewBB = PeelSingleBlockLoop(LPD, BB, MRI, TII);
  1464. if (LPD == LPD_Front)
  1465. PeeledFront.push_back(NewBB);
  1466. else
  1467. PeeledBack.push_front(NewBB);
  1468. for (auto I = BB->begin(), NI = NewBB->begin(); !I->isTerminator();
  1469. ++I, ++NI) {
  1470. CanonicalMIs[&*I] = &*I;
  1471. CanonicalMIs[&*NI] = &*I;
  1472. BlockMIs[{NewBB, &*I}] = &*NI;
  1473. BlockMIs[{BB, &*I}] = &*I;
  1474. }
  1475. return NewBB;
  1476. }
  1477. void PeelingModuloScheduleExpander::filterInstructions(MachineBasicBlock *MB,
  1478. int MinStage) {
  1479. for (auto I = MB->getFirstInstrTerminator()->getReverseIterator();
  1480. I != std::next(MB->getFirstNonPHI()->getReverseIterator());) {
  1481. MachineInstr *MI = &*I++;
  1482. int Stage = getStage(MI);
  1483. if (Stage == -1 || Stage >= MinStage)
  1484. continue;
  1485. for (MachineOperand &DefMO : MI->defs()) {
  1486. SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
  1487. for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
  1488. // Only PHIs can use values from this block by construction.
  1489. // Match with the equivalent PHI in B.
  1490. assert(UseMI.isPHI());
  1491. Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
  1492. MI->getParent());
  1493. Subs.emplace_back(&UseMI, Reg);
  1494. }
  1495. for (auto &Sub : Subs)
  1496. Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
  1497. *MRI.getTargetRegisterInfo());
  1498. }
  1499. if (LIS)
  1500. LIS->RemoveMachineInstrFromMaps(*MI);
  1501. MI->eraseFromParent();
  1502. }
  1503. }
  1504. void PeelingModuloScheduleExpander::moveStageBetweenBlocks(
  1505. MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage) {
  1506. auto InsertPt = DestBB->getFirstNonPHI();
  1507. DenseMap<Register, Register> Remaps;
  1508. for (MachineInstr &MI : llvm::make_early_inc_range(
  1509. llvm::make_range(SourceBB->getFirstNonPHI(), SourceBB->end()))) {
  1510. if (MI.isPHI()) {
  1511. // This is an illegal PHI. If we move any instructions using an illegal
  1512. // PHI, we need to create a legal Phi.
  1513. if (getStage(&MI) != Stage) {
  1514. // The legal Phi is not necessary if the illegal phi's stage
  1515. // is being moved.
  1516. Register PhiR = MI.getOperand(0).getReg();
  1517. auto RC = MRI.getRegClass(PhiR);
  1518. Register NR = MRI.createVirtualRegister(RC);
  1519. MachineInstr *NI = BuildMI(*DestBB, DestBB->getFirstNonPHI(),
  1520. DebugLoc(), TII->get(TargetOpcode::PHI), NR)
  1521. .addReg(PhiR)
  1522. .addMBB(SourceBB);
  1523. BlockMIs[{DestBB, CanonicalMIs[&MI]}] = NI;
  1524. CanonicalMIs[NI] = CanonicalMIs[&MI];
  1525. Remaps[PhiR] = NR;
  1526. }
  1527. }
  1528. if (getStage(&MI) != Stage)
  1529. continue;
  1530. MI.removeFromParent();
  1531. DestBB->insert(InsertPt, &MI);
  1532. auto *KernelMI = CanonicalMIs[&MI];
  1533. BlockMIs[{DestBB, KernelMI}] = &MI;
  1534. BlockMIs.erase({SourceBB, KernelMI});
  1535. }
  1536. SmallVector<MachineInstr *, 4> PhiToDelete;
  1537. for (MachineInstr &MI : DestBB->phis()) {
  1538. assert(MI.getNumOperands() == 3);
  1539. MachineInstr *Def = MRI.getVRegDef(MI.getOperand(1).getReg());
  1540. // If the instruction referenced by the phi is moved inside the block
  1541. // we don't need the phi anymore.
  1542. if (getStage(Def) == Stage) {
  1543. Register PhiReg = MI.getOperand(0).getReg();
  1544. assert(Def->findRegisterDefOperandIdx(MI.getOperand(1).getReg()) != -1);
  1545. MRI.replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
  1546. MI.getOperand(0).setReg(PhiReg);
  1547. PhiToDelete.push_back(&MI);
  1548. }
  1549. }
  1550. for (auto *P : PhiToDelete)
  1551. P->eraseFromParent();
  1552. InsertPt = DestBB->getFirstNonPHI();
  1553. // Helper to clone Phi instructions into the destination block. We clone Phi
  1554. // greedily to avoid combinatorial explosion of Phi instructions.
  1555. auto clonePhi = [&](MachineInstr *Phi) {
  1556. MachineInstr *NewMI = MF.CloneMachineInstr(Phi);
  1557. DestBB->insert(InsertPt, NewMI);
  1558. Register OrigR = Phi->getOperand(0).getReg();
  1559. Register R = MRI.createVirtualRegister(MRI.getRegClass(OrigR));
  1560. NewMI->getOperand(0).setReg(R);
  1561. NewMI->getOperand(1).setReg(OrigR);
  1562. NewMI->getOperand(2).setMBB(*DestBB->pred_begin());
  1563. Remaps[OrigR] = R;
  1564. CanonicalMIs[NewMI] = CanonicalMIs[Phi];
  1565. BlockMIs[{DestBB, CanonicalMIs[Phi]}] = NewMI;
  1566. PhiNodeLoopIteration[NewMI] = PhiNodeLoopIteration[Phi];
  1567. return R;
  1568. };
  1569. for (auto I = DestBB->getFirstNonPHI(); I != DestBB->end(); ++I) {
  1570. for (MachineOperand &MO : I->uses()) {
  1571. if (!MO.isReg())
  1572. continue;
  1573. if (Remaps.count(MO.getReg()))
  1574. MO.setReg(Remaps[MO.getReg()]);
  1575. else {
  1576. // If we are using a phi from the source block we need to add a new phi
  1577. // pointing to the old one.
  1578. MachineInstr *Use = MRI.getUniqueVRegDef(MO.getReg());
  1579. if (Use && Use->isPHI() && Use->getParent() == SourceBB) {
  1580. Register R = clonePhi(Use);
  1581. MO.setReg(R);
  1582. }
  1583. }
  1584. }
  1585. }
  1586. }
  1587. Register
  1588. PeelingModuloScheduleExpander::getPhiCanonicalReg(MachineInstr *CanonicalPhi,
  1589. MachineInstr *Phi) {
  1590. unsigned distance = PhiNodeLoopIteration[Phi];
  1591. MachineInstr *CanonicalUse = CanonicalPhi;
  1592. Register CanonicalUseReg = CanonicalUse->getOperand(0).getReg();
  1593. for (unsigned I = 0; I < distance; ++I) {
  1594. assert(CanonicalUse->isPHI());
  1595. assert(CanonicalUse->getNumOperands() == 5);
  1596. unsigned LoopRegIdx = 3, InitRegIdx = 1;
  1597. if (CanonicalUse->getOperand(2).getMBB() == CanonicalUse->getParent())
  1598. std::swap(LoopRegIdx, InitRegIdx);
  1599. CanonicalUseReg = CanonicalUse->getOperand(LoopRegIdx).getReg();
  1600. CanonicalUse = MRI.getVRegDef(CanonicalUseReg);
  1601. }
  1602. return CanonicalUseReg;
  1603. }
  1604. void PeelingModuloScheduleExpander::peelPrologAndEpilogs() {
  1605. BitVector LS(Schedule.getNumStages(), true);
  1606. BitVector AS(Schedule.getNumStages(), true);
  1607. LiveStages[BB] = LS;
  1608. AvailableStages[BB] = AS;
  1609. // Peel out the prologs.
  1610. LS.reset();
  1611. for (int I = 0; I < Schedule.getNumStages() - 1; ++I) {
  1612. LS[I] = true;
  1613. Prologs.push_back(peelKernel(LPD_Front));
  1614. LiveStages[Prologs.back()] = LS;
  1615. AvailableStages[Prologs.back()] = LS;
  1616. }
  1617. // Create a block that will end up as the new loop exiting block (dominated by
  1618. // all prologs and epilogs). It will only contain PHIs, in the same order as
  1619. // BB's PHIs. This gives us a poor-man's LCSSA with the inductive property
  1620. // that the exiting block is a (sub) clone of BB. This in turn gives us the
  1621. // property that any value deffed in BB but used outside of BB is used by a
  1622. // PHI in the exiting block.
  1623. MachineBasicBlock *ExitingBB = CreateLCSSAExitingBlock();
  1624. EliminateDeadPhis(ExitingBB, MRI, LIS, /*KeepSingleSrcPhi=*/true);
  1625. // Push out the epilogs, again in reverse order.
  1626. // We can't assume anything about the minumum loop trip count at this point,
  1627. // so emit a fairly complex epilog.
  1628. // We first peel number of stages minus one epilogue. Then we remove dead
  1629. // stages and reorder instructions based on their stage. If we have 3 stages
  1630. // we generate first:
  1631. // E0[3, 2, 1]
  1632. // E1[3', 2']
  1633. // E2[3'']
  1634. // And then we move instructions based on their stages to have:
  1635. // E0[3]
  1636. // E1[2, 3']
  1637. // E2[1, 2', 3'']
  1638. // The transformation is legal because we only move instructions past
  1639. // instructions of a previous loop iteration.
  1640. for (int I = 1; I <= Schedule.getNumStages() - 1; ++I) {
  1641. Epilogs.push_back(peelKernel(LPD_Back));
  1642. MachineBasicBlock *B = Epilogs.back();
  1643. filterInstructions(B, Schedule.getNumStages() - I);
  1644. // Keep track at which iteration each phi belongs to. We need it to know
  1645. // what version of the variable to use during prologue/epilogue stitching.
  1646. EliminateDeadPhis(B, MRI, LIS, /*KeepSingleSrcPhi=*/true);
  1647. for (MachineInstr &Phi : B->phis())
  1648. PhiNodeLoopIteration[&Phi] = Schedule.getNumStages() - I;
  1649. }
  1650. for (size_t I = 0; I < Epilogs.size(); I++) {
  1651. LS.reset();
  1652. for (size_t J = I; J < Epilogs.size(); J++) {
  1653. int Iteration = J;
  1654. unsigned Stage = Schedule.getNumStages() - 1 + I - J;
  1655. // Move stage one block at a time so that Phi nodes are updated correctly.
  1656. for (size_t K = Iteration; K > I; K--)
  1657. moveStageBetweenBlocks(Epilogs[K - 1], Epilogs[K], Stage);
  1658. LS[Stage] = true;
  1659. }
  1660. LiveStages[Epilogs[I]] = LS;
  1661. AvailableStages[Epilogs[I]] = AS;
  1662. }
  1663. // Now we've defined all the prolog and epilog blocks as a fallthrough
  1664. // sequence, add the edges that will be followed if the loop trip count is
  1665. // lower than the number of stages (connecting prologs directly with epilogs).
  1666. auto PI = Prologs.begin();
  1667. auto EI = Epilogs.begin();
  1668. assert(Prologs.size() == Epilogs.size());
  1669. for (; PI != Prologs.end(); ++PI, ++EI) {
  1670. MachineBasicBlock *Pred = *(*EI)->pred_begin();
  1671. (*PI)->addSuccessor(*EI);
  1672. for (MachineInstr &MI : (*EI)->phis()) {
  1673. Register Reg = MI.getOperand(1).getReg();
  1674. MachineInstr *Use = MRI.getUniqueVRegDef(Reg);
  1675. if (Use && Use->getParent() == Pred) {
  1676. MachineInstr *CanonicalUse = CanonicalMIs[Use];
  1677. if (CanonicalUse->isPHI()) {
  1678. // If the use comes from a phi we need to skip as many phi as the
  1679. // distance between the epilogue and the kernel. Trace through the phi
  1680. // chain to find the right value.
  1681. Reg = getPhiCanonicalReg(CanonicalUse, Use);
  1682. }
  1683. Reg = getEquivalentRegisterIn(Reg, *PI);
  1684. }
  1685. MI.addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/false));
  1686. MI.addOperand(MachineOperand::CreateMBB(*PI));
  1687. }
  1688. }
  1689. // Create a list of all blocks in order.
  1690. SmallVector<MachineBasicBlock *, 8> Blocks;
  1691. llvm::copy(PeeledFront, std::back_inserter(Blocks));
  1692. Blocks.push_back(BB);
  1693. llvm::copy(PeeledBack, std::back_inserter(Blocks));
  1694. // Iterate in reverse order over all instructions, remapping as we go.
  1695. for (MachineBasicBlock *B : reverse(Blocks)) {
  1696. for (auto I = B->instr_rbegin();
  1697. I != std::next(B->getFirstNonPHI()->getReverseIterator());) {
  1698. MachineBasicBlock::reverse_instr_iterator MI = I++;
  1699. rewriteUsesOf(&*MI);
  1700. }
  1701. }
  1702. for (auto *MI : IllegalPhisToDelete) {
  1703. if (LIS)
  1704. LIS->RemoveMachineInstrFromMaps(*MI);
  1705. MI->eraseFromParent();
  1706. }
  1707. IllegalPhisToDelete.clear();
  1708. // Now all remapping has been done, we're free to optimize the generated code.
  1709. for (MachineBasicBlock *B : reverse(Blocks))
  1710. EliminateDeadPhis(B, MRI, LIS);
  1711. EliminateDeadPhis(ExitingBB, MRI, LIS);
  1712. }
  1713. MachineBasicBlock *PeelingModuloScheduleExpander::CreateLCSSAExitingBlock() {
  1714. MachineFunction &MF = *BB->getParent();
  1715. MachineBasicBlock *Exit = *BB->succ_begin();
  1716. if (Exit == BB)
  1717. Exit = *std::next(BB->succ_begin());
  1718. MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
  1719. MF.insert(std::next(BB->getIterator()), NewBB);
  1720. // Clone all phis in BB into NewBB and rewrite.
  1721. for (MachineInstr &MI : BB->phis()) {
  1722. auto RC = MRI.getRegClass(MI.getOperand(0).getReg());
  1723. Register OldR = MI.getOperand(3).getReg();
  1724. Register R = MRI.createVirtualRegister(RC);
  1725. SmallVector<MachineInstr *, 4> Uses;
  1726. for (MachineInstr &Use : MRI.use_instructions(OldR))
  1727. if (Use.getParent() != BB)
  1728. Uses.push_back(&Use);
  1729. for (MachineInstr *Use : Uses)
  1730. Use->substituteRegister(OldR, R, /*SubIdx=*/0,
  1731. *MRI.getTargetRegisterInfo());
  1732. MachineInstr *NI = BuildMI(NewBB, DebugLoc(), TII->get(TargetOpcode::PHI), R)
  1733. .addReg(OldR)
  1734. .addMBB(BB);
  1735. BlockMIs[{NewBB, &MI}] = NI;
  1736. CanonicalMIs[NI] = &MI;
  1737. }
  1738. BB->replaceSuccessor(Exit, NewBB);
  1739. Exit->replacePhiUsesWith(BB, NewBB);
  1740. NewBB->addSuccessor(Exit);
  1741. MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
  1742. SmallVector<MachineOperand, 4> Cond;
  1743. bool CanAnalyzeBr = !TII->analyzeBranch(*BB, TBB, FBB, Cond);
  1744. (void)CanAnalyzeBr;
  1745. assert(CanAnalyzeBr && "Must be able to analyze the loop branch!");
  1746. TII->removeBranch(*BB);
  1747. TII->insertBranch(*BB, TBB == Exit ? NewBB : TBB, FBB == Exit ? NewBB : FBB,
  1748. Cond, DebugLoc());
  1749. TII->insertUnconditionalBranch(*NewBB, Exit, DebugLoc());
  1750. return NewBB;
  1751. }
  1752. Register
  1753. PeelingModuloScheduleExpander::getEquivalentRegisterIn(Register Reg,
  1754. MachineBasicBlock *BB) {
  1755. MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
  1756. unsigned OpIdx = MI->findRegisterDefOperandIdx(Reg);
  1757. return BlockMIs[{BB, CanonicalMIs[MI]}]->getOperand(OpIdx).getReg();
  1758. }
  1759. void PeelingModuloScheduleExpander::rewriteUsesOf(MachineInstr *MI) {
  1760. if (MI->isPHI()) {
  1761. // This is an illegal PHI. The loop-carried (desired) value is operand 3,
  1762. // and it is produced by this block.
  1763. Register PhiR = MI->getOperand(0).getReg();
  1764. Register R = MI->getOperand(3).getReg();
  1765. int RMIStage = getStage(MRI.getUniqueVRegDef(R));
  1766. if (RMIStage != -1 && !AvailableStages[MI->getParent()].test(RMIStage))
  1767. R = MI->getOperand(1).getReg();
  1768. MRI.setRegClass(R, MRI.getRegClass(PhiR));
  1769. MRI.replaceRegWith(PhiR, R);
  1770. // Postpone deleting the Phi as it may be referenced by BlockMIs and used
  1771. // later to figure out how to remap registers.
  1772. MI->getOperand(0).setReg(PhiR);
  1773. IllegalPhisToDelete.push_back(MI);
  1774. return;
  1775. }
  1776. int Stage = getStage(MI);
  1777. if (Stage == -1 || LiveStages.count(MI->getParent()) == 0 ||
  1778. LiveStages[MI->getParent()].test(Stage))
  1779. // Instruction is live, no rewriting to do.
  1780. return;
  1781. for (MachineOperand &DefMO : MI->defs()) {
  1782. SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
  1783. for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
  1784. // Only PHIs can use values from this block by construction.
  1785. // Match with the equivalent PHI in B.
  1786. assert(UseMI.isPHI());
  1787. Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
  1788. MI->getParent());
  1789. Subs.emplace_back(&UseMI, Reg);
  1790. }
  1791. for (auto &Sub : Subs)
  1792. Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
  1793. *MRI.getTargetRegisterInfo());
  1794. }
  1795. if (LIS)
  1796. LIS->RemoveMachineInstrFromMaps(*MI);
  1797. MI->eraseFromParent();
  1798. }
  1799. void PeelingModuloScheduleExpander::fixupBranches() {
  1800. // Work outwards from the kernel.
  1801. bool KernelDisposed = false;
  1802. int TC = Schedule.getNumStages() - 1;
  1803. for (auto PI = Prologs.rbegin(), EI = Epilogs.rbegin(); PI != Prologs.rend();
  1804. ++PI, ++EI, --TC) {
  1805. MachineBasicBlock *Prolog = *PI;
  1806. MachineBasicBlock *Fallthrough = *Prolog->succ_begin();
  1807. MachineBasicBlock *Epilog = *EI;
  1808. SmallVector<MachineOperand, 4> Cond;
  1809. TII->removeBranch(*Prolog);
  1810. std::optional<bool> StaticallyGreater =
  1811. LoopInfo->createTripCountGreaterCondition(TC, *Prolog, Cond);
  1812. if (!StaticallyGreater) {
  1813. LLVM_DEBUG(dbgs() << "Dynamic: TC > " << TC << "\n");
  1814. // Dynamically branch based on Cond.
  1815. TII->insertBranch(*Prolog, Epilog, Fallthrough, Cond, DebugLoc());
  1816. } else if (*StaticallyGreater == false) {
  1817. LLVM_DEBUG(dbgs() << "Static-false: TC > " << TC << "\n");
  1818. // Prolog never falls through; branch to epilog and orphan interior
  1819. // blocks. Leave it to unreachable-block-elim to clean up.
  1820. Prolog->removeSuccessor(Fallthrough);
  1821. for (MachineInstr &P : Fallthrough->phis()) {
  1822. P.removeOperand(2);
  1823. P.removeOperand(1);
  1824. }
  1825. TII->insertUnconditionalBranch(*Prolog, Epilog, DebugLoc());
  1826. KernelDisposed = true;
  1827. } else {
  1828. LLVM_DEBUG(dbgs() << "Static-true: TC > " << TC << "\n");
  1829. // Prolog always falls through; remove incoming values in epilog.
  1830. Prolog->removeSuccessor(Epilog);
  1831. for (MachineInstr &P : Epilog->phis()) {
  1832. P.removeOperand(4);
  1833. P.removeOperand(3);
  1834. }
  1835. }
  1836. }
  1837. if (!KernelDisposed) {
  1838. LoopInfo->adjustTripCount(-(Schedule.getNumStages() - 1));
  1839. LoopInfo->setPreheader(Prologs.back());
  1840. } else {
  1841. LoopInfo->disposed();
  1842. }
  1843. }
  1844. void PeelingModuloScheduleExpander::rewriteKernel() {
  1845. KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
  1846. KR.rewrite();
  1847. }
  1848. void PeelingModuloScheduleExpander::expand() {
  1849. BB = Schedule.getLoop()->getTopBlock();
  1850. Preheader = Schedule.getLoop()->getLoopPreheader();
  1851. LLVM_DEBUG(Schedule.dump());
  1852. LoopInfo = TII->analyzeLoopForPipelining(BB);
  1853. assert(LoopInfo);
  1854. rewriteKernel();
  1855. peelPrologAndEpilogs();
  1856. fixupBranches();
  1857. }
  1858. void PeelingModuloScheduleExpander::validateAgainstModuloScheduleExpander() {
  1859. BB = Schedule.getLoop()->getTopBlock();
  1860. Preheader = Schedule.getLoop()->getLoopPreheader();
  1861. // Dump the schedule before we invalidate and remap all its instructions.
  1862. // Stash it in a string so we can print it if we found an error.
  1863. std::string ScheduleDump;
  1864. raw_string_ostream OS(ScheduleDump);
  1865. Schedule.print(OS);
  1866. OS.flush();
  1867. // First, run the normal ModuleScheduleExpander. We don't support any
  1868. // InstrChanges.
  1869. assert(LIS && "Requires LiveIntervals!");
  1870. ModuloScheduleExpander MSE(MF, Schedule, *LIS,
  1871. ModuloScheduleExpander::InstrChangesTy());
  1872. MSE.expand();
  1873. MachineBasicBlock *ExpandedKernel = MSE.getRewrittenKernel();
  1874. if (!ExpandedKernel) {
  1875. // The expander optimized away the kernel. We can't do any useful checking.
  1876. MSE.cleanup();
  1877. return;
  1878. }
  1879. // Before running the KernelRewriter, re-add BB into the CFG.
  1880. Preheader->addSuccessor(BB);
  1881. // Now run the new expansion algorithm.
  1882. KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
  1883. KR.rewrite();
  1884. peelPrologAndEpilogs();
  1885. // Collect all illegal phis that the new algorithm created. We'll give these
  1886. // to KernelOperandInfo.
  1887. SmallPtrSet<MachineInstr *, 4> IllegalPhis;
  1888. for (auto NI = BB->getFirstNonPHI(); NI != BB->end(); ++NI) {
  1889. if (NI->isPHI())
  1890. IllegalPhis.insert(&*NI);
  1891. }
  1892. // Co-iterate across both kernels. We expect them to be identical apart from
  1893. // phis and full COPYs (we look through both).
  1894. SmallVector<std::pair<KernelOperandInfo, KernelOperandInfo>, 8> KOIs;
  1895. auto OI = ExpandedKernel->begin();
  1896. auto NI = BB->begin();
  1897. for (; !OI->isTerminator() && !NI->isTerminator(); ++OI, ++NI) {
  1898. while (OI->isPHI() || OI->isFullCopy())
  1899. ++OI;
  1900. while (NI->isPHI() || NI->isFullCopy())
  1901. ++NI;
  1902. assert(OI->getOpcode() == NI->getOpcode() && "Opcodes don't match?!");
  1903. // Analyze every operand separately.
  1904. for (auto OOpI = OI->operands_begin(), NOpI = NI->operands_begin();
  1905. OOpI != OI->operands_end(); ++OOpI, ++NOpI)
  1906. KOIs.emplace_back(KernelOperandInfo(&*OOpI, MRI, IllegalPhis),
  1907. KernelOperandInfo(&*NOpI, MRI, IllegalPhis));
  1908. }
  1909. bool Failed = false;
  1910. for (auto &OldAndNew : KOIs) {
  1911. if (OldAndNew.first == OldAndNew.second)
  1912. continue;
  1913. Failed = true;
  1914. errs() << "Modulo kernel validation error: [\n";
  1915. errs() << " [golden] ";
  1916. OldAndNew.first.print(errs());
  1917. errs() << " ";
  1918. OldAndNew.second.print(errs());
  1919. errs() << "]\n";
  1920. }
  1921. if (Failed) {
  1922. errs() << "Golden reference kernel:\n";
  1923. ExpandedKernel->print(errs());
  1924. errs() << "New kernel:\n";
  1925. BB->print(errs());
  1926. errs() << ScheduleDump;
  1927. report_fatal_error(
  1928. "Modulo kernel validation (-pipeliner-experimental-cg) failed");
  1929. }
  1930. // Cleanup by removing BB from the CFG again as the original
  1931. // ModuloScheduleExpander intended.
  1932. Preheader->removeSuccessor(BB);
  1933. MSE.cleanup();
  1934. }
  1935. //===----------------------------------------------------------------------===//
  1936. // ModuloScheduleTestPass implementation
  1937. //===----------------------------------------------------------------------===//
  1938. // This pass constructs a ModuloSchedule from its module and runs
  1939. // ModuloScheduleExpander.
  1940. //
  1941. // The module is expected to contain a single-block analyzable loop.
  1942. // The total order of instructions is taken from the loop as-is.
  1943. // Instructions are expected to be annotated with a PostInstrSymbol.
  1944. // This PostInstrSymbol must have the following format:
  1945. // "Stage=%d Cycle=%d".
  1946. //===----------------------------------------------------------------------===//
  1947. namespace {
  1948. class ModuloScheduleTest : public MachineFunctionPass {
  1949. public:
  1950. static char ID;
  1951. ModuloScheduleTest() : MachineFunctionPass(ID) {
  1952. initializeModuloScheduleTestPass(*PassRegistry::getPassRegistry());
  1953. }
  1954. bool runOnMachineFunction(MachineFunction &MF) override;
  1955. void runOnLoop(MachineFunction &MF, MachineLoop &L);
  1956. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1957. AU.addRequired<MachineLoopInfo>();
  1958. AU.addRequired<LiveIntervals>();
  1959. MachineFunctionPass::getAnalysisUsage(AU);
  1960. }
  1961. };
  1962. } // namespace
  1963. char ModuloScheduleTest::ID = 0;
  1964. INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
  1965. "Modulo Schedule test pass", false, false)
  1966. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  1967. INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
  1968. INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
  1969. "Modulo Schedule test pass", false, false)
  1970. bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
  1971. MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
  1972. for (auto *L : MLI) {
  1973. if (L->getTopBlock() != L->getBottomBlock())
  1974. continue;
  1975. runOnLoop(MF, *L);
  1976. return false;
  1977. }
  1978. return false;
  1979. }
  1980. static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
  1981. std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
  1982. std::pair<StringRef, StringRef> StageTokenAndValue =
  1983. getToken(StageAndCycle.first, "-");
  1984. std::pair<StringRef, StringRef> CycleTokenAndValue =
  1985. getToken(StageAndCycle.second, "-");
  1986. if (StageTokenAndValue.first != "Stage" ||
  1987. CycleTokenAndValue.first != "_Cycle") {
  1988. llvm_unreachable(
  1989. "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
  1990. return;
  1991. }
  1992. StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
  1993. CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
  1994. dbgs() << " Stage=" << Stage << ", Cycle=" << Cycle << "\n";
  1995. }
  1996. void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
  1997. LiveIntervals &LIS = getAnalysis<LiveIntervals>();
  1998. MachineBasicBlock *BB = L.getTopBlock();
  1999. dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
  2000. DenseMap<MachineInstr *, int> Cycle, Stage;
  2001. std::vector<MachineInstr *> Instrs;
  2002. for (MachineInstr &MI : *BB) {
  2003. if (MI.isTerminator())
  2004. continue;
  2005. Instrs.push_back(&MI);
  2006. if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
  2007. dbgs() << "Parsing post-instr symbol for " << MI;
  2008. parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
  2009. }
  2010. }
  2011. ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle),
  2012. std::move(Stage));
  2013. ModuloScheduleExpander MSE(
  2014. MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
  2015. MSE.expand();
  2016. MSE.cleanup();
  2017. }
  2018. //===----------------------------------------------------------------------===//
  2019. // ModuloScheduleTestAnnotater implementation
  2020. //===----------------------------------------------------------------------===//
  2021. void ModuloScheduleTestAnnotater::annotate() {
  2022. for (MachineInstr *MI : S.getInstructions()) {
  2023. SmallVector<char, 16> SV;
  2024. raw_svector_ostream OS(SV);
  2025. OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
  2026. MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
  2027. MI->setPostInstrSymbol(MF, Sym);
  2028. }
  2029. }