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