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