ModuloSchedule.cpp 84 KB

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