ModuloSchedule.cpp 69 KB

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