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