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