1790a779fSJames Molloy //===- ModuloSchedule.cpp - Software pipeline schedule expansion ----------===//
2790a779fSJames Molloy //
3790a779fSJames Molloy // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4790a779fSJames Molloy // See https://llvm.org/LICENSE.txt for license information.
5790a779fSJames Molloy // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6790a779fSJames Molloy //
7790a779fSJames Molloy //===----------------------------------------------------------------------===//
8790a779fSJames Molloy 
9790a779fSJames Molloy #include "llvm/CodeGen/ModuloSchedule.h"
1093549957SJames Molloy #include "llvm/ADT/StringExtras.h"
111815b77cSSimon Pilgrim #include "llvm/Analysis/MemoryLocation.h"
12790a779fSJames Molloy #include "llvm/CodeGen/LiveIntervals.h"
13790a779fSJames Molloy #include "llvm/CodeGen/MachineInstrBuilder.h"
14989f1c72Sserge-sans-paille #include "llvm/CodeGen/MachineLoopInfo.h"
15fef9f590SJames Molloy #include "llvm/CodeGen/MachineRegisterInfo.h"
1605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
1793549957SJames Molloy #include "llvm/MC/MCContext.h"
18790a779fSJames Molloy #include "llvm/Support/Debug.h"
19fef9f590SJames Molloy #include "llvm/Support/ErrorHandling.h"
20fef9f590SJames Molloy #include "llvm/Support/raw_ostream.h"
21790a779fSJames Molloy 
22790a779fSJames Molloy #define DEBUG_TYPE "pipeliner"
23790a779fSJames Molloy using namespace llvm;
24790a779fSJames Molloy 
print(raw_ostream & OS)25fef9f590SJames Molloy void ModuloSchedule::print(raw_ostream &OS) {
26fef9f590SJames Molloy   for (MachineInstr *MI : ScheduledInstrs)
27fef9f590SJames Molloy     OS << "[stage " << getStage(MI) << " @" << getCycle(MI) << "c] " << *MI;
28fef9f590SJames Molloy }
29fef9f590SJames Molloy 
3093549957SJames Molloy //===----------------------------------------------------------------------===//
3193549957SJames Molloy // ModuloScheduleExpander implementation
3293549957SJames Molloy //===----------------------------------------------------------------------===//
3393549957SJames Molloy 
34790a779fSJames Molloy /// Return the register values for  the operands of a Phi instruction.
35790a779fSJames Molloy /// This function assume the instruction is a Phi.
getPhiRegs(MachineInstr & Phi,MachineBasicBlock * Loop,unsigned & InitVal,unsigned & LoopVal)36790a779fSJames Molloy static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop,
37790a779fSJames Molloy                        unsigned &InitVal, unsigned &LoopVal) {
38790a779fSJames Molloy   assert(Phi.isPHI() && "Expecting a Phi.");
39790a779fSJames Molloy 
40790a779fSJames Molloy   InitVal = 0;
41790a779fSJames Molloy   LoopVal = 0;
42790a779fSJames Molloy   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
43790a779fSJames Molloy     if (Phi.getOperand(i + 1).getMBB() != Loop)
44790a779fSJames Molloy       InitVal = Phi.getOperand(i).getReg();
45790a779fSJames Molloy     else
46790a779fSJames Molloy       LoopVal = Phi.getOperand(i).getReg();
47790a779fSJames Molloy 
48790a779fSJames Molloy   assert(InitVal != 0 && LoopVal != 0 && "Unexpected Phi structure.");
49790a779fSJames Molloy }
50790a779fSJames Molloy 
51790a779fSJames Molloy /// Return the Phi register value that comes from the incoming block.
getInitPhiReg(MachineInstr & Phi,MachineBasicBlock * LoopBB)52790a779fSJames Molloy static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
53790a779fSJames Molloy   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
54790a779fSJames Molloy     if (Phi.getOperand(i + 1).getMBB() != LoopBB)
55790a779fSJames Molloy       return Phi.getOperand(i).getReg();
56790a779fSJames Molloy   return 0;
57790a779fSJames Molloy }
58790a779fSJames Molloy 
59790a779fSJames Molloy /// Return the Phi register value that comes the loop block.
getLoopPhiReg(MachineInstr & Phi,MachineBasicBlock * LoopBB)60790a779fSJames Molloy static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB) {
61790a779fSJames Molloy   for (unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
62790a779fSJames Molloy     if (Phi.getOperand(i + 1).getMBB() == LoopBB)
63790a779fSJames Molloy       return Phi.getOperand(i).getReg();
64790a779fSJames Molloy   return 0;
65790a779fSJames Molloy }
66790a779fSJames Molloy 
expand()67790a779fSJames Molloy void ModuloScheduleExpander::expand() {
68790a779fSJames Molloy   BB = Schedule.getLoop()->getTopBlock();
69790a779fSJames Molloy   Preheader = *BB->pred_begin();
70790a779fSJames Molloy   if (Preheader == BB)
71790a779fSJames Molloy     Preheader = *std::next(BB->pred_begin());
72790a779fSJames Molloy 
73790a779fSJames Molloy   // Iterate over the definitions in each instruction, and compute the
74790a779fSJames Molloy   // stage difference for each use.  Keep the maximum value.
75790a779fSJames Molloy   for (MachineInstr *MI : Schedule.getInstructions()) {
76790a779fSJames Molloy     int DefStage = Schedule.getStage(MI);
77387927bbSKazu Hirata     for (const MachineOperand &Op : MI->operands()) {
78790a779fSJames Molloy       if (!Op.isReg() || !Op.isDef())
79790a779fSJames Molloy         continue;
80790a779fSJames Molloy 
81790a779fSJames Molloy       Register Reg = Op.getReg();
82790a779fSJames Molloy       unsigned MaxDiff = 0;
83790a779fSJames Molloy       bool PhiIsSwapped = false;
842ca45adfSKazu Hirata       for (MachineOperand &UseOp : MRI.use_operands(Reg)) {
85790a779fSJames Molloy         MachineInstr *UseMI = UseOp.getParent();
86790a779fSJames Molloy         int UseStage = Schedule.getStage(UseMI);
87790a779fSJames Molloy         unsigned Diff = 0;
88790a779fSJames Molloy         if (UseStage != -1 && UseStage >= DefStage)
89790a779fSJames Molloy           Diff = UseStage - DefStage;
90790a779fSJames Molloy         if (MI->isPHI()) {
91790a779fSJames Molloy           if (isLoopCarried(*MI))
92790a779fSJames Molloy             ++Diff;
93790a779fSJames Molloy           else
94790a779fSJames Molloy             PhiIsSwapped = true;
95790a779fSJames Molloy         }
96790a779fSJames Molloy         MaxDiff = std::max(Diff, MaxDiff);
97790a779fSJames Molloy       }
98790a779fSJames Molloy       RegToStageDiff[Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
99790a779fSJames Molloy     }
100790a779fSJames Molloy   }
101790a779fSJames Molloy 
102790a779fSJames Molloy   generatePipelinedLoop();
103790a779fSJames Molloy }
104790a779fSJames Molloy 
generatePipelinedLoop()105790a779fSJames Molloy void ModuloScheduleExpander::generatePipelinedLoop() {
1068a74eca3SJames Molloy   LoopInfo = TII->analyzeLoopForPipelining(BB);
1078a74eca3SJames Molloy   assert(LoopInfo && "Must be able to analyze loop!");
1088a74eca3SJames Molloy 
109790a779fSJames Molloy   // Create a new basic block for the kernel and add it to the CFG.
110790a779fSJames Molloy   MachineBasicBlock *KernelBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
111790a779fSJames Molloy 
112790a779fSJames Molloy   unsigned MaxStageCount = Schedule.getNumStages() - 1;
113790a779fSJames Molloy 
114790a779fSJames Molloy   // Remember the registers that are used in different stages. The index is
115790a779fSJames Molloy   // the iteration, or stage, that the instruction is scheduled in.  This is
116790a779fSJames Molloy   // a map between register names in the original block and the names created
117790a779fSJames Molloy   // in each stage of the pipelined loop.
118790a779fSJames Molloy   ValueMapTy *VRMap = new ValueMapTy[(MaxStageCount + 1) * 2];
119790a779fSJames Molloy   InstrMapTy InstrMap;
120790a779fSJames Molloy 
121790a779fSJames Molloy   SmallVector<MachineBasicBlock *, 4> PrologBBs;
122790a779fSJames Molloy 
123790a779fSJames Molloy   // Generate the prolog instructions that set up the pipeline.
124790a779fSJames Molloy   generateProlog(MaxStageCount, KernelBB, VRMap, PrologBBs);
125790a779fSJames Molloy   MF.insert(BB->getIterator(), KernelBB);
126790a779fSJames Molloy 
127790a779fSJames Molloy   // Rearrange the instructions to generate the new, pipelined loop,
128790a779fSJames Molloy   // and update register names as needed.
129790a779fSJames Molloy   for (MachineInstr *CI : Schedule.getInstructions()) {
130790a779fSJames Molloy     if (CI->isPHI())
131790a779fSJames Molloy       continue;
132790a779fSJames Molloy     unsigned StageNum = Schedule.getStage(CI);
133790a779fSJames Molloy     MachineInstr *NewMI = cloneInstr(CI, MaxStageCount, StageNum);
134790a779fSJames Molloy     updateInstruction(NewMI, false, MaxStageCount, StageNum, VRMap);
135790a779fSJames Molloy     KernelBB->push_back(NewMI);
136790a779fSJames Molloy     InstrMap[NewMI] = CI;
137790a779fSJames Molloy   }
138790a779fSJames Molloy 
139790a779fSJames Molloy   // Copy any terminator instructions to the new kernel, and update
140790a779fSJames Molloy   // names as needed.
14172710af2SKazu Hirata   for (MachineInstr &MI : BB->terminators()) {
14272710af2SKazu Hirata     MachineInstr *NewMI = MF.CloneMachineInstr(&MI);
143790a779fSJames Molloy     updateInstruction(NewMI, false, MaxStageCount, 0, VRMap);
144790a779fSJames Molloy     KernelBB->push_back(NewMI);
14572710af2SKazu Hirata     InstrMap[NewMI] = &MI;
146790a779fSJames Molloy   }
147790a779fSJames Molloy 
148fef9f590SJames Molloy   NewKernel = KernelBB;
149790a779fSJames Molloy   KernelBB->transferSuccessors(BB);
150790a779fSJames Molloy   KernelBB->replaceSuccessor(BB, KernelBB);
151790a779fSJames Molloy 
152790a779fSJames Molloy   generateExistingPhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap,
153790a779fSJames Molloy                        InstrMap, MaxStageCount, MaxStageCount, false);
154790a779fSJames Molloy   generatePhis(KernelBB, PrologBBs.back(), KernelBB, KernelBB, VRMap, InstrMap,
155790a779fSJames Molloy                MaxStageCount, MaxStageCount, false);
156790a779fSJames Molloy 
157790a779fSJames Molloy   LLVM_DEBUG(dbgs() << "New block\n"; KernelBB->dump(););
158790a779fSJames Molloy 
159790a779fSJames Molloy   SmallVector<MachineBasicBlock *, 4> EpilogBBs;
160790a779fSJames Molloy   // Generate the epilog instructions to complete the pipeline.
161dcb77643SDavid Penry   generateEpilog(MaxStageCount, KernelBB, BB, VRMap, EpilogBBs, PrologBBs);
162790a779fSJames Molloy 
163790a779fSJames Molloy   // We need this step because the register allocation doesn't handle some
164790a779fSJames Molloy   // situations well, so we insert copies to help out.
165790a779fSJames Molloy   splitLifetimes(KernelBB, EpilogBBs);
166790a779fSJames Molloy 
167790a779fSJames Molloy   // Remove dead instructions due to loop induction variables.
168790a779fSJames Molloy   removeDeadInstructions(KernelBB, EpilogBBs);
169790a779fSJames Molloy 
170790a779fSJames Molloy   // Add branches between prolog and epilog blocks.
171790a779fSJames Molloy   addBranches(*Preheader, PrologBBs, KernelBB, EpilogBBs, VRMap);
172790a779fSJames Molloy 
173fef9f590SJames Molloy   delete[] VRMap;
174fef9f590SJames Molloy }
175fef9f590SJames Molloy 
cleanup()176fef9f590SJames Molloy void ModuloScheduleExpander::cleanup() {
177790a779fSJames Molloy   // Remove the original loop since it's no longer referenced.
178790a779fSJames Molloy   for (auto &I : *BB)
179790a779fSJames Molloy     LIS.RemoveMachineInstrFromMaps(I);
180790a779fSJames Molloy   BB->clear();
181790a779fSJames Molloy   BB->eraseFromParent();
182790a779fSJames Molloy }
183790a779fSJames Molloy 
184790a779fSJames Molloy /// Generate the pipeline prolog code.
generateProlog(unsigned LastStage,MachineBasicBlock * KernelBB,ValueMapTy * VRMap,MBBVectorTy & PrologBBs)185790a779fSJames Molloy void ModuloScheduleExpander::generateProlog(unsigned LastStage,
186790a779fSJames Molloy                                             MachineBasicBlock *KernelBB,
187790a779fSJames Molloy                                             ValueMapTy *VRMap,
188790a779fSJames Molloy                                             MBBVectorTy &PrologBBs) {
189790a779fSJames Molloy   MachineBasicBlock *PredBB = Preheader;
190790a779fSJames Molloy   InstrMapTy InstrMap;
191790a779fSJames Molloy 
192790a779fSJames Molloy   // Generate a basic block for each stage, not including the last stage,
193790a779fSJames Molloy   // which will be generated in the kernel. Each basic block may contain
194790a779fSJames Molloy   // instructions from multiple stages/iterations.
195790a779fSJames Molloy   for (unsigned i = 0; i < LastStage; ++i) {
196790a779fSJames Molloy     // Create and insert the prolog basic block prior to the original loop
197790a779fSJames Molloy     // basic block.  The original loop is removed later.
198790a779fSJames Molloy     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
199790a779fSJames Molloy     PrologBBs.push_back(NewBB);
200790a779fSJames Molloy     MF.insert(BB->getIterator(), NewBB);
201790a779fSJames Molloy     NewBB->transferSuccessors(PredBB);
202790a779fSJames Molloy     PredBB->addSuccessor(NewBB);
203790a779fSJames Molloy     PredBB = NewBB;
204790a779fSJames Molloy 
205790a779fSJames Molloy     // Generate instructions for each appropriate stage. Process instructions
206790a779fSJames Molloy     // in original program order.
207790a779fSJames Molloy     for (int StageNum = i; StageNum >= 0; --StageNum) {
208790a779fSJames Molloy       for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
209790a779fSJames Molloy                                        BBE = BB->getFirstTerminator();
210790a779fSJames Molloy            BBI != BBE; ++BBI) {
211790a779fSJames Molloy         if (Schedule.getStage(&*BBI) == StageNum) {
212790a779fSJames Molloy           if (BBI->isPHI())
213790a779fSJames Molloy             continue;
214790a779fSJames Molloy           MachineInstr *NewMI =
215790a779fSJames Molloy               cloneAndChangeInstr(&*BBI, i, (unsigned)StageNum);
216790a779fSJames Molloy           updateInstruction(NewMI, false, i, (unsigned)StageNum, VRMap);
217790a779fSJames Molloy           NewBB->push_back(NewMI);
218790a779fSJames Molloy           InstrMap[NewMI] = &*BBI;
219790a779fSJames Molloy         }
220790a779fSJames Molloy       }
221790a779fSJames Molloy     }
222790a779fSJames Molloy     rewritePhiValues(NewBB, i, VRMap, InstrMap);
223790a779fSJames Molloy     LLVM_DEBUG({
224790a779fSJames Molloy       dbgs() << "prolog:\n";
225790a779fSJames Molloy       NewBB->dump();
226790a779fSJames Molloy     });
227790a779fSJames Molloy   }
228790a779fSJames Molloy 
229790a779fSJames Molloy   PredBB->replaceSuccessor(BB, KernelBB);
230790a779fSJames Molloy 
231790a779fSJames Molloy   // Check if we need to remove the branch from the preheader to the original
232790a779fSJames Molloy   // loop, and replace it with a branch to the new loop.
233790a779fSJames Molloy   unsigned numBranches = TII->removeBranch(*Preheader);
234790a779fSJames Molloy   if (numBranches) {
235790a779fSJames Molloy     SmallVector<MachineOperand, 0> Cond;
236790a779fSJames Molloy     TII->insertBranch(*Preheader, PrologBBs[0], nullptr, Cond, DebugLoc());
237790a779fSJames Molloy   }
238790a779fSJames Molloy }
239790a779fSJames Molloy 
240790a779fSJames Molloy /// Generate the pipeline epilog code. The epilog code finishes the iterations
241790a779fSJames Molloy /// that were started in either the prolog or the kernel.  We create a basic
242790a779fSJames Molloy /// block for each stage that needs to complete.
generateEpilog(unsigned LastStage,MachineBasicBlock * KernelBB,MachineBasicBlock * OrigBB,ValueMapTy * VRMap,MBBVectorTy & EpilogBBs,MBBVectorTy & PrologBBs)243dcb77643SDavid Penry void ModuloScheduleExpander::generateEpilog(
244dcb77643SDavid Penry     unsigned LastStage, MachineBasicBlock *KernelBB, MachineBasicBlock *OrigBB,
245dcb77643SDavid Penry     ValueMapTy *VRMap, MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs) {
246790a779fSJames Molloy   // We need to change the branch from the kernel to the first epilog block, so
247790a779fSJames Molloy   // this call to analyze branch uses the kernel rather than the original BB.
248790a779fSJames Molloy   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
249790a779fSJames Molloy   SmallVector<MachineOperand, 4> Cond;
250790a779fSJames Molloy   bool checkBranch = TII->analyzeBranch(*KernelBB, TBB, FBB, Cond);
251790a779fSJames Molloy   assert(!checkBranch && "generateEpilog must be able to analyze the branch");
252790a779fSJames Molloy   if (checkBranch)
253790a779fSJames Molloy     return;
254790a779fSJames Molloy 
255790a779fSJames Molloy   MachineBasicBlock::succ_iterator LoopExitI = KernelBB->succ_begin();
256790a779fSJames Molloy   if (*LoopExitI == KernelBB)
257790a779fSJames Molloy     ++LoopExitI;
258790a779fSJames Molloy   assert(LoopExitI != KernelBB->succ_end() && "Expecting a successor");
259790a779fSJames Molloy   MachineBasicBlock *LoopExitBB = *LoopExitI;
260790a779fSJames Molloy 
261790a779fSJames Molloy   MachineBasicBlock *PredBB = KernelBB;
262790a779fSJames Molloy   MachineBasicBlock *EpilogStart = LoopExitBB;
263790a779fSJames Molloy   InstrMapTy InstrMap;
264790a779fSJames Molloy 
265790a779fSJames Molloy   // Generate a basic block for each stage, not including the last stage,
266790a779fSJames Molloy   // which was generated for the kernel.  Each basic block may contain
267790a779fSJames Molloy   // instructions from multiple stages/iterations.
268790a779fSJames Molloy   int EpilogStage = LastStage + 1;
269790a779fSJames Molloy   for (unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
270790a779fSJames Molloy     MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock();
271790a779fSJames Molloy     EpilogBBs.push_back(NewBB);
272790a779fSJames Molloy     MF.insert(BB->getIterator(), NewBB);
273790a779fSJames Molloy 
274790a779fSJames Molloy     PredBB->replaceSuccessor(LoopExitBB, NewBB);
275790a779fSJames Molloy     NewBB->addSuccessor(LoopExitBB);
276790a779fSJames Molloy 
277790a779fSJames Molloy     if (EpilogStart == LoopExitBB)
278790a779fSJames Molloy       EpilogStart = NewBB;
279790a779fSJames Molloy 
280790a779fSJames Molloy     // Add instructions to the epilog depending on the current block.
281790a779fSJames Molloy     // Process instructions in original program order.
282790a779fSJames Molloy     for (unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
283790a779fSJames Molloy       for (auto &BBI : *BB) {
284790a779fSJames Molloy         if (BBI.isPHI())
285790a779fSJames Molloy           continue;
286790a779fSJames Molloy         MachineInstr *In = &BBI;
287790a779fSJames Molloy         if ((unsigned)Schedule.getStage(In) == StageNum) {
288790a779fSJames Molloy           // Instructions with memoperands in the epilog are updated with
289790a779fSJames Molloy           // conservative values.
290790a779fSJames Molloy           MachineInstr *NewMI = cloneInstr(In, UINT_MAX, 0);
291790a779fSJames Molloy           updateInstruction(NewMI, i == 1, EpilogStage, 0, VRMap);
292790a779fSJames Molloy           NewBB->push_back(NewMI);
293790a779fSJames Molloy           InstrMap[NewMI] = In;
294790a779fSJames Molloy         }
295790a779fSJames Molloy       }
296790a779fSJames Molloy     }
297790a779fSJames Molloy     generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap,
298790a779fSJames Molloy                          InstrMap, LastStage, EpilogStage, i == 1);
299790a779fSJames Molloy     generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, VRMap, InstrMap,
300790a779fSJames Molloy                  LastStage, EpilogStage, i == 1);
301790a779fSJames Molloy     PredBB = NewBB;
302790a779fSJames Molloy 
303790a779fSJames Molloy     LLVM_DEBUG({
304790a779fSJames Molloy       dbgs() << "epilog:\n";
305790a779fSJames Molloy       NewBB->dump();
306790a779fSJames Molloy     });
307790a779fSJames Molloy   }
308790a779fSJames Molloy 
309790a779fSJames Molloy   // Fix any Phi nodes in the loop exit block.
310790a779fSJames Molloy   LoopExitBB->replacePhiUsesWith(BB, PredBB);
311790a779fSJames Molloy 
312790a779fSJames Molloy   // Create a branch to the new epilog from the kernel.
313790a779fSJames Molloy   // Remove the original branch and add a new branch to the epilog.
314790a779fSJames Molloy   TII->removeBranch(*KernelBB);
315dcb77643SDavid Penry   assert((OrigBB == TBB || OrigBB == FBB) &&
316dcb77643SDavid Penry          "Unable to determine looping branch direction");
317dcb77643SDavid Penry   if (OrigBB != TBB)
318dcb77643SDavid Penry     TII->insertBranch(*KernelBB, EpilogStart, KernelBB, Cond, DebugLoc());
319dcb77643SDavid Penry   else
320790a779fSJames Molloy     TII->insertBranch(*KernelBB, KernelBB, EpilogStart, Cond, DebugLoc());
321790a779fSJames Molloy   // Add a branch to the loop exit.
322790a779fSJames Molloy   if (EpilogBBs.size() > 0) {
323790a779fSJames Molloy     MachineBasicBlock *LastEpilogBB = EpilogBBs.back();
324790a779fSJames Molloy     SmallVector<MachineOperand, 4> Cond1;
325790a779fSJames Molloy     TII->insertBranch(*LastEpilogBB, LoopExitBB, nullptr, Cond1, DebugLoc());
326790a779fSJames Molloy   }
327790a779fSJames Molloy }
328790a779fSJames Molloy 
329790a779fSJames Molloy /// Replace all uses of FromReg that appear outside the specified
330790a779fSJames Molloy /// basic block with ToReg.
replaceRegUsesAfterLoop(unsigned FromReg,unsigned ToReg,MachineBasicBlock * MBB,MachineRegisterInfo & MRI,LiveIntervals & LIS)331790a779fSJames Molloy static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg,
332790a779fSJames Molloy                                     MachineBasicBlock *MBB,
333790a779fSJames Molloy                                     MachineRegisterInfo &MRI,
334790a779fSJames Molloy                                     LiveIntervals &LIS) {
335642a361bSKazu Hirata   for (MachineOperand &O :
336642a361bSKazu Hirata        llvm::make_early_inc_range(MRI.use_operands(FromReg)))
337790a779fSJames Molloy     if (O.getParent()->getParent() != MBB)
338790a779fSJames Molloy       O.setReg(ToReg);
339790a779fSJames Molloy   if (!LIS.hasInterval(ToReg))
340790a779fSJames Molloy     LIS.createEmptyInterval(ToReg);
341790a779fSJames Molloy }
342790a779fSJames Molloy 
343790a779fSJames Molloy /// Return true if the register has a use that occurs outside the
344790a779fSJames Molloy /// specified loop.
hasUseAfterLoop(unsigned Reg,MachineBasicBlock * BB,MachineRegisterInfo & MRI)345790a779fSJames Molloy static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB,
346790a779fSJames Molloy                             MachineRegisterInfo &MRI) {
3472ca45adfSKazu Hirata   for (const MachineOperand &MO : MRI.use_operands(Reg))
3482ca45adfSKazu Hirata     if (MO.getParent()->getParent() != BB)
349790a779fSJames Molloy       return true;
350790a779fSJames Molloy   return false;
351790a779fSJames Molloy }
352790a779fSJames Molloy 
353790a779fSJames Molloy /// Generate Phis for the specific block in the generated pipelined code.
354790a779fSJames Molloy /// This function looks at the Phis from the original code to guide the
355790a779fSJames Molloy /// creation of new Phis.
generateExistingPhis(MachineBasicBlock * NewBB,MachineBasicBlock * BB1,MachineBasicBlock * BB2,MachineBasicBlock * KernelBB,ValueMapTy * VRMap,InstrMapTy & InstrMap,unsigned LastStageNum,unsigned CurStageNum,bool IsLast)356790a779fSJames Molloy void ModuloScheduleExpander::generateExistingPhis(
357790a779fSJames Molloy     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
358790a779fSJames Molloy     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
359790a779fSJames Molloy     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
360790a779fSJames Molloy   // Compute the stage number for the initial value of the Phi, which
361790a779fSJames Molloy   // comes from the prolog. The prolog to use depends on to which kernel/
362790a779fSJames Molloy   // epilog that we're adding the Phi.
363790a779fSJames Molloy   unsigned PrologStage = 0;
364790a779fSJames Molloy   unsigned PrevStage = 0;
365790a779fSJames Molloy   bool InKernel = (LastStageNum == CurStageNum);
366790a779fSJames Molloy   if (InKernel) {
367790a779fSJames Molloy     PrologStage = LastStageNum - 1;
368790a779fSJames Molloy     PrevStage = CurStageNum;
369790a779fSJames Molloy   } else {
370790a779fSJames Molloy     PrologStage = LastStageNum - (CurStageNum - LastStageNum);
371790a779fSJames Molloy     PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
372790a779fSJames Molloy   }
373790a779fSJames Molloy 
374790a779fSJames Molloy   for (MachineBasicBlock::iterator BBI = BB->instr_begin(),
375790a779fSJames Molloy                                    BBE = BB->getFirstNonPHI();
376790a779fSJames Molloy        BBI != BBE; ++BBI) {
377790a779fSJames Molloy     Register Def = BBI->getOperand(0).getReg();
378790a779fSJames Molloy 
379790a779fSJames Molloy     unsigned InitVal = 0;
380790a779fSJames Molloy     unsigned LoopVal = 0;
381790a779fSJames Molloy     getPhiRegs(*BBI, BB, InitVal, LoopVal);
382790a779fSJames Molloy 
383790a779fSJames Molloy     unsigned PhiOp1 = 0;
384790a779fSJames Molloy     // The Phi value from the loop body typically is defined in the loop, but
385790a779fSJames Molloy     // not always. So, we need to check if the value is defined in the loop.
386790a779fSJames Molloy     unsigned PhiOp2 = LoopVal;
387790a779fSJames Molloy     if (VRMap[LastStageNum].count(LoopVal))
388790a779fSJames Molloy       PhiOp2 = VRMap[LastStageNum][LoopVal];
389790a779fSJames Molloy 
390790a779fSJames Molloy     int StageScheduled = Schedule.getStage(&*BBI);
391790a779fSJames Molloy     int LoopValStage = Schedule.getStage(MRI.getVRegDef(LoopVal));
392790a779fSJames Molloy     unsigned NumStages = getStagesForReg(Def, CurStageNum);
393790a779fSJames Molloy     if (NumStages == 0) {
394790a779fSJames Molloy       // We don't need to generate a Phi anymore, but we need to rename any uses
395790a779fSJames Molloy       // of the Phi value.
396790a779fSJames Molloy       unsigned NewReg = VRMap[PrevStage][LoopVal];
397790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, 0, &*BBI, Def,
398790a779fSJames Molloy                             InitVal, NewReg);
399790a779fSJames Molloy       if (VRMap[CurStageNum].count(LoopVal))
400790a779fSJames Molloy         VRMap[CurStageNum][Def] = VRMap[CurStageNum][LoopVal];
401790a779fSJames Molloy     }
402790a779fSJames Molloy     // Adjust the number of Phis needed depending on the number of prologs left,
403790a779fSJames Molloy     // and the distance from where the Phi is first scheduled. The number of
404790a779fSJames Molloy     // Phis cannot exceed the number of prolog stages. Each stage can
405790a779fSJames Molloy     // potentially define two values.
406790a779fSJames Molloy     unsigned MaxPhis = PrologStage + 2;
407790a779fSJames Molloy     if (!InKernel && (int)PrologStage <= LoopValStage)
408790a779fSJames Molloy       MaxPhis = std::max((int)MaxPhis - (int)LoopValStage, 1);
409790a779fSJames Molloy     unsigned NumPhis = std::min(NumStages, MaxPhis);
410790a779fSJames Molloy 
411790a779fSJames Molloy     unsigned NewReg = 0;
412790a779fSJames Molloy     unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
413790a779fSJames Molloy     // In the epilog, we may need to look back one stage to get the correct
4148a6a2c4cSHendrik Greving     // Phi name, because the epilog and prolog blocks execute the same stage.
415790a779fSJames Molloy     // The correct name is from the previous block only when the Phi has
416790a779fSJames Molloy     // been completely scheduled prior to the epilog, and Phi value is not
417790a779fSJames Molloy     // needed in multiple stages.
418790a779fSJames Molloy     int StageDiff = 0;
419790a779fSJames Molloy     if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
420790a779fSJames Molloy         NumPhis == 1)
421790a779fSJames Molloy       StageDiff = 1;
422790a779fSJames Molloy     // Adjust the computations below when the phi and the loop definition
423790a779fSJames Molloy     // are scheduled in different stages.
424790a779fSJames Molloy     if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
425790a779fSJames Molloy       StageDiff = StageScheduled - LoopValStage;
426790a779fSJames Molloy     for (unsigned np = 0; np < NumPhis; ++np) {
427790a779fSJames Molloy       // If the Phi hasn't been scheduled, then use the initial Phi operand
428790a779fSJames Molloy       // value. Otherwise, use the scheduled version of the instruction. This
429790a779fSJames Molloy       // is a little complicated when a Phi references another Phi.
430790a779fSJames Molloy       if (np > PrologStage || StageScheduled >= (int)LastStageNum)
431790a779fSJames Molloy         PhiOp1 = InitVal;
432790a779fSJames Molloy       // Check if the Phi has already been scheduled in a prolog stage.
433790a779fSJames Molloy       else if (PrologStage >= AccessStage + StageDiff + np &&
434790a779fSJames Molloy                VRMap[PrologStage - StageDiff - np].count(LoopVal) != 0)
435790a779fSJames Molloy         PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
436790a779fSJames Molloy       // Check if the Phi has already been scheduled, but the loop instruction
437790a779fSJames Molloy       // is either another Phi, or doesn't occur in the loop.
438790a779fSJames Molloy       else if (PrologStage >= AccessStage + StageDiff + np) {
439790a779fSJames Molloy         // If the Phi references another Phi, we need to examine the other
440790a779fSJames Molloy         // Phi to get the correct value.
441790a779fSJames Molloy         PhiOp1 = LoopVal;
442790a779fSJames Molloy         MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1);
443790a779fSJames Molloy         int Indirects = 1;
444790a779fSJames Molloy         while (InstOp1 && InstOp1->isPHI() && InstOp1->getParent() == BB) {
445790a779fSJames Molloy           int PhiStage = Schedule.getStage(InstOp1);
446790a779fSJames Molloy           if ((int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
447790a779fSJames Molloy             PhiOp1 = getInitPhiReg(*InstOp1, BB);
448790a779fSJames Molloy           else
449790a779fSJames Molloy             PhiOp1 = getLoopPhiReg(*InstOp1, BB);
450790a779fSJames Molloy           InstOp1 = MRI.getVRegDef(PhiOp1);
451790a779fSJames Molloy           int PhiOpStage = Schedule.getStage(InstOp1);
452790a779fSJames Molloy           int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
453790a779fSJames Molloy           if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
454790a779fSJames Molloy               VRMap[PrologStage - StageAdj - Indirects - np].count(PhiOp1)) {
455790a779fSJames Molloy             PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
456790a779fSJames Molloy             break;
457790a779fSJames Molloy           }
458790a779fSJames Molloy           ++Indirects;
459790a779fSJames Molloy         }
460790a779fSJames Molloy       } else
461790a779fSJames Molloy         PhiOp1 = InitVal;
462790a779fSJames Molloy       // If this references a generated Phi in the kernel, get the Phi operand
463790a779fSJames Molloy       // from the incoming block.
464790a779fSJames Molloy       if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1))
465790a779fSJames Molloy         if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
466790a779fSJames Molloy           PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
467790a779fSJames Molloy 
468790a779fSJames Molloy       MachineInstr *PhiInst = MRI.getVRegDef(LoopVal);
469790a779fSJames Molloy       bool LoopDefIsPhi = PhiInst && PhiInst->isPHI();
470790a779fSJames Molloy       // In the epilog, a map lookup is needed to get the value from the kernel,
471790a779fSJames Molloy       // or previous epilog block. How is does this depends on if the
472790a779fSJames Molloy       // instruction is scheduled in the previous block.
473790a779fSJames Molloy       if (!InKernel) {
474790a779fSJames Molloy         int StageDiffAdj = 0;
475790a779fSJames Molloy         if (LoopValStage != -1 && StageScheduled > LoopValStage)
476790a779fSJames Molloy           StageDiffAdj = StageScheduled - LoopValStage;
477790a779fSJames Molloy         // Use the loop value defined in the kernel, unless the kernel
478790a779fSJames Molloy         // contains the last definition of the Phi.
479790a779fSJames Molloy         if (np == 0 && PrevStage == LastStageNum &&
480790a779fSJames Molloy             (StageScheduled != 0 || LoopValStage != 0) &&
481790a779fSJames Molloy             VRMap[PrevStage - StageDiffAdj].count(LoopVal))
482790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
483790a779fSJames Molloy         // Use the value defined by the Phi. We add one because we switch
484790a779fSJames Molloy         // from looking at the loop value to the Phi definition.
485790a779fSJames Molloy         else if (np > 0 && PrevStage == LastStageNum &&
486790a779fSJames Molloy                  VRMap[PrevStage - np + 1].count(Def))
487790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - np + 1][Def];
488790a779fSJames Molloy         // Use the loop value defined in the kernel.
489790a779fSJames Molloy         else if (static_cast<unsigned>(LoopValStage) > PrologStage + 1 &&
490790a779fSJames Molloy                  VRMap[PrevStage - StageDiffAdj - np].count(LoopVal))
491790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
492790a779fSJames Molloy         // Use the value defined by the Phi, unless we're generating the first
493790a779fSJames Molloy         // epilog and the Phi refers to a Phi in a different stage.
494790a779fSJames Molloy         else if (VRMap[PrevStage - np].count(Def) &&
495790a779fSJames Molloy                  (!LoopDefIsPhi || (PrevStage != LastStageNum) ||
496790a779fSJames Molloy                   (LoopValStage == StageScheduled)))
497790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - np][Def];
498790a779fSJames Molloy       }
499790a779fSJames Molloy 
500790a779fSJames Molloy       // Check if we can reuse an existing Phi. This occurs when a Phi
501790a779fSJames Molloy       // references another Phi, and the other Phi is scheduled in an
502790a779fSJames Molloy       // earlier stage. We can try to reuse an existing Phi up until the last
503790a779fSJames Molloy       // stage of the current Phi.
504790a779fSJames Molloy       if (LoopDefIsPhi) {
505790a779fSJames Molloy         if (static_cast<int>(PrologStage - np) >= StageScheduled) {
506790a779fSJames Molloy           int LVNumStages = getStagesForPhi(LoopVal);
507790a779fSJames Molloy           int StageDiff = (StageScheduled - LoopValStage);
508790a779fSJames Molloy           LVNumStages -= StageDiff;
509790a779fSJames Molloy           // Make sure the loop value Phi has been processed already.
510790a779fSJames Molloy           if (LVNumStages > (int)np && VRMap[CurStageNum].count(LoopVal)) {
511790a779fSJames Molloy             NewReg = PhiOp2;
512790a779fSJames Molloy             unsigned ReuseStage = CurStageNum;
513790a779fSJames Molloy             if (isLoopCarried(*PhiInst))
514790a779fSJames Molloy               ReuseStage -= LVNumStages;
515790a779fSJames Molloy             // Check if the Phi to reuse has been generated yet. If not, then
516790a779fSJames Molloy             // there is nothing to reuse.
517790a779fSJames Molloy             if (VRMap[ReuseStage - np].count(LoopVal)) {
518790a779fSJames Molloy               NewReg = VRMap[ReuseStage - np][LoopVal];
519790a779fSJames Molloy 
520790a779fSJames Molloy               rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI,
521790a779fSJames Molloy                                     Def, NewReg);
522790a779fSJames Molloy               // Update the map with the new Phi name.
523790a779fSJames Molloy               VRMap[CurStageNum - np][Def] = NewReg;
524790a779fSJames Molloy               PhiOp2 = NewReg;
525790a779fSJames Molloy               if (VRMap[LastStageNum - np - 1].count(LoopVal))
526790a779fSJames Molloy                 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
527790a779fSJames Molloy 
528790a779fSJames Molloy               if (IsLast && np == NumPhis - 1)
529790a779fSJames Molloy                 replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
530790a779fSJames Molloy               continue;
531790a779fSJames Molloy             }
532790a779fSJames Molloy           }
533790a779fSJames Molloy         }
534790a779fSJames Molloy         if (InKernel && StageDiff > 0 &&
535790a779fSJames Molloy             VRMap[CurStageNum - StageDiff - np].count(LoopVal))
536790a779fSJames Molloy           PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
537790a779fSJames Molloy       }
538790a779fSJames Molloy 
539790a779fSJames Molloy       const TargetRegisterClass *RC = MRI.getRegClass(Def);
540790a779fSJames Molloy       NewReg = MRI.createVirtualRegister(RC);
541790a779fSJames Molloy 
542790a779fSJames Molloy       MachineInstrBuilder NewPhi =
543790a779fSJames Molloy           BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
544790a779fSJames Molloy                   TII->get(TargetOpcode::PHI), NewReg);
545790a779fSJames Molloy       NewPhi.addReg(PhiOp1).addMBB(BB1);
546790a779fSJames Molloy       NewPhi.addReg(PhiOp2).addMBB(BB2);
547790a779fSJames Molloy       if (np == 0)
548790a779fSJames Molloy         InstrMap[NewPhi] = &*BBI;
549790a779fSJames Molloy 
550790a779fSJames Molloy       // We define the Phis after creating the new pipelined code, so
551790a779fSJames Molloy       // we need to rename the Phi values in scheduled instructions.
552790a779fSJames Molloy 
553790a779fSJames Molloy       unsigned PrevReg = 0;
554790a779fSJames Molloy       if (InKernel && VRMap[PrevStage - np].count(LoopVal))
555790a779fSJames Molloy         PrevReg = VRMap[PrevStage - np][LoopVal];
556790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
557790a779fSJames Molloy                             NewReg, PrevReg);
558790a779fSJames Molloy       // If the Phi has been scheduled, use the new name for rewriting.
559790a779fSJames Molloy       if (VRMap[CurStageNum - np].count(Def)) {
560790a779fSJames Molloy         unsigned R = VRMap[CurStageNum - np][Def];
561790a779fSJames Molloy         rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, R,
562790a779fSJames Molloy                               NewReg);
563790a779fSJames Molloy       }
564790a779fSJames Molloy 
565790a779fSJames Molloy       // Check if we need to rename any uses that occurs after the loop. The
566790a779fSJames Molloy       // register to replace depends on whether the Phi is scheduled in the
567790a779fSJames Molloy       // epilog.
568790a779fSJames Molloy       if (IsLast && np == NumPhis - 1)
569790a779fSJames Molloy         replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
570790a779fSJames Molloy 
571790a779fSJames Molloy       // In the kernel, a dependent Phi uses the value from this Phi.
572790a779fSJames Molloy       if (InKernel)
573790a779fSJames Molloy         PhiOp2 = NewReg;
574790a779fSJames Molloy 
575790a779fSJames Molloy       // Update the map with the new Phi name.
576790a779fSJames Molloy       VRMap[CurStageNum - np][Def] = NewReg;
577790a779fSJames Molloy     }
578790a779fSJames Molloy 
579790a779fSJames Molloy     while (NumPhis++ < NumStages) {
580790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, NumPhis, &*BBI, Def,
581790a779fSJames Molloy                             NewReg, 0);
582790a779fSJames Molloy     }
583790a779fSJames Molloy 
584790a779fSJames Molloy     // Check if we need to rename a Phi that has been eliminated due to
585790a779fSJames Molloy     // scheduling.
586790a779fSJames Molloy     if (NumStages == 0 && IsLast && VRMap[CurStageNum].count(LoopVal))
587790a779fSJames Molloy       replaceRegUsesAfterLoop(Def, VRMap[CurStageNum][LoopVal], BB, MRI, LIS);
588790a779fSJames Molloy   }
589790a779fSJames Molloy }
590790a779fSJames Molloy 
591790a779fSJames Molloy /// Generate Phis for the specified block in the generated pipelined code.
592790a779fSJames Molloy /// These are new Phis needed because the definition is scheduled after the
593790a779fSJames Molloy /// use in the pipelined sequence.
generatePhis(MachineBasicBlock * NewBB,MachineBasicBlock * BB1,MachineBasicBlock * BB2,MachineBasicBlock * KernelBB,ValueMapTy * VRMap,InstrMapTy & InstrMap,unsigned LastStageNum,unsigned CurStageNum,bool IsLast)594790a779fSJames Molloy void ModuloScheduleExpander::generatePhis(
595790a779fSJames Molloy     MachineBasicBlock *NewBB, MachineBasicBlock *BB1, MachineBasicBlock *BB2,
596790a779fSJames Molloy     MachineBasicBlock *KernelBB, ValueMapTy *VRMap, InstrMapTy &InstrMap,
597790a779fSJames Molloy     unsigned LastStageNum, unsigned CurStageNum, bool IsLast) {
598790a779fSJames Molloy   // Compute the stage number that contains the initial Phi value, and
599790a779fSJames Molloy   // the Phi from the previous stage.
600790a779fSJames Molloy   unsigned PrologStage = 0;
601790a779fSJames Molloy   unsigned PrevStage = 0;
602790a779fSJames Molloy   unsigned StageDiff = CurStageNum - LastStageNum;
603790a779fSJames Molloy   bool InKernel = (StageDiff == 0);
604790a779fSJames Molloy   if (InKernel) {
605790a779fSJames Molloy     PrologStage = LastStageNum - 1;
606790a779fSJames Molloy     PrevStage = CurStageNum;
607790a779fSJames Molloy   } else {
608790a779fSJames Molloy     PrologStage = LastStageNum - StageDiff;
609790a779fSJames Molloy     PrevStage = LastStageNum + StageDiff - 1;
610790a779fSJames Molloy   }
611790a779fSJames Molloy 
612790a779fSJames Molloy   for (MachineBasicBlock::iterator BBI = BB->getFirstNonPHI(),
613790a779fSJames Molloy                                    BBE = BB->instr_end();
614790a779fSJames Molloy        BBI != BBE; ++BBI) {
615790a779fSJames Molloy     for (unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
616790a779fSJames Molloy       MachineOperand &MO = BBI->getOperand(i);
617790a779fSJames Molloy       if (!MO.isReg() || !MO.isDef() ||
618790a779fSJames Molloy           !Register::isVirtualRegister(MO.getReg()))
619790a779fSJames Molloy         continue;
620790a779fSJames Molloy 
621790a779fSJames Molloy       int StageScheduled = Schedule.getStage(&*BBI);
622790a779fSJames Molloy       assert(StageScheduled != -1 && "Expecting scheduled instruction.");
623790a779fSJames Molloy       Register Def = MO.getReg();
624790a779fSJames Molloy       unsigned NumPhis = getStagesForReg(Def, CurStageNum);
625790a779fSJames Molloy       // An instruction scheduled in stage 0 and is used after the loop
626790a779fSJames Molloy       // requires a phi in the epilog for the last definition from either
627790a779fSJames Molloy       // the kernel or prolog.
628790a779fSJames Molloy       if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
629790a779fSJames Molloy           hasUseAfterLoop(Def, BB, MRI))
630790a779fSJames Molloy         NumPhis = 1;
631790a779fSJames Molloy       if (!InKernel && (unsigned)StageScheduled > PrologStage)
632790a779fSJames Molloy         continue;
633790a779fSJames Molloy 
634790a779fSJames Molloy       unsigned PhiOp2 = VRMap[PrevStage][Def];
635790a779fSJames Molloy       if (MachineInstr *InstOp2 = MRI.getVRegDef(PhiOp2))
636790a779fSJames Molloy         if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
637790a779fSJames Molloy           PhiOp2 = getLoopPhiReg(*InstOp2, BB2);
638790a779fSJames Molloy       // The number of Phis can't exceed the number of prolog stages. The
639790a779fSJames Molloy       // prolog stage number is zero based.
640790a779fSJames Molloy       if (NumPhis > PrologStage + 1 - StageScheduled)
641790a779fSJames Molloy         NumPhis = PrologStage + 1 - StageScheduled;
642790a779fSJames Molloy       for (unsigned np = 0; np < NumPhis; ++np) {
643790a779fSJames Molloy         unsigned PhiOp1 = VRMap[PrologStage][Def];
644790a779fSJames Molloy         if (np <= PrologStage)
645790a779fSJames Molloy           PhiOp1 = VRMap[PrologStage - np][Def];
646790a779fSJames Molloy         if (MachineInstr *InstOp1 = MRI.getVRegDef(PhiOp1)) {
647790a779fSJames Molloy           if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
648790a779fSJames Molloy             PhiOp1 = getInitPhiReg(*InstOp1, KernelBB);
649790a779fSJames Molloy           if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
650790a779fSJames Molloy             PhiOp1 = getInitPhiReg(*InstOp1, NewBB);
651790a779fSJames Molloy         }
652790a779fSJames Molloy         if (!InKernel)
653790a779fSJames Molloy           PhiOp2 = VRMap[PrevStage - np][Def];
654790a779fSJames Molloy 
655790a779fSJames Molloy         const TargetRegisterClass *RC = MRI.getRegClass(Def);
656790a779fSJames Molloy         Register NewReg = MRI.createVirtualRegister(RC);
657790a779fSJames Molloy 
658790a779fSJames Molloy         MachineInstrBuilder NewPhi =
659790a779fSJames Molloy             BuildMI(*NewBB, NewBB->getFirstNonPHI(), DebugLoc(),
660790a779fSJames Molloy                     TII->get(TargetOpcode::PHI), NewReg);
661790a779fSJames Molloy         NewPhi.addReg(PhiOp1).addMBB(BB1);
662790a779fSJames Molloy         NewPhi.addReg(PhiOp2).addMBB(BB2);
663790a779fSJames Molloy         if (np == 0)
664790a779fSJames Molloy           InstrMap[NewPhi] = &*BBI;
665790a779fSJames Molloy 
666790a779fSJames Molloy         // Rewrite uses and update the map. The actions depend upon whether
667790a779fSJames Molloy         // we generating code for the kernel or epilog blocks.
668790a779fSJames Molloy         if (InKernel) {
669790a779fSJames Molloy           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp1,
670790a779fSJames Molloy                                 NewReg);
671790a779fSJames Molloy           rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, PhiOp2,
672790a779fSJames Molloy                                 NewReg);
673790a779fSJames Molloy 
674790a779fSJames Molloy           PhiOp2 = NewReg;
675790a779fSJames Molloy           VRMap[PrevStage - np - 1][Def] = NewReg;
676790a779fSJames Molloy         } else {
677790a779fSJames Molloy           VRMap[CurStageNum - np][Def] = NewReg;
678790a779fSJames Molloy           if (np == NumPhis - 1)
679790a779fSJames Molloy             rewriteScheduledInstr(NewBB, InstrMap, CurStageNum, np, &*BBI, Def,
680790a779fSJames Molloy                                   NewReg);
681790a779fSJames Molloy         }
682790a779fSJames Molloy         if (IsLast && np == NumPhis - 1)
683790a779fSJames Molloy           replaceRegUsesAfterLoop(Def, NewReg, BB, MRI, LIS);
684790a779fSJames Molloy       }
685790a779fSJames Molloy     }
686790a779fSJames Molloy   }
687790a779fSJames Molloy }
688790a779fSJames Molloy 
689790a779fSJames Molloy /// Remove instructions that generate values with no uses.
690790a779fSJames Molloy /// Typically, these are induction variable operations that generate values
691790a779fSJames Molloy /// used in the loop itself.  A dead instruction has a definition with
692790a779fSJames Molloy /// no uses, or uses that occur in the original loop only.
removeDeadInstructions(MachineBasicBlock * KernelBB,MBBVectorTy & EpilogBBs)693790a779fSJames Molloy void ModuloScheduleExpander::removeDeadInstructions(MachineBasicBlock *KernelBB,
694790a779fSJames Molloy                                                     MBBVectorTy &EpilogBBs) {
695790a779fSJames Molloy   // For each epilog block, check that the value defined by each instruction
696790a779fSJames Molloy   // is used.  If not, delete it.
697843d1edaSKazu Hirata   for (MachineBasicBlock *MBB : llvm::reverse(EpilogBBs))
698843d1edaSKazu Hirata     for (MachineBasicBlock::reverse_instr_iterator MI = MBB->instr_rbegin(),
699843d1edaSKazu Hirata                                                    ME = MBB->instr_rend();
700790a779fSJames Molloy          MI != ME;) {
701790a779fSJames Molloy       // From DeadMachineInstructionElem. Don't delete inline assembly.
702790a779fSJames Molloy       if (MI->isInlineAsm()) {
703790a779fSJames Molloy         ++MI;
704790a779fSJames Molloy         continue;
705790a779fSJames Molloy       }
706790a779fSJames Molloy       bool SawStore = false;
707790a779fSJames Molloy       // Check if it's safe to remove the instruction due to side effects.
708790a779fSJames Molloy       // We can, and want to, remove Phis here.
709790a779fSJames Molloy       if (!MI->isSafeToMove(nullptr, SawStore) && !MI->isPHI()) {
710790a779fSJames Molloy         ++MI;
711790a779fSJames Molloy         continue;
712790a779fSJames Molloy       }
713790a779fSJames Molloy       bool used = true;
714ce227ce3SKazu Hirata       for (const MachineOperand &MO : MI->operands()) {
715ce227ce3SKazu Hirata         if (!MO.isReg() || !MO.isDef())
716790a779fSJames Molloy           continue;
717ce227ce3SKazu Hirata         Register reg = MO.getReg();
718790a779fSJames Molloy         // Assume physical registers are used, unless they are marked dead.
719790a779fSJames Molloy         if (Register::isPhysicalRegister(reg)) {
720ce227ce3SKazu Hirata           used = !MO.isDead();
721790a779fSJames Molloy           if (used)
722790a779fSJames Molloy             break;
723790a779fSJames Molloy           continue;
724790a779fSJames Molloy         }
725790a779fSJames Molloy         unsigned realUses = 0;
7262ca45adfSKazu Hirata         for (const MachineOperand &U : MRI.use_operands(reg)) {
727790a779fSJames Molloy           // Check if there are any uses that occur only in the original
728790a779fSJames Molloy           // loop.  If so, that's not a real use.
7292ca45adfSKazu Hirata           if (U.getParent()->getParent() != BB) {
730790a779fSJames Molloy             realUses++;
731790a779fSJames Molloy             used = true;
732790a779fSJames Molloy             break;
733790a779fSJames Molloy           }
734790a779fSJames Molloy         }
735790a779fSJames Molloy         if (realUses > 0)
736790a779fSJames Molloy           break;
737790a779fSJames Molloy         used = false;
738790a779fSJames Molloy       }
739790a779fSJames Molloy       if (!used) {
740790a779fSJames Molloy         LIS.RemoveMachineInstrFromMaps(*MI);
741790a779fSJames Molloy         MI++->eraseFromParent();
742790a779fSJames Molloy         continue;
743790a779fSJames Molloy       }
744790a779fSJames Molloy       ++MI;
745790a779fSJames Molloy     }
746790a779fSJames Molloy   // In the kernel block, check if we can remove a Phi that generates a value
747790a779fSJames Molloy   // used in an instruction removed in the epilog block.
748c3e698e2SKazu Hirata   for (MachineInstr &MI : llvm::make_early_inc_range(KernelBB->phis())) {
749c3e698e2SKazu Hirata     Register reg = MI.getOperand(0).getReg();
750790a779fSJames Molloy     if (MRI.use_begin(reg) == MRI.use_end()) {
751c3e698e2SKazu Hirata       LIS.RemoveMachineInstrFromMaps(MI);
752c3e698e2SKazu Hirata       MI.eraseFromParent();
753790a779fSJames Molloy     }
754790a779fSJames Molloy   }
755790a779fSJames Molloy }
756790a779fSJames Molloy 
757790a779fSJames Molloy /// For loop carried definitions, we split the lifetime of a virtual register
758790a779fSJames Molloy /// that has uses past the definition in the next iteration. A copy with a new
759790a779fSJames Molloy /// virtual register is inserted before the definition, which helps with
760790a779fSJames Molloy /// generating a better register assignment.
761790a779fSJames Molloy ///
762790a779fSJames Molloy ///   v1 = phi(a, v2)     v1 = phi(a, v2)
763790a779fSJames Molloy ///   v2 = phi(b, v3)     v2 = phi(b, v3)
764790a779fSJames Molloy ///   v3 = ..             v4 = copy v1
765790a779fSJames Molloy ///   .. = V1             v3 = ..
766790a779fSJames Molloy ///                       .. = v4
splitLifetimes(MachineBasicBlock * KernelBB,MBBVectorTy & EpilogBBs)767790a779fSJames Molloy void ModuloScheduleExpander::splitLifetimes(MachineBasicBlock *KernelBB,
768790a779fSJames Molloy                                             MBBVectorTy &EpilogBBs) {
769790a779fSJames Molloy   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
770790a779fSJames Molloy   for (auto &PHI : KernelBB->phis()) {
771790a779fSJames Molloy     Register Def = PHI.getOperand(0).getReg();
772790a779fSJames Molloy     // Check for any Phi definition that used as an operand of another Phi
773790a779fSJames Molloy     // in the same block.
774790a779fSJames Molloy     for (MachineRegisterInfo::use_instr_iterator I = MRI.use_instr_begin(Def),
775790a779fSJames Molloy                                                  E = MRI.use_instr_end();
776790a779fSJames Molloy          I != E; ++I) {
777790a779fSJames Molloy       if (I->isPHI() && I->getParent() == KernelBB) {
778790a779fSJames Molloy         // Get the loop carried definition.
779790a779fSJames Molloy         unsigned LCDef = getLoopPhiReg(PHI, KernelBB);
780790a779fSJames Molloy         if (!LCDef)
781790a779fSJames Molloy           continue;
782790a779fSJames Molloy         MachineInstr *MI = MRI.getVRegDef(LCDef);
783790a779fSJames Molloy         if (!MI || MI->getParent() != KernelBB || MI->isPHI())
784790a779fSJames Molloy           continue;
785790a779fSJames Molloy         // Search through the rest of the block looking for uses of the Phi
786790a779fSJames Molloy         // definition. If one occurs, then split the lifetime.
787790a779fSJames Molloy         unsigned SplitReg = 0;
788790a779fSJames Molloy         for (auto &BBJ : make_range(MachineBasicBlock::instr_iterator(MI),
789790a779fSJames Molloy                                     KernelBB->instr_end()))
790790a779fSJames Molloy           if (BBJ.readsRegister(Def)) {
791790a779fSJames Molloy             // We split the lifetime when we find the first use.
792790a779fSJames Molloy             if (SplitReg == 0) {
793790a779fSJames Molloy               SplitReg = MRI.createVirtualRegister(MRI.getRegClass(Def));
794790a779fSJames Molloy               BuildMI(*KernelBB, MI, MI->getDebugLoc(),
795790a779fSJames Molloy                       TII->get(TargetOpcode::COPY), SplitReg)
796790a779fSJames Molloy                   .addReg(Def);
797790a779fSJames Molloy             }
798790a779fSJames Molloy             BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
799790a779fSJames Molloy           }
800790a779fSJames Molloy         if (!SplitReg)
801790a779fSJames Molloy           continue;
802790a779fSJames Molloy         // Search through each of the epilog blocks for any uses to be renamed.
803790a779fSJames Molloy         for (auto &Epilog : EpilogBBs)
804790a779fSJames Molloy           for (auto &I : *Epilog)
805790a779fSJames Molloy             if (I.readsRegister(Def))
806790a779fSJames Molloy               I.substituteRegister(Def, SplitReg, 0, *TRI);
807790a779fSJames Molloy         break;
808790a779fSJames Molloy       }
809790a779fSJames Molloy     }
810790a779fSJames Molloy   }
811790a779fSJames Molloy }
812790a779fSJames Molloy 
813790a779fSJames Molloy /// Remove the incoming block from the Phis in a basic block.
removePhis(MachineBasicBlock * BB,MachineBasicBlock * Incoming)814790a779fSJames Molloy static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming) {
815790a779fSJames Molloy   for (MachineInstr &MI : *BB) {
816790a779fSJames Molloy     if (!MI.isPHI())
817790a779fSJames Molloy       break;
818790a779fSJames Molloy     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2)
819790a779fSJames Molloy       if (MI.getOperand(i + 1).getMBB() == Incoming) {
82037b37838SShengchen Kan         MI.removeOperand(i + 1);
82137b37838SShengchen Kan         MI.removeOperand(i);
822790a779fSJames Molloy         break;
823790a779fSJames Molloy       }
824790a779fSJames Molloy   }
825790a779fSJames Molloy }
826790a779fSJames Molloy 
827790a779fSJames Molloy /// Create branches from each prolog basic block to the appropriate epilog
828790a779fSJames Molloy /// block.  These edges are needed if the loop ends before reaching the
829790a779fSJames Molloy /// kernel.
addBranches(MachineBasicBlock & PreheaderBB,MBBVectorTy & PrologBBs,MachineBasicBlock * KernelBB,MBBVectorTy & EpilogBBs,ValueMapTy * VRMap)830790a779fSJames Molloy void ModuloScheduleExpander::addBranches(MachineBasicBlock &PreheaderBB,
831790a779fSJames Molloy                                          MBBVectorTy &PrologBBs,
832790a779fSJames Molloy                                          MachineBasicBlock *KernelBB,
833790a779fSJames Molloy                                          MBBVectorTy &EpilogBBs,
834790a779fSJames Molloy                                          ValueMapTy *VRMap) {
835790a779fSJames Molloy   assert(PrologBBs.size() == EpilogBBs.size() && "Prolog/Epilog mismatch");
836790a779fSJames Molloy   MachineBasicBlock *LastPro = KernelBB;
837790a779fSJames Molloy   MachineBasicBlock *LastEpi = KernelBB;
838790a779fSJames Molloy 
839790a779fSJames Molloy   // Start from the blocks connected to the kernel and work "out"
840790a779fSJames Molloy   // to the first prolog and the last epilog blocks.
841790a779fSJames Molloy   SmallVector<MachineInstr *, 4> PrevInsts;
842790a779fSJames Molloy   unsigned MaxIter = PrologBBs.size() - 1;
843790a779fSJames Molloy   for (unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
844790a779fSJames Molloy     // Add branches to the prolog that go to the corresponding
845790a779fSJames Molloy     // epilog, and the fall-thru prolog/kernel block.
846790a779fSJames Molloy     MachineBasicBlock *Prolog = PrologBBs[j];
847790a779fSJames Molloy     MachineBasicBlock *Epilog = EpilogBBs[i];
8488a74eca3SJames Molloy 
849790a779fSJames Molloy     SmallVector<MachineOperand, 4> Cond;
8508a74eca3SJames Molloy     Optional<bool> StaticallyGreater =
8518a74eca3SJames Molloy         LoopInfo->createTripCountGreaterCondition(j + 1, *Prolog, Cond);
852790a779fSJames Molloy     unsigned numAdded = 0;
853e0e687a6SKazu Hirata     if (!StaticallyGreater) {
854790a779fSJames Molloy       Prolog->addSuccessor(Epilog);
855790a779fSJames Molloy       numAdded = TII->insertBranch(*Prolog, Epilog, LastPro, Cond, DebugLoc());
8568a74eca3SJames Molloy     } else if (*StaticallyGreater == false) {
857790a779fSJames Molloy       Prolog->addSuccessor(Epilog);
858790a779fSJames Molloy       Prolog->removeSuccessor(LastPro);
859790a779fSJames Molloy       LastEpi->removeSuccessor(Epilog);
860790a779fSJames Molloy       numAdded = TII->insertBranch(*Prolog, Epilog, nullptr, Cond, DebugLoc());
861790a779fSJames Molloy       removePhis(Epilog, LastEpi);
862790a779fSJames Molloy       // Remove the blocks that are no longer referenced.
863790a779fSJames Molloy       if (LastPro != LastEpi) {
864790a779fSJames Molloy         LastEpi->clear();
865790a779fSJames Molloy         LastEpi->eraseFromParent();
866790a779fSJames Molloy       }
8678a74eca3SJames Molloy       if (LastPro == KernelBB) {
8688a74eca3SJames Molloy         LoopInfo->disposed();
8698a74eca3SJames Molloy         NewKernel = nullptr;
8708a74eca3SJames Molloy       }
871790a779fSJames Molloy       LastPro->clear();
872790a779fSJames Molloy       LastPro->eraseFromParent();
873790a779fSJames Molloy     } else {
874790a779fSJames Molloy       numAdded = TII->insertBranch(*Prolog, LastPro, nullptr, Cond, DebugLoc());
875790a779fSJames Molloy       removePhis(Epilog, Prolog);
876790a779fSJames Molloy     }
877790a779fSJames Molloy     LastPro = Prolog;
878790a779fSJames Molloy     LastEpi = Epilog;
879790a779fSJames Molloy     for (MachineBasicBlock::reverse_instr_iterator I = Prolog->instr_rbegin(),
880790a779fSJames Molloy                                                    E = Prolog->instr_rend();
881790a779fSJames Molloy          I != E && numAdded > 0; ++I, --numAdded)
882790a779fSJames Molloy       updateInstruction(&*I, false, j, 0, VRMap);
883790a779fSJames Molloy   }
8848a74eca3SJames Molloy 
8858a74eca3SJames Molloy   if (NewKernel) {
8868a74eca3SJames Molloy     LoopInfo->setPreheader(PrologBBs[MaxIter]);
8878a74eca3SJames Molloy     LoopInfo->adjustTripCount(-(MaxIter + 1));
8888a74eca3SJames Molloy   }
889790a779fSJames Molloy }
890790a779fSJames Molloy 
891790a779fSJames Molloy /// Return true if we can compute the amount the instruction changes
892790a779fSJames Molloy /// during each iteration. Set Delta to the amount of the change.
computeDelta(MachineInstr & MI,unsigned & Delta)893790a779fSJames Molloy bool ModuloScheduleExpander::computeDelta(MachineInstr &MI, unsigned &Delta) {
894790a779fSJames Molloy   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
895790a779fSJames Molloy   const MachineOperand *BaseOp;
896790a779fSJames Molloy   int64_t Offset;
8978fbc9258SSander de Smalen   bool OffsetIsScalable;
8988fbc9258SSander de Smalen   if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, TRI))
8998fbc9258SSander de Smalen     return false;
9008fbc9258SSander de Smalen 
9018fbc9258SSander de Smalen   // FIXME: This algorithm assumes instructions have fixed-size offsets.
9028fbc9258SSander de Smalen   if (OffsetIsScalable)
903790a779fSJames Molloy     return false;
904790a779fSJames Molloy 
905790a779fSJames Molloy   if (!BaseOp->isReg())
906790a779fSJames Molloy     return false;
907790a779fSJames Molloy 
908790a779fSJames Molloy   Register BaseReg = BaseOp->getReg();
909790a779fSJames Molloy 
910790a779fSJames Molloy   MachineRegisterInfo &MRI = MF.getRegInfo();
911790a779fSJames Molloy   // Check if there is a Phi. If so, get the definition in the loop.
912790a779fSJames Molloy   MachineInstr *BaseDef = MRI.getVRegDef(BaseReg);
913790a779fSJames Molloy   if (BaseDef && BaseDef->isPHI()) {
914790a779fSJames Molloy     BaseReg = getLoopPhiReg(*BaseDef, MI.getParent());
915790a779fSJames Molloy     BaseDef = MRI.getVRegDef(BaseReg);
916790a779fSJames Molloy   }
917790a779fSJames Molloy   if (!BaseDef)
918790a779fSJames Molloy     return false;
919790a779fSJames Molloy 
920790a779fSJames Molloy   int D = 0;
921790a779fSJames Molloy   if (!TII->getIncrementValue(*BaseDef, D) && D >= 0)
922790a779fSJames Molloy     return false;
923790a779fSJames Molloy 
924790a779fSJames Molloy   Delta = D;
925790a779fSJames Molloy   return true;
926790a779fSJames Molloy }
927790a779fSJames Molloy 
928790a779fSJames Molloy /// Update the memory operand with a new offset when the pipeliner
929790a779fSJames Molloy /// generates a new copy of the instruction that refers to a
930790a779fSJames Molloy /// different memory location.
updateMemOperands(MachineInstr & NewMI,MachineInstr & OldMI,unsigned Num)931790a779fSJames Molloy void ModuloScheduleExpander::updateMemOperands(MachineInstr &NewMI,
932790a779fSJames Molloy                                                MachineInstr &OldMI,
933790a779fSJames Molloy                                                unsigned Num) {
934790a779fSJames Molloy   if (Num == 0)
935790a779fSJames Molloy     return;
936790a779fSJames Molloy   // If the instruction has memory operands, then adjust the offset
937790a779fSJames Molloy   // when the instruction appears in different stages.
938790a779fSJames Molloy   if (NewMI.memoperands_empty())
939790a779fSJames Molloy     return;
940790a779fSJames Molloy   SmallVector<MachineMemOperand *, 2> NewMMOs;
941790a779fSJames Molloy   for (MachineMemOperand *MMO : NewMI.memoperands()) {
942790a779fSJames Molloy     // TODO: Figure out whether isAtomic is really necessary (see D57601).
943790a779fSJames Molloy     if (MMO->isVolatile() || MMO->isAtomic() ||
944790a779fSJames Molloy         (MMO->isInvariant() && MMO->isDereferenceable()) ||
945790a779fSJames Molloy         (!MMO->getValue())) {
946790a779fSJames Molloy       NewMMOs.push_back(MMO);
947790a779fSJames Molloy       continue;
948790a779fSJames Molloy     }
949790a779fSJames Molloy     unsigned Delta;
950790a779fSJames Molloy     if (Num != UINT_MAX && computeDelta(OldMI, Delta)) {
951790a779fSJames Molloy       int64_t AdjOffset = Delta * Num;
952790a779fSJames Molloy       NewMMOs.push_back(
953790a779fSJames Molloy           MF.getMachineMemOperand(MMO, AdjOffset, MMO->getSize()));
954790a779fSJames Molloy     } else {
955790a779fSJames Molloy       NewMMOs.push_back(
956790a779fSJames Molloy           MF.getMachineMemOperand(MMO, 0, MemoryLocation::UnknownSize));
957790a779fSJames Molloy     }
958790a779fSJames Molloy   }
959790a779fSJames Molloy   NewMI.setMemRefs(MF, NewMMOs);
960790a779fSJames Molloy }
961790a779fSJames Molloy 
962790a779fSJames Molloy /// Clone the instruction for the new pipelined loop and update the
963790a779fSJames Molloy /// memory operands, if needed.
cloneInstr(MachineInstr * OldMI,unsigned CurStageNum,unsigned InstStageNum)964790a779fSJames Molloy MachineInstr *ModuloScheduleExpander::cloneInstr(MachineInstr *OldMI,
965790a779fSJames Molloy                                                  unsigned CurStageNum,
966790a779fSJames Molloy                                                  unsigned InstStageNum) {
967790a779fSJames Molloy   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
968790a779fSJames Molloy   // Check for tied operands in inline asm instructions. This should be handled
969790a779fSJames Molloy   // elsewhere, but I'm not sure of the best solution.
970790a779fSJames Molloy   if (OldMI->isInlineAsm())
971790a779fSJames Molloy     for (unsigned i = 0, e = OldMI->getNumOperands(); i != e; ++i) {
972790a779fSJames Molloy       const auto &MO = OldMI->getOperand(i);
973790a779fSJames Molloy       if (MO.isReg() && MO.isUse())
974790a779fSJames Molloy         break;
975790a779fSJames Molloy       unsigned UseIdx;
976790a779fSJames Molloy       if (OldMI->isRegTiedToUseOperand(i, &UseIdx))
977790a779fSJames Molloy         NewMI->tieOperands(i, UseIdx);
978790a779fSJames Molloy     }
979790a779fSJames Molloy   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
980790a779fSJames Molloy   return NewMI;
981790a779fSJames Molloy }
982790a779fSJames Molloy 
983790a779fSJames Molloy /// Clone the instruction for the new pipelined loop. If needed, this
984790a779fSJames Molloy /// function updates the instruction using the values saved in the
985790a779fSJames Molloy /// InstrChanges structure.
cloneAndChangeInstr(MachineInstr * OldMI,unsigned CurStageNum,unsigned InstStageNum)986790a779fSJames Molloy MachineInstr *ModuloScheduleExpander::cloneAndChangeInstr(
987790a779fSJames Molloy     MachineInstr *OldMI, unsigned CurStageNum, unsigned InstStageNum) {
988790a779fSJames Molloy   MachineInstr *NewMI = MF.CloneMachineInstr(OldMI);
989790a779fSJames Molloy   auto It = InstrChanges.find(OldMI);
990790a779fSJames Molloy   if (It != InstrChanges.end()) {
991790a779fSJames Molloy     std::pair<unsigned, int64_t> RegAndOffset = It->second;
992790a779fSJames Molloy     unsigned BasePos, OffsetPos;
993790a779fSJames Molloy     if (!TII->getBaseAndOffsetPosition(*OldMI, BasePos, OffsetPos))
994790a779fSJames Molloy       return nullptr;
995790a779fSJames Molloy     int64_t NewOffset = OldMI->getOperand(OffsetPos).getImm();
996790a779fSJames Molloy     MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
997790a779fSJames Molloy     if (Schedule.getStage(LoopDef) > (signed)InstStageNum)
998790a779fSJames Molloy       NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
999790a779fSJames Molloy     NewMI->getOperand(OffsetPos).setImm(NewOffset);
1000790a779fSJames Molloy   }
1001790a779fSJames Molloy   updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
1002790a779fSJames Molloy   return NewMI;
1003790a779fSJames Molloy }
1004790a779fSJames Molloy 
1005790a779fSJames Molloy /// Update the machine instruction with new virtual registers.  This
1006907aedbbSDavid Penry /// function may change the definitions and/or uses.
updateInstruction(MachineInstr * NewMI,bool LastDef,unsigned CurStageNum,unsigned InstrStageNum,ValueMapTy * VRMap)1007790a779fSJames Molloy void ModuloScheduleExpander::updateInstruction(MachineInstr *NewMI,
1008790a779fSJames Molloy                                                bool LastDef,
1009790a779fSJames Molloy                                                unsigned CurStageNum,
1010790a779fSJames Molloy                                                unsigned InstrStageNum,
1011790a779fSJames Molloy                                                ValueMapTy *VRMap) {
1012c73fc74cSKazu Hirata   for (MachineOperand &MO : NewMI->operands()) {
1013790a779fSJames Molloy     if (!MO.isReg() || !Register::isVirtualRegister(MO.getReg()))
1014790a779fSJames Molloy       continue;
1015790a779fSJames Molloy     Register reg = MO.getReg();
1016790a779fSJames Molloy     if (MO.isDef()) {
1017790a779fSJames Molloy       // Create a new virtual register for the definition.
1018790a779fSJames Molloy       const TargetRegisterClass *RC = MRI.getRegClass(reg);
1019790a779fSJames Molloy       Register NewReg = MRI.createVirtualRegister(RC);
1020790a779fSJames Molloy       MO.setReg(NewReg);
1021790a779fSJames Molloy       VRMap[CurStageNum][reg] = NewReg;
1022790a779fSJames Molloy       if (LastDef)
1023790a779fSJames Molloy         replaceRegUsesAfterLoop(reg, NewReg, BB, MRI, LIS);
1024790a779fSJames Molloy     } else if (MO.isUse()) {
1025790a779fSJames Molloy       MachineInstr *Def = MRI.getVRegDef(reg);
1026790a779fSJames Molloy       // Compute the stage that contains the last definition for instruction.
1027790a779fSJames Molloy       int DefStageNum = Schedule.getStage(Def);
1028790a779fSJames Molloy       unsigned StageNum = CurStageNum;
1029790a779fSJames Molloy       if (DefStageNum != -1 && (int)InstrStageNum > DefStageNum) {
1030790a779fSJames Molloy         // Compute the difference in stages between the defintion and the use.
1031790a779fSJames Molloy         unsigned StageDiff = (InstrStageNum - DefStageNum);
1032790a779fSJames Molloy         // Make an adjustment to get the last definition.
1033790a779fSJames Molloy         StageNum -= StageDiff;
1034790a779fSJames Molloy       }
1035790a779fSJames Molloy       if (VRMap[StageNum].count(reg))
1036790a779fSJames Molloy         MO.setReg(VRMap[StageNum][reg]);
1037790a779fSJames Molloy     }
1038790a779fSJames Molloy   }
1039790a779fSJames Molloy }
1040790a779fSJames Molloy 
1041790a779fSJames Molloy /// Return the instruction in the loop that defines the register.
1042790a779fSJames Molloy /// If the definition is a Phi, then follow the Phi operand to
1043790a779fSJames Molloy /// the instruction in the loop.
findDefInLoop(unsigned Reg)1044790a779fSJames Molloy MachineInstr *ModuloScheduleExpander::findDefInLoop(unsigned Reg) {
1045790a779fSJames Molloy   SmallPtrSet<MachineInstr *, 8> Visited;
1046790a779fSJames Molloy   MachineInstr *Def = MRI.getVRegDef(Reg);
1047790a779fSJames Molloy   while (Def->isPHI()) {
1048790a779fSJames Molloy     if (!Visited.insert(Def).second)
1049790a779fSJames Molloy       break;
1050790a779fSJames Molloy     for (unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
1051790a779fSJames Molloy       if (Def->getOperand(i + 1).getMBB() == BB) {
1052790a779fSJames Molloy         Def = MRI.getVRegDef(Def->getOperand(i).getReg());
1053790a779fSJames Molloy         break;
1054790a779fSJames Molloy       }
1055790a779fSJames Molloy   }
1056790a779fSJames Molloy   return Def;
1057790a779fSJames Molloy }
1058790a779fSJames Molloy 
1059790a779fSJames Molloy /// Return the new name for the value from the previous stage.
getPrevMapVal(unsigned StageNum,unsigned PhiStage,unsigned LoopVal,unsigned LoopStage,ValueMapTy * VRMap,MachineBasicBlock * BB)1060790a779fSJames Molloy unsigned ModuloScheduleExpander::getPrevMapVal(
1061790a779fSJames Molloy     unsigned StageNum, unsigned PhiStage, unsigned LoopVal, unsigned LoopStage,
1062790a779fSJames Molloy     ValueMapTy *VRMap, MachineBasicBlock *BB) {
1063790a779fSJames Molloy   unsigned PrevVal = 0;
1064790a779fSJames Molloy   if (StageNum > PhiStage) {
1065790a779fSJames Molloy     MachineInstr *LoopInst = MRI.getVRegDef(LoopVal);
1066790a779fSJames Molloy     if (PhiStage == LoopStage && VRMap[StageNum - 1].count(LoopVal))
1067790a779fSJames Molloy       // The name is defined in the previous stage.
1068790a779fSJames Molloy       PrevVal = VRMap[StageNum - 1][LoopVal];
1069790a779fSJames Molloy     else if (VRMap[StageNum].count(LoopVal))
1070790a779fSJames Molloy       // The previous name is defined in the current stage when the instruction
1071790a779fSJames Molloy       // order is swapped.
1072790a779fSJames Molloy       PrevVal = VRMap[StageNum][LoopVal];
1073790a779fSJames Molloy     else if (!LoopInst->isPHI() || LoopInst->getParent() != BB)
1074790a779fSJames Molloy       // The loop value hasn't yet been scheduled.
1075790a779fSJames Molloy       PrevVal = LoopVal;
1076790a779fSJames Molloy     else if (StageNum == PhiStage + 1)
1077790a779fSJames Molloy       // The loop value is another phi, which has not been scheduled.
1078790a779fSJames Molloy       PrevVal = getInitPhiReg(*LoopInst, BB);
1079790a779fSJames Molloy     else if (StageNum > PhiStage + 1 && LoopInst->getParent() == BB)
1080790a779fSJames Molloy       // The loop value is another phi, which has been scheduled.
1081790a779fSJames Molloy       PrevVal =
1082790a779fSJames Molloy           getPrevMapVal(StageNum - 1, PhiStage, getLoopPhiReg(*LoopInst, BB),
1083790a779fSJames Molloy                         LoopStage, VRMap, BB);
1084790a779fSJames Molloy   }
1085790a779fSJames Molloy   return PrevVal;
1086790a779fSJames Molloy }
1087790a779fSJames Molloy 
1088790a779fSJames Molloy /// Rewrite the Phi values in the specified block to use the mappings
1089790a779fSJames Molloy /// from the initial operand. Once the Phi is scheduled, we switch
1090790a779fSJames Molloy /// to using the loop value instead of the Phi value, so those names
1091790a779fSJames Molloy /// do not need to be rewritten.
rewritePhiValues(MachineBasicBlock * NewBB,unsigned StageNum,ValueMapTy * VRMap,InstrMapTy & InstrMap)1092790a779fSJames Molloy void ModuloScheduleExpander::rewritePhiValues(MachineBasicBlock *NewBB,
1093790a779fSJames Molloy                                               unsigned StageNum,
1094790a779fSJames Molloy                                               ValueMapTy *VRMap,
1095790a779fSJames Molloy                                               InstrMapTy &InstrMap) {
1096790a779fSJames Molloy   for (auto &PHI : BB->phis()) {
1097790a779fSJames Molloy     unsigned InitVal = 0;
1098790a779fSJames Molloy     unsigned LoopVal = 0;
1099790a779fSJames Molloy     getPhiRegs(PHI, BB, InitVal, LoopVal);
1100790a779fSJames Molloy     Register PhiDef = PHI.getOperand(0).getReg();
1101790a779fSJames Molloy 
1102790a779fSJames Molloy     unsigned PhiStage = (unsigned)Schedule.getStage(MRI.getVRegDef(PhiDef));
1103790a779fSJames Molloy     unsigned LoopStage = (unsigned)Schedule.getStage(MRI.getVRegDef(LoopVal));
1104790a779fSJames Molloy     unsigned NumPhis = getStagesForPhi(PhiDef);
1105790a779fSJames Molloy     if (NumPhis > StageNum)
1106790a779fSJames Molloy       NumPhis = StageNum;
1107790a779fSJames Molloy     for (unsigned np = 0; np <= NumPhis; ++np) {
1108790a779fSJames Molloy       unsigned NewVal =
1109790a779fSJames Molloy           getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
1110790a779fSJames Molloy       if (!NewVal)
1111790a779fSJames Molloy         NewVal = InitVal;
1112790a779fSJames Molloy       rewriteScheduledInstr(NewBB, InstrMap, StageNum - np, np, &PHI, PhiDef,
1113790a779fSJames Molloy                             NewVal);
1114790a779fSJames Molloy     }
1115790a779fSJames Molloy   }
1116790a779fSJames Molloy }
1117790a779fSJames Molloy 
1118790a779fSJames Molloy /// Rewrite a previously scheduled instruction to use the register value
1119790a779fSJames Molloy /// from the new instruction. Make sure the instruction occurs in the
1120790a779fSJames Molloy /// basic block, and we don't change the uses in the new instruction.
rewriteScheduledInstr(MachineBasicBlock * BB,InstrMapTy & InstrMap,unsigned CurStageNum,unsigned PhiNum,MachineInstr * Phi,unsigned OldReg,unsigned NewReg,unsigned PrevReg)1121790a779fSJames Molloy void ModuloScheduleExpander::rewriteScheduledInstr(
1122790a779fSJames Molloy     MachineBasicBlock *BB, InstrMapTy &InstrMap, unsigned CurStageNum,
1123790a779fSJames Molloy     unsigned PhiNum, MachineInstr *Phi, unsigned OldReg, unsigned NewReg,
1124790a779fSJames Molloy     unsigned PrevReg) {
1125790a779fSJames Molloy   bool InProlog = (CurStageNum < (unsigned)Schedule.getNumStages() - 1);
1126790a779fSJames Molloy   int StagePhi = Schedule.getStage(Phi) + PhiNum;
1127790a779fSJames Molloy   // Rewrite uses that have been scheduled already to use the new
1128790a779fSJames Molloy   // Phi register.
1129642a361bSKazu Hirata   for (MachineOperand &UseOp :
1130642a361bSKazu Hirata        llvm::make_early_inc_range(MRI.use_operands(OldReg))) {
1131790a779fSJames Molloy     MachineInstr *UseMI = UseOp.getParent();
1132790a779fSJames Molloy     if (UseMI->getParent() != BB)
1133790a779fSJames Molloy       continue;
1134790a779fSJames Molloy     if (UseMI->isPHI()) {
1135790a779fSJames Molloy       if (!Phi->isPHI() && UseMI->getOperand(0).getReg() == NewReg)
1136790a779fSJames Molloy         continue;
1137790a779fSJames Molloy       if (getLoopPhiReg(*UseMI, BB) != OldReg)
1138790a779fSJames Molloy         continue;
1139790a779fSJames Molloy     }
1140790a779fSJames Molloy     InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
1141790a779fSJames Molloy     assert(OrigInstr != InstrMap.end() && "Instruction not scheduled.");
1142790a779fSJames Molloy     MachineInstr *OrigMI = OrigInstr->second;
1143790a779fSJames Molloy     int StageSched = Schedule.getStage(OrigMI);
1144790a779fSJames Molloy     int CycleSched = Schedule.getCycle(OrigMI);
1145790a779fSJames Molloy     unsigned ReplaceReg = 0;
1146790a779fSJames Molloy     // This is the stage for the scheduled instruction.
1147790a779fSJames Molloy     if (StagePhi == StageSched && Phi->isPHI()) {
1148790a779fSJames Molloy       int CyclePhi = Schedule.getCycle(Phi);
1149790a779fSJames Molloy       if (PrevReg && InProlog)
1150790a779fSJames Molloy         ReplaceReg = PrevReg;
1151790a779fSJames Molloy       else if (PrevReg && !isLoopCarried(*Phi) &&
1152790a779fSJames Molloy                (CyclePhi <= CycleSched || OrigMI->isPHI()))
1153790a779fSJames Molloy         ReplaceReg = PrevReg;
1154790a779fSJames Molloy       else
1155790a779fSJames Molloy         ReplaceReg = NewReg;
1156790a779fSJames Molloy     }
1157790a779fSJames Molloy     // The scheduled instruction occurs before the scheduled Phi, and the
1158790a779fSJames Molloy     // Phi is not loop carried.
1159790a779fSJames Molloy     if (!InProlog && StagePhi + 1 == StageSched && !isLoopCarried(*Phi))
1160790a779fSJames Molloy       ReplaceReg = NewReg;
1161790a779fSJames Molloy     if (StagePhi > StageSched && Phi->isPHI())
1162790a779fSJames Molloy       ReplaceReg = NewReg;
1163790a779fSJames Molloy     if (!InProlog && !Phi->isPHI() && StagePhi < StageSched)
1164790a779fSJames Molloy       ReplaceReg = NewReg;
1165790a779fSJames Molloy     if (ReplaceReg) {
1166e995e344SDavid Green       const TargetRegisterClass *NRC =
1167790a779fSJames Molloy           MRI.constrainRegClass(ReplaceReg, MRI.getRegClass(OldReg));
1168e995e344SDavid Green       if (NRC)
1169790a779fSJames Molloy         UseOp.setReg(ReplaceReg);
1170e995e344SDavid Green       else {
1171e995e344SDavid Green         Register SplitReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
1172e995e344SDavid Green         BuildMI(*BB, UseMI, UseMI->getDebugLoc(), TII->get(TargetOpcode::COPY),
1173e995e344SDavid Green                 SplitReg)
1174e995e344SDavid Green             .addReg(ReplaceReg);
1175e995e344SDavid Green         UseOp.setReg(SplitReg);
1176e995e344SDavid Green       }
1177790a779fSJames Molloy     }
1178790a779fSJames Molloy   }
1179790a779fSJames Molloy }
1180790a779fSJames Molloy 
isLoopCarried(MachineInstr & Phi)1181790a779fSJames Molloy bool ModuloScheduleExpander::isLoopCarried(MachineInstr &Phi) {
1182790a779fSJames Molloy   if (!Phi.isPHI())
1183790a779fSJames Molloy     return false;
1184caabb713SThomas Raoux   int DefCycle = Schedule.getCycle(&Phi);
1185790a779fSJames Molloy   int DefStage = Schedule.getStage(&Phi);
1186790a779fSJames Molloy 
1187790a779fSJames Molloy   unsigned InitVal = 0;
1188790a779fSJames Molloy   unsigned LoopVal = 0;
1189790a779fSJames Molloy   getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
1190790a779fSJames Molloy   MachineInstr *Use = MRI.getVRegDef(LoopVal);
1191790a779fSJames Molloy   if (!Use || Use->isPHI())
1192790a779fSJames Molloy     return true;
1193caabb713SThomas Raoux   int LoopCycle = Schedule.getCycle(Use);
1194790a779fSJames Molloy   int LoopStage = Schedule.getStage(Use);
1195790a779fSJames Molloy   return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
1196790a779fSJames Molloy }
119793549957SJames Molloy 
119893549957SJames Molloy //===----------------------------------------------------------------------===//
1199fef9f590SJames Molloy // PeelingModuloScheduleExpander implementation
1200fef9f590SJames Molloy //===----------------------------------------------------------------------===//
1201fef9f590SJames Molloy // This is a reimplementation of ModuloScheduleExpander that works by creating
1202fef9f590SJames Molloy // a fully correct steady-state kernel and peeling off the prolog and epilogs.
1203fef9f590SJames Molloy //===----------------------------------------------------------------------===//
1204fef9f590SJames Molloy 
1205fef9f590SJames Molloy namespace {
1206fef9f590SJames Molloy // Remove any dead phis in MBB. Dead phis either have only one block as input
1207fef9f590SJames Molloy // (in which case they are the identity) or have no uses.
EliminateDeadPhis(MachineBasicBlock * MBB,MachineRegisterInfo & MRI,LiveIntervals * LIS,bool KeepSingleSrcPhi=false)1208fef9f590SJames Molloy void EliminateDeadPhis(MachineBasicBlock *MBB, MachineRegisterInfo &MRI,
1209e0297a8bSThomas Raoux                        LiveIntervals *LIS, bool KeepSingleSrcPhi = false) {
1210fef9f590SJames Molloy   bool Changed = true;
1211fef9f590SJames Molloy   while (Changed) {
1212fef9f590SJames Molloy     Changed = false;
1213c3e698e2SKazu Hirata     for (MachineInstr &MI : llvm::make_early_inc_range(MBB->phis())) {
1214fef9f590SJames Molloy       assert(MI.isPHI());
1215fef9f590SJames Molloy       if (MRI.use_empty(MI.getOperand(0).getReg())) {
1216fef9f590SJames Molloy         if (LIS)
1217fef9f590SJames Molloy           LIS->RemoveMachineInstrFromMaps(MI);
1218fef9f590SJames Molloy         MI.eraseFromParent();
1219fef9f590SJames Molloy         Changed = true;
1220e0297a8bSThomas Raoux       } else if (!KeepSingleSrcPhi && MI.getNumExplicitOperands() == 3) {
1221e995e344SDavid Green         const TargetRegisterClass *ConstrainRegClass =
1222fef9f590SJames Molloy             MRI.constrainRegClass(MI.getOperand(1).getReg(),
1223fef9f590SJames Molloy                                   MRI.getRegClass(MI.getOperand(0).getReg()));
1224e995e344SDavid Green         assert(ConstrainRegClass &&
1225e995e344SDavid Green                "Expected a valid constrained register class!");
1226e995e344SDavid Green         (void)ConstrainRegClass;
1227fef9f590SJames Molloy         MRI.replaceRegWith(MI.getOperand(0).getReg(),
1228fef9f590SJames Molloy                            MI.getOperand(1).getReg());
1229fef9f590SJames Molloy         if (LIS)
1230fef9f590SJames Molloy           LIS->RemoveMachineInstrFromMaps(MI);
1231fef9f590SJames Molloy         MI.eraseFromParent();
1232fef9f590SJames Molloy         Changed = true;
1233fef9f590SJames Molloy       }
1234fef9f590SJames Molloy     }
1235fef9f590SJames Molloy   }
1236fef9f590SJames Molloy }
1237fef9f590SJames Molloy 
1238fef9f590SJames Molloy /// Rewrites the kernel block in-place to adhere to the given schedule.
1239fef9f590SJames Molloy /// KernelRewriter holds all of the state required to perform the rewriting.
1240fef9f590SJames Molloy class KernelRewriter {
1241fef9f590SJames Molloy   ModuloSchedule &S;
1242fef9f590SJames Molloy   MachineBasicBlock *BB;
1243fef9f590SJames Molloy   MachineBasicBlock *PreheaderBB, *ExitBB;
1244fef9f590SJames Molloy   MachineRegisterInfo &MRI;
1245fef9f590SJames Molloy   const TargetInstrInfo *TII;
1246fef9f590SJames Molloy   LiveIntervals *LIS;
1247fef9f590SJames Molloy 
1248fef9f590SJames Molloy   // Map from register class to canonical undef register for that class.
1249fef9f590SJames Molloy   DenseMap<const TargetRegisterClass *, Register> Undefs;
1250fef9f590SJames Molloy   // Map from <LoopReg, InitReg> to phi register for all created phis. Note that
1251fef9f590SJames Molloy   // this map is only used when InitReg is non-undef.
1252fef9f590SJames Molloy   DenseMap<std::pair<unsigned, unsigned>, Register> Phis;
1253fef9f590SJames Molloy   // Map from LoopReg to phi register where the InitReg is undef.
1254fef9f590SJames Molloy   DenseMap<Register, Register> UndefPhis;
1255fef9f590SJames Molloy 
1256fef9f590SJames Molloy   // Reg is used by MI. Return the new register MI should use to adhere to the
1257fef9f590SJames Molloy   // schedule. Insert phis as necessary.
1258fef9f590SJames Molloy   Register remapUse(Register Reg, MachineInstr &MI);
1259fef9f590SJames Molloy   // Insert a phi that carries LoopReg from the loop body and InitReg otherwise.
1260fef9f590SJames Molloy   // If InitReg is not given it is chosen arbitrarily. It will either be undef
1261fef9f590SJames Molloy   // or will be chosen so as to share another phi.
1262fef9f590SJames Molloy   Register phi(Register LoopReg, Optional<Register> InitReg = {},
1263fef9f590SJames Molloy                const TargetRegisterClass *RC = nullptr);
1264fef9f590SJames Molloy   // Create an undef register of the given register class.
1265fef9f590SJames Molloy   Register undef(const TargetRegisterClass *RC);
1266fef9f590SJames Molloy 
1267fef9f590SJames Molloy public:
1268e15e1417SHendrik Greving   KernelRewriter(MachineLoop &L, ModuloSchedule &S, MachineBasicBlock *LoopBB,
1269fef9f590SJames Molloy                  LiveIntervals *LIS = nullptr);
1270fef9f590SJames Molloy   void rewrite();
1271fef9f590SJames Molloy };
1272fef9f590SJames Molloy } // namespace
1273fef9f590SJames Molloy 
KernelRewriter(MachineLoop & L,ModuloSchedule & S,MachineBasicBlock * LoopBB,LiveIntervals * LIS)1274fef9f590SJames Molloy KernelRewriter::KernelRewriter(MachineLoop &L, ModuloSchedule &S,
1275e15e1417SHendrik Greving                                MachineBasicBlock *LoopBB, LiveIntervals *LIS)
1276e15e1417SHendrik Greving     : S(S), BB(LoopBB), PreheaderBB(L.getLoopPreheader()),
1277fef9f590SJames Molloy       ExitBB(L.getExitBlock()), MRI(BB->getParent()->getRegInfo()),
1278fef9f590SJames Molloy       TII(BB->getParent()->getSubtarget().getInstrInfo()), LIS(LIS) {
1279fef9f590SJames Molloy   PreheaderBB = *BB->pred_begin();
1280fef9f590SJames Molloy   if (PreheaderBB == BB)
1281fef9f590SJames Molloy     PreheaderBB = *std::next(BB->pred_begin());
1282fef9f590SJames Molloy }
1283fef9f590SJames Molloy 
rewrite()1284fef9f590SJames Molloy void KernelRewriter::rewrite() {
1285fef9f590SJames Molloy   // Rearrange the loop to be in schedule order. Note that the schedule may
1286fef9f590SJames Molloy   // contain instructions that are not owned by the loop block (InstrChanges and
1287fef9f590SJames Molloy   // friends), so we gracefully handle unowned instructions and delete any
1288fef9f590SJames Molloy   // instructions that weren't in the schedule.
1289fef9f590SJames Molloy   auto InsertPt = BB->getFirstTerminator();
1290fef9f590SJames Molloy   MachineInstr *FirstMI = nullptr;
1291fef9f590SJames Molloy   for (MachineInstr *MI : S.getInstructions()) {
1292fef9f590SJames Molloy     if (MI->isPHI())
1293fef9f590SJames Molloy       continue;
1294fef9f590SJames Molloy     if (MI->getParent())
1295fef9f590SJames Molloy       MI->removeFromParent();
1296fef9f590SJames Molloy     BB->insert(InsertPt, MI);
1297fef9f590SJames Molloy     if (!FirstMI)
1298fef9f590SJames Molloy       FirstMI = MI;
1299fef9f590SJames Molloy   }
13009942c077SSimon Pilgrim   assert(FirstMI && "Failed to find first MI in schedule");
1301fef9f590SJames Molloy 
1302fef9f590SJames Molloy   // At this point all of the scheduled instructions are between FirstMI
1303fef9f590SJames Molloy   // and the end of the block. Kill from the first non-phi to FirstMI.
1304fef9f590SJames Molloy   for (auto I = BB->getFirstNonPHI(); I != FirstMI->getIterator();) {
1305fef9f590SJames Molloy     if (LIS)
1306fef9f590SJames Molloy       LIS->RemoveMachineInstrFromMaps(*I);
1307fef9f590SJames Molloy     (I++)->eraseFromParent();
1308fef9f590SJames Molloy   }
1309fef9f590SJames Molloy 
1310fef9f590SJames Molloy   // Now remap every instruction in the loop.
1311fef9f590SJames Molloy   for (MachineInstr &MI : *BB) {
13129baac83aSJames Molloy     if (MI.isPHI() || MI.isTerminator())
1313fef9f590SJames Molloy       continue;
1314fef9f590SJames Molloy     for (MachineOperand &MO : MI.uses()) {
1315fef9f590SJames Molloy       if (!MO.isReg() || MO.getReg().isPhysical() || MO.isImplicit())
1316fef9f590SJames Molloy         continue;
1317fef9f590SJames Molloy       Register Reg = remapUse(MO.getReg(), MI);
1318fef9f590SJames Molloy       MO.setReg(Reg);
1319fef9f590SJames Molloy     }
1320fef9f590SJames Molloy   }
1321fef9f590SJames Molloy   EliminateDeadPhis(BB, MRI, LIS);
1322fef9f590SJames Molloy 
1323fef9f590SJames Molloy   // Ensure a phi exists for all instructions that are either referenced by
1324fef9f590SJames Molloy   // an illegal phi or by an instruction outside the loop. This allows us to
1325fef9f590SJames Molloy   // treat remaps of these values the same as "normal" values that come from
1326fef9f590SJames Molloy   // loop-carried phis.
1327fef9f590SJames Molloy   for (auto MI = BB->getFirstNonPHI(); MI != BB->end(); ++MI) {
1328fef9f590SJames Molloy     if (MI->isPHI()) {
1329fef9f590SJames Molloy       Register R = MI->getOperand(0).getReg();
1330fef9f590SJames Molloy       phi(R);
1331fef9f590SJames Molloy       continue;
1332fef9f590SJames Molloy     }
1333fef9f590SJames Molloy 
1334fef9f590SJames Molloy     for (MachineOperand &Def : MI->defs()) {
1335fef9f590SJames Molloy       for (MachineInstr &MI : MRI.use_instructions(Def.getReg())) {
1336fef9f590SJames Molloy         if (MI.getParent() != BB) {
1337fef9f590SJames Molloy           phi(Def.getReg());
1338fef9f590SJames Molloy           break;
1339fef9f590SJames Molloy         }
1340fef9f590SJames Molloy       }
1341fef9f590SJames Molloy     }
1342fef9f590SJames Molloy   }
1343fef9f590SJames Molloy }
1344fef9f590SJames Molloy 
remapUse(Register Reg,MachineInstr & MI)1345fef9f590SJames Molloy Register KernelRewriter::remapUse(Register Reg, MachineInstr &MI) {
1346fef9f590SJames Molloy   MachineInstr *Producer = MRI.getUniqueVRegDef(Reg);
1347fef9f590SJames Molloy   if (!Producer)
1348fef9f590SJames Molloy     return Reg;
1349fef9f590SJames Molloy 
1350fef9f590SJames Molloy   int ConsumerStage = S.getStage(&MI);
1351fef9f590SJames Molloy   if (!Producer->isPHI()) {
1352fef9f590SJames Molloy     // Non-phi producers are simple to remap. Insert as many phis as the
1353fef9f590SJames Molloy     // difference between the consumer and producer stages.
1354fef9f590SJames Molloy     if (Producer->getParent() != BB)
1355fef9f590SJames Molloy       // Producer was not inside the loop. Use the register as-is.
1356fef9f590SJames Molloy       return Reg;
1357fef9f590SJames Molloy     int ProducerStage = S.getStage(Producer);
1358fef9f590SJames Molloy     assert(ConsumerStage != -1 &&
1359fef9f590SJames Molloy            "In-loop consumer should always be scheduled!");
1360fef9f590SJames Molloy     assert(ConsumerStage >= ProducerStage);
1361fef9f590SJames Molloy     unsigned StageDiff = ConsumerStage - ProducerStage;
1362fef9f590SJames Molloy 
1363fef9f590SJames Molloy     for (unsigned I = 0; I < StageDiff; ++I)
1364fef9f590SJames Molloy       Reg = phi(Reg);
1365fef9f590SJames Molloy     return Reg;
1366fef9f590SJames Molloy   }
1367fef9f590SJames Molloy 
1368fef9f590SJames Molloy   // First, dive through the phi chain to find the defaults for the generated
1369fef9f590SJames Molloy   // phis.
1370fef9f590SJames Molloy   SmallVector<Optional<Register>, 4> Defaults;
1371fef9f590SJames Molloy   Register LoopReg = Reg;
1372fef9f590SJames Molloy   auto LoopProducer = Producer;
1373fef9f590SJames Molloy   while (LoopProducer->isPHI() && LoopProducer->getParent() == BB) {
1374fef9f590SJames Molloy     LoopReg = getLoopPhiReg(*LoopProducer, BB);
1375fef9f590SJames Molloy     Defaults.emplace_back(getInitPhiReg(*LoopProducer, BB));
1376fef9f590SJames Molloy     LoopProducer = MRI.getUniqueVRegDef(LoopReg);
1377fef9f590SJames Molloy     assert(LoopProducer);
1378fef9f590SJames Molloy   }
1379fef9f590SJames Molloy   int LoopProducerStage = S.getStage(LoopProducer);
1380fef9f590SJames Molloy 
1381fef9f590SJames Molloy   Optional<Register> IllegalPhiDefault;
1382fef9f590SJames Molloy 
1383fef9f590SJames Molloy   if (LoopProducerStage == -1) {
1384fef9f590SJames Molloy     // Do nothing.
1385fef9f590SJames Molloy   } else if (LoopProducerStage > ConsumerStage) {
1386fef9f590SJames Molloy     // This schedule is only representable if ProducerStage == ConsumerStage+1.
1387fef9f590SJames Molloy     // In addition, Consumer's cycle must be scheduled after Producer in the
138811f0f7f5SJames Molloy     // rescheduled loop. This is enforced by the pipeliner's ASAP and ALAP
138911f0f7f5SJames Molloy     // functions.
139011f0f7f5SJames Molloy #ifndef NDEBUG // Silence unused variables in non-asserts mode.
139111f0f7f5SJames Molloy     int LoopProducerCycle = S.getCycle(LoopProducer);
139211f0f7f5SJames Molloy     int ConsumerCycle = S.getCycle(&MI);
139311f0f7f5SJames Molloy #endif
1394fef9f590SJames Molloy     assert(LoopProducerCycle <= ConsumerCycle);
1395fef9f590SJames Molloy     assert(LoopProducerStage == ConsumerStage + 1);
1396fef9f590SJames Molloy     // Peel off the first phi from Defaults and insert a phi between producer
1397fef9f590SJames Molloy     // and consumer. This phi will not be at the front of the block so we
1398fef9f590SJames Molloy     // consider it illegal. It will only exist during the rewrite process; it
1399fef9f590SJames Molloy     // needs to exist while we peel off prologs because these could take the
1400fef9f590SJames Molloy     // default value. After that we can replace all uses with the loop producer
1401fef9f590SJames Molloy     // value.
1402fef9f590SJames Molloy     IllegalPhiDefault = Defaults.front();
1403fef9f590SJames Molloy     Defaults.erase(Defaults.begin());
1404fef9f590SJames Molloy   } else {
1405fef9f590SJames Molloy     assert(ConsumerStage >= LoopProducerStage);
1406fef9f590SJames Molloy     int StageDiff = ConsumerStage - LoopProducerStage;
1407fef9f590SJames Molloy     if (StageDiff > 0) {
1408fef9f590SJames Molloy       LLVM_DEBUG(dbgs() << " -- padding defaults array from " << Defaults.size()
1409fef9f590SJames Molloy                         << " to " << (Defaults.size() + StageDiff) << "\n");
1410fef9f590SJames Molloy       // If we need more phis than we have defaults for, pad out with undefs for
1411fef9f590SJames Molloy       // the earliest phis, which are at the end of the defaults chain (the
1412fef9f590SJames Molloy       // chain is in reverse order).
1413fef9f590SJames Molloy       Defaults.resize(Defaults.size() + StageDiff, Defaults.empty()
1414fef9f590SJames Molloy                                                        ? Optional<Register>()
1415fef9f590SJames Molloy                                                        : Defaults.back());
1416fef9f590SJames Molloy     }
1417fef9f590SJames Molloy   }
1418fef9f590SJames Molloy 
1419fef9f590SJames Molloy   // Now we know the number of stages to jump back, insert the phi chain.
1420fef9f590SJames Molloy   auto DefaultI = Defaults.rbegin();
1421fef9f590SJames Molloy   while (DefaultI != Defaults.rend())
1422fef9f590SJames Molloy     LoopReg = phi(LoopReg, *DefaultI++, MRI.getRegClass(Reg));
1423fef9f590SJames Molloy 
1424e0e687a6SKazu Hirata   if (IllegalPhiDefault) {
1425fef9f590SJames Molloy     // The consumer optionally consumes LoopProducer in the same iteration
1426fef9f590SJames Molloy     // (because the producer is scheduled at an earlier cycle than the consumer)
1427fef9f590SJames Molloy     // or the initial value. To facilitate this we create an illegal block here
1428fef9f590SJames Molloy     // by embedding a phi in the middle of the block. We will fix this up
1429fef9f590SJames Molloy     // immediately prior to pruning.
1430fef9f590SJames Molloy     auto RC = MRI.getRegClass(Reg);
1431fef9f590SJames Molloy     Register R = MRI.createVirtualRegister(RC);
1432dc26dec3SThomas Raoux     MachineInstr *IllegalPhi =
1433fef9f590SJames Molloy         BuildMI(*BB, MI, DebugLoc(), TII->get(TargetOpcode::PHI), R)
14347a47ee51SKazu Hirata             .addReg(*IllegalPhiDefault)
1435fef9f590SJames Molloy             .addMBB(PreheaderBB) // Block choice is arbitrary and has no effect.
1436fef9f590SJames Molloy             .addReg(LoopReg)
1437fef9f590SJames Molloy             .addMBB(BB); // Block choice is arbitrary and has no effect.
1438dc26dec3SThomas Raoux     // Illegal phi should belong to the producer stage so that it can be
1439dc26dec3SThomas Raoux     // filtered correctly during peeling.
1440dc26dec3SThomas Raoux     S.setStage(IllegalPhi, LoopProducerStage);
1441fef9f590SJames Molloy     return R;
1442fef9f590SJames Molloy   }
1443fef9f590SJames Molloy 
1444fef9f590SJames Molloy   return LoopReg;
1445fef9f590SJames Molloy }
1446fef9f590SJames Molloy 
phi(Register LoopReg,Optional<Register> InitReg,const TargetRegisterClass * RC)1447fef9f590SJames Molloy Register KernelRewriter::phi(Register LoopReg, Optional<Register> InitReg,
1448fef9f590SJames Molloy                              const TargetRegisterClass *RC) {
1449fef9f590SJames Molloy   // If the init register is not undef, try and find an existing phi.
1450a7938c74SKazu Hirata   if (InitReg) {
1451*611ffcf4SKazu Hirata     auto I = Phis.find({LoopReg, InitReg.value()});
1452fef9f590SJames Molloy     if (I != Phis.end())
1453fef9f590SJames Molloy       return I->second;
1454fef9f590SJames Molloy   } else {
1455fef9f590SJames Molloy     for (auto &KV : Phis) {
1456fef9f590SJames Molloy       if (KV.first.first == LoopReg)
1457fef9f590SJames Molloy         return KV.second;
1458fef9f590SJames Molloy     }
1459fef9f590SJames Molloy   }
1460fef9f590SJames Molloy 
1461fef9f590SJames Molloy   // InitReg is either undef or no existing phi takes InitReg as input. Try and
1462fef9f590SJames Molloy   // find a phi that takes undef as input.
1463fef9f590SJames Molloy   auto I = UndefPhis.find(LoopReg);
1464fef9f590SJames Molloy   if (I != UndefPhis.end()) {
1465fef9f590SJames Molloy     Register R = I->second;
1466e0e687a6SKazu Hirata     if (!InitReg)
1467fef9f590SJames Molloy       // Found a phi taking undef as input, and this input is undef so return
1468fef9f590SJames Molloy       // without any more changes.
1469fef9f590SJames Molloy       return R;
1470fef9f590SJames Molloy     // Found a phi taking undef as input, so rewrite it to take InitReg.
1471fef9f590SJames Molloy     MachineInstr *MI = MRI.getVRegDef(R);
1472*611ffcf4SKazu Hirata     MI->getOperand(1).setReg(InitReg.value());
1473*611ffcf4SKazu Hirata     Phis.insert({{LoopReg, InitReg.value()}, R});
1474e995e344SDavid Green     const TargetRegisterClass *ConstrainRegClass =
1475*611ffcf4SKazu Hirata         MRI.constrainRegClass(R, MRI.getRegClass(InitReg.value()));
1476e995e344SDavid Green     assert(ConstrainRegClass && "Expected a valid constrained register class!");
1477e995e344SDavid Green     (void)ConstrainRegClass;
1478fef9f590SJames Molloy     UndefPhis.erase(I);
1479fef9f590SJames Molloy     return R;
1480fef9f590SJames Molloy   }
1481fef9f590SJames Molloy 
1482fef9f590SJames Molloy   // Failed to find any existing phi to reuse, so create a new one.
1483fef9f590SJames Molloy   if (!RC)
1484fef9f590SJames Molloy     RC = MRI.getRegClass(LoopReg);
1485fef9f590SJames Molloy   Register R = MRI.createVirtualRegister(RC);
1486a7938c74SKazu Hirata   if (InitReg) {
1487e995e344SDavid Green     const TargetRegisterClass *ConstrainRegClass =
1488fef9f590SJames Molloy         MRI.constrainRegClass(R, MRI.getRegClass(*InitReg));
1489e995e344SDavid Green     assert(ConstrainRegClass && "Expected a valid constrained register class!");
1490e995e344SDavid Green     (void)ConstrainRegClass;
1491e995e344SDavid Green   }
1492fef9f590SJames Molloy   BuildMI(*BB, BB->getFirstNonPHI(), DebugLoc(), TII->get(TargetOpcode::PHI), R)
1493a7938c74SKazu Hirata       .addReg(InitReg ? *InitReg : undef(RC))
1494fef9f590SJames Molloy       .addMBB(PreheaderBB)
1495fef9f590SJames Molloy       .addReg(LoopReg)
1496fef9f590SJames Molloy       .addMBB(BB);
1497a7938c74SKazu Hirata   if (!InitReg)
1498fef9f590SJames Molloy     UndefPhis[LoopReg] = R;
1499fef9f590SJames Molloy   else
1500fef9f590SJames Molloy     Phis[{LoopReg, *InitReg}] = R;
1501fef9f590SJames Molloy   return R;
1502fef9f590SJames Molloy }
1503fef9f590SJames Molloy 
undef(const TargetRegisterClass * RC)1504fef9f590SJames Molloy Register KernelRewriter::undef(const TargetRegisterClass *RC) {
1505fef9f590SJames Molloy   Register &R = Undefs[RC];
1506fef9f590SJames Molloy   if (R == 0) {
1507fef9f590SJames Molloy     // Create an IMPLICIT_DEF that defines this register if we need it.
1508fef9f590SJames Molloy     // All uses of this should be removed by the time we have finished unrolling
1509fef9f590SJames Molloy     // prologs and epilogs.
1510fef9f590SJames Molloy     R = MRI.createVirtualRegister(RC);
1511fef9f590SJames Molloy     auto *InsertBB = &PreheaderBB->getParent()->front();
1512fef9f590SJames Molloy     BuildMI(*InsertBB, InsertBB->getFirstTerminator(), DebugLoc(),
1513fef9f590SJames Molloy             TII->get(TargetOpcode::IMPLICIT_DEF), R);
1514fef9f590SJames Molloy   }
1515fef9f590SJames Molloy   return R;
1516fef9f590SJames Molloy }
1517fef9f590SJames Molloy 
1518fef9f590SJames Molloy namespace {
1519fef9f590SJames Molloy /// Describes an operand in the kernel of a pipelined loop. Characteristics of
1520fef9f590SJames Molloy /// the operand are discovered, such as how many in-loop PHIs it has to jump
1521fef9f590SJames Molloy /// through and defaults for these phis.
1522fef9f590SJames Molloy class KernelOperandInfo {
1523fef9f590SJames Molloy   MachineBasicBlock *BB;
1524fef9f590SJames Molloy   MachineRegisterInfo &MRI;
1525fef9f590SJames Molloy   SmallVector<Register, 4> PhiDefaults;
1526fef9f590SJames Molloy   MachineOperand *Source;
1527fef9f590SJames Molloy   MachineOperand *Target;
1528fef9f590SJames Molloy 
1529fef9f590SJames Molloy public:
KernelOperandInfo(MachineOperand * MO,MachineRegisterInfo & MRI,const SmallPtrSetImpl<MachineInstr * > & IllegalPhis)1530fef9f590SJames Molloy   KernelOperandInfo(MachineOperand *MO, MachineRegisterInfo &MRI,
1531fef9f590SJames Molloy                     const SmallPtrSetImpl<MachineInstr *> &IllegalPhis)
1532fef9f590SJames Molloy       : MRI(MRI) {
1533fef9f590SJames Molloy     Source = MO;
1534fef9f590SJames Molloy     BB = MO->getParent()->getParent();
1535fef9f590SJames Molloy     while (isRegInLoop(MO)) {
1536fef9f590SJames Molloy       MachineInstr *MI = MRI.getVRegDef(MO->getReg());
1537fef9f590SJames Molloy       if (MI->isFullCopy()) {
1538fef9f590SJames Molloy         MO = &MI->getOperand(1);
1539fef9f590SJames Molloy         continue;
1540fef9f590SJames Molloy       }
1541fef9f590SJames Molloy       if (!MI->isPHI())
1542fef9f590SJames Molloy         break;
1543fef9f590SJames Molloy       // If this is an illegal phi, don't count it in distance.
1544fef9f590SJames Molloy       if (IllegalPhis.count(MI)) {
1545fef9f590SJames Molloy         MO = &MI->getOperand(3);
1546fef9f590SJames Molloy         continue;
1547fef9f590SJames Molloy       }
1548fef9f590SJames Molloy 
1549fef9f590SJames Molloy       Register Default = getInitPhiReg(*MI, BB);
1550fef9f590SJames Molloy       MO = MI->getOperand(2).getMBB() == BB ? &MI->getOperand(1)
1551fef9f590SJames Molloy                                             : &MI->getOperand(3);
1552fef9f590SJames Molloy       PhiDefaults.push_back(Default);
1553fef9f590SJames Molloy     }
1554fef9f590SJames Molloy     Target = MO;
1555fef9f590SJames Molloy   }
1556fef9f590SJames Molloy 
operator ==(const KernelOperandInfo & Other) const1557fef9f590SJames Molloy   bool operator==(const KernelOperandInfo &Other) const {
1558fef9f590SJames Molloy     return PhiDefaults.size() == Other.PhiDefaults.size();
1559fef9f590SJames Molloy   }
1560fef9f590SJames Molloy 
print(raw_ostream & OS) const1561fef9f590SJames Molloy   void print(raw_ostream &OS) const {
1562fef9f590SJames Molloy     OS << "use of " << *Source << ": distance(" << PhiDefaults.size() << ") in "
1563fef9f590SJames Molloy        << *Source->getParent();
1564fef9f590SJames Molloy   }
1565fef9f590SJames Molloy 
1566fef9f590SJames Molloy private:
isRegInLoop(MachineOperand * MO)1567fef9f590SJames Molloy   bool isRegInLoop(MachineOperand *MO) {
1568fef9f590SJames Molloy     return MO->isReg() && MO->getReg().isVirtual() &&
1569fef9f590SJames Molloy            MRI.getVRegDef(MO->getReg())->getParent() == BB;
1570fef9f590SJames Molloy   }
1571fef9f590SJames Molloy };
1572fef9f590SJames Molloy } // namespace
1573fef9f590SJames Molloy 
15749026518eSJames Molloy MachineBasicBlock *
peelKernel(LoopPeelDirection LPD)15759026518eSJames Molloy PeelingModuloScheduleExpander::peelKernel(LoopPeelDirection LPD) {
15769026518eSJames Molloy   MachineBasicBlock *NewBB = PeelSingleBlockLoop(LPD, BB, MRI, TII);
15779026518eSJames Molloy   if (LPD == LPD_Front)
15789026518eSJames Molloy     PeeledFront.push_back(NewBB);
15799026518eSJames Molloy   else
15809026518eSJames Molloy     PeeledBack.push_front(NewBB);
15819026518eSJames Molloy   for (auto I = BB->begin(), NI = NewBB->begin(); !I->isTerminator();
15829026518eSJames Molloy        ++I, ++NI) {
15839026518eSJames Molloy     CanonicalMIs[&*I] = &*I;
15849026518eSJames Molloy     CanonicalMIs[&*NI] = &*I;
15859026518eSJames Molloy     BlockMIs[{NewBB, &*I}] = &*NI;
15869026518eSJames Molloy     BlockMIs[{BB, &*I}] = &*I;
15879026518eSJames Molloy   }
15889026518eSJames Molloy   return NewBB;
15899026518eSJames Molloy }
15909026518eSJames Molloy 
filterInstructions(MachineBasicBlock * MB,int MinStage)1591e0f1d9d8SThomas Raoux void PeelingModuloScheduleExpander::filterInstructions(MachineBasicBlock *MB,
1592e0f1d9d8SThomas Raoux                                                        int MinStage) {
1593e0f1d9d8SThomas Raoux   for (auto I = MB->getFirstInstrTerminator()->getReverseIterator();
1594e0f1d9d8SThomas Raoux        I != std::next(MB->getFirstNonPHI()->getReverseIterator());) {
1595e0f1d9d8SThomas Raoux     MachineInstr *MI = &*I++;
1596e0f1d9d8SThomas Raoux     int Stage = getStage(MI);
1597e0f1d9d8SThomas Raoux     if (Stage == -1 || Stage >= MinStage)
1598e0f1d9d8SThomas Raoux       continue;
1599e0f1d9d8SThomas Raoux 
1600e0f1d9d8SThomas Raoux     for (MachineOperand &DefMO : MI->defs()) {
1601e0f1d9d8SThomas Raoux       SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
1602e0f1d9d8SThomas Raoux       for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
1603e0f1d9d8SThomas Raoux         // Only PHIs can use values from this block by construction.
1604e0f1d9d8SThomas Raoux         // Match with the equivalent PHI in B.
1605e0f1d9d8SThomas Raoux         assert(UseMI.isPHI());
1606e0f1d9d8SThomas Raoux         Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
1607e0f1d9d8SThomas Raoux                                                MI->getParent());
1608e0f1d9d8SThomas Raoux         Subs.emplace_back(&UseMI, Reg);
1609e0f1d9d8SThomas Raoux       }
1610e0f1d9d8SThomas Raoux       for (auto &Sub : Subs)
1611e0f1d9d8SThomas Raoux         Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
1612e0f1d9d8SThomas Raoux                                       *MRI.getTargetRegisterInfo());
1613e0f1d9d8SThomas Raoux     }
1614e0f1d9d8SThomas Raoux     if (LIS)
1615e0f1d9d8SThomas Raoux       LIS->RemoveMachineInstrFromMaps(*MI);
1616e0f1d9d8SThomas Raoux     MI->eraseFromParent();
1617e0f1d9d8SThomas Raoux   }
1618e0f1d9d8SThomas Raoux }
1619e0f1d9d8SThomas Raoux 
moveStageBetweenBlocks(MachineBasicBlock * DestBB,MachineBasicBlock * SourceBB,unsigned Stage)1620e0f1d9d8SThomas Raoux void PeelingModuloScheduleExpander::moveStageBetweenBlocks(
1621e0f1d9d8SThomas Raoux     MachineBasicBlock *DestBB, MachineBasicBlock *SourceBB, unsigned Stage) {
1622e0f1d9d8SThomas Raoux   auto InsertPt = DestBB->getFirstNonPHI();
1623e0f1d9d8SThomas Raoux   DenseMap<Register, Register> Remaps;
16246bdb61c5SKazu Hirata   for (MachineInstr &MI : llvm::make_early_inc_range(
16256bdb61c5SKazu Hirata            llvm::make_range(SourceBB->getFirstNonPHI(), SourceBB->end()))) {
16266bdb61c5SKazu Hirata     if (MI.isPHI()) {
1627e0f1d9d8SThomas Raoux       // This is an illegal PHI. If we move any instructions using an illegal
1628d8f2814cSHendrik Greving       // PHI, we need to create a legal Phi.
16296bdb61c5SKazu Hirata       if (getStage(&MI) != Stage) {
1630d8f2814cSHendrik Greving         // The legal Phi is not necessary if the illegal phi's stage
1631d8f2814cSHendrik Greving         // is being moved.
16326bdb61c5SKazu Hirata         Register PhiR = MI.getOperand(0).getReg();
1633e0f1d9d8SThomas Raoux         auto RC = MRI.getRegClass(PhiR);
1634e0f1d9d8SThomas Raoux         Register NR = MRI.createVirtualRegister(RC);
1635d8f2814cSHendrik Greving         MachineInstr *NI = BuildMI(*DestBB, DestBB->getFirstNonPHI(),
1636d8f2814cSHendrik Greving                                    DebugLoc(), TII->get(TargetOpcode::PHI), NR)
1637e0f1d9d8SThomas Raoux                                .addReg(PhiR)
1638e0f1d9d8SThomas Raoux                                .addMBB(SourceBB);
16396bdb61c5SKazu Hirata         BlockMIs[{DestBB, CanonicalMIs[&MI]}] = NI;
16406bdb61c5SKazu Hirata         CanonicalMIs[NI] = CanonicalMIs[&MI];
1641e0f1d9d8SThomas Raoux         Remaps[PhiR] = NR;
1642d8f2814cSHendrik Greving       }
1643e0f1d9d8SThomas Raoux     }
16446bdb61c5SKazu Hirata     if (getStage(&MI) != Stage)
1645e0f1d9d8SThomas Raoux       continue;
16466bdb61c5SKazu Hirata     MI.removeFromParent();
16476bdb61c5SKazu Hirata     DestBB->insert(InsertPt, &MI);
16486bdb61c5SKazu Hirata     auto *KernelMI = CanonicalMIs[&MI];
16496bdb61c5SKazu Hirata     BlockMIs[{DestBB, KernelMI}] = &MI;
1650e0f1d9d8SThomas Raoux     BlockMIs.erase({SourceBB, KernelMI});
1651e0f1d9d8SThomas Raoux   }
1652e0f1d9d8SThomas Raoux   SmallVector<MachineInstr *, 4> PhiToDelete;
1653e0f1d9d8SThomas Raoux   for (MachineInstr &MI : DestBB->phis()) {
1654e0f1d9d8SThomas Raoux     assert(MI.getNumOperands() == 3);
1655e0f1d9d8SThomas Raoux     MachineInstr *Def = MRI.getVRegDef(MI.getOperand(1).getReg());
1656e0f1d9d8SThomas Raoux     // If the instruction referenced by the phi is moved inside the block
1657e0f1d9d8SThomas Raoux     // we don't need the phi anymore.
1658e0f1d9d8SThomas Raoux     if (getStage(Def) == Stage) {
1659e0f1d9d8SThomas Raoux       Register PhiReg = MI.getOperand(0).getReg();
166020c0527aSThomas Raoux       assert(Def->findRegisterDefOperandIdx(MI.getOperand(1).getReg()) != -1);
166120c0527aSThomas Raoux       MRI.replaceRegWith(MI.getOperand(0).getReg(), MI.getOperand(1).getReg());
1662e0f1d9d8SThomas Raoux       MI.getOperand(0).setReg(PhiReg);
1663e0f1d9d8SThomas Raoux       PhiToDelete.push_back(&MI);
1664e0f1d9d8SThomas Raoux     }
1665e0f1d9d8SThomas Raoux   }
1666e0f1d9d8SThomas Raoux   for (auto *P : PhiToDelete)
1667e0f1d9d8SThomas Raoux     P->eraseFromParent();
1668e0f1d9d8SThomas Raoux   InsertPt = DestBB->getFirstNonPHI();
1669e0297a8bSThomas Raoux   // Helper to clone Phi instructions into the destination block. We clone Phi
1670e0297a8bSThomas Raoux   // greedily to avoid combinatorial explosion of Phi instructions.
1671e0297a8bSThomas Raoux   auto clonePhi = [&](MachineInstr *Phi) {
1672e0297a8bSThomas Raoux     MachineInstr *NewMI = MF.CloneMachineInstr(Phi);
1673e0f1d9d8SThomas Raoux     DestBB->insert(InsertPt, NewMI);
1674e0297a8bSThomas Raoux     Register OrigR = Phi->getOperand(0).getReg();
1675e0f1d9d8SThomas Raoux     Register R = MRI.createVirtualRegister(MRI.getRegClass(OrigR));
1676e0f1d9d8SThomas Raoux     NewMI->getOperand(0).setReg(R);
1677e0f1d9d8SThomas Raoux     NewMI->getOperand(1).setReg(OrigR);
1678e0f1d9d8SThomas Raoux     NewMI->getOperand(2).setMBB(*DestBB->pred_begin());
1679e0f1d9d8SThomas Raoux     Remaps[OrigR] = R;
1680e0297a8bSThomas Raoux     CanonicalMIs[NewMI] = CanonicalMIs[Phi];
1681e0297a8bSThomas Raoux     BlockMIs[{DestBB, CanonicalMIs[Phi]}] = NewMI;
1682e0297a8bSThomas Raoux     PhiNodeLoopIteration[NewMI] = PhiNodeLoopIteration[Phi];
1683e0297a8bSThomas Raoux     return R;
1684e0297a8bSThomas Raoux   };
1685e0297a8bSThomas Raoux   for (auto I = DestBB->getFirstNonPHI(); I != DestBB->end(); ++I) {
1686e0297a8bSThomas Raoux     for (MachineOperand &MO : I->uses()) {
1687e0297a8bSThomas Raoux       if (!MO.isReg())
1688e0297a8bSThomas Raoux         continue;
1689e0297a8bSThomas Raoux       if (Remaps.count(MO.getReg()))
1690e0f1d9d8SThomas Raoux         MO.setReg(Remaps[MO.getReg()]);
1691e0297a8bSThomas Raoux       else {
1692e0297a8bSThomas Raoux         // If we are using a phi from the source block we need to add a new phi
1693e0297a8bSThomas Raoux         // pointing to the old one.
1694e0297a8bSThomas Raoux         MachineInstr *Use = MRI.getUniqueVRegDef(MO.getReg());
1695e0297a8bSThomas Raoux         if (Use && Use->isPHI() && Use->getParent() == SourceBB) {
1696e0297a8bSThomas Raoux           Register R = clonePhi(Use);
1697e0297a8bSThomas Raoux           MO.setReg(R);
1698e0297a8bSThomas Raoux         }
1699e0297a8bSThomas Raoux       }
1700e0297a8bSThomas Raoux     }
1701e0297a8bSThomas Raoux   }
1702e0297a8bSThomas Raoux }
1703e0297a8bSThomas Raoux 
1704e0297a8bSThomas Raoux Register
getPhiCanonicalReg(MachineInstr * CanonicalPhi,MachineInstr * Phi)1705e0297a8bSThomas Raoux PeelingModuloScheduleExpander::getPhiCanonicalReg(MachineInstr *CanonicalPhi,
1706e0297a8bSThomas Raoux                                                   MachineInstr *Phi) {
1707e0297a8bSThomas Raoux   unsigned distance = PhiNodeLoopIteration[Phi];
1708e0297a8bSThomas Raoux   MachineInstr *CanonicalUse = CanonicalPhi;
1709f3d8a939SHendrik Greving   Register CanonicalUseReg = CanonicalUse->getOperand(0).getReg();
1710e0297a8bSThomas Raoux   for (unsigned I = 0; I < distance; ++I) {
1711e0297a8bSThomas Raoux     assert(CanonicalUse->isPHI());
1712e0297a8bSThomas Raoux     assert(CanonicalUse->getNumOperands() == 5);
1713e0297a8bSThomas Raoux     unsigned LoopRegIdx = 3, InitRegIdx = 1;
1714e0297a8bSThomas Raoux     if (CanonicalUse->getOperand(2).getMBB() == CanonicalUse->getParent())
1715e0297a8bSThomas Raoux       std::swap(LoopRegIdx, InitRegIdx);
1716f3d8a939SHendrik Greving     CanonicalUseReg = CanonicalUse->getOperand(LoopRegIdx).getReg();
1717f3d8a939SHendrik Greving     CanonicalUse = MRI.getVRegDef(CanonicalUseReg);
1718e0297a8bSThomas Raoux   }
1719f3d8a939SHendrik Greving   return CanonicalUseReg;
1720e0f1d9d8SThomas Raoux }
1721e0f1d9d8SThomas Raoux 
peelPrologAndEpilogs()17229026518eSJames Molloy void PeelingModuloScheduleExpander::peelPrologAndEpilogs() {
17239026518eSJames Molloy   BitVector LS(Schedule.getNumStages(), true);
17249026518eSJames Molloy   BitVector AS(Schedule.getNumStages(), true);
17259026518eSJames Molloy   LiveStages[BB] = LS;
17269026518eSJames Molloy   AvailableStages[BB] = AS;
17279026518eSJames Molloy 
17289026518eSJames Molloy   // Peel out the prologs.
17299026518eSJames Molloy   LS.reset();
17309026518eSJames Molloy   for (int I = 0; I < Schedule.getNumStages() - 1; ++I) {
17312aed0813SKazu Hirata     LS[I] = true;
17329026518eSJames Molloy     Prologs.push_back(peelKernel(LPD_Front));
17339026518eSJames Molloy     LiveStages[Prologs.back()] = LS;
17349026518eSJames Molloy     AvailableStages[Prologs.back()] = LS;
17359026518eSJames Molloy   }
17369026518eSJames Molloy 
17379026518eSJames Molloy   // Create a block that will end up as the new loop exiting block (dominated by
17389026518eSJames Molloy   // all prologs and epilogs). It will only contain PHIs, in the same order as
17399026518eSJames Molloy   // BB's PHIs. This gives us a poor-man's LCSSA with the inductive property
17409026518eSJames Molloy   // that the exiting block is a (sub) clone of BB. This in turn gives us the
17419026518eSJames Molloy   // property that any value deffed in BB but used outside of BB is used by a
17429026518eSJames Molloy   // PHI in the exiting block.
17439026518eSJames Molloy   MachineBasicBlock *ExitingBB = CreateLCSSAExitingBlock();
1744e0297a8bSThomas Raoux   EliminateDeadPhis(ExitingBB, MRI, LIS, /*KeepSingleSrcPhi=*/true);
17459026518eSJames Molloy   // Push out the epilogs, again in reverse order.
17469026518eSJames Molloy   // We can't assume anything about the minumum loop trip count at this point,
1747e0f1d9d8SThomas Raoux   // so emit a fairly complex epilog.
1748e0f1d9d8SThomas Raoux 
1749e0f1d9d8SThomas Raoux   // We first peel number of stages minus one epilogue. Then we remove dead
1750e0f1d9d8SThomas Raoux   // stages and reorder instructions based on their stage. If we have 3 stages
1751e0f1d9d8SThomas Raoux   // we generate first:
1752e0f1d9d8SThomas Raoux   // E0[3, 2, 1]
1753e0f1d9d8SThomas Raoux   // E1[3', 2']
1754e0f1d9d8SThomas Raoux   // E2[3'']
1755e0f1d9d8SThomas Raoux   // And then we move instructions based on their stages to have:
1756e0f1d9d8SThomas Raoux   // E0[3]
1757e0f1d9d8SThomas Raoux   // E1[2, 3']
1758e0f1d9d8SThomas Raoux   // E2[1, 2', 3'']
1759e0f1d9d8SThomas Raoux   // The transformation is legal because we only move instructions past
1760e0f1d9d8SThomas Raoux   // instructions of a previous loop iteration.
17619026518eSJames Molloy   for (int I = 1; I <= Schedule.getNumStages() - 1; ++I) {
1762e0f1d9d8SThomas Raoux     Epilogs.push_back(peelKernel(LPD_Back));
1763e0297a8bSThomas Raoux     MachineBasicBlock *B = Epilogs.back();
1764e0297a8bSThomas Raoux     filterInstructions(B, Schedule.getNumStages() - I);
1765e0297a8bSThomas Raoux     // Keep track at which iteration each phi belongs to. We need it to know
1766e0297a8bSThomas Raoux     // what version of the variable to use during prologue/epilogue stitching.
1767e0297a8bSThomas Raoux     EliminateDeadPhis(B, MRI, LIS, /*KeepSingleSrcPhi=*/true);
1768c3e698e2SKazu Hirata     for (MachineInstr &Phi : B->phis())
1769c3e698e2SKazu Hirata       PhiNodeLoopIteration[&Phi] = Schedule.getNumStages() - I;
17709026518eSJames Molloy   }
1771e0f1d9d8SThomas Raoux   for (size_t I = 0; I < Epilogs.size(); I++) {
1772e0f1d9d8SThomas Raoux     LS.reset();
1773e0f1d9d8SThomas Raoux     for (size_t J = I; J < Epilogs.size(); J++) {
1774e0f1d9d8SThomas Raoux       int Iteration = J;
1775e0f1d9d8SThomas Raoux       unsigned Stage = Schedule.getNumStages() - 1 + I - J;
1776e0f1d9d8SThomas Raoux       // Move stage one block at a time so that Phi nodes are updated correctly.
1777e0f1d9d8SThomas Raoux       for (size_t K = Iteration; K > I; K--)
1778e0f1d9d8SThomas Raoux         moveStageBetweenBlocks(Epilogs[K - 1], Epilogs[K], Stage);
17792aed0813SKazu Hirata       LS[Stage] = true;
1780e0f1d9d8SThomas Raoux     }
1781e0f1d9d8SThomas Raoux     LiveStages[Epilogs[I]] = LS;
1782e0f1d9d8SThomas Raoux     AvailableStages[Epilogs[I]] = AS;
17839026518eSJames Molloy   }
17849026518eSJames Molloy 
17859026518eSJames Molloy   // Now we've defined all the prolog and epilog blocks as a fallthrough
17869026518eSJames Molloy   // sequence, add the edges that will be followed if the loop trip count is
17879026518eSJames Molloy   // lower than the number of stages (connecting prologs directly with epilogs).
17889026518eSJames Molloy   auto PI = Prologs.begin();
17899026518eSJames Molloy   auto EI = Epilogs.begin();
17909026518eSJames Molloy   assert(Prologs.size() == Epilogs.size());
17919026518eSJames Molloy   for (; PI != Prologs.end(); ++PI, ++EI) {
17929026518eSJames Molloy     MachineBasicBlock *Pred = *(*EI)->pred_begin();
17939026518eSJames Molloy     (*PI)->addSuccessor(*EI);
17949026518eSJames Molloy     for (MachineInstr &MI : (*EI)->phis()) {
17959026518eSJames Molloy       Register Reg = MI.getOperand(1).getReg();
17969026518eSJames Molloy       MachineInstr *Use = MRI.getUniqueVRegDef(Reg);
1797e0297a8bSThomas Raoux       if (Use && Use->getParent() == Pred) {
1798e0297a8bSThomas Raoux         MachineInstr *CanonicalUse = CanonicalMIs[Use];
1799e0297a8bSThomas Raoux         if (CanonicalUse->isPHI()) {
1800e0297a8bSThomas Raoux           // If the use comes from a phi we need to skip as many phi as the
1801e0297a8bSThomas Raoux           // distance between the epilogue and the kernel. Trace through the phi
1802e0297a8bSThomas Raoux           // chain to find the right value.
1803e0297a8bSThomas Raoux           Reg = getPhiCanonicalReg(CanonicalUse, Use);
1804e0297a8bSThomas Raoux         }
18059026518eSJames Molloy         Reg = getEquivalentRegisterIn(Reg, *PI);
1806e0297a8bSThomas Raoux       }
18079026518eSJames Molloy       MI.addOperand(MachineOperand::CreateReg(Reg, /*isDef=*/false));
18089026518eSJames Molloy       MI.addOperand(MachineOperand::CreateMBB(*PI));
18099026518eSJames Molloy     }
18109026518eSJames Molloy   }
18119026518eSJames Molloy 
18129026518eSJames Molloy   // Create a list of all blocks in order.
18139026518eSJames Molloy   SmallVector<MachineBasicBlock *, 8> Blocks;
18149026518eSJames Molloy   llvm::copy(PeeledFront, std::back_inserter(Blocks));
18159026518eSJames Molloy   Blocks.push_back(BB);
18169026518eSJames Molloy   llvm::copy(PeeledBack, std::back_inserter(Blocks));
18179026518eSJames Molloy 
18189026518eSJames Molloy   // Iterate in reverse order over all instructions, remapping as we go.
18199026518eSJames Molloy   for (MachineBasicBlock *B : reverse(Blocks)) {
1820a43d2573SHendrik Greving     for (auto I = B->instr_rbegin();
18219026518eSJames Molloy          I != std::next(B->getFirstNonPHI()->getReverseIterator());) {
1822a43d2573SHendrik Greving       MachineBasicBlock::reverse_instr_iterator MI = I++;
1823a43d2573SHendrik Greving       rewriteUsesOf(&*MI);
18249026518eSJames Molloy     }
18259026518eSJames Molloy   }
1826e0f1d9d8SThomas Raoux   for (auto *MI : IllegalPhisToDelete) {
1827e0f1d9d8SThomas Raoux     if (LIS)
1828e0f1d9d8SThomas Raoux       LIS->RemoveMachineInstrFromMaps(*MI);
1829e0f1d9d8SThomas Raoux     MI->eraseFromParent();
1830e0f1d9d8SThomas Raoux   }
1831e0f1d9d8SThomas Raoux   IllegalPhisToDelete.clear();
1832e0f1d9d8SThomas Raoux 
18339026518eSJames Molloy   // Now all remapping has been done, we're free to optimize the generated code.
18349026518eSJames Molloy   for (MachineBasicBlock *B : reverse(Blocks))
18359026518eSJames Molloy     EliminateDeadPhis(B, MRI, LIS);
18369026518eSJames Molloy   EliminateDeadPhis(ExitingBB, MRI, LIS);
18379026518eSJames Molloy }
18389026518eSJames Molloy 
CreateLCSSAExitingBlock()18399026518eSJames Molloy MachineBasicBlock *PeelingModuloScheduleExpander::CreateLCSSAExitingBlock() {
18409026518eSJames Molloy   MachineFunction &MF = *BB->getParent();
18419026518eSJames Molloy   MachineBasicBlock *Exit = *BB->succ_begin();
18429026518eSJames Molloy   if (Exit == BB)
18439026518eSJames Molloy     Exit = *std::next(BB->succ_begin());
18449026518eSJames Molloy 
18459026518eSJames Molloy   MachineBasicBlock *NewBB = MF.CreateMachineBasicBlock(BB->getBasicBlock());
18469026518eSJames Molloy   MF.insert(std::next(BB->getIterator()), NewBB);
18479026518eSJames Molloy 
18489026518eSJames Molloy   // Clone all phis in BB into NewBB and rewrite.
18499026518eSJames Molloy   for (MachineInstr &MI : BB->phis()) {
18509026518eSJames Molloy     auto RC = MRI.getRegClass(MI.getOperand(0).getReg());
18519026518eSJames Molloy     Register OldR = MI.getOperand(3).getReg();
18529026518eSJames Molloy     Register R = MRI.createVirtualRegister(RC);
18539026518eSJames Molloy     SmallVector<MachineInstr *, 4> Uses;
18549026518eSJames Molloy     for (MachineInstr &Use : MRI.use_instructions(OldR))
18559026518eSJames Molloy       if (Use.getParent() != BB)
18569026518eSJames Molloy         Uses.push_back(&Use);
18579026518eSJames Molloy     for (MachineInstr *Use : Uses)
18589026518eSJames Molloy       Use->substituteRegister(OldR, R, /*SubIdx=*/0,
18599026518eSJames Molloy                               *MRI.getTargetRegisterInfo());
18609026518eSJames Molloy     MachineInstr *NI = BuildMI(NewBB, DebugLoc(), TII->get(TargetOpcode::PHI), R)
18619026518eSJames Molloy         .addReg(OldR)
18629026518eSJames Molloy         .addMBB(BB);
18639026518eSJames Molloy     BlockMIs[{NewBB, &MI}] = NI;
18649026518eSJames Molloy     CanonicalMIs[NI] = &MI;
18659026518eSJames Molloy   }
18669026518eSJames Molloy   BB->replaceSuccessor(Exit, NewBB);
18679026518eSJames Molloy   Exit->replacePhiUsesWith(BB, NewBB);
18689026518eSJames Molloy   NewBB->addSuccessor(Exit);
18699026518eSJames Molloy 
18709026518eSJames Molloy   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
18719026518eSJames Molloy   SmallVector<MachineOperand, 4> Cond;
18729026518eSJames Molloy   bool CanAnalyzeBr = !TII->analyzeBranch(*BB, TBB, FBB, Cond);
18739026518eSJames Molloy   (void)CanAnalyzeBr;
18749026518eSJames Molloy   assert(CanAnalyzeBr && "Must be able to analyze the loop branch!");
18759026518eSJames Molloy   TII->removeBranch(*BB);
18769026518eSJames Molloy   TII->insertBranch(*BB, TBB == Exit ? NewBB : TBB, FBB == Exit ? NewBB : FBB,
18779026518eSJames Molloy                     Cond, DebugLoc());
18789026518eSJames Molloy   TII->insertUnconditionalBranch(*NewBB, Exit, DebugLoc());
18799026518eSJames Molloy   return NewBB;
18809026518eSJames Molloy }
18819026518eSJames Molloy 
18829026518eSJames Molloy Register
getEquivalentRegisterIn(Register Reg,MachineBasicBlock * BB)18839026518eSJames Molloy PeelingModuloScheduleExpander::getEquivalentRegisterIn(Register Reg,
18849026518eSJames Molloy                                                        MachineBasicBlock *BB) {
18859026518eSJames Molloy   MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
18869026518eSJames Molloy   unsigned OpIdx = MI->findRegisterDefOperandIdx(Reg);
18879026518eSJames Molloy   return BlockMIs[{BB, CanonicalMIs[MI]}]->getOperand(OpIdx).getReg();
18889026518eSJames Molloy }
18899026518eSJames Molloy 
rewriteUsesOf(MachineInstr * MI)18909026518eSJames Molloy void PeelingModuloScheduleExpander::rewriteUsesOf(MachineInstr *MI) {
18919026518eSJames Molloy   if (MI->isPHI()) {
18929026518eSJames Molloy     // This is an illegal PHI. The loop-carried (desired) value is operand 3,
18939026518eSJames Molloy     // and it is produced by this block.
18949026518eSJames Molloy     Register PhiR = MI->getOperand(0).getReg();
18959026518eSJames Molloy     Register R = MI->getOperand(3).getReg();
18969026518eSJames Molloy     int RMIStage = getStage(MRI.getUniqueVRegDef(R));
18979026518eSJames Molloy     if (RMIStage != -1 && !AvailableStages[MI->getParent()].test(RMIStage))
18989026518eSJames Molloy       R = MI->getOperand(1).getReg();
18999026518eSJames Molloy     MRI.setRegClass(R, MRI.getRegClass(PhiR));
19009026518eSJames Molloy     MRI.replaceRegWith(PhiR, R);
1901e0f1d9d8SThomas Raoux     // Postpone deleting the Phi as it may be referenced by BlockMIs and used
1902e0f1d9d8SThomas Raoux     // later to figure out how to remap registers.
1903e0f1d9d8SThomas Raoux     MI->getOperand(0).setReg(PhiR);
1904e0f1d9d8SThomas Raoux     IllegalPhisToDelete.push_back(MI);
19059026518eSJames Molloy     return;
19069026518eSJames Molloy   }
19079026518eSJames Molloy 
19089026518eSJames Molloy   int Stage = getStage(MI);
19099026518eSJames Molloy   if (Stage == -1 || LiveStages.count(MI->getParent()) == 0 ||
19109026518eSJames Molloy       LiveStages[MI->getParent()].test(Stage))
19119026518eSJames Molloy     // Instruction is live, no rewriting to do.
19129026518eSJames Molloy     return;
19139026518eSJames Molloy 
19149026518eSJames Molloy   for (MachineOperand &DefMO : MI->defs()) {
19159026518eSJames Molloy     SmallVector<std::pair<MachineInstr *, Register>, 4> Subs;
19169026518eSJames Molloy     for (MachineInstr &UseMI : MRI.use_instructions(DefMO.getReg())) {
19179026518eSJames Molloy       // Only PHIs can use values from this block by construction.
19189026518eSJames Molloy       // Match with the equivalent PHI in B.
19199026518eSJames Molloy       assert(UseMI.isPHI());
19209026518eSJames Molloy       Register Reg = getEquivalentRegisterIn(UseMI.getOperand(0).getReg(),
19219026518eSJames Molloy                                              MI->getParent());
19229026518eSJames Molloy       Subs.emplace_back(&UseMI, Reg);
19239026518eSJames Molloy     }
19249026518eSJames Molloy     for (auto &Sub : Subs)
19259026518eSJames Molloy       Sub.first->substituteRegister(DefMO.getReg(), Sub.second, /*SubIdx=*/0,
19269026518eSJames Molloy                                     *MRI.getTargetRegisterInfo());
19279026518eSJames Molloy   }
19289026518eSJames Molloy   if (LIS)
19299026518eSJames Molloy     LIS->RemoveMachineInstrFromMaps(*MI);
19309026518eSJames Molloy   MI->eraseFromParent();
19319026518eSJames Molloy }
19329026518eSJames Molloy 
fixupBranches()19339026518eSJames Molloy void PeelingModuloScheduleExpander::fixupBranches() {
19349026518eSJames Molloy   // Work outwards from the kernel.
19359026518eSJames Molloy   bool KernelDisposed = false;
19369026518eSJames Molloy   int TC = Schedule.getNumStages() - 1;
19379026518eSJames Molloy   for (auto PI = Prologs.rbegin(), EI = Epilogs.rbegin(); PI != Prologs.rend();
19389026518eSJames Molloy        ++PI, ++EI, --TC) {
19399026518eSJames Molloy     MachineBasicBlock *Prolog = *PI;
19409026518eSJames Molloy     MachineBasicBlock *Fallthrough = *Prolog->succ_begin();
19419026518eSJames Molloy     MachineBasicBlock *Epilog = *EI;
19429026518eSJames Molloy     SmallVector<MachineOperand, 4> Cond;
19439972c992SJames Molloy     TII->removeBranch(*Prolog);
19449026518eSJames Molloy     Optional<bool> StaticallyGreater =
194550ac7ce9SHendrik Greving         LoopInfo->createTripCountGreaterCondition(TC, *Prolog, Cond);
1946e0e687a6SKazu Hirata     if (!StaticallyGreater) {
19479026518eSJames Molloy       LLVM_DEBUG(dbgs() << "Dynamic: TC > " << TC << "\n");
19489026518eSJames Molloy       // Dynamically branch based on Cond.
19499026518eSJames Molloy       TII->insertBranch(*Prolog, Epilog, Fallthrough, Cond, DebugLoc());
19509026518eSJames Molloy     } else if (*StaticallyGreater == false) {
19519026518eSJames Molloy       LLVM_DEBUG(dbgs() << "Static-false: TC > " << TC << "\n");
19529026518eSJames Molloy       // Prolog never falls through; branch to epilog and orphan interior
19539026518eSJames Molloy       // blocks. Leave it to unreachable-block-elim to clean up.
19549026518eSJames Molloy       Prolog->removeSuccessor(Fallthrough);
19559026518eSJames Molloy       for (MachineInstr &P : Fallthrough->phis()) {
195637b37838SShengchen Kan         P.removeOperand(2);
195737b37838SShengchen Kan         P.removeOperand(1);
19589026518eSJames Molloy       }
19599026518eSJames Molloy       TII->insertUnconditionalBranch(*Prolog, Epilog, DebugLoc());
19609026518eSJames Molloy       KernelDisposed = true;
19619026518eSJames Molloy     } else {
19629026518eSJames Molloy       LLVM_DEBUG(dbgs() << "Static-true: TC > " << TC << "\n");
19639026518eSJames Molloy       // Prolog always falls through; remove incoming values in epilog.
19649026518eSJames Molloy       Prolog->removeSuccessor(Epilog);
19659026518eSJames Molloy       for (MachineInstr &P : Epilog->phis()) {
196637b37838SShengchen Kan         P.removeOperand(4);
196737b37838SShengchen Kan         P.removeOperand(3);
19689026518eSJames Molloy       }
19699026518eSJames Molloy     }
19709026518eSJames Molloy   }
19719026518eSJames Molloy 
19729026518eSJames Molloy   if (!KernelDisposed) {
197350ac7ce9SHendrik Greving     LoopInfo->adjustTripCount(-(Schedule.getNumStages() - 1));
197450ac7ce9SHendrik Greving     LoopInfo->setPreheader(Prologs.back());
19759026518eSJames Molloy   } else {
197650ac7ce9SHendrik Greving     LoopInfo->disposed();
19779026518eSJames Molloy   }
19789026518eSJames Molloy }
19799026518eSJames Molloy 
rewriteKernel()19809026518eSJames Molloy void PeelingModuloScheduleExpander::rewriteKernel() {
1981e15e1417SHendrik Greving   KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
19829026518eSJames Molloy   KR.rewrite();
19839026518eSJames Molloy }
19849026518eSJames Molloy 
expand()19859026518eSJames Molloy void PeelingModuloScheduleExpander::expand() {
19869026518eSJames Molloy   BB = Schedule.getLoop()->getTopBlock();
19879026518eSJames Molloy   Preheader = Schedule.getLoop()->getLoopPreheader();
19889026518eSJames Molloy   LLVM_DEBUG(Schedule.dump());
198950ac7ce9SHendrik Greving   LoopInfo = TII->analyzeLoopForPipelining(BB);
199050ac7ce9SHendrik Greving   assert(LoopInfo);
19919026518eSJames Molloy 
19929026518eSJames Molloy   rewriteKernel();
19939026518eSJames Molloy   peelPrologAndEpilogs();
19949026518eSJames Molloy   fixupBranches();
19959026518eSJames Molloy }
19969026518eSJames Molloy 
validateAgainstModuloScheduleExpander()1997fef9f590SJames Molloy void PeelingModuloScheduleExpander::validateAgainstModuloScheduleExpander() {
1998fef9f590SJames Molloy   BB = Schedule.getLoop()->getTopBlock();
1999fef9f590SJames Molloy   Preheader = Schedule.getLoop()->getLoopPreheader();
2000fef9f590SJames Molloy 
2001fef9f590SJames Molloy   // Dump the schedule before we invalidate and remap all its instructions.
2002fef9f590SJames Molloy   // Stash it in a string so we can print it if we found an error.
2003fef9f590SJames Molloy   std::string ScheduleDump;
2004fef9f590SJames Molloy   raw_string_ostream OS(ScheduleDump);
2005fef9f590SJames Molloy   Schedule.print(OS);
2006fef9f590SJames Molloy   OS.flush();
2007fef9f590SJames Molloy 
2008fef9f590SJames Molloy   // First, run the normal ModuleScheduleExpander. We don't support any
2009fef9f590SJames Molloy   // InstrChanges.
2010fef9f590SJames Molloy   assert(LIS && "Requires LiveIntervals!");
2011fef9f590SJames Molloy   ModuloScheduleExpander MSE(MF, Schedule, *LIS,
2012fef9f590SJames Molloy                              ModuloScheduleExpander::InstrChangesTy());
2013fef9f590SJames Molloy   MSE.expand();
2014fef9f590SJames Molloy   MachineBasicBlock *ExpandedKernel = MSE.getRewrittenKernel();
2015fef9f590SJames Molloy   if (!ExpandedKernel) {
2016fef9f590SJames Molloy     // The expander optimized away the kernel. We can't do any useful checking.
2017fef9f590SJames Molloy     MSE.cleanup();
2018fef9f590SJames Molloy     return;
2019fef9f590SJames Molloy   }
2020fef9f590SJames Molloy   // Before running the KernelRewriter, re-add BB into the CFG.
2021fef9f590SJames Molloy   Preheader->addSuccessor(BB);
2022fef9f590SJames Molloy 
2023fef9f590SJames Molloy   // Now run the new expansion algorithm.
2024e15e1417SHendrik Greving   KernelRewriter KR(*Schedule.getLoop(), Schedule, BB);
2025fef9f590SJames Molloy   KR.rewrite();
20269026518eSJames Molloy   peelPrologAndEpilogs();
2027fef9f590SJames Molloy 
2028fef9f590SJames Molloy   // Collect all illegal phis that the new algorithm created. We'll give these
2029fef9f590SJames Molloy   // to KernelOperandInfo.
2030fef9f590SJames Molloy   SmallPtrSet<MachineInstr *, 4> IllegalPhis;
2031fef9f590SJames Molloy   for (auto NI = BB->getFirstNonPHI(); NI != BB->end(); ++NI) {
2032fef9f590SJames Molloy     if (NI->isPHI())
2033fef9f590SJames Molloy       IllegalPhis.insert(&*NI);
2034fef9f590SJames Molloy   }
2035fef9f590SJames Molloy 
2036fef9f590SJames Molloy   // Co-iterate across both kernels. We expect them to be identical apart from
2037fef9f590SJames Molloy   // phis and full COPYs (we look through both).
2038fef9f590SJames Molloy   SmallVector<std::pair<KernelOperandInfo, KernelOperandInfo>, 8> KOIs;
2039fef9f590SJames Molloy   auto OI = ExpandedKernel->begin();
2040fef9f590SJames Molloy   auto NI = BB->begin();
2041fef9f590SJames Molloy   for (; !OI->isTerminator() && !NI->isTerminator(); ++OI, ++NI) {
2042fef9f590SJames Molloy     while (OI->isPHI() || OI->isFullCopy())
2043fef9f590SJames Molloy       ++OI;
2044fef9f590SJames Molloy     while (NI->isPHI() || NI->isFullCopy())
2045fef9f590SJames Molloy       ++NI;
2046fef9f590SJames Molloy     assert(OI->getOpcode() == NI->getOpcode() && "Opcodes don't match?!");
2047fef9f590SJames Molloy     // Analyze every operand separately.
2048fef9f590SJames Molloy     for (auto OOpI = OI->operands_begin(), NOpI = NI->operands_begin();
2049fef9f590SJames Molloy          OOpI != OI->operands_end(); ++OOpI, ++NOpI)
2050fef9f590SJames Molloy       KOIs.emplace_back(KernelOperandInfo(&*OOpI, MRI, IllegalPhis),
2051fef9f590SJames Molloy                         KernelOperandInfo(&*NOpI, MRI, IllegalPhis));
2052fef9f590SJames Molloy   }
2053fef9f590SJames Molloy 
2054fef9f590SJames Molloy   bool Failed = false;
2055fef9f590SJames Molloy   for (auto &OldAndNew : KOIs) {
2056fef9f590SJames Molloy     if (OldAndNew.first == OldAndNew.second)
2057fef9f590SJames Molloy       continue;
2058fef9f590SJames Molloy     Failed = true;
2059fef9f590SJames Molloy     errs() << "Modulo kernel validation error: [\n";
2060fef9f590SJames Molloy     errs() << " [golden] ";
2061fef9f590SJames Molloy     OldAndNew.first.print(errs());
2062fef9f590SJames Molloy     errs() << "          ";
2063fef9f590SJames Molloy     OldAndNew.second.print(errs());
2064fef9f590SJames Molloy     errs() << "]\n";
2065fef9f590SJames Molloy   }
2066fef9f590SJames Molloy 
2067fef9f590SJames Molloy   if (Failed) {
2068fef9f590SJames Molloy     errs() << "Golden reference kernel:\n";
206911f0f7f5SJames Molloy     ExpandedKernel->print(errs());
2070fef9f590SJames Molloy     errs() << "New kernel:\n";
207111f0f7f5SJames Molloy     BB->print(errs());
2072fef9f590SJames Molloy     errs() << ScheduleDump;
2073fef9f590SJames Molloy     report_fatal_error(
2074fef9f590SJames Molloy         "Modulo kernel validation (-pipeliner-experimental-cg) failed");
2075fef9f590SJames Molloy   }
2076fef9f590SJames Molloy 
2077fef9f590SJames Molloy   // Cleanup by removing BB from the CFG again as the original
2078fef9f590SJames Molloy   // ModuloScheduleExpander intended.
2079fef9f590SJames Molloy   Preheader->removeSuccessor(BB);
2080fef9f590SJames Molloy   MSE.cleanup();
2081fef9f590SJames Molloy }
2082fef9f590SJames Molloy 
2083fef9f590SJames Molloy //===----------------------------------------------------------------------===//
208493549957SJames Molloy // ModuloScheduleTestPass implementation
208593549957SJames Molloy //===----------------------------------------------------------------------===//
208693549957SJames Molloy // This pass constructs a ModuloSchedule from its module and runs
208793549957SJames Molloy // ModuloScheduleExpander.
208893549957SJames Molloy //
208993549957SJames Molloy // The module is expected to contain a single-block analyzable loop.
209093549957SJames Molloy // The total order of instructions is taken from the loop as-is.
209193549957SJames Molloy // Instructions are expected to be annotated with a PostInstrSymbol.
209293549957SJames Molloy // This PostInstrSymbol must have the following format:
209393549957SJames Molloy //  "Stage=%d Cycle=%d".
209493549957SJames Molloy //===----------------------------------------------------------------------===//
209593549957SJames Molloy 
2096df4b9a3fSBenjamin Kramer namespace {
209793549957SJames Molloy class ModuloScheduleTest : public MachineFunctionPass {
209893549957SJames Molloy public:
209993549957SJames Molloy   static char ID;
210093549957SJames Molloy 
ModuloScheduleTest()210193549957SJames Molloy   ModuloScheduleTest() : MachineFunctionPass(ID) {
210293549957SJames Molloy     initializeModuloScheduleTestPass(*PassRegistry::getPassRegistry());
210393549957SJames Molloy   }
210493549957SJames Molloy 
210593549957SJames Molloy   bool runOnMachineFunction(MachineFunction &MF) override;
210693549957SJames Molloy   void runOnLoop(MachineFunction &MF, MachineLoop &L);
210793549957SJames Molloy 
getAnalysisUsage(AnalysisUsage & AU) const210893549957SJames Molloy   void getAnalysisUsage(AnalysisUsage &AU) const override {
210993549957SJames Molloy     AU.addRequired<MachineLoopInfo>();
211093549957SJames Molloy     AU.addRequired<LiveIntervals>();
211193549957SJames Molloy     MachineFunctionPass::getAnalysisUsage(AU);
211293549957SJames Molloy   }
211393549957SJames Molloy };
2114df4b9a3fSBenjamin Kramer } // namespace
211593549957SJames Molloy 
211693549957SJames Molloy char ModuloScheduleTest::ID = 0;
211793549957SJames Molloy 
211893549957SJames Molloy INITIALIZE_PASS_BEGIN(ModuloScheduleTest, "modulo-schedule-test",
211993549957SJames Molloy                       "Modulo Schedule test pass", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)212093549957SJames Molloy INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
212193549957SJames Molloy INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
212293549957SJames Molloy INITIALIZE_PASS_END(ModuloScheduleTest, "modulo-schedule-test",
212393549957SJames Molloy                     "Modulo Schedule test pass", false, false)
212493549957SJames Molloy 
212593549957SJames Molloy bool ModuloScheduleTest::runOnMachineFunction(MachineFunction &MF) {
212693549957SJames Molloy   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
212793549957SJames Molloy   for (auto *L : MLI) {
212893549957SJames Molloy     if (L->getTopBlock() != L->getBottomBlock())
212993549957SJames Molloy       continue;
213093549957SJames Molloy     runOnLoop(MF, *L);
213193549957SJames Molloy     return false;
213293549957SJames Molloy   }
213393549957SJames Molloy   return false;
213493549957SJames Molloy }
213593549957SJames Molloy 
parseSymbolString(StringRef S,int & Cycle,int & Stage)213693549957SJames Molloy static void parseSymbolString(StringRef S, int &Cycle, int &Stage) {
213793549957SJames Molloy   std::pair<StringRef, StringRef> StageAndCycle = getToken(S, "_");
213893549957SJames Molloy   std::pair<StringRef, StringRef> StageTokenAndValue =
213993549957SJames Molloy       getToken(StageAndCycle.first, "-");
214093549957SJames Molloy   std::pair<StringRef, StringRef> CycleTokenAndValue =
214193549957SJames Molloy       getToken(StageAndCycle.second, "-");
214293549957SJames Molloy   if (StageTokenAndValue.first != "Stage" ||
214393549957SJames Molloy       CycleTokenAndValue.first != "_Cycle") {
214493549957SJames Molloy     llvm_unreachable(
214593549957SJames Molloy         "Bad post-instr symbol syntax: see comment in ModuloScheduleTest");
214693549957SJames Molloy     return;
214793549957SJames Molloy   }
214893549957SJames Molloy 
214993549957SJames Molloy   StageTokenAndValue.second.drop_front().getAsInteger(10, Stage);
215093549957SJames Molloy   CycleTokenAndValue.second.drop_front().getAsInteger(10, Cycle);
215193549957SJames Molloy 
215293549957SJames Molloy   dbgs() << "  Stage=" << Stage << ", Cycle=" << Cycle << "\n";
215393549957SJames Molloy }
215493549957SJames Molloy 
runOnLoop(MachineFunction & MF,MachineLoop & L)215593549957SJames Molloy void ModuloScheduleTest::runOnLoop(MachineFunction &MF, MachineLoop &L) {
215693549957SJames Molloy   LiveIntervals &LIS = getAnalysis<LiveIntervals>();
215793549957SJames Molloy   MachineBasicBlock *BB = L.getTopBlock();
215893549957SJames Molloy   dbgs() << "--- ModuloScheduleTest running on BB#" << BB->getNumber() << "\n";
215993549957SJames Molloy 
216093549957SJames Molloy   DenseMap<MachineInstr *, int> Cycle, Stage;
216193549957SJames Molloy   std::vector<MachineInstr *> Instrs;
216293549957SJames Molloy   for (MachineInstr &MI : *BB) {
216393549957SJames Molloy     if (MI.isTerminator())
216493549957SJames Molloy       continue;
216593549957SJames Molloy     Instrs.push_back(&MI);
216693549957SJames Molloy     if (MCSymbol *Sym = MI.getPostInstrSymbol()) {
216793549957SJames Molloy       dbgs() << "Parsing post-instr symbol for " << MI;
216893549957SJames Molloy       parseSymbolString(Sym->getName(), Cycle[&MI], Stage[&MI]);
216993549957SJames Molloy     }
217093549957SJames Molloy   }
217193549957SJames Molloy 
2172fef9f590SJames Molloy   ModuloSchedule MS(MF, &L, std::move(Instrs), std::move(Cycle),
2173fef9f590SJames Molloy                     std::move(Stage));
217493549957SJames Molloy   ModuloScheduleExpander MSE(
217593549957SJames Molloy       MF, MS, LIS, /*InstrChanges=*/ModuloScheduleExpander::InstrChangesTy());
217693549957SJames Molloy   MSE.expand();
2177fef9f590SJames Molloy   MSE.cleanup();
217893549957SJames Molloy }
217993549957SJames Molloy 
218093549957SJames Molloy //===----------------------------------------------------------------------===//
218193549957SJames Molloy // ModuloScheduleTestAnnotater implementation
218293549957SJames Molloy //===----------------------------------------------------------------------===//
218393549957SJames Molloy 
annotate()218493549957SJames Molloy void ModuloScheduleTestAnnotater::annotate() {
218593549957SJames Molloy   for (MachineInstr *MI : S.getInstructions()) {
218693549957SJames Molloy     SmallVector<char, 16> SV;
218793549957SJames Molloy     raw_svector_ostream OS(SV);
218893549957SJames Molloy     OS << "Stage-" << S.getStage(MI) << "_Cycle-" << S.getCycle(MI);
218993549957SJames Molloy     MCSymbol *Sym = MF.getContext().getOrCreateSymbol(OS.str());
219093549957SJames Molloy     MI->setPostInstrSymbol(MF, Sym);
219193549957SJames Molloy   }
219293549957SJames Molloy }
2193