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