1 //===- SIFixSGPRCopies.cpp - Remove potential VGPR => SGPR copies ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Copies from VGPR to SGPR registers are illegal and the register coalescer
11 /// will sometimes generate these illegal copies in situations like this:
12 ///
13 ///  Register Class <vsrc> is the union of <vgpr> and <sgpr>
14 ///
15 /// BB0:
16 ///   %0 <sgpr> = SCALAR_INST
17 ///   %1 <vsrc> = COPY %0 <sgpr>
18 ///    ...
19 ///    BRANCH %cond BB1, BB2
20 ///  BB1:
21 ///    %2 <vgpr> = VECTOR_INST
22 ///    %3 <vsrc> = COPY %2 <vgpr>
23 ///  BB2:
24 ///    %4 <vsrc> = PHI %1 <vsrc>, <%bb.0>, %3 <vrsc>, <%bb.1>
25 ///    %5 <vgpr> = VECTOR_INST %4 <vsrc>
26 ///
27 ///
28 /// The coalescer will begin at BB0 and eliminate its copy, then the resulting
29 /// code will look like this:
30 ///
31 /// BB0:
32 ///   %0 <sgpr> = SCALAR_INST
33 ///    ...
34 ///    BRANCH %cond BB1, BB2
35 /// BB1:
36 ///   %2 <vgpr> = VECTOR_INST
37 ///   %3 <vsrc> = COPY %2 <vgpr>
38 /// BB2:
39 ///   %4 <sgpr> = PHI %0 <sgpr>, <%bb.0>, %3 <vsrc>, <%bb.1>
40 ///   %5 <vgpr> = VECTOR_INST %4 <sgpr>
41 ///
42 /// Now that the result of the PHI instruction is an SGPR, the register
43 /// allocator is now forced to constrain the register class of %3 to
44 /// <sgpr> so we end up with final code like this:
45 ///
46 /// BB0:
47 ///   %0 <sgpr> = SCALAR_INST
48 ///    ...
49 ///    BRANCH %cond BB1, BB2
50 /// BB1:
51 ///   %2 <vgpr> = VECTOR_INST
52 ///   %3 <sgpr> = COPY %2 <vgpr>
53 /// BB2:
54 ///   %4 <sgpr> = PHI %0 <sgpr>, <%bb.0>, %3 <sgpr>, <%bb.1>
55 ///   %5 <vgpr> = VECTOR_INST %4 <sgpr>
56 ///
57 /// Now this code contains an illegal copy from a VGPR to an SGPR.
58 ///
59 /// In order to avoid this problem, this pass searches for PHI instructions
60 /// which define a <vsrc> register and constrains its definition class to
61 /// <vgpr> if the user of the PHI's definition register is a vector instruction.
62 /// If the PHI's definition class is constrained to <vgpr> then the coalescer
63 /// will be unable to perform the COPY removal from the above example  which
64 /// ultimately led to the creation of an illegal COPY.
65 //===----------------------------------------------------------------------===//
66 
67 #include "AMDGPU.h"
68 #include "AMDGPUSubtarget.h"
69 #include "llvm/CodeGen/MachineDominators.h"
70 #include "llvm/InitializePasses.h"
71 #include "llvm/Target/TargetMachine.h"
72 
73 using namespace llvm;
74 
75 #define DEBUG_TYPE "si-fix-sgpr-copies"
76 
77 static cl::opt<bool> EnableM0Merge(
78   "amdgpu-enable-merge-m0",
79   cl::desc("Merge and hoist M0 initializations"),
80   cl::init(true));
81 
82 namespace {
83 
84 class SIFixSGPRCopies : public MachineFunctionPass {
85   MachineDominatorTree *MDT;
86 
87 public:
88   static char ID;
89 
90   MachineRegisterInfo *MRI;
91   const SIRegisterInfo *TRI;
92   const SIInstrInfo *TII;
93 
94   SIFixSGPRCopies() : MachineFunctionPass(ID) {}
95 
96   bool runOnMachineFunction(MachineFunction &MF) override;
97 
98   MachineBasicBlock *processPHINode(MachineInstr &MI);
99 
100   StringRef getPassName() const override { return "SI Fix SGPR copies"; }
101 
102   void getAnalysisUsage(AnalysisUsage &AU) const override {
103     AU.addRequired<MachineDominatorTree>();
104     AU.addPreserved<MachineDominatorTree>();
105     AU.setPreservesCFG();
106     MachineFunctionPass::getAnalysisUsage(AU);
107   }
108 };
109 
110 } // end anonymous namespace
111 
112 INITIALIZE_PASS_BEGIN(SIFixSGPRCopies, DEBUG_TYPE,
113                      "SI Fix SGPR copies", false, false)
114 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
115 INITIALIZE_PASS_END(SIFixSGPRCopies, DEBUG_TYPE,
116                      "SI Fix SGPR copies", false, false)
117 
118 char SIFixSGPRCopies::ID = 0;
119 
120 char &llvm::SIFixSGPRCopiesID = SIFixSGPRCopies::ID;
121 
122 FunctionPass *llvm::createSIFixSGPRCopiesPass() {
123   return new SIFixSGPRCopies();
124 }
125 
126 static bool hasVectorOperands(const MachineInstr &MI,
127                               const SIRegisterInfo *TRI) {
128   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
129   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
130     if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
131       continue;
132 
133     if (TRI->hasVectorRegisters(MRI.getRegClass(MI.getOperand(i).getReg())))
134       return true;
135   }
136   return false;
137 }
138 
139 static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
140 getCopyRegClasses(const MachineInstr &Copy,
141                   const SIRegisterInfo &TRI,
142                   const MachineRegisterInfo &MRI) {
143   Register DstReg = Copy.getOperand(0).getReg();
144   Register SrcReg = Copy.getOperand(1).getReg();
145 
146   const TargetRegisterClass *SrcRC = SrcReg.isVirtual()
147                                          ? MRI.getRegClass(SrcReg)
148                                          : TRI.getPhysRegClass(SrcReg);
149 
150   // We don't really care about the subregister here.
151   // SrcRC = TRI.getSubRegClass(SrcRC, Copy.getOperand(1).getSubReg());
152 
153   const TargetRegisterClass *DstRC = DstReg.isVirtual()
154                                          ? MRI.getRegClass(DstReg)
155                                          : TRI.getPhysRegClass(DstReg);
156 
157   return std::make_pair(SrcRC, DstRC);
158 }
159 
160 static bool isVGPRToSGPRCopy(const TargetRegisterClass *SrcRC,
161                              const TargetRegisterClass *DstRC,
162                              const SIRegisterInfo &TRI) {
163   return SrcRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(DstRC) &&
164          TRI.hasVectorRegisters(SrcRC);
165 }
166 
167 static bool isSGPRToVGPRCopy(const TargetRegisterClass *SrcRC,
168                              const TargetRegisterClass *DstRC,
169                              const SIRegisterInfo &TRI) {
170   return DstRC != &AMDGPU::VReg_1RegClass && TRI.isSGPRClass(SrcRC) &&
171          TRI.hasVectorRegisters(DstRC);
172 }
173 
174 static bool tryChangeVGPRtoSGPRinCopy(MachineInstr &MI,
175                                       const SIRegisterInfo *TRI,
176                                       const SIInstrInfo *TII) {
177   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
178   auto &Src = MI.getOperand(1);
179   Register DstReg = MI.getOperand(0).getReg();
180   Register SrcReg = Src.getReg();
181   if (!SrcReg.isVirtual() || !DstReg.isVirtual())
182     return false;
183 
184   for (const auto &MO : MRI.reg_nodbg_operands(DstReg)) {
185     const auto *UseMI = MO.getParent();
186     if (UseMI == &MI)
187       continue;
188     if (MO.isDef() || UseMI->getParent() != MI.getParent() ||
189         UseMI->getOpcode() <= TargetOpcode::GENERIC_OP_END)
190       return false;
191 
192     unsigned OpIdx = UseMI->getOperandNo(&MO);
193     if (OpIdx >= UseMI->getDesc().getNumOperands() ||
194         !TII->isOperandLegal(*UseMI, OpIdx, &Src))
195       return false;
196   }
197   // Change VGPR to SGPR destination.
198   MRI.setRegClass(DstReg, TRI->getEquivalentSGPRClass(MRI.getRegClass(DstReg)));
199   return true;
200 }
201 
202 // Distribute an SGPR->VGPR copy of a REG_SEQUENCE into a VGPR REG_SEQUENCE.
203 //
204 // SGPRx = ...
205 // SGPRy = REG_SEQUENCE SGPRx, sub0 ...
206 // VGPRz = COPY SGPRy
207 //
208 // ==>
209 //
210 // VGPRx = COPY SGPRx
211 // VGPRz = REG_SEQUENCE VGPRx, sub0
212 //
213 // This exposes immediate folding opportunities when materializing 64-bit
214 // immediates.
215 static bool foldVGPRCopyIntoRegSequence(MachineInstr &MI,
216                                         const SIRegisterInfo *TRI,
217                                         const SIInstrInfo *TII,
218                                         MachineRegisterInfo &MRI) {
219   assert(MI.isRegSequence());
220 
221   Register DstReg = MI.getOperand(0).getReg();
222   if (!TRI->isSGPRClass(MRI.getRegClass(DstReg)))
223     return false;
224 
225   if (!MRI.hasOneUse(DstReg))
226     return false;
227 
228   MachineInstr &CopyUse = *MRI.use_instr_begin(DstReg);
229   if (!CopyUse.isCopy())
230     return false;
231 
232   // It is illegal to have vreg inputs to a physreg defining reg_sequence.
233   if (CopyUse.getOperand(0).getReg().isPhysical())
234     return false;
235 
236   const TargetRegisterClass *SrcRC, *DstRC;
237   std::tie(SrcRC, DstRC) = getCopyRegClasses(CopyUse, *TRI, MRI);
238 
239   if (!isSGPRToVGPRCopy(SrcRC, DstRC, *TRI))
240     return false;
241 
242   if (tryChangeVGPRtoSGPRinCopy(CopyUse, TRI, TII))
243     return true;
244 
245   // TODO: Could have multiple extracts?
246   unsigned SubReg = CopyUse.getOperand(1).getSubReg();
247   if (SubReg != AMDGPU::NoSubRegister)
248     return false;
249 
250   MRI.setRegClass(DstReg, DstRC);
251 
252   // SGPRx = ...
253   // SGPRy = REG_SEQUENCE SGPRx, sub0 ...
254   // VGPRz = COPY SGPRy
255 
256   // =>
257   // VGPRx = COPY SGPRx
258   // VGPRz = REG_SEQUENCE VGPRx, sub0
259 
260   MI.getOperand(0).setReg(CopyUse.getOperand(0).getReg());
261   bool IsAGPR = TRI->hasAGPRs(DstRC);
262 
263   for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
264     Register SrcReg = MI.getOperand(I).getReg();
265     unsigned SrcSubReg = MI.getOperand(I).getSubReg();
266 
267     const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
268     assert(TRI->isSGPRClass(SrcRC) &&
269            "Expected SGPR REG_SEQUENCE to only have SGPR inputs");
270 
271     SrcRC = TRI->getSubRegClass(SrcRC, SrcSubReg);
272     const TargetRegisterClass *NewSrcRC = TRI->getEquivalentVGPRClass(SrcRC);
273 
274     Register TmpReg = MRI.createVirtualRegister(NewSrcRC);
275 
276     BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
277             TmpReg)
278         .add(MI.getOperand(I));
279 
280     if (IsAGPR) {
281       const TargetRegisterClass *NewSrcRC = TRI->getEquivalentAGPRClass(SrcRC);
282       Register TmpAReg = MRI.createVirtualRegister(NewSrcRC);
283       unsigned Opc = NewSrcRC == &AMDGPU::AGPR_32RegClass ?
284         AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::COPY;
285       BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), TII->get(Opc),
286             TmpAReg)
287         .addReg(TmpReg, RegState::Kill);
288       TmpReg = TmpAReg;
289     }
290 
291     MI.getOperand(I).setReg(TmpReg);
292   }
293 
294   CopyUse.eraseFromParent();
295   return true;
296 }
297 
298 static bool isSafeToFoldImmIntoCopy(const MachineInstr *Copy,
299                                     const MachineInstr *MoveImm,
300                                     const SIInstrInfo *TII,
301                                     unsigned &SMovOp,
302                                     int64_t &Imm) {
303   if (Copy->getOpcode() != AMDGPU::COPY)
304     return false;
305 
306   if (!MoveImm->isMoveImmediate())
307     return false;
308 
309   const MachineOperand *ImmOp =
310       TII->getNamedOperand(*MoveImm, AMDGPU::OpName::src0);
311   if (!ImmOp->isImm())
312     return false;
313 
314   // FIXME: Handle copies with sub-regs.
315   if (Copy->getOperand(0).getSubReg())
316     return false;
317 
318   switch (MoveImm->getOpcode()) {
319   default:
320     return false;
321   case AMDGPU::V_MOV_B32_e32:
322     SMovOp = AMDGPU::S_MOV_B32;
323     break;
324   case AMDGPU::V_MOV_B64_PSEUDO:
325     SMovOp = AMDGPU::S_MOV_B64;
326     break;
327   }
328   Imm = ImmOp->getImm();
329   return true;
330 }
331 
332 template <class UnaryPredicate>
333 bool searchPredecessors(const MachineBasicBlock *MBB,
334                         const MachineBasicBlock *CutOff,
335                         UnaryPredicate Predicate) {
336   if (MBB == CutOff)
337     return false;
338 
339   DenseSet<const MachineBasicBlock *> Visited;
340   SmallVector<MachineBasicBlock *, 4> Worklist(MBB->predecessors());
341 
342   while (!Worklist.empty()) {
343     MachineBasicBlock *MBB = Worklist.pop_back_val();
344 
345     if (!Visited.insert(MBB).second)
346       continue;
347     if (MBB == CutOff)
348       continue;
349     if (Predicate(MBB))
350       return true;
351 
352     Worklist.append(MBB->pred_begin(), MBB->pred_end());
353   }
354 
355   return false;
356 }
357 
358 // Checks if there is potential path From instruction To instruction.
359 // If CutOff is specified and it sits in between of that path we ignore
360 // a higher portion of the path and report it is not reachable.
361 static bool isReachable(const MachineInstr *From,
362                         const MachineInstr *To,
363                         const MachineBasicBlock *CutOff,
364                         MachineDominatorTree &MDT) {
365   if (MDT.dominates(From, To))
366     return true;
367 
368   const MachineBasicBlock *MBBFrom = From->getParent();
369   const MachineBasicBlock *MBBTo = To->getParent();
370 
371   // Do predecessor search.
372   // We should almost never get here since we do not usually produce M0 stores
373   // other than -1.
374   return searchPredecessors(MBBTo, CutOff, [MBBFrom]
375            (const MachineBasicBlock *MBB) { return MBB == MBBFrom; });
376 }
377 
378 // Return the first non-prologue instruction in the block.
379 static MachineBasicBlock::iterator
380 getFirstNonPrologue(MachineBasicBlock *MBB, const TargetInstrInfo *TII) {
381   MachineBasicBlock::iterator I = MBB->getFirstNonPHI();
382   while (I != MBB->end() && TII->isBasicBlockPrologue(*I))
383     ++I;
384 
385   return I;
386 }
387 
388 // Hoist and merge identical SGPR initializations into a common predecessor.
389 // This is intended to combine M0 initializations, but can work with any
390 // SGPR. A VGPR cannot be processed since we cannot guarantee vector
391 // executioon.
392 static bool hoistAndMergeSGPRInits(unsigned Reg,
393                                    const MachineRegisterInfo &MRI,
394                                    const TargetRegisterInfo *TRI,
395                                    MachineDominatorTree &MDT,
396                                    const TargetInstrInfo *TII) {
397   // List of inits by immediate value.
398   using InitListMap = std::map<unsigned, std::list<MachineInstr *>>;
399   InitListMap Inits;
400   // List of clobbering instructions.
401   SmallVector<MachineInstr*, 8> Clobbers;
402   // List of instructions marked for deletion.
403   SmallSet<MachineInstr*, 8> MergedInstrs;
404 
405   bool Changed = false;
406 
407   for (auto &MI : MRI.def_instructions(Reg)) {
408     MachineOperand *Imm = nullptr;
409     for (auto &MO : MI.operands()) {
410       if ((MO.isReg() && ((MO.isDef() && MO.getReg() != Reg) || !MO.isDef())) ||
411           (!MO.isImm() && !MO.isReg()) || (MO.isImm() && Imm)) {
412         Imm = nullptr;
413         break;
414       } else if (MO.isImm())
415         Imm = &MO;
416     }
417     if (Imm)
418       Inits[Imm->getImm()].push_front(&MI);
419     else
420       Clobbers.push_back(&MI);
421   }
422 
423   for (auto &Init : Inits) {
424     auto &Defs = Init.second;
425 
426     for (auto I1 = Defs.begin(), E = Defs.end(); I1 != E; ) {
427       MachineInstr *MI1 = *I1;
428 
429       for (auto I2 = std::next(I1); I2 != E; ) {
430         MachineInstr *MI2 = *I2;
431 
432         // Check any possible interference
433         auto interferes = [&](MachineBasicBlock::iterator From,
434                               MachineBasicBlock::iterator To) -> bool {
435 
436           assert(MDT.dominates(&*To, &*From));
437 
438           auto interferes = [&MDT, From, To](MachineInstr* &Clobber) -> bool {
439             const MachineBasicBlock *MBBFrom = From->getParent();
440             const MachineBasicBlock *MBBTo = To->getParent();
441             bool MayClobberFrom = isReachable(Clobber, &*From, MBBTo, MDT);
442             bool MayClobberTo = isReachable(Clobber, &*To, MBBTo, MDT);
443             if (!MayClobberFrom && !MayClobberTo)
444               return false;
445             if ((MayClobberFrom && !MayClobberTo) ||
446                 (!MayClobberFrom && MayClobberTo))
447               return true;
448             // Both can clobber, this is not an interference only if both are
449             // dominated by Clobber and belong to the same block or if Clobber
450             // properly dominates To, given that To >> From, so it dominates
451             // both and located in a common dominator.
452             return !((MBBFrom == MBBTo &&
453                       MDT.dominates(Clobber, &*From) &&
454                       MDT.dominates(Clobber, &*To)) ||
455                      MDT.properlyDominates(Clobber->getParent(), MBBTo));
456           };
457 
458           return (llvm::any_of(Clobbers, interferes)) ||
459                  (llvm::any_of(Inits, [&](InitListMap::value_type &C) {
460                     return C.first != Init.first &&
461                            llvm::any_of(C.second, interferes);
462                   }));
463         };
464 
465         if (MDT.dominates(MI1, MI2)) {
466           if (!interferes(MI2, MI1)) {
467             LLVM_DEBUG(dbgs()
468                        << "Erasing from "
469                        << printMBBReference(*MI2->getParent()) << " " << *MI2);
470             MergedInstrs.insert(MI2);
471             Changed = true;
472             ++I2;
473             continue;
474           }
475         } else if (MDT.dominates(MI2, MI1)) {
476           if (!interferes(MI1, MI2)) {
477             LLVM_DEBUG(dbgs()
478                        << "Erasing from "
479                        << printMBBReference(*MI1->getParent()) << " " << *MI1);
480             MergedInstrs.insert(MI1);
481             Changed = true;
482             ++I1;
483             break;
484           }
485         } else {
486           auto *MBB = MDT.findNearestCommonDominator(MI1->getParent(),
487                                                      MI2->getParent());
488           if (!MBB) {
489             ++I2;
490             continue;
491           }
492 
493           MachineBasicBlock::iterator I = getFirstNonPrologue(MBB, TII);
494           if (!interferes(MI1, I) && !interferes(MI2, I)) {
495             LLVM_DEBUG(dbgs()
496                        << "Erasing from "
497                        << printMBBReference(*MI1->getParent()) << " " << *MI1
498                        << "and moving from "
499                        << printMBBReference(*MI2->getParent()) << " to "
500                        << printMBBReference(*I->getParent()) << " " << *MI2);
501             I->getParent()->splice(I, MI2->getParent(), MI2);
502             MergedInstrs.insert(MI1);
503             Changed = true;
504             ++I1;
505             break;
506           }
507         }
508         ++I2;
509       }
510       ++I1;
511     }
512   }
513 
514   // Remove initializations that were merged into another.
515   for (auto &Init : Inits) {
516     auto &Defs = Init.second;
517     auto I = Defs.begin();
518     while (I != Defs.end()) {
519       if (MergedInstrs.count(*I)) {
520         (*I)->eraseFromParent();
521         I = Defs.erase(I);
522       } else
523         ++I;
524     }
525   }
526 
527   // Try to schedule SGPR initializations as early as possible in the MBB.
528   for (auto &Init : Inits) {
529     auto &Defs = Init.second;
530     for (auto MI : Defs) {
531       auto MBB = MI->getParent();
532       MachineInstr &BoundaryMI = *getFirstNonPrologue(MBB, TII);
533       MachineBasicBlock::reverse_iterator B(BoundaryMI);
534       // Check if B should actually be a boundary. If not set the previous
535       // instruction as the boundary instead.
536       if (!TII->isBasicBlockPrologue(*B))
537         B++;
538 
539       auto R = std::next(MI->getReverseIterator());
540       const unsigned Threshold = 50;
541       // Search until B or Threshold for a place to insert the initialization.
542       for (unsigned I = 0; R != B && I < Threshold; ++R, ++I)
543         if (R->readsRegister(Reg, TRI) || R->definesRegister(Reg, TRI) ||
544             TII->isSchedulingBoundary(*R, MBB, *MBB->getParent()))
545           break;
546 
547       // Move to directly after R.
548       if (&*--R != MI)
549         MBB->splice(*R, MBB, MI);
550     }
551   }
552 
553   if (Changed)
554     MRI.clearKillFlags(Reg);
555 
556   return Changed;
557 }
558 
559 bool SIFixSGPRCopies::runOnMachineFunction(MachineFunction &MF) {
560   // Only need to run this in SelectionDAG path.
561   if (MF.getProperties().hasProperty(
562         MachineFunctionProperties::Property::Selected))
563     return false;
564 
565   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
566   MRI = &MF.getRegInfo();
567   TRI = ST.getRegisterInfo();
568   TII = ST.getInstrInfo();
569   MDT = &getAnalysis<MachineDominatorTree>();
570 
571   for (MachineFunction::iterator BI = MF.begin(), BE = MF.end();
572                                                   BI != BE; ++BI) {
573     MachineBasicBlock *MBB = &*BI;
574     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
575          ++I) {
576       MachineInstr &MI = *I;
577 
578       switch (MI.getOpcode()) {
579       default:
580         continue;
581       case AMDGPU::COPY:
582       case AMDGPU::WQM:
583       case AMDGPU::SOFT_WQM:
584       case AMDGPU::WWM: {
585         Register DstReg = MI.getOperand(0).getReg();
586 
587         const TargetRegisterClass *SrcRC, *DstRC;
588         std::tie(SrcRC, DstRC) = getCopyRegClasses(MI, *TRI, *MRI);
589 
590         if (!DstReg.isVirtual()) {
591           // If the destination register is a physical register there isn't
592           // really much we can do to fix this.
593           // Some special instructions use M0 as an input. Some even only use
594           // the first lane. Insert a readfirstlane and hope for the best.
595           if (DstReg == AMDGPU::M0 && TRI->hasVectorRegisters(SrcRC)) {
596             Register TmpReg
597               = MRI->createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
598 
599             BuildMI(*MBB, MI, MI.getDebugLoc(),
600                     TII->get(AMDGPU::V_READFIRSTLANE_B32), TmpReg)
601                 .add(MI.getOperand(1));
602             MI.getOperand(1).setReg(TmpReg);
603           }
604 
605           continue;
606         }
607 
608         if (isVGPRToSGPRCopy(SrcRC, DstRC, *TRI)) {
609           Register SrcReg = MI.getOperand(1).getReg();
610           if (!SrcReg.isVirtual()) {
611             MachineBasicBlock *NewBB = TII->moveToVALU(MI, MDT);
612             if (NewBB && NewBB != MBB) {
613               MBB = NewBB;
614               E = MBB->end();
615               BI = MachineFunction::iterator(MBB);
616               BE = MF.end();
617             }
618             assert((!NewBB || NewBB == I->getParent()) &&
619                    "moveToVALU did not return the right basic block");
620             break;
621           }
622 
623           MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
624           unsigned SMovOp;
625           int64_t Imm;
626           // If we are just copying an immediate, we can replace the copy with
627           // s_mov_b32.
628           if (isSafeToFoldImmIntoCopy(&MI, DefMI, TII, SMovOp, Imm)) {
629             MI.getOperand(1).ChangeToImmediate(Imm);
630             MI.addImplicitDefUseOperands(MF);
631             MI.setDesc(TII->get(SMovOp));
632             break;
633           }
634           MachineBasicBlock *NewBB = TII->moveToVALU(MI, MDT);
635           if (NewBB && NewBB != MBB) {
636             MBB = NewBB;
637             E = MBB->end();
638             BI = MachineFunction::iterator(MBB);
639             BE = MF.end();
640           }
641           assert((!NewBB || NewBB == I->getParent()) &&
642                  "moveToVALU did not return the right basic block");
643         } else if (isSGPRToVGPRCopy(SrcRC, DstRC, *TRI)) {
644           tryChangeVGPRtoSGPRinCopy(MI, TRI, TII);
645         }
646 
647         break;
648       }
649       case AMDGPU::PHI: {
650         MachineBasicBlock *NewBB = processPHINode(MI);
651         if (NewBB && NewBB != MBB) {
652           MBB = NewBB;
653           E = MBB->end();
654           BI = MachineFunction::iterator(MBB);
655           BE = MF.end();
656         }
657         assert((!NewBB || NewBB == I->getParent()) &&
658                "moveToVALU did not return the right basic block");
659         break;
660       }
661       case AMDGPU::REG_SEQUENCE: {
662         if (TRI->hasVectorRegisters(TII->getOpRegClass(MI, 0)) ||
663             !hasVectorOperands(MI, TRI)) {
664           foldVGPRCopyIntoRegSequence(MI, TRI, TII, *MRI);
665           continue;
666         }
667 
668         LLVM_DEBUG(dbgs() << "Fixing REG_SEQUENCE: " << MI);
669 
670         MachineBasicBlock *NewBB = TII->moveToVALU(MI, MDT);
671         if (NewBB && NewBB != MBB) {
672           MBB = NewBB;
673           E = MBB->end();
674           BI = MachineFunction::iterator(MBB);
675           BE = MF.end();
676         }
677         assert((!NewBB || NewBB == I->getParent()) &&
678                "moveToVALU did not return the right basic block");
679         break;
680       }
681       case AMDGPU::INSERT_SUBREG: {
682         const TargetRegisterClass *DstRC, *Src0RC, *Src1RC;
683         DstRC = MRI->getRegClass(MI.getOperand(0).getReg());
684         Src0RC = MRI->getRegClass(MI.getOperand(1).getReg());
685         Src1RC = MRI->getRegClass(MI.getOperand(2).getReg());
686         if (TRI->isSGPRClass(DstRC) &&
687             (TRI->hasVectorRegisters(Src0RC) ||
688              TRI->hasVectorRegisters(Src1RC))) {
689           LLVM_DEBUG(dbgs() << " Fixing INSERT_SUBREG: " << MI);
690           MachineBasicBlock *NewBB = TII->moveToVALU(MI, MDT);
691           if (NewBB && NewBB != MBB) {
692             MBB = NewBB;
693             E = MBB->end();
694             BI = MachineFunction::iterator(MBB);
695             BE = MF.end();
696           }
697           assert((!NewBB || NewBB == I->getParent()) &&
698                  "moveToVALU did not return the right basic block");
699         }
700         break;
701       }
702       case AMDGPU::V_WRITELANE_B32: {
703         // Some architectures allow more than one constant bus access without
704         // SGPR restriction
705         if (ST.getConstantBusLimit(MI.getOpcode()) != 1)
706           break;
707 
708         // Writelane is special in that it can use SGPR and M0 (which would
709         // normally count as using the constant bus twice - but in this case it
710         // is allowed since the lane selector doesn't count as a use of the
711         // constant bus). However, it is still required to abide by the 1 SGPR
712         // rule. Apply a fix here as we might have multiple SGPRs after
713         // legalizing VGPRs to SGPRs
714         int Src0Idx =
715             AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src0);
716         int Src1Idx =
717             AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::src1);
718         MachineOperand &Src0 = MI.getOperand(Src0Idx);
719         MachineOperand &Src1 = MI.getOperand(Src1Idx);
720 
721         // Check to see if the instruction violates the 1 SGPR rule
722         if ((Src0.isReg() && TRI->isSGPRReg(*MRI, Src0.getReg()) &&
723              Src0.getReg() != AMDGPU::M0) &&
724             (Src1.isReg() && TRI->isSGPRReg(*MRI, Src1.getReg()) &&
725              Src1.getReg() != AMDGPU::M0)) {
726 
727           // Check for trivially easy constant prop into one of the operands
728           // If this is the case then perform the operation now to resolve SGPR
729           // issue. If we don't do that here we will always insert a mov to m0
730           // that can't be resolved in later operand folding pass
731           bool Resolved = false;
732           for (MachineOperand *MO : {&Src0, &Src1}) {
733             if (MO->getReg().isVirtual()) {
734               MachineInstr *DefMI = MRI->getVRegDef(MO->getReg());
735               if (DefMI && TII->isFoldableCopy(*DefMI)) {
736                 const MachineOperand &Def = DefMI->getOperand(0);
737                 if (Def.isReg() &&
738                     MO->getReg() == Def.getReg() &&
739                     MO->getSubReg() == Def.getSubReg()) {
740                   const MachineOperand &Copied = DefMI->getOperand(1);
741                   if (Copied.isImm() &&
742                       TII->isInlineConstant(APInt(64, Copied.getImm(), true))) {
743                     MO->ChangeToImmediate(Copied.getImm());
744                     Resolved = true;
745                     break;
746                   }
747                 }
748               }
749             }
750           }
751 
752           if (!Resolved) {
753             // Haven't managed to resolve by replacing an SGPR with an immediate
754             // Move src1 to be in M0
755             BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
756                     TII->get(AMDGPU::COPY), AMDGPU::M0)
757                 .add(Src1);
758             Src1.ChangeToRegister(AMDGPU::M0, false);
759           }
760         }
761         break;
762       }
763       }
764     }
765   }
766 
767   if (MF.getTarget().getOptLevel() > CodeGenOpt::None && EnableM0Merge)
768     hoistAndMergeSGPRInits(AMDGPU::M0, *MRI, TRI, *MDT, TII);
769 
770   return true;
771 }
772 
773 MachineBasicBlock *SIFixSGPRCopies::processPHINode(MachineInstr &MI) {
774   unsigned numVGPRUses = 0;
775   bool AllAGPRUses = true;
776   SetVector<const MachineInstr *> worklist;
777   SmallSet<const MachineInstr *, 4> Visited;
778   SetVector<MachineInstr *> PHIOperands;
779   MachineBasicBlock *CreatedBB = nullptr;
780   worklist.insert(&MI);
781   Visited.insert(&MI);
782   while (!worklist.empty()) {
783     const MachineInstr *Instr = worklist.pop_back_val();
784     Register Reg = Instr->getOperand(0).getReg();
785     for (const auto &Use : MRI->use_operands(Reg)) {
786       const MachineInstr *UseMI = Use.getParent();
787       AllAGPRUses &= (UseMI->isCopy() &&
788                       TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg())) ||
789                      TRI->isAGPR(*MRI, Use.getReg());
790       if (UseMI->isCopy() || UseMI->isRegSequence()) {
791         if (UseMI->isCopy() &&
792           UseMI->getOperand(0).getReg().isPhysical() &&
793           !TRI->isSGPRReg(*MRI, UseMI->getOperand(0).getReg())) {
794           numVGPRUses++;
795         }
796         if (Visited.insert(UseMI).second)
797           worklist.insert(UseMI);
798 
799         continue;
800       }
801 
802       if (UseMI->isPHI()) {
803         const TargetRegisterClass *UseRC = MRI->getRegClass(Use.getReg());
804         if (!TRI->isSGPRReg(*MRI, Use.getReg()) &&
805           UseRC != &AMDGPU::VReg_1RegClass)
806           numVGPRUses++;
807         continue;
808       }
809 
810       const TargetRegisterClass *OpRC =
811         TII->getOpRegClass(*UseMI, UseMI->getOperandNo(&Use));
812       if (!TRI->isSGPRClass(OpRC) && OpRC != &AMDGPU::VS_32RegClass &&
813         OpRC != &AMDGPU::VS_64RegClass) {
814         numVGPRUses++;
815       }
816     }
817   }
818 
819   Register PHIRes = MI.getOperand(0).getReg();
820   const TargetRegisterClass *RC0 = MRI->getRegClass(PHIRes);
821   if (AllAGPRUses && numVGPRUses && !TRI->hasAGPRs(RC0)) {
822     LLVM_DEBUG(dbgs() << "Moving PHI to AGPR: " << MI);
823     MRI->setRegClass(PHIRes, TRI->getEquivalentAGPRClass(RC0));
824     for (unsigned I = 1, N = MI.getNumOperands(); I != N; I += 2) {
825       MachineInstr *DefMI = MRI->getVRegDef(MI.getOperand(I).getReg());
826       if (DefMI && DefMI->isPHI())
827         PHIOperands.insert(DefMI);
828     }
829   }
830 
831   bool hasVGPRInput = false;
832   for (unsigned i = 1; i < MI.getNumOperands(); i += 2) {
833     Register InputReg = MI.getOperand(i).getReg();
834     MachineInstr *Def = MRI->getVRegDef(InputReg);
835     if (TRI->isVectorRegister(*MRI, InputReg)) {
836       if (Def->isCopy()) {
837         Register SrcReg = Def->getOperand(1).getReg();
838         const TargetRegisterClass *RC =
839           TRI->getRegClassForReg(*MRI, SrcReg);
840         if (TRI->isSGPRClass(RC))
841           continue;
842       }
843       hasVGPRInput = true;
844       break;
845     }
846     else if (Def->isCopy() &&
847       TRI->isVectorRegister(*MRI, Def->getOperand(1).getReg())) {
848       Register SrcReg = Def->getOperand(1).getReg();
849       MachineInstr *SrcDef = MRI->getVRegDef(SrcReg);
850       unsigned SMovOp;
851       int64_t Imm;
852       if (!isSafeToFoldImmIntoCopy(Def, SrcDef, TII, SMovOp, Imm)) {
853         hasVGPRInput = true;
854         break;
855       } else {
856         // Formally, if we did not do this right away
857         // it would be done on the next iteration of the
858         // runOnMachineFunction main loop. But why not if we can?
859         MachineFunction *MF = MI.getParent()->getParent();
860         Def->getOperand(1).ChangeToImmediate(Imm);
861         Def->addImplicitDefUseOperands(*MF);
862         Def->setDesc(TII->get(SMovOp));
863       }
864     }
865   }
866 
867   if ((!TRI->isVectorRegister(*MRI, PHIRes) &&
868        RC0 != &AMDGPU::VReg_1RegClass) &&
869     (hasVGPRInput || numVGPRUses > 1)) {
870     LLVM_DEBUG(dbgs() << "Fixing PHI: " << MI);
871     CreatedBB = TII->moveToVALU(MI);
872   }
873   else {
874     LLVM_DEBUG(dbgs() << "Legalizing PHI: " << MI);
875     TII->legalizeOperands(MI, MDT);
876   }
877 
878   // Propagate register class back to PHI operands which are PHI themselves.
879   while (!PHIOperands.empty()) {
880     processPHINode(*PHIOperands.pop_back_val());
881   }
882   return CreatedBB;
883 }
884