1 //===- SIInstrInfo.cpp - SI Instruction Information  ----------------------===//
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 /// SI Implementation of TargetInstrInfo.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIInstrInfo.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "GCNHazardRecognizer.h"
18 #include "GCNSubtarget.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineDominators.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/CodeGen/ScheduleDAG.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Target/TargetMachine.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "si-instr-info"
34 
35 #define GET_INSTRINFO_CTOR_DTOR
36 #include "AMDGPUGenInstrInfo.inc"
37 
38 namespace llvm {
39 
40 class AAResults;
41 
42 namespace AMDGPU {
43 #define GET_D16ImageDimIntrinsics_IMPL
44 #define GET_ImageDimIntrinsicTable_IMPL
45 #define GET_RsrcIntrinsics_IMPL
46 #include "AMDGPUGenSearchableTables.inc"
47 }
48 }
49 
50 
51 // Must be at least 4 to be able to branch over minimum unconditional branch
52 // code. This is only for making it possible to write reasonably small tests for
53 // long branches.
54 static cl::opt<unsigned>
55 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
56                  cl::desc("Restrict range of branch instructions (DEBUG)"));
57 
58 static cl::opt<bool> Fix16BitCopies(
59   "amdgpu-fix-16-bit-physreg-copies",
60   cl::desc("Fix copies between 32 and 16 bit registers by extending to 32 bit"),
61   cl::init(true),
62   cl::ReallyHidden);
63 
64 SIInstrInfo::SIInstrInfo(const GCNSubtarget &ST)
65   : AMDGPUGenInstrInfo(AMDGPU::ADJCALLSTACKUP, AMDGPU::ADJCALLSTACKDOWN),
66     RI(ST), ST(ST) {
67   SchedModel.init(&ST);
68 }
69 
70 //===----------------------------------------------------------------------===//
71 // TargetInstrInfo callbacks
72 //===----------------------------------------------------------------------===//
73 
74 static unsigned getNumOperandsNoGlue(SDNode *Node) {
75   unsigned N = Node->getNumOperands();
76   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
77     --N;
78   return N;
79 }
80 
81 /// Returns true if both nodes have the same value for the given
82 ///        operand \p Op, or if both nodes do not have this operand.
83 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
84   unsigned Opc0 = N0->getMachineOpcode();
85   unsigned Opc1 = N1->getMachineOpcode();
86 
87   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
88   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
89 
90   if (Op0Idx == -1 && Op1Idx == -1)
91     return true;
92 
93 
94   if ((Op0Idx == -1 && Op1Idx != -1) ||
95       (Op1Idx == -1 && Op0Idx != -1))
96     return false;
97 
98   // getNamedOperandIdx returns the index for the MachineInstr's operands,
99   // which includes the result as the first operand. We are indexing into the
100   // MachineSDNode's operands, so we need to skip the result operand to get
101   // the real index.
102   --Op0Idx;
103   --Op1Idx;
104 
105   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
106 }
107 
108 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
109                                                     AAResults *AA) const {
110   // TODO: The generic check fails for VALU instructions that should be
111   // rematerializable due to implicit reads of exec. We really want all of the
112   // generic logic for this except for this.
113   switch (MI.getOpcode()) {
114   case AMDGPU::V_MOV_B32_e32:
115   case AMDGPU::V_MOV_B32_e64:
116   case AMDGPU::V_MOV_B64_PSEUDO:
117   case AMDGPU::V_ACCVGPR_READ_B32_e64:
118   case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
119     // No non-standard implicit operands.
120     assert(MI.getDesc().getNumOperands() == 2);
121     assert(MI.getDesc().getNumImplicitDefs() == 0);
122     assert(MI.getDesc().getNumImplicitUses() == 1);
123     return MI.getNumOperands() == 3;
124   default:
125     return false;
126   }
127 }
128 
129 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
130                                           int64_t &Offset0,
131                                           int64_t &Offset1) const {
132   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
133     return false;
134 
135   unsigned Opc0 = Load0->getMachineOpcode();
136   unsigned Opc1 = Load1->getMachineOpcode();
137 
138   // Make sure both are actually loads.
139   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
140     return false;
141 
142   if (isDS(Opc0) && isDS(Opc1)) {
143 
144     // FIXME: Handle this case:
145     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
146       return false;
147 
148     // Check base reg.
149     if (Load0->getOperand(0) != Load1->getOperand(0))
150       return false;
151 
152     // Skip read2 / write2 variants for simplicity.
153     // TODO: We should report true if the used offsets are adjacent (excluded
154     // st64 versions).
155     int Offset0Idx = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
156     int Offset1Idx = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
157     if (Offset0Idx == -1 || Offset1Idx == -1)
158       return false;
159 
160     // XXX - be careful of datalesss loads
161     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
162     // include the output in the operand list, but SDNodes don't, we need to
163     // subtract the index by one.
164     Offset0Idx -= get(Opc0).NumDefs;
165     Offset1Idx -= get(Opc1).NumDefs;
166     Offset0 = cast<ConstantSDNode>(Load0->getOperand(Offset0Idx))->getZExtValue();
167     Offset1 = cast<ConstantSDNode>(Load1->getOperand(Offset1Idx))->getZExtValue();
168     return true;
169   }
170 
171   if (isSMRD(Opc0) && isSMRD(Opc1)) {
172     // Skip time and cache invalidation instructions.
173     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::sbase) == -1 ||
174         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::sbase) == -1)
175       return false;
176 
177     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
178 
179     // Check base reg.
180     if (Load0->getOperand(0) != Load1->getOperand(0))
181       return false;
182 
183     const ConstantSDNode *Load0Offset =
184         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
185     const ConstantSDNode *Load1Offset =
186         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
187 
188     if (!Load0Offset || !Load1Offset)
189       return false;
190 
191     Offset0 = Load0Offset->getZExtValue();
192     Offset1 = Load1Offset->getZExtValue();
193     return true;
194   }
195 
196   // MUBUF and MTBUF can access the same addresses.
197   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
198 
199     // MUBUF and MTBUF have vaddr at different indices.
200     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
201         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
202         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
203       return false;
204 
205     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
206     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
207 
208     if (OffIdx0 == -1 || OffIdx1 == -1)
209       return false;
210 
211     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
212     // include the output in the operand list, but SDNodes don't, we need to
213     // subtract the index by one.
214     OffIdx0 -= get(Opc0).NumDefs;
215     OffIdx1 -= get(Opc1).NumDefs;
216 
217     SDValue Off0 = Load0->getOperand(OffIdx0);
218     SDValue Off1 = Load1->getOperand(OffIdx1);
219 
220     // The offset might be a FrameIndexSDNode.
221     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
222       return false;
223 
224     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
225     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
226     return true;
227   }
228 
229   return false;
230 }
231 
232 static bool isStride64(unsigned Opc) {
233   switch (Opc) {
234   case AMDGPU::DS_READ2ST64_B32:
235   case AMDGPU::DS_READ2ST64_B64:
236   case AMDGPU::DS_WRITE2ST64_B32:
237   case AMDGPU::DS_WRITE2ST64_B64:
238     return true;
239   default:
240     return false;
241   }
242 }
243 
244 bool SIInstrInfo::getMemOperandsWithOffsetWidth(
245     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
246     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
247     const TargetRegisterInfo *TRI) const {
248   if (!LdSt.mayLoadOrStore())
249     return false;
250 
251   unsigned Opc = LdSt.getOpcode();
252   OffsetIsScalable = false;
253   const MachineOperand *BaseOp, *OffsetOp;
254   int DataOpIdx;
255 
256   if (isDS(LdSt)) {
257     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
258     OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
259     if (OffsetOp) {
260       // Normal, single offset LDS instruction.
261       if (!BaseOp) {
262         // DS_CONSUME/DS_APPEND use M0 for the base address.
263         // TODO: find the implicit use operand for M0 and use that as BaseOp?
264         return false;
265       }
266       BaseOps.push_back(BaseOp);
267       Offset = OffsetOp->getImm();
268       // Get appropriate operand, and compute width accordingly.
269       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
270       if (DataOpIdx == -1)
271         DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
272       Width = getOpSize(LdSt, DataOpIdx);
273     } else {
274       // The 2 offset instructions use offset0 and offset1 instead. We can treat
275       // these as a load with a single offset if the 2 offsets are consecutive.
276       // We will use this for some partially aligned loads.
277       const MachineOperand *Offset0Op =
278           getNamedOperand(LdSt, AMDGPU::OpName::offset0);
279       const MachineOperand *Offset1Op =
280           getNamedOperand(LdSt, AMDGPU::OpName::offset1);
281 
282       unsigned Offset0 = Offset0Op->getImm();
283       unsigned Offset1 = Offset1Op->getImm();
284       if (Offset0 + 1 != Offset1)
285         return false;
286 
287       // Each of these offsets is in element sized units, so we need to convert
288       // to bytes of the individual reads.
289 
290       unsigned EltSize;
291       if (LdSt.mayLoad())
292         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, 0)) / 16;
293       else {
294         assert(LdSt.mayStore());
295         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
296         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, Data0Idx)) / 8;
297       }
298 
299       if (isStride64(Opc))
300         EltSize *= 64;
301 
302       BaseOps.push_back(BaseOp);
303       Offset = EltSize * Offset0;
304       // Get appropriate operand(s), and compute width accordingly.
305       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
306       if (DataOpIdx == -1) {
307         DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
308         Width = getOpSize(LdSt, DataOpIdx);
309         DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data1);
310         Width += getOpSize(LdSt, DataOpIdx);
311       } else {
312         Width = getOpSize(LdSt, DataOpIdx);
313       }
314     }
315     return true;
316   }
317 
318   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
319     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
320     if (SOffset && SOffset->isReg()) {
321       // We can only handle this if it's a stack access, as any other resource
322       // would require reporting multiple base registers.
323       const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
324       if (AddrReg && !AddrReg->isFI())
325         return false;
326 
327       const MachineOperand *RSrc = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
328       const SIMachineFunctionInfo *MFI
329         = LdSt.getParent()->getParent()->getInfo<SIMachineFunctionInfo>();
330       if (RSrc->getReg() != MFI->getScratchRSrcReg())
331         return false;
332 
333       const MachineOperand *OffsetImm =
334         getNamedOperand(LdSt, AMDGPU::OpName::offset);
335       BaseOps.push_back(RSrc);
336       BaseOps.push_back(SOffset);
337       Offset = OffsetImm->getImm();
338     } else {
339       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::srsrc);
340       if (!BaseOp) // e.g. BUFFER_WBINVL1_VOL
341         return false;
342       BaseOps.push_back(BaseOp);
343 
344       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
345       if (BaseOp)
346         BaseOps.push_back(BaseOp);
347 
348       const MachineOperand *OffsetImm =
349           getNamedOperand(LdSt, AMDGPU::OpName::offset);
350       Offset = OffsetImm->getImm();
351       if (SOffset) // soffset can be an inline immediate.
352         Offset += SOffset->getImm();
353     }
354     // Get appropriate operand, and compute width accordingly.
355     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
356     if (DataOpIdx == -1)
357       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
358     Width = getOpSize(LdSt, DataOpIdx);
359     return true;
360   }
361 
362   if (isMIMG(LdSt)) {
363     int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
364     BaseOps.push_back(&LdSt.getOperand(SRsrcIdx));
365     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
366     if (VAddr0Idx >= 0) {
367       // GFX10 possible NSA encoding.
368       for (int I = VAddr0Idx; I < SRsrcIdx; ++I)
369         BaseOps.push_back(&LdSt.getOperand(I));
370     } else {
371       BaseOps.push_back(getNamedOperand(LdSt, AMDGPU::OpName::vaddr));
372     }
373     Offset = 0;
374     // Get appropriate operand, and compute width accordingly.
375     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
376     Width = getOpSize(LdSt, DataOpIdx);
377     return true;
378   }
379 
380   if (isSMRD(LdSt)) {
381     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::sbase);
382     if (!BaseOp) // e.g. S_MEMTIME
383       return false;
384     BaseOps.push_back(BaseOp);
385     OffsetOp = getNamedOperand(LdSt, AMDGPU::OpName::offset);
386     Offset = OffsetOp ? OffsetOp->getImm() : 0;
387     // Get appropriate operand, and compute width accordingly.
388     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::sdst);
389     Width = getOpSize(LdSt, DataOpIdx);
390     return true;
391   }
392 
393   if (isFLAT(LdSt)) {
394     // Instructions have either vaddr or saddr or both or none.
395     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
396     if (BaseOp)
397       BaseOps.push_back(BaseOp);
398     BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::saddr);
399     if (BaseOp)
400       BaseOps.push_back(BaseOp);
401     Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
402     // Get appropriate operand, and compute width accordingly.
403     DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
404     if (DataOpIdx == -1)
405       DataOpIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
406     Width = getOpSize(LdSt, DataOpIdx);
407     return true;
408   }
409 
410   return false;
411 }
412 
413 static bool memOpsHaveSameBasePtr(const MachineInstr &MI1,
414                                   ArrayRef<const MachineOperand *> BaseOps1,
415                                   const MachineInstr &MI2,
416                                   ArrayRef<const MachineOperand *> BaseOps2) {
417   // Only examine the first "base" operand of each instruction, on the
418   // assumption that it represents the real base address of the memory access.
419   // Other operands are typically offsets or indices from this base address.
420   if (BaseOps1.front()->isIdenticalTo(*BaseOps2.front()))
421     return true;
422 
423   if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
424     return false;
425 
426   auto MO1 = *MI1.memoperands_begin();
427   auto MO2 = *MI2.memoperands_begin();
428   if (MO1->getAddrSpace() != MO2->getAddrSpace())
429     return false;
430 
431   auto Base1 = MO1->getValue();
432   auto Base2 = MO2->getValue();
433   if (!Base1 || !Base2)
434     return false;
435   Base1 = getUnderlyingObject(Base1);
436   Base2 = getUnderlyingObject(Base2);
437 
438   if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
439     return false;
440 
441   return Base1 == Base2;
442 }
443 
444 bool SIInstrInfo::shouldClusterMemOps(ArrayRef<const MachineOperand *> BaseOps1,
445                                       ArrayRef<const MachineOperand *> BaseOps2,
446                                       unsigned NumLoads,
447                                       unsigned NumBytes) const {
448   // If the mem ops (to be clustered) do not have the same base ptr, then they
449   // should not be clustered
450   if (!BaseOps1.empty() && !BaseOps2.empty()) {
451     const MachineInstr &FirstLdSt = *BaseOps1.front()->getParent();
452     const MachineInstr &SecondLdSt = *BaseOps2.front()->getParent();
453     if (!memOpsHaveSameBasePtr(FirstLdSt, BaseOps1, SecondLdSt, BaseOps2))
454       return false;
455   } else if (!BaseOps1.empty() || !BaseOps2.empty()) {
456     // If only one base op is empty, they do not have the same base ptr
457     return false;
458   }
459 
460   // In order to avoid regester pressure, on an average, the number of DWORDS
461   // loaded together by all clustered mem ops should not exceed 8. This is an
462   // empirical value based on certain observations and performance related
463   // experiments.
464   // The good thing about this heuristic is - it avoids clustering of too many
465   // sub-word loads, and also avoids clustering of wide loads. Below is the
466   // brief summary of how the heuristic behaves for various `LoadSize`.
467   // (1) 1 <= LoadSize <= 4: cluster at max 8 mem ops
468   // (2) 5 <= LoadSize <= 8: cluster at max 4 mem ops
469   // (3) 9 <= LoadSize <= 12: cluster at max 2 mem ops
470   // (4) 13 <= LoadSize <= 16: cluster at max 2 mem ops
471   // (5) LoadSize >= 17: do not cluster
472   const unsigned LoadSize = NumBytes / NumLoads;
473   const unsigned NumDWORDs = ((LoadSize + 3) / 4) * NumLoads;
474   return NumDWORDs <= 8;
475 }
476 
477 // FIXME: This behaves strangely. If, for example, you have 32 load + stores,
478 // the first 16 loads will be interleaved with the stores, and the next 16 will
479 // be clustered as expected. It should really split into 2 16 store batches.
480 //
481 // Loads are clustered until this returns false, rather than trying to schedule
482 // groups of stores. This also means we have to deal with saying different
483 // address space loads should be clustered, and ones which might cause bank
484 // conflicts.
485 //
486 // This might be deprecated so it might not be worth that much effort to fix.
487 bool SIInstrInfo::shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1,
488                                           int64_t Offset0, int64_t Offset1,
489                                           unsigned NumLoads) const {
490   assert(Offset1 > Offset0 &&
491          "Second offset should be larger than first offset!");
492   // If we have less than 16 loads in a row, and the offsets are within 64
493   // bytes, then schedule together.
494 
495   // A cacheline is 64 bytes (for global memory).
496   return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
497 }
498 
499 static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB,
500                               MachineBasicBlock::iterator MI,
501                               const DebugLoc &DL, MCRegister DestReg,
502                               MCRegister SrcReg, bool KillSrc,
503                               const char *Msg = "illegal SGPR to VGPR copy") {
504   MachineFunction *MF = MBB.getParent();
505   DiagnosticInfoUnsupported IllegalCopy(MF->getFunction(), Msg, DL, DS_Error);
506   LLVMContext &C = MF->getFunction().getContext();
507   C.diagnose(IllegalCopy);
508 
509   BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
510     .addReg(SrcReg, getKillRegState(KillSrc));
511 }
512 
513 /// Handle copying from SGPR to AGPR, or from AGPR to AGPR. It is not possible
514 /// to directly copy, so an intermediate VGPR needs to be used.
515 static void indirectCopyToAGPR(const SIInstrInfo &TII,
516                                MachineBasicBlock &MBB,
517                                MachineBasicBlock::iterator MI,
518                                const DebugLoc &DL, MCRegister DestReg,
519                                MCRegister SrcReg, bool KillSrc,
520                                RegScavenger &RS,
521                                Register ImpDefSuperReg = Register(),
522                                Register ImpUseSuperReg = Register()) {
523   const SIRegisterInfo &RI = TII.getRegisterInfo();
524 
525   assert(AMDGPU::SReg_32RegClass.contains(SrcReg) ||
526          AMDGPU::AGPR_32RegClass.contains(SrcReg));
527 
528   // First try to find defining accvgpr_write to avoid temporary registers.
529   for (auto Def = MI, E = MBB.begin(); Def != E; ) {
530     --Def;
531     if (!Def->definesRegister(SrcReg, &RI))
532       continue;
533     if (Def->getOpcode() != AMDGPU::V_ACCVGPR_WRITE_B32_e64)
534       break;
535 
536     MachineOperand &DefOp = Def->getOperand(1);
537     assert(DefOp.isReg() || DefOp.isImm());
538 
539     if (DefOp.isReg()) {
540       // Check that register source operand if not clobbered before MI.
541       // Immediate operands are always safe to propagate.
542       bool SafeToPropagate = true;
543       for (auto I = Def; I != MI && SafeToPropagate; ++I)
544         if (I->modifiesRegister(DefOp.getReg(), &RI))
545           SafeToPropagate = false;
546 
547       if (!SafeToPropagate)
548         break;
549 
550       DefOp.setIsKill(false);
551     }
552 
553     MachineInstrBuilder Builder =
554       BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
555       .add(DefOp);
556     if (ImpDefSuperReg)
557       Builder.addReg(ImpDefSuperReg, RegState::Define | RegState::Implicit);
558 
559     if (ImpUseSuperReg) {
560       Builder.addReg(ImpUseSuperReg,
561                      getKillRegState(KillSrc) | RegState::Implicit);
562     }
563 
564     return;
565   }
566 
567   RS.enterBasicBlock(MBB);
568   RS.forward(MI);
569 
570   // Ideally we want to have three registers for a long reg_sequence copy
571   // to hide 2 waitstates between v_mov_b32 and accvgpr_write.
572   unsigned MaxVGPRs = RI.getRegPressureLimit(&AMDGPU::VGPR_32RegClass,
573                                              *MBB.getParent());
574 
575   // Registers in the sequence are allocated contiguously so we can just
576   // use register number to pick one of three round-robin temps.
577   unsigned RegNo = DestReg % 3;
578   Register Tmp = RS.scavengeRegister(&AMDGPU::VGPR_32RegClass, 0);
579   if (!Tmp)
580     report_fatal_error("Cannot scavenge VGPR to copy to AGPR");
581   RS.setRegUsed(Tmp);
582 
583   if (!TII.getSubtarget().hasGFX90AInsts()) {
584     // Only loop through if there are any free registers left, otherwise
585     // scavenger may report a fatal error without emergency spill slot
586     // or spill with the slot.
587     while (RegNo-- && RS.FindUnusedReg(&AMDGPU::VGPR_32RegClass)) {
588       Register Tmp2 = RS.scavengeRegister(&AMDGPU::VGPR_32RegClass, 0);
589       if (!Tmp2 || RI.getHWRegIndex(Tmp2) >= MaxVGPRs)
590         break;
591       Tmp = Tmp2;
592       RS.setRegUsed(Tmp);
593     }
594   }
595 
596   // Insert copy to temporary VGPR.
597   unsigned TmpCopyOp = AMDGPU::V_MOV_B32_e32;
598   if (AMDGPU::AGPR_32RegClass.contains(SrcReg)) {
599     TmpCopyOp = AMDGPU::V_ACCVGPR_READ_B32_e64;
600   } else {
601     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
602   }
603 
604   MachineInstrBuilder UseBuilder = BuildMI(MBB, MI, DL, TII.get(TmpCopyOp), Tmp)
605     .addReg(SrcReg, getKillRegState(KillSrc));
606   if (ImpUseSuperReg) {
607     UseBuilder.addReg(ImpUseSuperReg,
608                       getKillRegState(KillSrc) | RegState::Implicit);
609   }
610 
611   MachineInstrBuilder DefBuilder
612     = BuildMI(MBB, MI, DL, TII.get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
613     .addReg(Tmp, RegState::Kill);
614 
615   if (ImpDefSuperReg)
616     DefBuilder.addReg(ImpDefSuperReg, RegState::Define | RegState::Implicit);
617 }
618 
619 static void expandSGPRCopy(const SIInstrInfo &TII, MachineBasicBlock &MBB,
620                            MachineBasicBlock::iterator MI, const DebugLoc &DL,
621                            MCRegister DestReg, MCRegister SrcReg, bool KillSrc,
622                            const TargetRegisterClass *RC, bool Forward) {
623   const SIRegisterInfo &RI = TII.getRegisterInfo();
624   ArrayRef<int16_t> BaseIndices = RI.getRegSplitParts(RC, 4);
625   MachineBasicBlock::iterator I = MI;
626   MachineInstr *FirstMI = nullptr, *LastMI = nullptr;
627 
628   for (unsigned Idx = 0; Idx < BaseIndices.size(); ++Idx) {
629     int16_t SubIdx = BaseIndices[Idx];
630     Register Reg = RI.getSubReg(DestReg, SubIdx);
631     unsigned Opcode = AMDGPU::S_MOV_B32;
632 
633     // Is SGPR aligned? If so try to combine with next.
634     Register Src = RI.getSubReg(SrcReg, SubIdx);
635     bool AlignedDest = ((Reg - AMDGPU::SGPR0) % 2) == 0;
636     bool AlignedSrc = ((Src - AMDGPU::SGPR0) % 2) == 0;
637     if (AlignedDest && AlignedSrc && (Idx + 1 < BaseIndices.size())) {
638       // Can use SGPR64 copy
639       unsigned Channel = RI.getChannelFromSubReg(SubIdx);
640       SubIdx = RI.getSubRegFromChannel(Channel, 2);
641       Opcode = AMDGPU::S_MOV_B64;
642       Idx++;
643     }
644 
645     LastMI = BuildMI(MBB, I, DL, TII.get(Opcode), RI.getSubReg(DestReg, SubIdx))
646                  .addReg(RI.getSubReg(SrcReg, SubIdx))
647                  .addReg(SrcReg, RegState::Implicit);
648 
649     if (!FirstMI)
650       FirstMI = LastMI;
651 
652     if (!Forward)
653       I--;
654   }
655 
656   assert(FirstMI && LastMI);
657   if (!Forward)
658     std::swap(FirstMI, LastMI);
659 
660   FirstMI->addOperand(
661       MachineOperand::CreateReg(DestReg, true /*IsDef*/, true /*IsImp*/));
662 
663   if (KillSrc)
664     LastMI->addRegisterKilled(SrcReg, &RI);
665 }
666 
667 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
668                               MachineBasicBlock::iterator MI,
669                               const DebugLoc &DL, MCRegister DestReg,
670                               MCRegister SrcReg, bool KillSrc) const {
671   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
672 
673   // FIXME: This is hack to resolve copies between 16 bit and 32 bit
674   // registers until all patterns are fixed.
675   if (Fix16BitCopies &&
676       ((RI.getRegSizeInBits(*RC) == 16) ^
677        (RI.getRegSizeInBits(*RI.getPhysRegClass(SrcReg)) == 16))) {
678     MCRegister &RegToFix = (RI.getRegSizeInBits(*RC) == 16) ? DestReg : SrcReg;
679     MCRegister Super = RI.get32BitRegister(RegToFix);
680     assert(RI.getSubReg(Super, AMDGPU::lo16) == RegToFix);
681     RegToFix = Super;
682 
683     if (DestReg == SrcReg) {
684       // Insert empty bundle since ExpandPostRA expects an instruction here.
685       BuildMI(MBB, MI, DL, get(AMDGPU::BUNDLE));
686       return;
687     }
688 
689     RC = RI.getPhysRegClass(DestReg);
690   }
691 
692   if (RC == &AMDGPU::VGPR_32RegClass) {
693     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
694            AMDGPU::SReg_32RegClass.contains(SrcReg) ||
695            AMDGPU::AGPR_32RegClass.contains(SrcReg));
696     unsigned Opc = AMDGPU::AGPR_32RegClass.contains(SrcReg) ?
697                      AMDGPU::V_ACCVGPR_READ_B32_e64 : AMDGPU::V_MOV_B32_e32;
698     BuildMI(MBB, MI, DL, get(Opc), DestReg)
699       .addReg(SrcReg, getKillRegState(KillSrc));
700     return;
701   }
702 
703   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
704       RC == &AMDGPU::SReg_32RegClass) {
705     if (SrcReg == AMDGPU::SCC) {
706       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
707           .addImm(1)
708           .addImm(0);
709       return;
710     }
711 
712     if (DestReg == AMDGPU::VCC_LO) {
713       if (AMDGPU::SReg_32RegClass.contains(SrcReg)) {
714         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), AMDGPU::VCC_LO)
715           .addReg(SrcReg, getKillRegState(KillSrc));
716       } else {
717         // FIXME: Hack until VReg_1 removed.
718         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
719         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
720           .addImm(0)
721           .addReg(SrcReg, getKillRegState(KillSrc));
722       }
723 
724       return;
725     }
726 
727     if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
728       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
729       return;
730     }
731 
732     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
733             .addReg(SrcReg, getKillRegState(KillSrc));
734     return;
735   }
736 
737   if (RC == &AMDGPU::SReg_64RegClass) {
738     if (SrcReg == AMDGPU::SCC) {
739       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B64), DestReg)
740           .addImm(1)
741           .addImm(0);
742       return;
743     }
744 
745     if (DestReg == AMDGPU::VCC) {
746       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
747         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
748           .addReg(SrcReg, getKillRegState(KillSrc));
749       } else {
750         // FIXME: Hack until VReg_1 removed.
751         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
752         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
753           .addImm(0)
754           .addReg(SrcReg, getKillRegState(KillSrc));
755       }
756 
757       return;
758     }
759 
760     if (!AMDGPU::SReg_64RegClass.contains(SrcReg)) {
761       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
762       return;
763     }
764 
765     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
766             .addReg(SrcReg, getKillRegState(KillSrc));
767     return;
768   }
769 
770   if (DestReg == AMDGPU::SCC) {
771     // Copying 64-bit or 32-bit sources to SCC barely makes sense,
772     // but SelectionDAG emits such copies for i1 sources.
773     if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
774       // This copy can only be produced by patterns
775       // with explicit SCC, which are known to be enabled
776       // only for subtargets with S_CMP_LG_U64 present.
777       assert(ST.hasScalarCompareEq64());
778       BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U64))
779           .addReg(SrcReg, getKillRegState(KillSrc))
780           .addImm(0);
781     } else {
782       assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
783       BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
784           .addReg(SrcReg, getKillRegState(KillSrc))
785           .addImm(0);
786     }
787 
788     return;
789   }
790 
791   if (RC == &AMDGPU::AGPR_32RegClass) {
792     if (AMDGPU::VGPR_32RegClass.contains(SrcReg)) {
793       BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg)
794         .addReg(SrcReg, getKillRegState(KillSrc));
795       return;
796     }
797 
798     if (AMDGPU::AGPR_32RegClass.contains(SrcReg) && ST.hasGFX90AInsts()) {
799       BuildMI(MBB, MI, DL, get(AMDGPU::V_ACCVGPR_MOV_B32), DestReg)
800         .addReg(SrcReg, getKillRegState(KillSrc));
801       return;
802     }
803 
804     // FIXME: Pass should maintain scavenger to avoid scan through the block on
805     // every AGPR spill.
806     RegScavenger RS;
807     indirectCopyToAGPR(*this, MBB, MI, DL, DestReg, SrcReg, KillSrc, RS);
808     return;
809   }
810 
811   const unsigned Size = RI.getRegSizeInBits(*RC);
812   if (Size == 16) {
813     assert(AMDGPU::VGPR_LO16RegClass.contains(SrcReg) ||
814            AMDGPU::VGPR_HI16RegClass.contains(SrcReg) ||
815            AMDGPU::SReg_LO16RegClass.contains(SrcReg) ||
816            AMDGPU::AGPR_LO16RegClass.contains(SrcReg));
817 
818     bool IsSGPRDst = AMDGPU::SReg_LO16RegClass.contains(DestReg);
819     bool IsSGPRSrc = AMDGPU::SReg_LO16RegClass.contains(SrcReg);
820     bool IsAGPRDst = AMDGPU::AGPR_LO16RegClass.contains(DestReg);
821     bool IsAGPRSrc = AMDGPU::AGPR_LO16RegClass.contains(SrcReg);
822     bool DstLow = AMDGPU::VGPR_LO16RegClass.contains(DestReg) ||
823                   AMDGPU::SReg_LO16RegClass.contains(DestReg) ||
824                   AMDGPU::AGPR_LO16RegClass.contains(DestReg);
825     bool SrcLow = AMDGPU::VGPR_LO16RegClass.contains(SrcReg) ||
826                   AMDGPU::SReg_LO16RegClass.contains(SrcReg) ||
827                   AMDGPU::AGPR_LO16RegClass.contains(SrcReg);
828     MCRegister NewDestReg = RI.get32BitRegister(DestReg);
829     MCRegister NewSrcReg = RI.get32BitRegister(SrcReg);
830 
831     if (IsSGPRDst) {
832       if (!IsSGPRSrc) {
833         reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
834         return;
835       }
836 
837       BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), NewDestReg)
838         .addReg(NewSrcReg, getKillRegState(KillSrc));
839       return;
840     }
841 
842     if (IsAGPRDst || IsAGPRSrc) {
843       if (!DstLow || !SrcLow) {
844         reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
845                           "Cannot use hi16 subreg with an AGPR!");
846       }
847 
848       copyPhysReg(MBB, MI, DL, NewDestReg, NewSrcReg, KillSrc);
849       return;
850     }
851 
852     if (IsSGPRSrc && !ST.hasSDWAScalar()) {
853       if (!DstLow || !SrcLow) {
854         reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc,
855                           "Cannot use hi16 subreg on VI!");
856       }
857 
858       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), NewDestReg)
859         .addReg(NewSrcReg, getKillRegState(KillSrc));
860       return;
861     }
862 
863     auto MIB = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_sdwa), NewDestReg)
864       .addImm(0) // src0_modifiers
865       .addReg(NewSrcReg)
866       .addImm(0) // clamp
867       .addImm(DstLow ? AMDGPU::SDWA::SdwaSel::WORD_0
868                      : AMDGPU::SDWA::SdwaSel::WORD_1)
869       .addImm(AMDGPU::SDWA::DstUnused::UNUSED_PRESERVE)
870       .addImm(SrcLow ? AMDGPU::SDWA::SdwaSel::WORD_0
871                      : AMDGPU::SDWA::SdwaSel::WORD_1)
872       .addReg(NewDestReg, RegState::Implicit | RegState::Undef);
873     // First implicit operand is $exec.
874     MIB->tieOperands(0, MIB->getNumOperands() - 1);
875     return;
876   }
877 
878   const TargetRegisterClass *SrcRC = RI.getPhysRegClass(SrcReg);
879   if (RC == RI.getVGPR64Class() && (SrcRC == RC || RI.isSGPRClass(SrcRC))) {
880     if (ST.hasPackedFP32Ops()) {
881       BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DestReg)
882         .addImm(SISrcMods::OP_SEL_1)
883         .addReg(SrcReg)
884         .addImm(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1)
885         .addReg(SrcReg)
886         .addImm(0) // op_sel_lo
887         .addImm(0) // op_sel_hi
888         .addImm(0) // neg_lo
889         .addImm(0) // neg_hi
890         .addImm(0) // clamp
891         .addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
892       return;
893     }
894   }
895 
896   const bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
897   if (RI.isSGPRClass(RC)) {
898     if (!RI.isSGPRClass(SrcRC)) {
899       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
900       return;
901     }
902     expandSGPRCopy(*this, MBB, MI, DL, DestReg, SrcReg, KillSrc, RC, Forward);
903     return;
904   }
905 
906   unsigned EltSize = 4;
907   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
908   if (RI.hasAGPRs(RC)) {
909     Opcode = (RI.hasVGPRs(SrcRC)) ?
910       AMDGPU::V_ACCVGPR_WRITE_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
911   } else if (RI.hasVGPRs(RC) && RI.hasAGPRs(SrcRC)) {
912     Opcode = AMDGPU::V_ACCVGPR_READ_B32_e64;
913   } else if ((Size % 64 == 0) && RI.hasVGPRs(RC) &&
914              (RI.isProperlyAlignedRC(*RC) &&
915               (SrcRC == RC || RI.isSGPRClass(SrcRC)))) {
916     // TODO: In 96-bit case, could do a 64-bit mov and then a 32-bit mov.
917     if (ST.hasPackedFP32Ops()) {
918       Opcode = AMDGPU::V_PK_MOV_B32;
919       EltSize = 8;
920     }
921   }
922 
923   // For the cases where we need an intermediate instruction/temporary register
924   // (destination is an AGPR), we need a scavenger.
925   //
926   // FIXME: The pass should maintain this for us so we don't have to re-scan the
927   // whole block for every handled copy.
928   std::unique_ptr<RegScavenger> RS;
929   if (Opcode == AMDGPU::INSTRUCTION_LIST_END)
930     RS.reset(new RegScavenger());
931 
932   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
933 
934   // If there is an overlap, we can't kill the super-register on the last
935   // instruction, since it will also kill the components made live by this def.
936   const bool CanKillSuperReg = KillSrc && !RI.regsOverlap(SrcReg, DestReg);
937 
938   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
939     unsigned SubIdx;
940     if (Forward)
941       SubIdx = SubIndices[Idx];
942     else
943       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
944 
945     bool UseKill = CanKillSuperReg && Idx == SubIndices.size() - 1;
946 
947     if (Opcode == AMDGPU::INSTRUCTION_LIST_END) {
948       Register ImpDefSuper = Idx == 0 ? Register(DestReg) : Register();
949       Register ImpUseSuper = SrcReg;
950       indirectCopyToAGPR(*this, MBB, MI, DL, RI.getSubReg(DestReg, SubIdx),
951                          RI.getSubReg(SrcReg, SubIdx), UseKill, *RS,
952                          ImpDefSuper, ImpUseSuper);
953     } else if (Opcode == AMDGPU::V_PK_MOV_B32) {
954       Register DstSubReg = RI.getSubReg(DestReg, SubIdx);
955       Register SrcSubReg = RI.getSubReg(SrcReg, SubIdx);
956       MachineInstrBuilder MIB =
957         BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), DstSubReg)
958         .addImm(SISrcMods::OP_SEL_1)
959         .addReg(SrcSubReg)
960         .addImm(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1)
961         .addReg(SrcSubReg)
962         .addImm(0) // op_sel_lo
963         .addImm(0) // op_sel_hi
964         .addImm(0) // neg_lo
965         .addImm(0) // neg_hi
966         .addImm(0) // clamp
967         .addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
968       if (Idx == 0)
969         MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
970     } else {
971       MachineInstrBuilder Builder =
972         BuildMI(MBB, MI, DL, get(Opcode), RI.getSubReg(DestReg, SubIdx))
973         .addReg(RI.getSubReg(SrcReg, SubIdx));
974       if (Idx == 0)
975         Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
976 
977       Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
978     }
979   }
980 }
981 
982 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
983   int NewOpc;
984 
985   // Try to map original to commuted opcode
986   NewOpc = AMDGPU::getCommuteRev(Opcode);
987   if (NewOpc != -1)
988     // Check if the commuted (REV) opcode exists on the target.
989     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
990 
991   // Try to map commuted to original opcode
992   NewOpc = AMDGPU::getCommuteOrig(Opcode);
993   if (NewOpc != -1)
994     // Check if the original (non-REV) opcode exists on the target.
995     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
996 
997   return Opcode;
998 }
999 
1000 void SIInstrInfo::materializeImmediate(MachineBasicBlock &MBB,
1001                                        MachineBasicBlock::iterator MI,
1002                                        const DebugLoc &DL, unsigned DestReg,
1003                                        int64_t Value) const {
1004   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1005   const TargetRegisterClass *RegClass = MRI.getRegClass(DestReg);
1006   if (RegClass == &AMDGPU::SReg_32RegClass ||
1007       RegClass == &AMDGPU::SGPR_32RegClass ||
1008       RegClass == &AMDGPU::SReg_32_XM0RegClass ||
1009       RegClass == &AMDGPU::SReg_32_XM0_XEXECRegClass) {
1010     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
1011       .addImm(Value);
1012     return;
1013   }
1014 
1015   if (RegClass == &AMDGPU::SReg_64RegClass ||
1016       RegClass == &AMDGPU::SGPR_64RegClass ||
1017       RegClass == &AMDGPU::SReg_64_XEXECRegClass) {
1018     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
1019       .addImm(Value);
1020     return;
1021   }
1022 
1023   if (RegClass == &AMDGPU::VGPR_32RegClass) {
1024     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
1025       .addImm(Value);
1026     return;
1027   }
1028   if (RegClass->hasSuperClassEq(&AMDGPU::VReg_64RegClass)) {
1029     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO), DestReg)
1030       .addImm(Value);
1031     return;
1032   }
1033 
1034   unsigned EltSize = 4;
1035   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1036   if (RI.isSGPRClass(RegClass)) {
1037     if (RI.getRegSizeInBits(*RegClass) > 32) {
1038       Opcode =  AMDGPU::S_MOV_B64;
1039       EltSize = 8;
1040     } else {
1041       Opcode = AMDGPU::S_MOV_B32;
1042       EltSize = 4;
1043     }
1044   }
1045 
1046   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RegClass, EltSize);
1047   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
1048     int64_t IdxValue = Idx == 0 ? Value : 0;
1049 
1050     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
1051       get(Opcode), RI.getSubReg(DestReg, SubIndices[Idx]));
1052     Builder.addImm(IdxValue);
1053   }
1054 }
1055 
1056 const TargetRegisterClass *
1057 SIInstrInfo::getPreferredSelectRegClass(unsigned Size) const {
1058   return &AMDGPU::VGPR_32RegClass;
1059 }
1060 
1061 void SIInstrInfo::insertVectorSelect(MachineBasicBlock &MBB,
1062                                      MachineBasicBlock::iterator I,
1063                                      const DebugLoc &DL, Register DstReg,
1064                                      ArrayRef<MachineOperand> Cond,
1065                                      Register TrueReg,
1066                                      Register FalseReg) const {
1067   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1068   const TargetRegisterClass *BoolXExecRC =
1069     RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
1070   assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass &&
1071          "Not a VGPR32 reg");
1072 
1073   if (Cond.size() == 1) {
1074     Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1075     BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1076       .add(Cond[0]);
1077     BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1078       .addImm(0)
1079       .addReg(FalseReg)
1080       .addImm(0)
1081       .addReg(TrueReg)
1082       .addReg(SReg);
1083   } else if (Cond.size() == 2) {
1084     assert(Cond[0].isImm() && "Cond[0] is not an immediate");
1085     switch (Cond[0].getImm()) {
1086     case SIInstrInfo::SCC_TRUE: {
1087       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1088       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1089                                             : AMDGPU::S_CSELECT_B64), SReg)
1090         .addImm(1)
1091         .addImm(0);
1092       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1093         .addImm(0)
1094         .addReg(FalseReg)
1095         .addImm(0)
1096         .addReg(TrueReg)
1097         .addReg(SReg);
1098       break;
1099     }
1100     case SIInstrInfo::SCC_FALSE: {
1101       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1102       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1103                                             : AMDGPU::S_CSELECT_B64), SReg)
1104         .addImm(0)
1105         .addImm(1);
1106       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1107         .addImm(0)
1108         .addReg(FalseReg)
1109         .addImm(0)
1110         .addReg(TrueReg)
1111         .addReg(SReg);
1112       break;
1113     }
1114     case SIInstrInfo::VCCNZ: {
1115       MachineOperand RegOp = Cond[1];
1116       RegOp.setImplicit(false);
1117       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1118       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1119         .add(RegOp);
1120       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1121           .addImm(0)
1122           .addReg(FalseReg)
1123           .addImm(0)
1124           .addReg(TrueReg)
1125           .addReg(SReg);
1126       break;
1127     }
1128     case SIInstrInfo::VCCZ: {
1129       MachineOperand RegOp = Cond[1];
1130       RegOp.setImplicit(false);
1131       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1132       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
1133         .add(RegOp);
1134       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1135           .addImm(0)
1136           .addReg(TrueReg)
1137           .addImm(0)
1138           .addReg(FalseReg)
1139           .addReg(SReg);
1140       break;
1141     }
1142     case SIInstrInfo::EXECNZ: {
1143       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1144       Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
1145       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1146                                             : AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
1147         .addImm(0);
1148       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1149                                             : AMDGPU::S_CSELECT_B64), SReg)
1150         .addImm(1)
1151         .addImm(0);
1152       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1153         .addImm(0)
1154         .addReg(FalseReg)
1155         .addImm(0)
1156         .addReg(TrueReg)
1157         .addReg(SReg);
1158       break;
1159     }
1160     case SIInstrInfo::EXECZ: {
1161       Register SReg = MRI.createVirtualRegister(BoolXExecRC);
1162       Register SReg2 = MRI.createVirtualRegister(RI.getBoolRC());
1163       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1164                                             : AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
1165         .addImm(0);
1166       BuildMI(MBB, I, DL, get(ST.isWave32() ? AMDGPU::S_CSELECT_B32
1167                                             : AMDGPU::S_CSELECT_B64), SReg)
1168         .addImm(0)
1169         .addImm(1);
1170       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
1171         .addImm(0)
1172         .addReg(FalseReg)
1173         .addImm(0)
1174         .addReg(TrueReg)
1175         .addReg(SReg);
1176       llvm_unreachable("Unhandled branch predicate EXECZ");
1177       break;
1178     }
1179     default:
1180       llvm_unreachable("invalid branch predicate");
1181     }
1182   } else {
1183     llvm_unreachable("Can only handle Cond size 1 or 2");
1184   }
1185 }
1186 
1187 Register SIInstrInfo::insertEQ(MachineBasicBlock *MBB,
1188                                MachineBasicBlock::iterator I,
1189                                const DebugLoc &DL,
1190                                Register SrcReg, int Value) const {
1191   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1192   Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
1193   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg)
1194     .addImm(Value)
1195     .addReg(SrcReg);
1196 
1197   return Reg;
1198 }
1199 
1200 Register SIInstrInfo::insertNE(MachineBasicBlock *MBB,
1201                                MachineBasicBlock::iterator I,
1202                                const DebugLoc &DL,
1203                                Register SrcReg, int Value) const {
1204   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1205   Register Reg = MRI.createVirtualRegister(RI.getBoolRC());
1206   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg)
1207     .addImm(Value)
1208     .addReg(SrcReg);
1209 
1210   return Reg;
1211 }
1212 
1213 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
1214 
1215   if (RI.hasAGPRs(DstRC))
1216     return AMDGPU::COPY;
1217   if (RI.getRegSizeInBits(*DstRC) == 32) {
1218     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1219   } else if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC)) {
1220     return AMDGPU::S_MOV_B64;
1221   } else if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC)) {
1222     return  AMDGPU::V_MOV_B64_PSEUDO;
1223   }
1224   return AMDGPU::COPY;
1225 }
1226 
1227 const MCInstrDesc &
1228 SIInstrInfo::getIndirectGPRIDXPseudo(unsigned VecSize,
1229                                      bool IsIndirectSrc) const {
1230   if (IsIndirectSrc) {
1231     if (VecSize <= 32) // 4 bytes
1232       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1);
1233     if (VecSize <= 64) // 8 bytes
1234       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2);
1235     if (VecSize <= 96) // 12 bytes
1236       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3);
1237     if (VecSize <= 128) // 16 bytes
1238       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4);
1239     if (VecSize <= 160) // 20 bytes
1240       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5);
1241     if (VecSize <= 256) // 32 bytes
1242       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8);
1243     if (VecSize <= 512) // 64 bytes
1244       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16);
1245     if (VecSize <= 1024) // 128 bytes
1246       return get(AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32);
1247 
1248     llvm_unreachable("unsupported size for IndirectRegReadGPRIDX pseudos");
1249   }
1250 
1251   if (VecSize <= 32) // 4 bytes
1252     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1);
1253   if (VecSize <= 64) // 8 bytes
1254     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2);
1255   if (VecSize <= 96) // 12 bytes
1256     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3);
1257   if (VecSize <= 128) // 16 bytes
1258     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4);
1259   if (VecSize <= 160) // 20 bytes
1260     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5);
1261   if (VecSize <= 256) // 32 bytes
1262     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8);
1263   if (VecSize <= 512) // 64 bytes
1264     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16);
1265   if (VecSize <= 1024) // 128 bytes
1266     return get(AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32);
1267 
1268   llvm_unreachable("unsupported size for IndirectRegWriteGPRIDX pseudos");
1269 }
1270 
1271 static unsigned getIndirectVGPRWriteMovRelPseudoOpc(unsigned VecSize) {
1272   if (VecSize <= 32) // 4 bytes
1273     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1274   if (VecSize <= 64) // 8 bytes
1275     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1276   if (VecSize <= 96) // 12 bytes
1277     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1278   if (VecSize <= 128) // 16 bytes
1279     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1280   if (VecSize <= 160) // 20 bytes
1281     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1282   if (VecSize <= 256) // 32 bytes
1283     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1284   if (VecSize <= 512) // 64 bytes
1285     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1286   if (VecSize <= 1024) // 128 bytes
1287     return AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1288 
1289   llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1290 }
1291 
1292 static unsigned getIndirectSGPRWriteMovRelPseudo32(unsigned VecSize) {
1293   if (VecSize <= 32) // 4 bytes
1294     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1;
1295   if (VecSize <= 64) // 8 bytes
1296     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2;
1297   if (VecSize <= 96) // 12 bytes
1298     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3;
1299   if (VecSize <= 128) // 16 bytes
1300     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4;
1301   if (VecSize <= 160) // 20 bytes
1302     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5;
1303   if (VecSize <= 256) // 32 bytes
1304     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8;
1305   if (VecSize <= 512) // 64 bytes
1306     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16;
1307   if (VecSize <= 1024) // 128 bytes
1308     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32;
1309 
1310   llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1311 }
1312 
1313 static unsigned getIndirectSGPRWriteMovRelPseudo64(unsigned VecSize) {
1314   if (VecSize <= 64) // 8 bytes
1315     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1;
1316   if (VecSize <= 128) // 16 bytes
1317     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2;
1318   if (VecSize <= 256) // 32 bytes
1319     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4;
1320   if (VecSize <= 512) // 64 bytes
1321     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8;
1322   if (VecSize <= 1024) // 128 bytes
1323     return AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16;
1324 
1325   llvm_unreachable("unsupported size for IndirectRegWrite pseudos");
1326 }
1327 
1328 const MCInstrDesc &
1329 SIInstrInfo::getIndirectRegWriteMovRelPseudo(unsigned VecSize, unsigned EltSize,
1330                                              bool IsSGPR) const {
1331   if (IsSGPR) {
1332     switch (EltSize) {
1333     case 32:
1334       return get(getIndirectSGPRWriteMovRelPseudo32(VecSize));
1335     case 64:
1336       return get(getIndirectSGPRWriteMovRelPseudo64(VecSize));
1337     default:
1338       llvm_unreachable("invalid reg indexing elt size");
1339     }
1340   }
1341 
1342   assert(EltSize == 32 && "invalid reg indexing elt size");
1343   return get(getIndirectVGPRWriteMovRelPseudoOpc(VecSize));
1344 }
1345 
1346 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
1347   switch (Size) {
1348   case 4:
1349     return AMDGPU::SI_SPILL_S32_SAVE;
1350   case 8:
1351     return AMDGPU::SI_SPILL_S64_SAVE;
1352   case 12:
1353     return AMDGPU::SI_SPILL_S96_SAVE;
1354   case 16:
1355     return AMDGPU::SI_SPILL_S128_SAVE;
1356   case 20:
1357     return AMDGPU::SI_SPILL_S160_SAVE;
1358   case 24:
1359     return AMDGPU::SI_SPILL_S192_SAVE;
1360   case 32:
1361     return AMDGPU::SI_SPILL_S256_SAVE;
1362   case 64:
1363     return AMDGPU::SI_SPILL_S512_SAVE;
1364   case 128:
1365     return AMDGPU::SI_SPILL_S1024_SAVE;
1366   default:
1367     llvm_unreachable("unknown register size");
1368   }
1369 }
1370 
1371 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
1372   switch (Size) {
1373   case 4:
1374     return AMDGPU::SI_SPILL_V32_SAVE;
1375   case 8:
1376     return AMDGPU::SI_SPILL_V64_SAVE;
1377   case 12:
1378     return AMDGPU::SI_SPILL_V96_SAVE;
1379   case 16:
1380     return AMDGPU::SI_SPILL_V128_SAVE;
1381   case 20:
1382     return AMDGPU::SI_SPILL_V160_SAVE;
1383   case 24:
1384     return AMDGPU::SI_SPILL_V192_SAVE;
1385   case 32:
1386     return AMDGPU::SI_SPILL_V256_SAVE;
1387   case 64:
1388     return AMDGPU::SI_SPILL_V512_SAVE;
1389   case 128:
1390     return AMDGPU::SI_SPILL_V1024_SAVE;
1391   default:
1392     llvm_unreachable("unknown register size");
1393   }
1394 }
1395 
1396 static unsigned getAGPRSpillSaveOpcode(unsigned Size) {
1397   switch (Size) {
1398   case 4:
1399     return AMDGPU::SI_SPILL_A32_SAVE;
1400   case 8:
1401     return AMDGPU::SI_SPILL_A64_SAVE;
1402   case 12:
1403     return AMDGPU::SI_SPILL_A96_SAVE;
1404   case 16:
1405     return AMDGPU::SI_SPILL_A128_SAVE;
1406   case 20:
1407     return AMDGPU::SI_SPILL_A160_SAVE;
1408   case 24:
1409     return AMDGPU::SI_SPILL_A192_SAVE;
1410   case 32:
1411     return AMDGPU::SI_SPILL_A256_SAVE;
1412   case 64:
1413     return AMDGPU::SI_SPILL_A512_SAVE;
1414   case 128:
1415     return AMDGPU::SI_SPILL_A1024_SAVE;
1416   default:
1417     llvm_unreachable("unknown register size");
1418   }
1419 }
1420 
1421 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
1422                                       MachineBasicBlock::iterator MI,
1423                                       Register SrcReg, bool isKill,
1424                                       int FrameIndex,
1425                                       const TargetRegisterClass *RC,
1426                                       const TargetRegisterInfo *TRI) const {
1427   MachineFunction *MF = MBB.getParent();
1428   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1429   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1430   const DebugLoc &DL = MBB.findDebugLoc(MI);
1431 
1432   MachinePointerInfo PtrInfo
1433     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1434   MachineMemOperand *MMO = MF->getMachineMemOperand(
1435       PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FrameIndex),
1436       FrameInfo.getObjectAlign(FrameIndex));
1437   unsigned SpillSize = TRI->getSpillSize(*RC);
1438 
1439   if (RI.isSGPRClass(RC)) {
1440     MFI->setHasSpilledSGPRs();
1441     assert(SrcReg != AMDGPU::M0 && "m0 should not be spilled");
1442     assert(SrcReg != AMDGPU::EXEC_LO && SrcReg != AMDGPU::EXEC_HI &&
1443            SrcReg != AMDGPU::EXEC && "exec should not be spilled");
1444 
1445     // We are only allowed to create one new instruction when spilling
1446     // registers, so we need to use pseudo instruction for spilling SGPRs.
1447     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(SpillSize));
1448 
1449     // The SGPR spill/restore instructions only work on number sgprs, so we need
1450     // to make sure we are using the correct register class.
1451     if (SrcReg.isVirtual() && SpillSize == 4) {
1452       MachineRegisterInfo &MRI = MF->getRegInfo();
1453       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1454     }
1455 
1456     BuildMI(MBB, MI, DL, OpDesc)
1457       .addReg(SrcReg, getKillRegState(isKill)) // data
1458       .addFrameIndex(FrameIndex)               // addr
1459       .addMemOperand(MMO)
1460       .addReg(MFI->getStackPtrOffsetReg(), RegState::Implicit);
1461 
1462     if (RI.spillSGPRToVGPR())
1463       FrameInfo.setStackID(FrameIndex, TargetStackID::SGPRSpill);
1464     return;
1465   }
1466 
1467   unsigned Opcode = RI.hasAGPRs(RC) ? getAGPRSpillSaveOpcode(SpillSize)
1468                                     : getVGPRSpillSaveOpcode(SpillSize);
1469   MFI->setHasSpilledVGPRs();
1470 
1471   BuildMI(MBB, MI, DL, get(Opcode))
1472     .addReg(SrcReg, getKillRegState(isKill)) // data
1473     .addFrameIndex(FrameIndex)               // addr
1474     .addReg(MFI->getStackPtrOffsetReg())     // scratch_offset
1475     .addImm(0)                               // offset
1476     .addMemOperand(MMO);
1477 }
1478 
1479 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
1480   switch (Size) {
1481   case 4:
1482     return AMDGPU::SI_SPILL_S32_RESTORE;
1483   case 8:
1484     return AMDGPU::SI_SPILL_S64_RESTORE;
1485   case 12:
1486     return AMDGPU::SI_SPILL_S96_RESTORE;
1487   case 16:
1488     return AMDGPU::SI_SPILL_S128_RESTORE;
1489   case 20:
1490     return AMDGPU::SI_SPILL_S160_RESTORE;
1491   case 24:
1492     return AMDGPU::SI_SPILL_S192_RESTORE;
1493   case 32:
1494     return AMDGPU::SI_SPILL_S256_RESTORE;
1495   case 64:
1496     return AMDGPU::SI_SPILL_S512_RESTORE;
1497   case 128:
1498     return AMDGPU::SI_SPILL_S1024_RESTORE;
1499   default:
1500     llvm_unreachable("unknown register size");
1501   }
1502 }
1503 
1504 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
1505   switch (Size) {
1506   case 4:
1507     return AMDGPU::SI_SPILL_V32_RESTORE;
1508   case 8:
1509     return AMDGPU::SI_SPILL_V64_RESTORE;
1510   case 12:
1511     return AMDGPU::SI_SPILL_V96_RESTORE;
1512   case 16:
1513     return AMDGPU::SI_SPILL_V128_RESTORE;
1514   case 20:
1515     return AMDGPU::SI_SPILL_V160_RESTORE;
1516   case 24:
1517     return AMDGPU::SI_SPILL_V192_RESTORE;
1518   case 32:
1519     return AMDGPU::SI_SPILL_V256_RESTORE;
1520   case 64:
1521     return AMDGPU::SI_SPILL_V512_RESTORE;
1522   case 128:
1523     return AMDGPU::SI_SPILL_V1024_RESTORE;
1524   default:
1525     llvm_unreachable("unknown register size");
1526   }
1527 }
1528 
1529 static unsigned getAGPRSpillRestoreOpcode(unsigned Size) {
1530   switch (Size) {
1531   case 4:
1532     return AMDGPU::SI_SPILL_A32_RESTORE;
1533   case 8:
1534     return AMDGPU::SI_SPILL_A64_RESTORE;
1535   case 12:
1536     return AMDGPU::SI_SPILL_A96_RESTORE;
1537   case 16:
1538     return AMDGPU::SI_SPILL_A128_RESTORE;
1539   case 20:
1540     return AMDGPU::SI_SPILL_A160_RESTORE;
1541   case 24:
1542     return AMDGPU::SI_SPILL_A192_RESTORE;
1543   case 32:
1544     return AMDGPU::SI_SPILL_A256_RESTORE;
1545   case 64:
1546     return AMDGPU::SI_SPILL_A512_RESTORE;
1547   case 128:
1548     return AMDGPU::SI_SPILL_A1024_RESTORE;
1549   default:
1550     llvm_unreachable("unknown register size");
1551   }
1552 }
1553 
1554 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1555                                        MachineBasicBlock::iterator MI,
1556                                        Register DestReg, int FrameIndex,
1557                                        const TargetRegisterClass *RC,
1558                                        const TargetRegisterInfo *TRI) const {
1559   MachineFunction *MF = MBB.getParent();
1560   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1561   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
1562   const DebugLoc &DL = MBB.findDebugLoc(MI);
1563   unsigned SpillSize = TRI->getSpillSize(*RC);
1564 
1565   MachinePointerInfo PtrInfo
1566     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
1567 
1568   MachineMemOperand *MMO = MF->getMachineMemOperand(
1569       PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FrameIndex),
1570       FrameInfo.getObjectAlign(FrameIndex));
1571 
1572   if (RI.isSGPRClass(RC)) {
1573     MFI->setHasSpilledSGPRs();
1574     assert(DestReg != AMDGPU::M0 && "m0 should not be reloaded into");
1575     assert(DestReg != AMDGPU::EXEC_LO && DestReg != AMDGPU::EXEC_HI &&
1576            DestReg != AMDGPU::EXEC && "exec should not be spilled");
1577 
1578     // FIXME: Maybe this should not include a memoperand because it will be
1579     // lowered to non-memory instructions.
1580     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
1581     if (DestReg.isVirtual() && SpillSize == 4) {
1582       MachineRegisterInfo &MRI = MF->getRegInfo();
1583       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
1584     }
1585 
1586     if (RI.spillSGPRToVGPR())
1587       FrameInfo.setStackID(FrameIndex, TargetStackID::SGPRSpill);
1588     BuildMI(MBB, MI, DL, OpDesc, DestReg)
1589       .addFrameIndex(FrameIndex) // addr
1590       .addMemOperand(MMO)
1591       .addReg(MFI->getStackPtrOffsetReg(), RegState::Implicit);
1592 
1593     return;
1594   }
1595 
1596   unsigned Opcode = RI.hasAGPRs(RC) ? getAGPRSpillRestoreOpcode(SpillSize)
1597                                     : getVGPRSpillRestoreOpcode(SpillSize);
1598   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
1599     .addFrameIndex(FrameIndex)        // vaddr
1600     .addReg(MFI->getStackPtrOffsetReg()) // scratch_offset
1601     .addImm(0)                           // offset
1602     .addMemOperand(MMO);
1603 }
1604 
1605 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
1606                              MachineBasicBlock::iterator MI) const {
1607   insertNoops(MBB, MI, 1);
1608 }
1609 
1610 void SIInstrInfo::insertNoops(MachineBasicBlock &MBB,
1611                               MachineBasicBlock::iterator MI,
1612                               unsigned Quantity) const {
1613   DebugLoc DL = MBB.findDebugLoc(MI);
1614   while (Quantity > 0) {
1615     unsigned Arg = std::min(Quantity, 8u);
1616     Quantity -= Arg;
1617     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP)).addImm(Arg - 1);
1618   }
1619 }
1620 
1621 void SIInstrInfo::insertReturn(MachineBasicBlock &MBB) const {
1622   auto MF = MBB.getParent();
1623   SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1624 
1625   assert(Info->isEntryFunction());
1626 
1627   if (MBB.succ_empty()) {
1628     bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end();
1629     if (HasNoTerminator) {
1630       if (Info->returnsVoid()) {
1631         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::S_ENDPGM)).addImm(0);
1632       } else {
1633         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::SI_RETURN_TO_EPILOG));
1634       }
1635     }
1636   }
1637 }
1638 
1639 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) {
1640   switch (MI.getOpcode()) {
1641   default: return 1; // FIXME: Do wait states equal cycles?
1642 
1643   case AMDGPU::S_NOP:
1644     return MI.getOperand(0).getImm() + 1;
1645   }
1646 }
1647 
1648 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1649   const SIRegisterInfo *TRI = ST.getRegisterInfo();
1650   MachineBasicBlock &MBB = *MI.getParent();
1651   DebugLoc DL = MBB.findDebugLoc(MI);
1652   switch (MI.getOpcode()) {
1653   default: return TargetInstrInfo::expandPostRAPseudo(MI);
1654   case AMDGPU::S_MOV_B64_term:
1655     // This is only a terminator to get the correct spill code placement during
1656     // register allocation.
1657     MI.setDesc(get(AMDGPU::S_MOV_B64));
1658     break;
1659 
1660   case AMDGPU::S_MOV_B32_term:
1661     // This is only a terminator to get the correct spill code placement during
1662     // register allocation.
1663     MI.setDesc(get(AMDGPU::S_MOV_B32));
1664     break;
1665 
1666   case AMDGPU::S_XOR_B64_term:
1667     // This is only a terminator to get the correct spill code placement during
1668     // register allocation.
1669     MI.setDesc(get(AMDGPU::S_XOR_B64));
1670     break;
1671 
1672   case AMDGPU::S_XOR_B32_term:
1673     // This is only a terminator to get the correct spill code placement during
1674     // register allocation.
1675     MI.setDesc(get(AMDGPU::S_XOR_B32));
1676     break;
1677   case AMDGPU::S_OR_B64_term:
1678     // This is only a terminator to get the correct spill code placement during
1679     // register allocation.
1680     MI.setDesc(get(AMDGPU::S_OR_B64));
1681     break;
1682   case AMDGPU::S_OR_B32_term:
1683     // This is only a terminator to get the correct spill code placement during
1684     // register allocation.
1685     MI.setDesc(get(AMDGPU::S_OR_B32));
1686     break;
1687 
1688   case AMDGPU::S_ANDN2_B64_term:
1689     // This is only a terminator to get the correct spill code placement during
1690     // register allocation.
1691     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
1692     break;
1693 
1694   case AMDGPU::S_ANDN2_B32_term:
1695     // This is only a terminator to get the correct spill code placement during
1696     // register allocation.
1697     MI.setDesc(get(AMDGPU::S_ANDN2_B32));
1698     break;
1699 
1700   case AMDGPU::S_AND_B64_term:
1701     // This is only a terminator to get the correct spill code placement during
1702     // register allocation.
1703     MI.setDesc(get(AMDGPU::S_AND_B64));
1704     break;
1705 
1706   case AMDGPU::S_AND_B32_term:
1707     // This is only a terminator to get the correct spill code placement during
1708     // register allocation.
1709     MI.setDesc(get(AMDGPU::S_AND_B32));
1710     break;
1711 
1712   case AMDGPU::V_MOV_B64_PSEUDO: {
1713     Register Dst = MI.getOperand(0).getReg();
1714     Register DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
1715     Register DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
1716 
1717     const MachineOperand &SrcOp = MI.getOperand(1);
1718     // FIXME: Will this work for 64-bit floating point immediates?
1719     assert(!SrcOp.isFPImm());
1720     if (SrcOp.isImm()) {
1721       APInt Imm(64, SrcOp.getImm());
1722       APInt Lo(32, Imm.getLoBits(32).getZExtValue());
1723       APInt Hi(32, Imm.getHiBits(32).getZExtValue());
1724       if (ST.hasPackedFP32Ops() && Lo == Hi && isInlineConstant(Lo)) {
1725         BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), Dst)
1726           .addImm(SISrcMods::OP_SEL_1)
1727           .addImm(Lo.getSExtValue())
1728           .addImm(SISrcMods::OP_SEL_1)
1729           .addImm(Lo.getSExtValue())
1730           .addImm(0)  // op_sel_lo
1731           .addImm(0)  // op_sel_hi
1732           .addImm(0)  // neg_lo
1733           .addImm(0)  // neg_hi
1734           .addImm(0); // clamp
1735       } else {
1736         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1737           .addImm(Lo.getZExtValue())
1738           .addReg(Dst, RegState::Implicit | RegState::Define);
1739         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1740           .addImm(Hi.getZExtValue())
1741           .addReg(Dst, RegState::Implicit | RegState::Define);
1742       }
1743     } else {
1744       assert(SrcOp.isReg());
1745       if (ST.hasPackedFP32Ops() &&
1746           !RI.isAGPR(MBB.getParent()->getRegInfo(), SrcOp.getReg())) {
1747         BuildMI(MBB, MI, DL, get(AMDGPU::V_PK_MOV_B32), Dst)
1748           .addImm(SISrcMods::OP_SEL_1) // src0_mod
1749           .addReg(SrcOp.getReg())
1750           .addImm(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1) // src1_mod
1751           .addReg(SrcOp.getReg())
1752           .addImm(0)  // op_sel_lo
1753           .addImm(0)  // op_sel_hi
1754           .addImm(0)  // neg_lo
1755           .addImm(0)  // neg_hi
1756           .addImm(0); // clamp
1757       } else {
1758         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1759           .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
1760           .addReg(Dst, RegState::Implicit | RegState::Define);
1761         BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1762           .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
1763           .addReg(Dst, RegState::Implicit | RegState::Define);
1764       }
1765     }
1766     MI.eraseFromParent();
1767     break;
1768   }
1769   case AMDGPU::V_MOV_B64_DPP_PSEUDO: {
1770     expandMovDPP64(MI);
1771     break;
1772   }
1773   case AMDGPU::V_SET_INACTIVE_B32: {
1774     unsigned NotOpc = ST.isWave32() ? AMDGPU::S_NOT_B32 : AMDGPU::S_NOT_B64;
1775     unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1776     auto FirstNot = BuildMI(MBB, MI, DL, get(NotOpc), Exec).addReg(Exec);
1777     FirstNot->addRegisterDead(AMDGPU::SCC, TRI); // SCC is overwritten
1778     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), MI.getOperand(0).getReg())
1779       .add(MI.getOperand(2));
1780     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1781       .addReg(Exec);
1782     MI.eraseFromParent();
1783     break;
1784   }
1785   case AMDGPU::V_SET_INACTIVE_B64: {
1786     unsigned NotOpc = ST.isWave32() ? AMDGPU::S_NOT_B32 : AMDGPU::S_NOT_B64;
1787     unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1788     auto FirstNot = BuildMI(MBB, MI, DL, get(NotOpc), Exec).addReg(Exec);
1789     FirstNot->addRegisterDead(AMDGPU::SCC, TRI); // SCC is overwritten
1790     MachineInstr *Copy = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO),
1791                                  MI.getOperand(0).getReg())
1792       .add(MI.getOperand(2));
1793     expandPostRAPseudo(*Copy);
1794     BuildMI(MBB, MI, DL, get(NotOpc), Exec)
1795       .addReg(Exec);
1796     MI.eraseFromParent();
1797     break;
1798   }
1799   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V1:
1800   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V2:
1801   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V3:
1802   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V4:
1803   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V5:
1804   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V8:
1805   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V16:
1806   case AMDGPU::V_INDIRECT_REG_WRITE_MOVREL_B32_V32:
1807   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V1:
1808   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V2:
1809   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V3:
1810   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V4:
1811   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V5:
1812   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V8:
1813   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V16:
1814   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B32_V32:
1815   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V1:
1816   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V2:
1817   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V4:
1818   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V8:
1819   case AMDGPU::S_INDIRECT_REG_WRITE_MOVREL_B64_V16: {
1820     const TargetRegisterClass *EltRC = getOpRegClass(MI, 2);
1821 
1822     unsigned Opc;
1823     if (RI.hasVGPRs(EltRC)) {
1824       Opc = AMDGPU::V_MOVRELD_B32_e32;
1825     } else {
1826       Opc = RI.getRegSizeInBits(*EltRC) == 64 ? AMDGPU::S_MOVRELD_B64
1827                                               : AMDGPU::S_MOVRELD_B32;
1828     }
1829 
1830     const MCInstrDesc &OpDesc = get(Opc);
1831     Register VecReg = MI.getOperand(0).getReg();
1832     bool IsUndef = MI.getOperand(1).isUndef();
1833     unsigned SubReg = MI.getOperand(3).getImm();
1834     assert(VecReg == MI.getOperand(1).getReg());
1835 
1836     MachineInstrBuilder MIB =
1837       BuildMI(MBB, MI, DL, OpDesc)
1838         .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1839         .add(MI.getOperand(2))
1840         .addReg(VecReg, RegState::ImplicitDefine)
1841         .addReg(VecReg, RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1842 
1843     const int ImpDefIdx =
1844       OpDesc.getNumOperands() + OpDesc.getNumImplicitUses();
1845     const int ImpUseIdx = ImpDefIdx + 1;
1846     MIB->tieOperands(ImpDefIdx, ImpUseIdx);
1847     MI.eraseFromParent();
1848     break;
1849   }
1850   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V1:
1851   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V2:
1852   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V3:
1853   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V4:
1854   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V5:
1855   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V8:
1856   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V16:
1857   case AMDGPU::V_INDIRECT_REG_WRITE_GPR_IDX_B32_V32: {
1858     assert(ST.useVGPRIndexMode());
1859     Register VecReg = MI.getOperand(0).getReg();
1860     bool IsUndef = MI.getOperand(1).isUndef();
1861     Register Idx = MI.getOperand(3).getReg();
1862     Register SubReg = MI.getOperand(4).getImm();
1863 
1864     MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
1865                               .addReg(Idx)
1866                               .addImm(AMDGPU::VGPRIndexMode::DST_ENABLE);
1867     SetOn->getOperand(3).setIsUndef();
1868 
1869     const MCInstrDesc &OpDesc = get(AMDGPU::V_MOV_B32_indirect);
1870     MachineInstrBuilder MIB =
1871         BuildMI(MBB, MI, DL, OpDesc)
1872             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1873             .add(MI.getOperand(2))
1874             .addReg(VecReg, RegState::ImplicitDefine)
1875             .addReg(VecReg,
1876                     RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1877 
1878     const int ImpDefIdx = OpDesc.getNumOperands() + OpDesc.getNumImplicitUses();
1879     const int ImpUseIdx = ImpDefIdx + 1;
1880     MIB->tieOperands(ImpDefIdx, ImpUseIdx);
1881 
1882     MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
1883 
1884     finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
1885 
1886     MI.eraseFromParent();
1887     break;
1888   }
1889   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V1:
1890   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V2:
1891   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V3:
1892   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V4:
1893   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V5:
1894   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V8:
1895   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V16:
1896   case AMDGPU::V_INDIRECT_REG_READ_GPR_IDX_B32_V32: {
1897     assert(ST.useVGPRIndexMode());
1898     Register Dst = MI.getOperand(0).getReg();
1899     Register VecReg = MI.getOperand(1).getReg();
1900     bool IsUndef = MI.getOperand(1).isUndef();
1901     Register Idx = MI.getOperand(2).getReg();
1902     Register SubReg = MI.getOperand(3).getImm();
1903 
1904     MachineInstr *SetOn = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_ON))
1905                               .addReg(Idx)
1906                               .addImm(AMDGPU::VGPRIndexMode::SRC0_ENABLE);
1907     SetOn->getOperand(3).setIsUndef();
1908 
1909     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32))
1910         .addDef(Dst)
1911         .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1912         .addReg(VecReg, RegState::Implicit | (IsUndef ? RegState::Undef : 0))
1913         .addReg(AMDGPU::M0, RegState::Implicit);
1914 
1915     MachineInstr *SetOff = BuildMI(MBB, MI, DL, get(AMDGPU::S_SET_GPR_IDX_OFF));
1916 
1917     finalizeBundle(MBB, SetOn->getIterator(), std::next(SetOff->getIterator()));
1918 
1919     MI.eraseFromParent();
1920     break;
1921   }
1922   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
1923     MachineFunction &MF = *MBB.getParent();
1924     Register Reg = MI.getOperand(0).getReg();
1925     Register RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
1926     Register RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
1927 
1928     // Create a bundle so these instructions won't be re-ordered by the
1929     // post-RA scheduler.
1930     MIBundleBuilder Bundler(MBB, MI);
1931     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
1932 
1933     // Add 32-bit offset from this instruction to the start of the
1934     // constant data.
1935     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
1936                        .addReg(RegLo)
1937                        .add(MI.getOperand(1)));
1938 
1939     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
1940                                   .addReg(RegHi);
1941     MIB.add(MI.getOperand(2));
1942 
1943     Bundler.append(MIB);
1944     finalizeBundle(MBB, Bundler.begin());
1945 
1946     MI.eraseFromParent();
1947     break;
1948   }
1949   case AMDGPU::ENTER_STRICT_WWM: {
1950     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1951     // Whole Wave Mode is entered.
1952     MI.setDesc(get(ST.isWave32() ? AMDGPU::S_OR_SAVEEXEC_B32
1953                                  : AMDGPU::S_OR_SAVEEXEC_B64));
1954     break;
1955   }
1956   case AMDGPU::ENTER_STRICT_WQM: {
1957     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1958     // STRICT_WQM is entered.
1959     const unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
1960     const unsigned WQMOp = ST.isWave32() ? AMDGPU::S_WQM_B32 : AMDGPU::S_WQM_B64;
1961     const unsigned MovOp = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
1962     BuildMI(MBB, MI, DL, get(MovOp), MI.getOperand(0).getReg()).addReg(Exec);
1963     BuildMI(MBB, MI, DL, get(WQMOp), Exec).addReg(Exec);
1964 
1965     MI.eraseFromParent();
1966     break;
1967   }
1968   case AMDGPU::EXIT_STRICT_WWM:
1969   case AMDGPU::EXIT_STRICT_WQM: {
1970     // This only gets its own opcode so that SIPreAllocateWWMRegs can tell when
1971     // WWM/STICT_WQM is exited.
1972     MI.setDesc(get(ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64));
1973     break;
1974   }
1975   }
1976   return true;
1977 }
1978 
1979 std::pair<MachineInstr*, MachineInstr*>
1980 SIInstrInfo::expandMovDPP64(MachineInstr &MI) const {
1981   assert (MI.getOpcode() == AMDGPU::V_MOV_B64_DPP_PSEUDO);
1982 
1983   MachineBasicBlock &MBB = *MI.getParent();
1984   DebugLoc DL = MBB.findDebugLoc(MI);
1985   MachineFunction *MF = MBB.getParent();
1986   MachineRegisterInfo &MRI = MF->getRegInfo();
1987   Register Dst = MI.getOperand(0).getReg();
1988   unsigned Part = 0;
1989   MachineInstr *Split[2];
1990 
1991   for (auto Sub : { AMDGPU::sub0, AMDGPU::sub1 }) {
1992     auto MovDPP = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_dpp));
1993     if (Dst.isPhysical()) {
1994       MovDPP.addDef(RI.getSubReg(Dst, Sub));
1995     } else {
1996       assert(MRI.isSSA());
1997       auto Tmp = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1998       MovDPP.addDef(Tmp);
1999     }
2000 
2001     for (unsigned I = 1; I <= 2; ++I) { // old and src operands.
2002       const MachineOperand &SrcOp = MI.getOperand(I);
2003       assert(!SrcOp.isFPImm());
2004       if (SrcOp.isImm()) {
2005         APInt Imm(64, SrcOp.getImm());
2006         Imm.ashrInPlace(Part * 32);
2007         MovDPP.addImm(Imm.getLoBits(32).getZExtValue());
2008       } else {
2009         assert(SrcOp.isReg());
2010         Register Src = SrcOp.getReg();
2011         if (Src.isPhysical())
2012           MovDPP.addReg(RI.getSubReg(Src, Sub));
2013         else
2014           MovDPP.addReg(Src, SrcOp.isUndef() ? RegState::Undef : 0, Sub);
2015       }
2016     }
2017 
2018     for (unsigned I = 3; I < MI.getNumExplicitOperands(); ++I)
2019       MovDPP.addImm(MI.getOperand(I).getImm());
2020 
2021     Split[Part] = MovDPP;
2022     ++Part;
2023   }
2024 
2025   if (Dst.isVirtual())
2026     BuildMI(MBB, MI, DL, get(AMDGPU::REG_SEQUENCE), Dst)
2027       .addReg(Split[0]->getOperand(0).getReg())
2028       .addImm(AMDGPU::sub0)
2029       .addReg(Split[1]->getOperand(0).getReg())
2030       .addImm(AMDGPU::sub1);
2031 
2032   MI.eraseFromParent();
2033   return std::make_pair(Split[0], Split[1]);
2034 }
2035 
2036 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
2037                                       MachineOperand &Src0,
2038                                       unsigned Src0OpName,
2039                                       MachineOperand &Src1,
2040                                       unsigned Src1OpName) const {
2041   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
2042   if (!Src0Mods)
2043     return false;
2044 
2045   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
2046   assert(Src1Mods &&
2047          "All commutable instructions have both src0 and src1 modifiers");
2048 
2049   int Src0ModsVal = Src0Mods->getImm();
2050   int Src1ModsVal = Src1Mods->getImm();
2051 
2052   Src1Mods->setImm(Src0ModsVal);
2053   Src0Mods->setImm(Src1ModsVal);
2054   return true;
2055 }
2056 
2057 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
2058                                              MachineOperand &RegOp,
2059                                              MachineOperand &NonRegOp) {
2060   Register Reg = RegOp.getReg();
2061   unsigned SubReg = RegOp.getSubReg();
2062   bool IsKill = RegOp.isKill();
2063   bool IsDead = RegOp.isDead();
2064   bool IsUndef = RegOp.isUndef();
2065   bool IsDebug = RegOp.isDebug();
2066 
2067   if (NonRegOp.isImm())
2068     RegOp.ChangeToImmediate(NonRegOp.getImm());
2069   else if (NonRegOp.isFI())
2070     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
2071   else if (NonRegOp.isGlobal()) {
2072     RegOp.ChangeToGA(NonRegOp.getGlobal(), NonRegOp.getOffset(),
2073                      NonRegOp.getTargetFlags());
2074   } else
2075     return nullptr;
2076 
2077   // Make sure we don't reinterpret a subreg index in the target flags.
2078   RegOp.setTargetFlags(NonRegOp.getTargetFlags());
2079 
2080   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
2081   NonRegOp.setSubReg(SubReg);
2082 
2083   return &MI;
2084 }
2085 
2086 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
2087                                                   unsigned Src0Idx,
2088                                                   unsigned Src1Idx) const {
2089   assert(!NewMI && "this should never be used");
2090 
2091   unsigned Opc = MI.getOpcode();
2092   int CommutedOpcode = commuteOpcode(Opc);
2093   if (CommutedOpcode == -1)
2094     return nullptr;
2095 
2096   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
2097            static_cast<int>(Src0Idx) &&
2098          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
2099            static_cast<int>(Src1Idx) &&
2100          "inconsistency with findCommutedOpIndices");
2101 
2102   MachineOperand &Src0 = MI.getOperand(Src0Idx);
2103   MachineOperand &Src1 = MI.getOperand(Src1Idx);
2104 
2105   MachineInstr *CommutedMI = nullptr;
2106   if (Src0.isReg() && Src1.isReg()) {
2107     if (isOperandLegal(MI, Src1Idx, &Src0)) {
2108       // Be sure to copy the source modifiers to the right place.
2109       CommutedMI
2110         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
2111     }
2112 
2113   } else if (Src0.isReg() && !Src1.isReg()) {
2114     // src0 should always be able to support any operand type, so no need to
2115     // check operand legality.
2116     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
2117   } else if (!Src0.isReg() && Src1.isReg()) {
2118     if (isOperandLegal(MI, Src1Idx, &Src0))
2119       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
2120   } else {
2121     // FIXME: Found two non registers to commute. This does happen.
2122     return nullptr;
2123   }
2124 
2125   if (CommutedMI) {
2126     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
2127                         Src1, AMDGPU::OpName::src1_modifiers);
2128 
2129     CommutedMI->setDesc(get(CommutedOpcode));
2130   }
2131 
2132   return CommutedMI;
2133 }
2134 
2135 // This needs to be implemented because the source modifiers may be inserted
2136 // between the true commutable operands, and the base
2137 // TargetInstrInfo::commuteInstruction uses it.
2138 bool SIInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
2139                                         unsigned &SrcOpIdx0,
2140                                         unsigned &SrcOpIdx1) const {
2141   return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
2142 }
2143 
2144 bool SIInstrInfo::findCommutedOpIndices(MCInstrDesc Desc, unsigned &SrcOpIdx0,
2145                                         unsigned &SrcOpIdx1) const {
2146   if (!Desc.isCommutable())
2147     return false;
2148 
2149   unsigned Opc = Desc.getOpcode();
2150   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2151   if (Src0Idx == -1)
2152     return false;
2153 
2154   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2155   if (Src1Idx == -1)
2156     return false;
2157 
2158   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
2159 }
2160 
2161 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
2162                                         int64_t BrOffset) const {
2163   // BranchRelaxation should never have to check s_setpc_b64 because its dest
2164   // block is unanalyzable.
2165   assert(BranchOp != AMDGPU::S_SETPC_B64);
2166 
2167   // Convert to dwords.
2168   BrOffset /= 4;
2169 
2170   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
2171   // from the next instruction.
2172   BrOffset -= 1;
2173 
2174   return isIntN(BranchOffsetBits, BrOffset);
2175 }
2176 
2177 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
2178   const MachineInstr &MI) const {
2179   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
2180     // This would be a difficult analysis to perform, but can always be legal so
2181     // there's no need to analyze it.
2182     return nullptr;
2183   }
2184 
2185   return MI.getOperand(0).getMBB();
2186 }
2187 
2188 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
2189                                            MachineBasicBlock &DestBB,
2190                                            const DebugLoc &DL,
2191                                            int64_t BrOffset,
2192                                            RegScavenger *RS) const {
2193   assert(RS && "RegScavenger required for long branching");
2194   assert(MBB.empty() &&
2195          "new block should be inserted for expanding unconditional branch");
2196   assert(MBB.pred_size() == 1);
2197 
2198   MachineFunction *MF = MBB.getParent();
2199   MachineRegisterInfo &MRI = MF->getRegInfo();
2200 
2201   // FIXME: Virtual register workaround for RegScavenger not working with empty
2202   // blocks.
2203   Register PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2204 
2205   auto I = MBB.end();
2206 
2207   // We need to compute the offset relative to the instruction immediately after
2208   // s_getpc_b64. Insert pc arithmetic code before last terminator.
2209   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
2210 
2211   // TODO: Handle > 32-bit block address.
2212   if (BrOffset >= 0) {
2213     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
2214       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
2215       .addReg(PCReg, 0, AMDGPU::sub0)
2216       .addMBB(&DestBB, MO_LONG_BRANCH_FORWARD);
2217     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
2218       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
2219       .addReg(PCReg, 0, AMDGPU::sub1)
2220       .addImm(0);
2221   } else {
2222     // Backwards branch.
2223     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
2224       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
2225       .addReg(PCReg, 0, AMDGPU::sub0)
2226       .addMBB(&DestBB, MO_LONG_BRANCH_BACKWARD);
2227     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
2228       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
2229       .addReg(PCReg, 0, AMDGPU::sub1)
2230       .addImm(0);
2231   }
2232 
2233   // Insert the indirect branch after the other terminator.
2234   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
2235     .addReg(PCReg);
2236 
2237   // FIXME: If spilling is necessary, this will fail because this scavenger has
2238   // no emergency stack slots. It is non-trivial to spill in this situation,
2239   // because the restore code needs to be specially placed after the
2240   // jump. BranchRelaxation then needs to be made aware of the newly inserted
2241   // block.
2242   //
2243   // If a spill is needed for the pc register pair, we need to insert a spill
2244   // restore block right before the destination block, and insert a short branch
2245   // into the old destination block's fallthrough predecessor.
2246   // e.g.:
2247   //
2248   // s_cbranch_scc0 skip_long_branch:
2249   //
2250   // long_branch_bb:
2251   //   spill s[8:9]
2252   //   s_getpc_b64 s[8:9]
2253   //   s_add_u32 s8, s8, restore_bb
2254   //   s_addc_u32 s9, s9, 0
2255   //   s_setpc_b64 s[8:9]
2256   //
2257   // skip_long_branch:
2258   //   foo;
2259   //
2260   // .....
2261   //
2262   // dest_bb_fallthrough_predecessor:
2263   // bar;
2264   // s_branch dest_bb
2265   //
2266   // restore_bb:
2267   //  restore s[8:9]
2268   //  fallthrough dest_bb
2269   ///
2270   // dest_bb:
2271   //   buzz;
2272 
2273   RS->enterBasicBlockEnd(MBB);
2274   Register Scav = RS->scavengeRegisterBackwards(
2275     AMDGPU::SReg_64RegClass,
2276     MachineBasicBlock::iterator(GetPC), false, 0);
2277   MRI.replaceRegWith(PCReg, Scav);
2278   MRI.clearVirtRegs();
2279   RS->setRegUsed(Scav);
2280 
2281   return 4 + 8 + 4 + 4;
2282 }
2283 
2284 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
2285   switch (Cond) {
2286   case SIInstrInfo::SCC_TRUE:
2287     return AMDGPU::S_CBRANCH_SCC1;
2288   case SIInstrInfo::SCC_FALSE:
2289     return AMDGPU::S_CBRANCH_SCC0;
2290   case SIInstrInfo::VCCNZ:
2291     return AMDGPU::S_CBRANCH_VCCNZ;
2292   case SIInstrInfo::VCCZ:
2293     return AMDGPU::S_CBRANCH_VCCZ;
2294   case SIInstrInfo::EXECNZ:
2295     return AMDGPU::S_CBRANCH_EXECNZ;
2296   case SIInstrInfo::EXECZ:
2297     return AMDGPU::S_CBRANCH_EXECZ;
2298   default:
2299     llvm_unreachable("invalid branch predicate");
2300   }
2301 }
2302 
2303 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
2304   switch (Opcode) {
2305   case AMDGPU::S_CBRANCH_SCC0:
2306     return SCC_FALSE;
2307   case AMDGPU::S_CBRANCH_SCC1:
2308     return SCC_TRUE;
2309   case AMDGPU::S_CBRANCH_VCCNZ:
2310     return VCCNZ;
2311   case AMDGPU::S_CBRANCH_VCCZ:
2312     return VCCZ;
2313   case AMDGPU::S_CBRANCH_EXECNZ:
2314     return EXECNZ;
2315   case AMDGPU::S_CBRANCH_EXECZ:
2316     return EXECZ;
2317   default:
2318     return INVALID_BR;
2319   }
2320 }
2321 
2322 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
2323                                     MachineBasicBlock::iterator I,
2324                                     MachineBasicBlock *&TBB,
2325                                     MachineBasicBlock *&FBB,
2326                                     SmallVectorImpl<MachineOperand> &Cond,
2327                                     bool AllowModify) const {
2328   if (I->getOpcode() == AMDGPU::S_BRANCH) {
2329     // Unconditional Branch
2330     TBB = I->getOperand(0).getMBB();
2331     return false;
2332   }
2333 
2334   MachineBasicBlock *CondBB = nullptr;
2335 
2336   if (I->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
2337     CondBB = I->getOperand(1).getMBB();
2338     Cond.push_back(I->getOperand(0));
2339   } else {
2340     BranchPredicate Pred = getBranchPredicate(I->getOpcode());
2341     if (Pred == INVALID_BR)
2342       return true;
2343 
2344     CondBB = I->getOperand(0).getMBB();
2345     Cond.push_back(MachineOperand::CreateImm(Pred));
2346     Cond.push_back(I->getOperand(1)); // Save the branch register.
2347   }
2348   ++I;
2349 
2350   if (I == MBB.end()) {
2351     // Conditional branch followed by fall-through.
2352     TBB = CondBB;
2353     return false;
2354   }
2355 
2356   if (I->getOpcode() == AMDGPU::S_BRANCH) {
2357     TBB = CondBB;
2358     FBB = I->getOperand(0).getMBB();
2359     return false;
2360   }
2361 
2362   return true;
2363 }
2364 
2365 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
2366                                 MachineBasicBlock *&FBB,
2367                                 SmallVectorImpl<MachineOperand> &Cond,
2368                                 bool AllowModify) const {
2369   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
2370   auto E = MBB.end();
2371   if (I == E)
2372     return false;
2373 
2374   // Skip over the instructions that are artificially terminators for special
2375   // exec management.
2376   while (I != E && !I->isBranch() && !I->isReturn()) {
2377     switch (I->getOpcode()) {
2378     case AMDGPU::S_MOV_B64_term:
2379     case AMDGPU::S_XOR_B64_term:
2380     case AMDGPU::S_OR_B64_term:
2381     case AMDGPU::S_ANDN2_B64_term:
2382     case AMDGPU::S_AND_B64_term:
2383     case AMDGPU::S_MOV_B32_term:
2384     case AMDGPU::S_XOR_B32_term:
2385     case AMDGPU::S_OR_B32_term:
2386     case AMDGPU::S_ANDN2_B32_term:
2387     case AMDGPU::S_AND_B32_term:
2388       break;
2389     case AMDGPU::SI_IF:
2390     case AMDGPU::SI_ELSE:
2391     case AMDGPU::SI_KILL_I1_TERMINATOR:
2392     case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
2393       // FIXME: It's messy that these need to be considered here at all.
2394       return true;
2395     default:
2396       llvm_unreachable("unexpected non-branch terminator inst");
2397     }
2398 
2399     ++I;
2400   }
2401 
2402   if (I == E)
2403     return false;
2404 
2405   return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
2406 }
2407 
2408 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
2409                                    int *BytesRemoved) const {
2410   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
2411 
2412   unsigned Count = 0;
2413   unsigned RemovedSize = 0;
2414   while (I != MBB.end()) {
2415     MachineBasicBlock::iterator Next = std::next(I);
2416     RemovedSize += getInstSizeInBytes(*I);
2417     I->eraseFromParent();
2418     ++Count;
2419     I = Next;
2420   }
2421 
2422   if (BytesRemoved)
2423     *BytesRemoved = RemovedSize;
2424 
2425   return Count;
2426 }
2427 
2428 // Copy the flags onto the implicit condition register operand.
2429 static void preserveCondRegFlags(MachineOperand &CondReg,
2430                                  const MachineOperand &OrigCond) {
2431   CondReg.setIsUndef(OrigCond.isUndef());
2432   CondReg.setIsKill(OrigCond.isKill());
2433 }
2434 
2435 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
2436                                    MachineBasicBlock *TBB,
2437                                    MachineBasicBlock *FBB,
2438                                    ArrayRef<MachineOperand> Cond,
2439                                    const DebugLoc &DL,
2440                                    int *BytesAdded) const {
2441   if (!FBB && Cond.empty()) {
2442     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
2443       .addMBB(TBB);
2444     if (BytesAdded)
2445       *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
2446     return 1;
2447   }
2448 
2449   if(Cond.size() == 1 && Cond[0].isReg()) {
2450      BuildMI(&MBB, DL, get(AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO))
2451        .add(Cond[0])
2452        .addMBB(TBB);
2453      return 1;
2454   }
2455 
2456   assert(TBB && Cond[0].isImm());
2457 
2458   unsigned Opcode
2459     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
2460 
2461   if (!FBB) {
2462     Cond[1].isUndef();
2463     MachineInstr *CondBr =
2464       BuildMI(&MBB, DL, get(Opcode))
2465       .addMBB(TBB);
2466 
2467     // Copy the flags onto the implicit condition register operand.
2468     preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
2469     fixImplicitOperands(*CondBr);
2470 
2471     if (BytesAdded)
2472       *BytesAdded = ST.hasOffset3fBug() ? 8 : 4;
2473     return 1;
2474   }
2475 
2476   assert(TBB && FBB);
2477 
2478   MachineInstr *CondBr =
2479     BuildMI(&MBB, DL, get(Opcode))
2480     .addMBB(TBB);
2481   fixImplicitOperands(*CondBr);
2482   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
2483     .addMBB(FBB);
2484 
2485   MachineOperand &CondReg = CondBr->getOperand(1);
2486   CondReg.setIsUndef(Cond[1].isUndef());
2487   CondReg.setIsKill(Cond[1].isKill());
2488 
2489   if (BytesAdded)
2490     *BytesAdded = ST.hasOffset3fBug() ? 16 : 8;
2491 
2492   return 2;
2493 }
2494 
2495 bool SIInstrInfo::reverseBranchCondition(
2496   SmallVectorImpl<MachineOperand> &Cond) const {
2497   if (Cond.size() != 2) {
2498     return true;
2499   }
2500 
2501   if (Cond[0].isImm()) {
2502     Cond[0].setImm(-Cond[0].getImm());
2503     return false;
2504   }
2505 
2506   return true;
2507 }
2508 
2509 bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
2510                                   ArrayRef<MachineOperand> Cond,
2511                                   Register DstReg, Register TrueReg,
2512                                   Register FalseReg, int &CondCycles,
2513                                   int &TrueCycles, int &FalseCycles) const {
2514   switch (Cond[0].getImm()) {
2515   case VCCNZ:
2516   case VCCZ: {
2517     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2518     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
2519     if (MRI.getRegClass(FalseReg) != RC)
2520       return false;
2521 
2522     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
2523     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
2524 
2525     // Limit to equal cost for branch vs. N v_cndmask_b32s.
2526     return RI.hasVGPRs(RC) && NumInsts <= 6;
2527   }
2528   case SCC_TRUE:
2529   case SCC_FALSE: {
2530     // FIXME: We could insert for VGPRs if we could replace the original compare
2531     // with a vector one.
2532     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2533     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
2534     if (MRI.getRegClass(FalseReg) != RC)
2535       return false;
2536 
2537     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
2538 
2539     // Multiples of 8 can do s_cselect_b64
2540     if (NumInsts % 2 == 0)
2541       NumInsts /= 2;
2542 
2543     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
2544     return RI.isSGPRClass(RC);
2545   }
2546   default:
2547     return false;
2548   }
2549 }
2550 
2551 void SIInstrInfo::insertSelect(MachineBasicBlock &MBB,
2552                                MachineBasicBlock::iterator I, const DebugLoc &DL,
2553                                Register DstReg, ArrayRef<MachineOperand> Cond,
2554                                Register TrueReg, Register FalseReg) const {
2555   BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
2556   if (Pred == VCCZ || Pred == SCC_FALSE) {
2557     Pred = static_cast<BranchPredicate>(-Pred);
2558     std::swap(TrueReg, FalseReg);
2559   }
2560 
2561   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2562   const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
2563   unsigned DstSize = RI.getRegSizeInBits(*DstRC);
2564 
2565   if (DstSize == 32) {
2566     MachineInstr *Select;
2567     if (Pred == SCC_TRUE) {
2568       Select = BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B32), DstReg)
2569         .addReg(TrueReg)
2570         .addReg(FalseReg);
2571     } else {
2572       // Instruction's operands are backwards from what is expected.
2573       Select = BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e32), DstReg)
2574         .addReg(FalseReg)
2575         .addReg(TrueReg);
2576     }
2577 
2578     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2579     return;
2580   }
2581 
2582   if (DstSize == 64 && Pred == SCC_TRUE) {
2583     MachineInstr *Select =
2584       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
2585       .addReg(TrueReg)
2586       .addReg(FalseReg);
2587 
2588     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2589     return;
2590   }
2591 
2592   static const int16_t Sub0_15[] = {
2593     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
2594     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
2595     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
2596     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
2597   };
2598 
2599   static const int16_t Sub0_15_64[] = {
2600     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
2601     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
2602     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
2603     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
2604   };
2605 
2606   unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
2607   const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
2608   const int16_t *SubIndices = Sub0_15;
2609   int NElts = DstSize / 32;
2610 
2611   // 64-bit select is only available for SALU.
2612   // TODO: Split 96-bit into 64-bit and 32-bit, not 3x 32-bit.
2613   if (Pred == SCC_TRUE) {
2614     if (NElts % 2) {
2615       SelOp = AMDGPU::S_CSELECT_B32;
2616       EltRC = &AMDGPU::SGPR_32RegClass;
2617     } else {
2618       SelOp = AMDGPU::S_CSELECT_B64;
2619       EltRC = &AMDGPU::SGPR_64RegClass;
2620       SubIndices = Sub0_15_64;
2621       NElts /= 2;
2622     }
2623   }
2624 
2625   MachineInstrBuilder MIB = BuildMI(
2626     MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
2627 
2628   I = MIB->getIterator();
2629 
2630   SmallVector<Register, 8> Regs;
2631   for (int Idx = 0; Idx != NElts; ++Idx) {
2632     Register DstElt = MRI.createVirtualRegister(EltRC);
2633     Regs.push_back(DstElt);
2634 
2635     unsigned SubIdx = SubIndices[Idx];
2636 
2637     MachineInstr *Select;
2638     if (SelOp == AMDGPU::V_CNDMASK_B32_e32) {
2639       Select =
2640         BuildMI(MBB, I, DL, get(SelOp), DstElt)
2641         .addReg(FalseReg, 0, SubIdx)
2642         .addReg(TrueReg, 0, SubIdx);
2643     } else {
2644       Select =
2645         BuildMI(MBB, I, DL, get(SelOp), DstElt)
2646         .addReg(TrueReg, 0, SubIdx)
2647         .addReg(FalseReg, 0, SubIdx);
2648     }
2649 
2650     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
2651     fixImplicitOperands(*Select);
2652 
2653     MIB.addReg(DstElt)
2654        .addImm(SubIdx);
2655   }
2656 }
2657 
2658 bool SIInstrInfo::isFoldableCopy(const MachineInstr &MI) const {
2659   switch (MI.getOpcode()) {
2660   case AMDGPU::V_MOV_B32_e32:
2661   case AMDGPU::V_MOV_B32_e64:
2662   case AMDGPU::V_MOV_B64_PSEUDO: {
2663     // If there are additional implicit register operands, this may be used for
2664     // register indexing so the source register operand isn't simply copied.
2665     unsigned NumOps = MI.getDesc().getNumOperands() +
2666       MI.getDesc().getNumImplicitUses();
2667 
2668     return MI.getNumOperands() == NumOps;
2669   }
2670   case AMDGPU::S_MOV_B32:
2671   case AMDGPU::S_MOV_B64:
2672   case AMDGPU::COPY:
2673   case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
2674   case AMDGPU::V_ACCVGPR_READ_B32_e64:
2675   case AMDGPU::V_ACCVGPR_MOV_B32:
2676     return true;
2677   default:
2678     return false;
2679   }
2680 }
2681 
2682 unsigned SIInstrInfo::getAddressSpaceForPseudoSourceKind(
2683     unsigned Kind) const {
2684   switch(Kind) {
2685   case PseudoSourceValue::Stack:
2686   case PseudoSourceValue::FixedStack:
2687     return AMDGPUAS::PRIVATE_ADDRESS;
2688   case PseudoSourceValue::ConstantPool:
2689   case PseudoSourceValue::GOT:
2690   case PseudoSourceValue::JumpTable:
2691   case PseudoSourceValue::GlobalValueCallEntry:
2692   case PseudoSourceValue::ExternalSymbolCallEntry:
2693   case PseudoSourceValue::TargetCustom:
2694     return AMDGPUAS::CONSTANT_ADDRESS;
2695   }
2696   return AMDGPUAS::FLAT_ADDRESS;
2697 }
2698 
2699 static void removeModOperands(MachineInstr &MI) {
2700   unsigned Opc = MI.getOpcode();
2701   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2702                                               AMDGPU::OpName::src0_modifiers);
2703   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2704                                               AMDGPU::OpName::src1_modifiers);
2705   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
2706                                               AMDGPU::OpName::src2_modifiers);
2707 
2708   MI.RemoveOperand(Src2ModIdx);
2709   MI.RemoveOperand(Src1ModIdx);
2710   MI.RemoveOperand(Src0ModIdx);
2711 }
2712 
2713 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2714                                 Register Reg, MachineRegisterInfo *MRI) const {
2715   if (!MRI->hasOneNonDBGUse(Reg))
2716     return false;
2717 
2718   switch (DefMI.getOpcode()) {
2719   default:
2720     return false;
2721   case AMDGPU::S_MOV_B64:
2722     // TODO: We could fold 64-bit immediates, but this get compilicated
2723     // when there are sub-registers.
2724     return false;
2725 
2726   case AMDGPU::V_MOV_B32_e32:
2727   case AMDGPU::S_MOV_B32:
2728   case AMDGPU::V_ACCVGPR_WRITE_B32_e64:
2729     break;
2730   }
2731 
2732   const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
2733   assert(ImmOp);
2734   // FIXME: We could handle FrameIndex values here.
2735   if (!ImmOp->isImm())
2736     return false;
2737 
2738   unsigned Opc = UseMI.getOpcode();
2739   if (Opc == AMDGPU::COPY) {
2740     Register DstReg = UseMI.getOperand(0).getReg();
2741     bool Is16Bit = getOpSize(UseMI, 0) == 2;
2742     bool isVGPRCopy = RI.isVGPR(*MRI, DstReg);
2743     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
2744     APInt Imm(32, ImmOp->getImm());
2745 
2746     if (UseMI.getOperand(1).getSubReg() == AMDGPU::hi16)
2747       Imm = Imm.ashr(16);
2748 
2749     if (RI.isAGPR(*MRI, DstReg)) {
2750       if (!isInlineConstant(Imm))
2751         return false;
2752       NewOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
2753     }
2754 
2755     if (Is16Bit) {
2756        if (isVGPRCopy)
2757          return false; // Do not clobber vgpr_hi16
2758 
2759        if (DstReg.isVirtual() &&
2760            UseMI.getOperand(0).getSubReg() != AMDGPU::lo16)
2761          return false;
2762 
2763       UseMI.getOperand(0).setSubReg(0);
2764       if (DstReg.isPhysical()) {
2765         DstReg = RI.get32BitRegister(DstReg);
2766         UseMI.getOperand(0).setReg(DstReg);
2767       }
2768       assert(UseMI.getOperand(1).getReg().isVirtual());
2769     }
2770 
2771     UseMI.setDesc(get(NewOpc));
2772     UseMI.getOperand(1).ChangeToImmediate(Imm.getSExtValue());
2773     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
2774     return true;
2775   }
2776 
2777   if (Opc == AMDGPU::V_MAD_F32_e64 || Opc == AMDGPU::V_MAC_F32_e64 ||
2778       Opc == AMDGPU::V_MAD_F16_e64 || Opc == AMDGPU::V_MAC_F16_e64 ||
2779       Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2780       Opc == AMDGPU::V_FMA_F16_e64 || Opc == AMDGPU::V_FMAC_F16_e64) {
2781     // Don't fold if we are using source or output modifiers. The new VOP2
2782     // instructions don't have them.
2783     if (hasAnyModifiersSet(UseMI))
2784       return false;
2785 
2786     // If this is a free constant, there's no reason to do this.
2787     // TODO: We could fold this here instead of letting SIFoldOperands do it
2788     // later.
2789     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
2790 
2791     // Any src operand can be used for the legality check.
2792     if (isInlineConstant(UseMI, *Src0, *ImmOp))
2793       return false;
2794 
2795     bool IsF32 = Opc == AMDGPU::V_MAD_F32_e64 || Opc == AMDGPU::V_MAC_F32_e64 ||
2796                  Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64;
2797     bool IsFMA = Opc == AMDGPU::V_FMA_F32_e64 || Opc == AMDGPU::V_FMAC_F32_e64 ||
2798                  Opc == AMDGPU::V_FMA_F16_e64 || Opc == AMDGPU::V_FMAC_F16_e64;
2799     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
2800     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
2801 
2802     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
2803     // We should only expect these to be on src0 due to canonicalizations.
2804     if (Src0->isReg() && Src0->getReg() == Reg) {
2805       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
2806         return false;
2807 
2808       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
2809         return false;
2810 
2811       unsigned NewOpc =
2812         IsFMA ? (IsF32 ? AMDGPU::V_FMAMK_F32 : AMDGPU::V_FMAMK_F16)
2813               : (IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16);
2814       if (pseudoToMCOpcode(NewOpc) == -1)
2815         return false;
2816 
2817       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
2818 
2819       const int64_t Imm = ImmOp->getImm();
2820 
2821       // FIXME: This would be a lot easier if we could return a new instruction
2822       // instead of having to modify in place.
2823 
2824       // Remove these first since they are at the end.
2825       UseMI.RemoveOperand(
2826           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2827       UseMI.RemoveOperand(
2828           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2829 
2830       Register Src1Reg = Src1->getReg();
2831       unsigned Src1SubReg = Src1->getSubReg();
2832       Src0->setReg(Src1Reg);
2833       Src0->setSubReg(Src1SubReg);
2834       Src0->setIsKill(Src1->isKill());
2835 
2836       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2837           Opc == AMDGPU::V_MAC_F16_e64 ||
2838           Opc == AMDGPU::V_FMAC_F32_e64 ||
2839           Opc == AMDGPU::V_FMAC_F16_e64)
2840         UseMI.untieRegOperand(
2841             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2842 
2843       Src1->ChangeToImmediate(Imm);
2844 
2845       removeModOperands(UseMI);
2846       UseMI.setDesc(get(NewOpc));
2847 
2848       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2849       if (DeleteDef)
2850         DefMI.eraseFromParent();
2851 
2852       return true;
2853     }
2854 
2855     // Added part is the constant: Use v_madak_{f16, f32}.
2856     if (Src2->isReg() && Src2->getReg() == Reg) {
2857       // Not allowed to use constant bus for another operand.
2858       // We can however allow an inline immediate as src0.
2859       bool Src0Inlined = false;
2860       if (Src0->isReg()) {
2861         // Try to inline constant if possible.
2862         // If the Def moves immediate and the use is single
2863         // We are saving VGPR here.
2864         MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
2865         if (Def && Def->isMoveImmediate() &&
2866           isInlineConstant(Def->getOperand(1)) &&
2867           MRI->hasOneUse(Src0->getReg())) {
2868           Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2869           Src0Inlined = true;
2870         } else if ((Src0->getReg().isPhysical() &&
2871                     (ST.getConstantBusLimit(Opc) <= 1 &&
2872                      RI.isSGPRClass(RI.getPhysRegClass(Src0->getReg())))) ||
2873                    (Src0->getReg().isVirtual() &&
2874                     (ST.getConstantBusLimit(Opc) <= 1 &&
2875                      RI.isSGPRClass(MRI->getRegClass(Src0->getReg())))))
2876           return false;
2877           // VGPR is okay as Src0 - fallthrough
2878       }
2879 
2880       if (Src1->isReg() && !Src0Inlined ) {
2881         // We have one slot for inlinable constant so far - try to fill it
2882         MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
2883         if (Def && Def->isMoveImmediate() &&
2884             isInlineConstant(Def->getOperand(1)) &&
2885             MRI->hasOneUse(Src1->getReg()) &&
2886             commuteInstruction(UseMI)) {
2887             Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2888         } else if ((Src1->getReg().isPhysical() &&
2889                     RI.isSGPRClass(RI.getPhysRegClass(Src1->getReg()))) ||
2890                    (Src1->getReg().isVirtual() &&
2891                     RI.isSGPRClass(MRI->getRegClass(Src1->getReg()))))
2892           return false;
2893           // VGPR is okay as Src1 - fallthrough
2894       }
2895 
2896       unsigned NewOpc =
2897         IsFMA ? (IsF32 ? AMDGPU::V_FMAAK_F32 : AMDGPU::V_FMAAK_F16)
2898               : (IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16);
2899       if (pseudoToMCOpcode(NewOpc) == -1)
2900         return false;
2901 
2902       const int64_t Imm = ImmOp->getImm();
2903 
2904       // FIXME: This would be a lot easier if we could return a new instruction
2905       // instead of having to modify in place.
2906 
2907       // Remove these first since they are at the end.
2908       UseMI.RemoveOperand(
2909           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2910       UseMI.RemoveOperand(
2911           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2912 
2913       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2914           Opc == AMDGPU::V_MAC_F16_e64 ||
2915           Opc == AMDGPU::V_FMAC_F32_e64 ||
2916           Opc == AMDGPU::V_FMAC_F16_e64)
2917         UseMI.untieRegOperand(
2918             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2919 
2920       // ChangingToImmediate adds Src2 back to the instruction.
2921       Src2->ChangeToImmediate(Imm);
2922 
2923       // These come before src2.
2924       removeModOperands(UseMI);
2925       UseMI.setDesc(get(NewOpc));
2926       // It might happen that UseMI was commuted
2927       // and we now have SGPR as SRC1. If so 2 inlined
2928       // constant and SGPR are illegal.
2929       legalizeOperands(UseMI);
2930 
2931       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2932       if (DeleteDef)
2933         DefMI.eraseFromParent();
2934 
2935       return true;
2936     }
2937   }
2938 
2939   return false;
2940 }
2941 
2942 static bool
2943 memOpsHaveSameBaseOperands(ArrayRef<const MachineOperand *> BaseOps1,
2944                            ArrayRef<const MachineOperand *> BaseOps2) {
2945   if (BaseOps1.size() != BaseOps2.size())
2946     return false;
2947   for (size_t I = 0, E = BaseOps1.size(); I < E; ++I) {
2948     if (!BaseOps1[I]->isIdenticalTo(*BaseOps2[I]))
2949       return false;
2950   }
2951   return true;
2952 }
2953 
2954 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
2955                                 int WidthB, int OffsetB) {
2956   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
2957   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
2958   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
2959   return LowOffset + LowWidth <= HighOffset;
2960 }
2961 
2962 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(const MachineInstr &MIa,
2963                                                const MachineInstr &MIb) const {
2964   SmallVector<const MachineOperand *, 4> BaseOps0, BaseOps1;
2965   int64_t Offset0, Offset1;
2966   unsigned Dummy0, Dummy1;
2967   bool Offset0IsScalable, Offset1IsScalable;
2968   if (!getMemOperandsWithOffsetWidth(MIa, BaseOps0, Offset0, Offset0IsScalable,
2969                                      Dummy0, &RI) ||
2970       !getMemOperandsWithOffsetWidth(MIb, BaseOps1, Offset1, Offset1IsScalable,
2971                                      Dummy1, &RI))
2972     return false;
2973 
2974   if (!memOpsHaveSameBaseOperands(BaseOps0, BaseOps1))
2975     return false;
2976 
2977   if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
2978     // FIXME: Handle ds_read2 / ds_write2.
2979     return false;
2980   }
2981   unsigned Width0 = MIa.memoperands().front()->getSize();
2982   unsigned Width1 = MIb.memoperands().front()->getSize();
2983   return offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1);
2984 }
2985 
2986 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(const MachineInstr &MIa,
2987                                                   const MachineInstr &MIb) const {
2988   assert(MIa.mayLoadOrStore() &&
2989          "MIa must load from or modify a memory location");
2990   assert(MIb.mayLoadOrStore() &&
2991          "MIb must load from or modify a memory location");
2992 
2993   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
2994     return false;
2995 
2996   // XXX - Can we relax this between address spaces?
2997   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
2998     return false;
2999 
3000   // TODO: Should we check the address space from the MachineMemOperand? That
3001   // would allow us to distinguish objects we know don't alias based on the
3002   // underlying address space, even if it was lowered to a different one,
3003   // e.g. private accesses lowered to use MUBUF instructions on a scratch
3004   // buffer.
3005   if (isDS(MIa)) {
3006     if (isDS(MIb))
3007       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3008 
3009     return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
3010   }
3011 
3012   if (isMUBUF(MIa) || isMTBUF(MIa)) {
3013     if (isMUBUF(MIb) || isMTBUF(MIb))
3014       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3015 
3016     return !isFLAT(MIb) && !isSMRD(MIb);
3017   }
3018 
3019   if (isSMRD(MIa)) {
3020     if (isSMRD(MIb))
3021       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3022 
3023     return !isFLAT(MIb) && !isMUBUF(MIb) && !isMTBUF(MIb);
3024   }
3025 
3026   if (isFLAT(MIa)) {
3027     if (isFLAT(MIb))
3028       return checkInstOffsetsDoNotOverlap(MIa, MIb);
3029 
3030     return false;
3031   }
3032 
3033   return false;
3034 }
3035 
3036 static int64_t getFoldableImm(const MachineOperand* MO) {
3037   if (!MO->isReg())
3038     return false;
3039   const MachineFunction *MF = MO->getParent()->getParent()->getParent();
3040   const MachineRegisterInfo &MRI = MF->getRegInfo();
3041   auto Def = MRI.getUniqueVRegDef(MO->getReg());
3042   if (Def && Def->getOpcode() == AMDGPU::V_MOV_B32_e32 &&
3043       Def->getOperand(1).isImm())
3044     return Def->getOperand(1).getImm();
3045   return AMDGPU::NoRegister;
3046 }
3047 
3048 static void updateLiveVariables(LiveVariables *LV, MachineInstr &MI,
3049                                 MachineInstr &NewMI) {
3050   if (LV) {
3051     unsigned NumOps = MI.getNumOperands();
3052     for (unsigned I = 1; I < NumOps; ++I) {
3053       MachineOperand &Op = MI.getOperand(I);
3054       if (Op.isReg() && Op.isKill())
3055         LV->replaceKillInstruction(Op.getReg(), MI, NewMI);
3056     }
3057   }
3058 }
3059 
3060 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
3061                                                  MachineInstr &MI,
3062                                                  LiveVariables *LV) const {
3063   unsigned Opc = MI.getOpcode();
3064   bool IsF16 = false;
3065   bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F32_e64 ||
3066                Opc == AMDGPU::V_FMAC_F16_e32 || Opc == AMDGPU::V_FMAC_F16_e64 ||
3067                Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64;
3068   bool IsF64 = Opc == AMDGPU::V_FMAC_F64_e32 || Opc == AMDGPU::V_FMAC_F64_e64;
3069 
3070   switch (Opc) {
3071   default:
3072     return nullptr;
3073   case AMDGPU::V_MAC_F16_e64:
3074   case AMDGPU::V_FMAC_F16_e64:
3075     IsF16 = true;
3076     LLVM_FALLTHROUGH;
3077   case AMDGPU::V_MAC_F32_e64:
3078   case AMDGPU::V_FMAC_F32_e64:
3079   case AMDGPU::V_FMAC_F64_e64:
3080     break;
3081   case AMDGPU::V_MAC_F16_e32:
3082   case AMDGPU::V_FMAC_F16_e32:
3083     IsF16 = true;
3084     LLVM_FALLTHROUGH;
3085   case AMDGPU::V_MAC_F32_e32:
3086   case AMDGPU::V_FMAC_F32_e32:
3087   case AMDGPU::V_FMAC_F64_e32: {
3088     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
3089                                              AMDGPU::OpName::src0);
3090     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
3091     if (!Src0->isReg() && !Src0->isImm())
3092       return nullptr;
3093 
3094     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
3095       return nullptr;
3096 
3097     break;
3098   }
3099   }
3100 
3101   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
3102   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
3103   const MachineOperand *Src0Mods =
3104     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
3105   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3106   const MachineOperand *Src1Mods =
3107     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
3108   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3109   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
3110   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
3111   MachineInstrBuilder MIB;
3112 
3113   if (!Src0Mods && !Src1Mods && !Clamp && !Omod && !IsF64 &&
3114       // If we have an SGPR input, we will violate the constant bus restriction.
3115       (ST.getConstantBusLimit(Opc) > 1 || !Src0->isReg() ||
3116        !RI.isSGPRReg(MBB->getParent()->getRegInfo(), Src0->getReg()))) {
3117     if (auto Imm = getFoldableImm(Src2)) {
3118       unsigned NewOpc =
3119           IsFMA ? (IsF16 ? AMDGPU::V_FMAAK_F16 : AMDGPU::V_FMAAK_F32)
3120                 : (IsF16 ? AMDGPU::V_MADAK_F16 : AMDGPU::V_MADAK_F32);
3121       if (pseudoToMCOpcode(NewOpc) != -1) {
3122         MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3123                   .add(*Dst)
3124                   .add(*Src0)
3125                   .add(*Src1)
3126                   .addImm(Imm);
3127         updateLiveVariables(LV, MI, *MIB);
3128         return MIB;
3129       }
3130     }
3131     unsigned NewOpc = IsFMA
3132                           ? (IsF16 ? AMDGPU::V_FMAMK_F16 : AMDGPU::V_FMAMK_F32)
3133                           : (IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32);
3134     if (auto Imm = getFoldableImm(Src1)) {
3135       if (pseudoToMCOpcode(NewOpc) != -1) {
3136         MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3137                   .add(*Dst)
3138                   .add(*Src0)
3139                   .addImm(Imm)
3140                   .add(*Src2);
3141         updateLiveVariables(LV, MI, *MIB);
3142         return MIB;
3143       }
3144     }
3145     if (auto Imm = getFoldableImm(Src0)) {
3146       if (pseudoToMCOpcode(NewOpc) != -1 &&
3147           isOperandLegal(
3148               MI, AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::src0),
3149               Src1)) {
3150         MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3151                   .add(*Dst)
3152                   .add(*Src1)
3153                   .addImm(Imm)
3154                   .add(*Src2);
3155         updateLiveVariables(LV, MI, *MIB);
3156         return MIB;
3157       }
3158     }
3159   }
3160 
3161   unsigned NewOpc = IsFMA ? (IsF16 ? AMDGPU::V_FMA_F16_e64
3162                                    : IsF64 ? AMDGPU::V_FMA_F64_e64
3163                                            : AMDGPU::V_FMA_F32_e64)
3164                           : (IsF16 ? AMDGPU::V_MAD_F16_e64 : AMDGPU::V_MAD_F32_e64);
3165   if (pseudoToMCOpcode(NewOpc) == -1)
3166     return nullptr;
3167 
3168   MIB = BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
3169             .add(*Dst)
3170             .addImm(Src0Mods ? Src0Mods->getImm() : 0)
3171             .add(*Src0)
3172             .addImm(Src1Mods ? Src1Mods->getImm() : 0)
3173             .add(*Src1)
3174             .addImm(0) // Src mods
3175             .add(*Src2)
3176             .addImm(Clamp ? Clamp->getImm() : 0)
3177             .addImm(Omod ? Omod->getImm() : 0);
3178   updateLiveVariables(LV, MI, *MIB);
3179   return MIB;
3180 }
3181 
3182 // It's not generally safe to move VALU instructions across these since it will
3183 // start using the register as a base index rather than directly.
3184 // XXX - Why isn't hasSideEffects sufficient for these?
3185 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
3186   switch (MI.getOpcode()) {
3187   case AMDGPU::S_SET_GPR_IDX_ON:
3188   case AMDGPU::S_SET_GPR_IDX_MODE:
3189   case AMDGPU::S_SET_GPR_IDX_OFF:
3190     return true;
3191   default:
3192     return false;
3193   }
3194 }
3195 
3196 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
3197                                        const MachineBasicBlock *MBB,
3198                                        const MachineFunction &MF) const {
3199   // Skipping the check for SP writes in the base implementation. The reason it
3200   // was added was apparently due to compile time concerns.
3201   //
3202   // TODO: Do we really want this barrier? It triggers unnecessary hazard nops
3203   // but is probably avoidable.
3204 
3205   // Copied from base implementation.
3206   // Terminators and labels can't be scheduled around.
3207   if (MI.isTerminator() || MI.isPosition())
3208     return true;
3209 
3210   // INLINEASM_BR can jump to another block
3211   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
3212     return true;
3213 
3214   // Target-independent instructions do not have an implicit-use of EXEC, even
3215   // when they operate on VGPRs. Treating EXEC modifications as scheduling
3216   // boundaries prevents incorrect movements of such instructions.
3217   return MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
3218          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
3219          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
3220          changesVGPRIndexingMode(MI);
3221 }
3222 
3223 bool SIInstrInfo::isAlwaysGDS(uint16_t Opcode) const {
3224   return Opcode == AMDGPU::DS_ORDERED_COUNT ||
3225          Opcode == AMDGPU::DS_GWS_INIT ||
3226          Opcode == AMDGPU::DS_GWS_SEMA_V ||
3227          Opcode == AMDGPU::DS_GWS_SEMA_BR ||
3228          Opcode == AMDGPU::DS_GWS_SEMA_P ||
3229          Opcode == AMDGPU::DS_GWS_SEMA_RELEASE_ALL ||
3230          Opcode == AMDGPU::DS_GWS_BARRIER;
3231 }
3232 
3233 bool SIInstrInfo::modifiesModeRegister(const MachineInstr &MI) {
3234   // Skip the full operand and register alias search modifiesRegister
3235   // does. There's only a handful of instructions that touch this, it's only an
3236   // implicit def, and doesn't alias any other registers.
3237   if (const MCPhysReg *ImpDef = MI.getDesc().getImplicitDefs()) {
3238     for (; ImpDef && *ImpDef; ++ImpDef) {
3239       if (*ImpDef == AMDGPU::MODE)
3240         return true;
3241     }
3242   }
3243 
3244   return false;
3245 }
3246 
3247 bool SIInstrInfo::hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const {
3248   unsigned Opcode = MI.getOpcode();
3249 
3250   if (MI.mayStore() && isSMRD(MI))
3251     return true; // scalar store or atomic
3252 
3253   // This will terminate the function when other lanes may need to continue.
3254   if (MI.isReturn())
3255     return true;
3256 
3257   // These instructions cause shader I/O that may cause hardware lockups
3258   // when executed with an empty EXEC mask.
3259   //
3260   // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
3261   //       EXEC = 0, but checking for that case here seems not worth it
3262   //       given the typical code patterns.
3263   if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
3264       isEXP(Opcode) ||
3265       Opcode == AMDGPU::DS_ORDERED_COUNT || Opcode == AMDGPU::S_TRAP ||
3266       Opcode == AMDGPU::DS_GWS_INIT || Opcode == AMDGPU::DS_GWS_BARRIER)
3267     return true;
3268 
3269   if (MI.isCall() || MI.isInlineAsm())
3270     return true; // conservative assumption
3271 
3272   // A mode change is a scalar operation that influences vector instructions.
3273   if (modifiesModeRegister(MI))
3274     return true;
3275 
3276   // These are like SALU instructions in terms of effects, so it's questionable
3277   // whether we should return true for those.
3278   //
3279   // However, executing them with EXEC = 0 causes them to operate on undefined
3280   // data, which we avoid by returning true here.
3281   if (Opcode == AMDGPU::V_READFIRSTLANE_B32 ||
3282       Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32)
3283     return true;
3284 
3285   return false;
3286 }
3287 
3288 bool SIInstrInfo::mayReadEXEC(const MachineRegisterInfo &MRI,
3289                               const MachineInstr &MI) const {
3290   if (MI.isMetaInstruction())
3291     return false;
3292 
3293   // This won't read exec if this is an SGPR->SGPR copy.
3294   if (MI.isCopyLike()) {
3295     if (!RI.isSGPRReg(MRI, MI.getOperand(0).getReg()))
3296       return true;
3297 
3298     // Make sure this isn't copying exec as a normal operand
3299     return MI.readsRegister(AMDGPU::EXEC, &RI);
3300   }
3301 
3302   // Make a conservative assumption about the callee.
3303   if (MI.isCall())
3304     return true;
3305 
3306   // Be conservative with any unhandled generic opcodes.
3307   if (!isTargetSpecificOpcode(MI.getOpcode()))
3308     return true;
3309 
3310   return !isSALU(MI) || MI.readsRegister(AMDGPU::EXEC, &RI);
3311 }
3312 
3313 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
3314   switch (Imm.getBitWidth()) {
3315   case 1: // This likely will be a condition code mask.
3316     return true;
3317 
3318   case 32:
3319     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
3320                                         ST.hasInv2PiInlineImm());
3321   case 64:
3322     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
3323                                         ST.hasInv2PiInlineImm());
3324   case 16:
3325     return ST.has16BitInsts() &&
3326            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
3327                                         ST.hasInv2PiInlineImm());
3328   default:
3329     llvm_unreachable("invalid bitwidth");
3330   }
3331 }
3332 
3333 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
3334                                    uint8_t OperandType) const {
3335   if (!MO.isImm() ||
3336       OperandType < AMDGPU::OPERAND_SRC_FIRST ||
3337       OperandType > AMDGPU::OPERAND_SRC_LAST)
3338     return false;
3339 
3340   // MachineOperand provides no way to tell the true operand size, since it only
3341   // records a 64-bit value. We need to know the size to determine if a 32-bit
3342   // floating point immediate bit pattern is legal for an integer immediate. It
3343   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
3344 
3345   int64_t Imm = MO.getImm();
3346   switch (OperandType) {
3347   case AMDGPU::OPERAND_REG_IMM_INT32:
3348   case AMDGPU::OPERAND_REG_IMM_FP32:
3349   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3350   case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3351   case AMDGPU::OPERAND_REG_IMM_V2FP32:
3352   case AMDGPU::OPERAND_REG_INLINE_C_V2FP32:
3353   case AMDGPU::OPERAND_REG_IMM_V2INT32:
3354   case AMDGPU::OPERAND_REG_INLINE_C_V2INT32:
3355   case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3356   case AMDGPU::OPERAND_REG_INLINE_AC_FP32: {
3357     int32_t Trunc = static_cast<int32_t>(Imm);
3358     return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
3359   }
3360   case AMDGPU::OPERAND_REG_IMM_INT64:
3361   case AMDGPU::OPERAND_REG_IMM_FP64:
3362   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3363   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3364   case AMDGPU::OPERAND_REG_INLINE_AC_FP64:
3365     return AMDGPU::isInlinableLiteral64(MO.getImm(),
3366                                         ST.hasInv2PiInlineImm());
3367   case AMDGPU::OPERAND_REG_IMM_INT16:
3368   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3369   case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3370     // We would expect inline immediates to not be concerned with an integer/fp
3371     // distinction. However, in the case of 16-bit integer operations, the
3372     // "floating point" values appear to not work. It seems read the low 16-bits
3373     // of 32-bit immediates, which happens to always work for the integer
3374     // values.
3375     //
3376     // See llvm bugzilla 46302.
3377     //
3378     // TODO: Theoretically we could use op-sel to use the high bits of the
3379     // 32-bit FP values.
3380     return AMDGPU::isInlinableIntLiteral(Imm);
3381   case AMDGPU::OPERAND_REG_IMM_V2INT16:
3382   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
3383   case AMDGPU::OPERAND_REG_INLINE_AC_V2INT16:
3384     // This suffers the same problem as the scalar 16-bit cases.
3385     return AMDGPU::isInlinableIntLiteralV216(Imm);
3386   case AMDGPU::OPERAND_REG_IMM_FP16:
3387   case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3388   case AMDGPU::OPERAND_REG_INLINE_AC_FP16: {
3389     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
3390       // A few special case instructions have 16-bit operands on subtargets
3391       // where 16-bit instructions are not legal.
3392       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
3393       // constants in these cases
3394       int16_t Trunc = static_cast<int16_t>(Imm);
3395       return ST.has16BitInsts() &&
3396              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
3397     }
3398 
3399     return false;
3400   }
3401   case AMDGPU::OPERAND_REG_IMM_V2FP16:
3402   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
3403   case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: {
3404     uint32_t Trunc = static_cast<uint32_t>(Imm);
3405     return AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
3406   }
3407   default:
3408     llvm_unreachable("invalid bitwidth");
3409   }
3410 }
3411 
3412 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
3413                                         const MCOperandInfo &OpInfo) const {
3414   switch (MO.getType()) {
3415   case MachineOperand::MO_Register:
3416     return false;
3417   case MachineOperand::MO_Immediate:
3418     return !isInlineConstant(MO, OpInfo);
3419   case MachineOperand::MO_FrameIndex:
3420   case MachineOperand::MO_MachineBasicBlock:
3421   case MachineOperand::MO_ExternalSymbol:
3422   case MachineOperand::MO_GlobalAddress:
3423   case MachineOperand::MO_MCSymbol:
3424     return true;
3425   default:
3426     llvm_unreachable("unexpected operand type");
3427   }
3428 }
3429 
3430 static bool compareMachineOp(const MachineOperand &Op0,
3431                              const MachineOperand &Op1) {
3432   if (Op0.getType() != Op1.getType())
3433     return false;
3434 
3435   switch (Op0.getType()) {
3436   case MachineOperand::MO_Register:
3437     return Op0.getReg() == Op1.getReg();
3438   case MachineOperand::MO_Immediate:
3439     return Op0.getImm() == Op1.getImm();
3440   default:
3441     llvm_unreachable("Didn't expect to be comparing these operand types");
3442   }
3443 }
3444 
3445 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
3446                                     const MachineOperand &MO) const {
3447   const MCInstrDesc &InstDesc = MI.getDesc();
3448   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo];
3449 
3450   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
3451 
3452   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
3453     return true;
3454 
3455   if (OpInfo.RegClass < 0)
3456     return false;
3457 
3458   if (MO.isImm() && isInlineConstant(MO, OpInfo)) {
3459     if (isMAI(MI) && ST.hasMFMAInlineLiteralBug() &&
3460         OpNo ==(unsigned)AMDGPU::getNamedOperandIdx(MI.getOpcode(),
3461                                                     AMDGPU::OpName::src2))
3462       return false;
3463     return RI.opCanUseInlineConstant(OpInfo.OperandType);
3464   }
3465 
3466   if (!RI.opCanUseLiteralConstant(OpInfo.OperandType))
3467     return false;
3468 
3469   if (!isVOP3(MI) || !AMDGPU::isSISrcOperand(InstDesc, OpNo))
3470     return true;
3471 
3472   return ST.hasVOP3Literal();
3473 }
3474 
3475 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
3476   // GFX90A does not have V_MUL_LEGACY_F32_e32.
3477   if (Opcode == AMDGPU::V_MUL_LEGACY_F32_e64 && ST.hasGFX90AInsts())
3478     return false;
3479 
3480   int Op32 = AMDGPU::getVOPe32(Opcode);
3481   if (Op32 == -1)
3482     return false;
3483 
3484   return pseudoToMCOpcode(Op32) != -1;
3485 }
3486 
3487 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
3488   // The src0_modifier operand is present on all instructions
3489   // that have modifiers.
3490 
3491   return AMDGPU::getNamedOperandIdx(Opcode,
3492                                     AMDGPU::OpName::src0_modifiers) != -1;
3493 }
3494 
3495 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
3496                                   unsigned OpName) const {
3497   const MachineOperand *Mods = getNamedOperand(MI, OpName);
3498   return Mods && Mods->getImm();
3499 }
3500 
3501 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
3502   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
3503          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
3504          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
3505          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
3506          hasModifiersSet(MI, AMDGPU::OpName::omod);
3507 }
3508 
3509 bool SIInstrInfo::canShrink(const MachineInstr &MI,
3510                             const MachineRegisterInfo &MRI) const {
3511   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3512   // Can't shrink instruction with three operands.
3513   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
3514   // a special case for it.  It can only be shrunk if the third operand
3515   // is vcc, and src0_modifiers and src1_modifiers are not set.
3516   // We should handle this the same way we handle vopc, by addding
3517   // a register allocation hint pre-regalloc and then do the shrinking
3518   // post-regalloc.
3519   if (Src2) {
3520     switch (MI.getOpcode()) {
3521       default: return false;
3522 
3523       case AMDGPU::V_ADDC_U32_e64:
3524       case AMDGPU::V_SUBB_U32_e64:
3525       case AMDGPU::V_SUBBREV_U32_e64: {
3526         const MachineOperand *Src1
3527           = getNamedOperand(MI, AMDGPU::OpName::src1);
3528         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
3529           return false;
3530         // Additional verification is needed for sdst/src2.
3531         return true;
3532       }
3533       case AMDGPU::V_MAC_F32_e64:
3534       case AMDGPU::V_MAC_F16_e64:
3535       case AMDGPU::V_FMAC_F32_e64:
3536       case AMDGPU::V_FMAC_F16_e64:
3537       case AMDGPU::V_FMAC_F64_e64:
3538         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
3539             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
3540           return false;
3541         break;
3542 
3543       case AMDGPU::V_CNDMASK_B32_e64:
3544         break;
3545     }
3546   }
3547 
3548   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3549   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
3550                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
3551     return false;
3552 
3553   // We don't need to check src0, all input types are legal, so just make sure
3554   // src0 isn't using any modifiers.
3555   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
3556     return false;
3557 
3558   // Can it be shrunk to a valid 32 bit opcode?
3559   if (!hasVALU32BitEncoding(MI.getOpcode()))
3560     return false;
3561 
3562   // Check output modifiers
3563   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
3564          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
3565 }
3566 
3567 // Set VCC operand with all flags from \p Orig, except for setting it as
3568 // implicit.
3569 static void copyFlagsToImplicitVCC(MachineInstr &MI,
3570                                    const MachineOperand &Orig) {
3571 
3572   for (MachineOperand &Use : MI.implicit_operands()) {
3573     if (Use.isUse() &&
3574         (Use.getReg() == AMDGPU::VCC || Use.getReg() == AMDGPU::VCC_LO)) {
3575       Use.setIsUndef(Orig.isUndef());
3576       Use.setIsKill(Orig.isKill());
3577       return;
3578     }
3579   }
3580 }
3581 
3582 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
3583                                            unsigned Op32) const {
3584   MachineBasicBlock *MBB = MI.getParent();;
3585   MachineInstrBuilder Inst32 =
3586     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32))
3587     .setMIFlags(MI.getFlags());
3588 
3589   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
3590   // For VOPC instructions, this is replaced by an implicit def of vcc.
3591   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
3592   if (Op32DstIdx != -1) {
3593     // dst
3594     Inst32.add(MI.getOperand(0));
3595   } else {
3596     assert(((MI.getOperand(0).getReg() == AMDGPU::VCC) ||
3597             (MI.getOperand(0).getReg() == AMDGPU::VCC_LO)) &&
3598            "Unexpected case");
3599   }
3600 
3601   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
3602 
3603   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3604   if (Src1)
3605     Inst32.add(*Src1);
3606 
3607   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3608 
3609   if (Src2) {
3610     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
3611     if (Op32Src2Idx != -1) {
3612       Inst32.add(*Src2);
3613     } else {
3614       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
3615       // replaced with an implicit read of vcc or vcc_lo. The implicit read
3616       // of vcc was already added during the initial BuildMI, but we
3617       // 1) may need to change vcc to vcc_lo to preserve the original register
3618       // 2) have to preserve the original flags.
3619       fixImplicitOperands(*Inst32);
3620       copyFlagsToImplicitVCC(*Inst32, *Src2);
3621     }
3622   }
3623 
3624   return Inst32;
3625 }
3626 
3627 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
3628                                   const MachineOperand &MO,
3629                                   const MCOperandInfo &OpInfo) const {
3630   // Literal constants use the constant bus.
3631   //if (isLiteralConstantLike(MO, OpInfo))
3632   // return true;
3633   if (MO.isImm())
3634     return !isInlineConstant(MO, OpInfo);
3635 
3636   if (!MO.isReg())
3637     return true; // Misc other operands like FrameIndex
3638 
3639   if (!MO.isUse())
3640     return false;
3641 
3642   if (MO.getReg().isVirtual())
3643     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
3644 
3645   // Null is free
3646   if (MO.getReg() == AMDGPU::SGPR_NULL)
3647     return false;
3648 
3649   // SGPRs use the constant bus
3650   if (MO.isImplicit()) {
3651     return MO.getReg() == AMDGPU::M0 ||
3652            MO.getReg() == AMDGPU::VCC ||
3653            MO.getReg() == AMDGPU::VCC_LO;
3654   } else {
3655     return AMDGPU::SReg_32RegClass.contains(MO.getReg()) ||
3656            AMDGPU::SReg_64RegClass.contains(MO.getReg());
3657   }
3658 }
3659 
3660 static Register findImplicitSGPRRead(const MachineInstr &MI) {
3661   for (const MachineOperand &MO : MI.implicit_operands()) {
3662     // We only care about reads.
3663     if (MO.isDef())
3664       continue;
3665 
3666     switch (MO.getReg()) {
3667     case AMDGPU::VCC:
3668     case AMDGPU::VCC_LO:
3669     case AMDGPU::VCC_HI:
3670     case AMDGPU::M0:
3671     case AMDGPU::FLAT_SCR:
3672       return MO.getReg();
3673 
3674     default:
3675       break;
3676     }
3677   }
3678 
3679   return AMDGPU::NoRegister;
3680 }
3681 
3682 static bool shouldReadExec(const MachineInstr &MI) {
3683   if (SIInstrInfo::isVALU(MI)) {
3684     switch (MI.getOpcode()) {
3685     case AMDGPU::V_READLANE_B32:
3686     case AMDGPU::V_WRITELANE_B32:
3687       return false;
3688     }
3689 
3690     return true;
3691   }
3692 
3693   if (MI.isPreISelOpcode() ||
3694       SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
3695       SIInstrInfo::isSALU(MI) ||
3696       SIInstrInfo::isSMRD(MI))
3697     return false;
3698 
3699   return true;
3700 }
3701 
3702 static bool isSubRegOf(const SIRegisterInfo &TRI,
3703                        const MachineOperand &SuperVec,
3704                        const MachineOperand &SubReg) {
3705   if (SubReg.getReg().isPhysical())
3706     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
3707 
3708   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
3709          SubReg.getReg() == SuperVec.getReg();
3710 }
3711 
3712 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
3713                                     StringRef &ErrInfo) const {
3714   uint16_t Opcode = MI.getOpcode();
3715   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
3716     return true;
3717 
3718   const MachineFunction *MF = MI.getParent()->getParent();
3719   const MachineRegisterInfo &MRI = MF->getRegInfo();
3720 
3721   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
3722   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
3723   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
3724 
3725   // Make sure the number of operands is correct.
3726   const MCInstrDesc &Desc = get(Opcode);
3727   if (!Desc.isVariadic() &&
3728       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
3729     ErrInfo = "Instruction has wrong number of operands.";
3730     return false;
3731   }
3732 
3733   if (MI.isInlineAsm()) {
3734     // Verify register classes for inlineasm constraints.
3735     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
3736          I != E; ++I) {
3737       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
3738       if (!RC)
3739         continue;
3740 
3741       const MachineOperand &Op = MI.getOperand(I);
3742       if (!Op.isReg())
3743         continue;
3744 
3745       Register Reg = Op.getReg();
3746       if (!Reg.isVirtual() && !RC->contains(Reg)) {
3747         ErrInfo = "inlineasm operand has incorrect register class.";
3748         return false;
3749       }
3750     }
3751 
3752     return true;
3753   }
3754 
3755   if (isMIMG(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
3756     ErrInfo = "missing memory operand from MIMG instruction.";
3757     return false;
3758   }
3759 
3760   // Make sure the register classes are correct.
3761   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
3762     const MachineOperand &MO = MI.getOperand(i);
3763     if (MO.isFPImm()) {
3764       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
3765                 "all fp values to integers.";
3766       return false;
3767     }
3768 
3769     int RegClass = Desc.OpInfo[i].RegClass;
3770 
3771     switch (Desc.OpInfo[i].OperandType) {
3772     case MCOI::OPERAND_REGISTER:
3773       if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
3774         ErrInfo = "Illegal immediate value for operand.";
3775         return false;
3776       }
3777       break;
3778     case AMDGPU::OPERAND_REG_IMM_INT32:
3779     case AMDGPU::OPERAND_REG_IMM_FP32:
3780       break;
3781     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3782     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3783     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3784     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3785     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3786     case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3787     case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3788     case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
3789     case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3790     case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
3791     case AMDGPU::OPERAND_REG_INLINE_AC_FP64: {
3792       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
3793         ErrInfo = "Illegal immediate value for operand.";
3794         return false;
3795       }
3796       break;
3797     }
3798     case MCOI::OPERAND_IMMEDIATE:
3799     case AMDGPU::OPERAND_KIMM32:
3800       // Check if this operand is an immediate.
3801       // FrameIndex operands will be replaced by immediates, so they are
3802       // allowed.
3803       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
3804         ErrInfo = "Expected immediate, but got non-immediate";
3805         return false;
3806       }
3807       LLVM_FALLTHROUGH;
3808     default:
3809       continue;
3810     }
3811 
3812     if (!MO.isReg())
3813       continue;
3814     Register Reg = MO.getReg();
3815     if (!Reg)
3816       continue;
3817 
3818     // FIXME: Ideally we would have separate instruction definitions with the
3819     // aligned register constraint.
3820     // FIXME: We do not verify inline asm operands, but custom inline asm
3821     // verification is broken anyway
3822     if (ST.needsAlignedVGPRs()) {
3823       const TargetRegisterClass *RC = RI.getRegClassForReg(MRI, Reg);
3824       const bool IsVGPR = RI.hasVGPRs(RC);
3825       const bool IsAGPR = !IsVGPR && RI.hasAGPRs(RC);
3826       if ((IsVGPR || IsAGPR) && MO.getSubReg()) {
3827         const TargetRegisterClass *SubRC =
3828             RI.getSubRegClass(RC, MO.getSubReg());
3829         RC = RI.getCompatibleSubRegClass(RC, SubRC, MO.getSubReg());
3830         if (RC)
3831           RC = SubRC;
3832       }
3833 
3834       // Check that this is the aligned version of the class.
3835       if (!RC || !RI.isProperlyAlignedRC(*RC)) {
3836         ErrInfo = "Subtarget requires even aligned vector registers";
3837         return false;
3838       }
3839     }
3840 
3841     if (RegClass != -1) {
3842       if (Reg.isVirtual())
3843         continue;
3844 
3845       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
3846       if (!RC->contains(Reg)) {
3847         ErrInfo = "Operand has incorrect register class.";
3848         return false;
3849       }
3850     }
3851   }
3852 
3853   // Verify SDWA
3854   if (isSDWA(MI)) {
3855     if (!ST.hasSDWA()) {
3856       ErrInfo = "SDWA is not supported on this target";
3857       return false;
3858     }
3859 
3860     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
3861 
3862     const int OpIndicies[] = { DstIdx, Src0Idx, Src1Idx, Src2Idx };
3863 
3864     for (int OpIdx: OpIndicies) {
3865       if (OpIdx == -1)
3866         continue;
3867       const MachineOperand &MO = MI.getOperand(OpIdx);
3868 
3869       if (!ST.hasSDWAScalar()) {
3870         // Only VGPRS on VI
3871         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
3872           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
3873           return false;
3874         }
3875       } else {
3876         // No immediates on GFX9
3877         if (!MO.isReg()) {
3878           ErrInfo =
3879             "Only reg allowed as operands in SDWA instructions on GFX9+";
3880           return false;
3881         }
3882       }
3883     }
3884 
3885     if (!ST.hasSDWAOmod()) {
3886       // No omod allowed on VI
3887       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
3888       if (OMod != nullptr &&
3889         (!OMod->isImm() || OMod->getImm() != 0)) {
3890         ErrInfo = "OMod not allowed in SDWA instructions on VI";
3891         return false;
3892       }
3893     }
3894 
3895     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
3896     if (isVOPC(BasicOpcode)) {
3897       if (!ST.hasSDWASdst() && DstIdx != -1) {
3898         // Only vcc allowed as dst on VI for VOPC
3899         const MachineOperand &Dst = MI.getOperand(DstIdx);
3900         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
3901           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
3902           return false;
3903         }
3904       } else if (!ST.hasSDWAOutModsVOPC()) {
3905         // No clamp allowed on GFX9 for VOPC
3906         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
3907         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
3908           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
3909           return false;
3910         }
3911 
3912         // No omod allowed on GFX9 for VOPC
3913         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
3914         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
3915           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
3916           return false;
3917         }
3918       }
3919     }
3920 
3921     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
3922     if (DstUnused && DstUnused->isImm() &&
3923         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
3924       const MachineOperand &Dst = MI.getOperand(DstIdx);
3925       if (!Dst.isReg() || !Dst.isTied()) {
3926         ErrInfo = "Dst register should have tied register";
3927         return false;
3928       }
3929 
3930       const MachineOperand &TiedMO =
3931           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
3932       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
3933         ErrInfo =
3934             "Dst register should be tied to implicit use of preserved register";
3935         return false;
3936       } else if (TiedMO.getReg().isPhysical() &&
3937                  Dst.getReg() != TiedMO.getReg()) {
3938         ErrInfo = "Dst register should use same physical register as preserved";
3939         return false;
3940       }
3941     }
3942   }
3943 
3944   // Verify MIMG
3945   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
3946     // Ensure that the return type used is large enough for all the options
3947     // being used TFE/LWE require an extra result register.
3948     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
3949     if (DMask) {
3950       uint64_t DMaskImm = DMask->getImm();
3951       uint32_t RegCount =
3952           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
3953       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
3954       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
3955       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
3956 
3957       // Adjust for packed 16 bit values
3958       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
3959         RegCount >>= 1;
3960 
3961       // Adjust if using LWE or TFE
3962       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
3963         RegCount += 1;
3964 
3965       const uint32_t DstIdx =
3966           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
3967       const MachineOperand &Dst = MI.getOperand(DstIdx);
3968       if (Dst.isReg()) {
3969         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
3970         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
3971         if (RegCount > DstSize) {
3972           ErrInfo = "MIMG instruction returns too many registers for dst "
3973                     "register class";
3974           return false;
3975         }
3976       }
3977     }
3978   }
3979 
3980   // Verify VOP*. Ignore multiple sgpr operands on writelane.
3981   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
3982       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
3983     // Only look at the true operands. Only a real operand can use the constant
3984     // bus, and we don't want to check pseudo-operands like the source modifier
3985     // flags.
3986     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
3987 
3988     unsigned ConstantBusCount = 0;
3989     unsigned LiteralCount = 0;
3990 
3991     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
3992       ++ConstantBusCount;
3993 
3994     SmallVector<Register, 2> SGPRsUsed;
3995     Register SGPRUsed;
3996 
3997     for (int OpIdx : OpIndices) {
3998       if (OpIdx == -1)
3999         break;
4000       const MachineOperand &MO = MI.getOperand(OpIdx);
4001       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4002         if (MO.isReg()) {
4003           SGPRUsed = MO.getReg();
4004           if (llvm::all_of(SGPRsUsed, [SGPRUsed](unsigned SGPR) {
4005                 return SGPRUsed != SGPR;
4006               })) {
4007             ++ConstantBusCount;
4008             SGPRsUsed.push_back(SGPRUsed);
4009           }
4010         } else {
4011           ++ConstantBusCount;
4012           ++LiteralCount;
4013         }
4014       }
4015     }
4016 
4017     SGPRUsed = findImplicitSGPRRead(MI);
4018     if (SGPRUsed != AMDGPU::NoRegister) {
4019       // Implicit uses may safely overlap true overands
4020       if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
4021             return !RI.regsOverlap(SGPRUsed, SGPR);
4022           })) {
4023         ++ConstantBusCount;
4024         SGPRsUsed.push_back(SGPRUsed);
4025       }
4026     }
4027 
4028     // v_writelane_b32 is an exception from constant bus restriction:
4029     // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
4030     if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
4031         Opcode != AMDGPU::V_WRITELANE_B32) {
4032       ErrInfo = "VOP* instruction violates constant bus restriction";
4033       return false;
4034     }
4035 
4036     if (isVOP3(MI) && LiteralCount) {
4037       if (!ST.hasVOP3Literal()) {
4038         ErrInfo = "VOP3 instruction uses literal";
4039         return false;
4040       }
4041       if (LiteralCount > 1) {
4042         ErrInfo = "VOP3 instruction uses more than one literal";
4043         return false;
4044       }
4045     }
4046   }
4047 
4048   // Special case for writelane - this can break the multiple constant bus rule,
4049   // but still can't use more than one SGPR register
4050   if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
4051     unsigned SGPRCount = 0;
4052     Register SGPRUsed = AMDGPU::NoRegister;
4053 
4054     for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx}) {
4055       if (OpIdx == -1)
4056         break;
4057 
4058       const MachineOperand &MO = MI.getOperand(OpIdx);
4059 
4060       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4061         if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
4062           if (MO.getReg() != SGPRUsed)
4063             ++SGPRCount;
4064           SGPRUsed = MO.getReg();
4065         }
4066       }
4067       if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
4068         ErrInfo = "WRITELANE instruction violates constant bus restriction";
4069         return false;
4070       }
4071     }
4072   }
4073 
4074   // Verify misc. restrictions on specific instructions.
4075   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
4076       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
4077     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4078     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4079     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
4080     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
4081       if (!compareMachineOp(Src0, Src1) &&
4082           !compareMachineOp(Src0, Src2)) {
4083         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
4084         return false;
4085       }
4086     }
4087     if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
4088          SISrcMods::ABS) ||
4089         (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
4090          SISrcMods::ABS) ||
4091         (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
4092          SISrcMods::ABS)) {
4093       ErrInfo = "ABS not allowed in VOP3B instructions";
4094       return false;
4095     }
4096   }
4097 
4098   if (isSOP2(MI) || isSOPC(MI)) {
4099     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4100     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4101     unsigned Immediates = 0;
4102 
4103     if (!Src0.isReg() &&
4104         !isInlineConstant(Src0, Desc.OpInfo[Src0Idx].OperandType))
4105       Immediates++;
4106     if (!Src1.isReg() &&
4107         !isInlineConstant(Src1, Desc.OpInfo[Src1Idx].OperandType))
4108       Immediates++;
4109 
4110     if (Immediates > 1) {
4111       ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
4112       return false;
4113     }
4114   }
4115 
4116   if (isSOPK(MI)) {
4117     auto Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
4118     if (Desc.isBranch()) {
4119       if (!Op->isMBB()) {
4120         ErrInfo = "invalid branch target for SOPK instruction";
4121         return false;
4122       }
4123     } else {
4124       uint64_t Imm = Op->getImm();
4125       if (sopkIsZext(MI)) {
4126         if (!isUInt<16>(Imm)) {
4127           ErrInfo = "invalid immediate for SOPK instruction";
4128           return false;
4129         }
4130       } else {
4131         if (!isInt<16>(Imm)) {
4132           ErrInfo = "invalid immediate for SOPK instruction";
4133           return false;
4134         }
4135       }
4136     }
4137   }
4138 
4139   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
4140       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
4141       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4142       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
4143     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4144                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
4145 
4146     const unsigned StaticNumOps = Desc.getNumOperands() +
4147       Desc.getNumImplicitUses();
4148     const unsigned NumImplicitOps = IsDst ? 2 : 1;
4149 
4150     // Allow additional implicit operands. This allows a fixup done by the post
4151     // RA scheduler where the main implicit operand is killed and implicit-defs
4152     // are added for sub-registers that remain live after this instruction.
4153     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
4154       ErrInfo = "missing implicit register operands";
4155       return false;
4156     }
4157 
4158     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4159     if (IsDst) {
4160       if (!Dst->isUse()) {
4161         ErrInfo = "v_movreld_b32 vdst should be a use operand";
4162         return false;
4163       }
4164 
4165       unsigned UseOpIdx;
4166       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
4167           UseOpIdx != StaticNumOps + 1) {
4168         ErrInfo = "movrel implicit operands should be tied";
4169         return false;
4170       }
4171     }
4172 
4173     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4174     const MachineOperand &ImpUse
4175       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
4176     if (!ImpUse.isReg() || !ImpUse.isUse() ||
4177         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
4178       ErrInfo = "src0 should be subreg of implicit vector use";
4179       return false;
4180     }
4181   }
4182 
4183   // Make sure we aren't losing exec uses in the td files. This mostly requires
4184   // being careful when using let Uses to try to add other use registers.
4185   if (shouldReadExec(MI)) {
4186     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
4187       ErrInfo = "VALU instruction does not implicitly read exec mask";
4188       return false;
4189     }
4190   }
4191 
4192   if (isSMRD(MI)) {
4193     if (MI.mayStore()) {
4194       // The register offset form of scalar stores may only use m0 as the
4195       // soffset register.
4196       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
4197       if (Soff && Soff->getReg() != AMDGPU::M0) {
4198         ErrInfo = "scalar stores must use m0 as offset register";
4199         return false;
4200       }
4201     }
4202   }
4203 
4204   if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
4205     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4206     if (Offset->getImm() != 0) {
4207       ErrInfo = "subtarget does not support offsets in flat instructions";
4208       return false;
4209     }
4210   }
4211 
4212   if (isMIMG(MI)) {
4213     const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
4214     if (DimOp) {
4215       int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
4216                                                  AMDGPU::OpName::vaddr0);
4217       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
4218       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
4219       const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4220           AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
4221       const AMDGPU::MIMGDimInfo *Dim =
4222           AMDGPU::getMIMGDimInfoByEncoding(DimOp->getImm());
4223 
4224       if (!Dim) {
4225         ErrInfo = "dim is out of range";
4226         return false;
4227       }
4228 
4229       bool IsA16 = false;
4230       if (ST.hasR128A16()) {
4231         const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
4232         IsA16 = R128A16->getImm() != 0;
4233       } else if (ST.hasGFX10A16()) {
4234         const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
4235         IsA16 = A16->getImm() != 0;
4236       }
4237 
4238       bool PackDerivatives = IsA16 || BaseOpcode->G16;
4239       bool IsNSA = SRsrcIdx - VAddr0Idx > 1;
4240 
4241       unsigned AddrWords = BaseOpcode->NumExtraArgs;
4242       unsigned AddrComponents = (BaseOpcode->Coordinates ? Dim->NumCoords : 0) +
4243                                 (BaseOpcode->LodOrClampOrMip ? 1 : 0);
4244       if (IsA16)
4245         AddrWords += (AddrComponents + 1) / 2;
4246       else
4247         AddrWords += AddrComponents;
4248 
4249       if (BaseOpcode->Gradients) {
4250         if (PackDerivatives)
4251           // There are two gradients per coordinate, we pack them separately.
4252           // For the 3d case, we get (dy/du, dx/du) (-, dz/du) (dy/dv, dx/dv) (-, dz/dv)
4253           AddrWords += (Dim->NumGradients / 2 + 1) / 2 * 2;
4254         else
4255           AddrWords += Dim->NumGradients;
4256       }
4257 
4258       unsigned VAddrWords;
4259       if (IsNSA) {
4260         VAddrWords = SRsrcIdx - VAddr0Idx;
4261       } else {
4262         const TargetRegisterClass *RC = getOpRegClass(MI, VAddr0Idx);
4263         VAddrWords = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 32;
4264         if (AddrWords > 8)
4265           AddrWords = 16;
4266         else if (AddrWords > 4)
4267           AddrWords = 8;
4268         else if (AddrWords == 4)
4269           AddrWords = 4;
4270         else if (AddrWords == 3)
4271           AddrWords = 3;
4272       }
4273 
4274       if (VAddrWords != AddrWords) {
4275         LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
4276                           << " but got " << VAddrWords << "\n");
4277         ErrInfo = "bad vaddr size";
4278         return false;
4279       }
4280     }
4281   }
4282 
4283   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
4284   if (DppCt) {
4285     using namespace AMDGPU::DPP;
4286 
4287     unsigned DC = DppCt->getImm();
4288     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
4289         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
4290         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
4291         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
4292         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
4293         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
4294         (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
4295       ErrInfo = "Invalid dpp_ctrl value";
4296       return false;
4297     }
4298     if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
4299         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4300       ErrInfo = "Invalid dpp_ctrl value: "
4301                 "wavefront shifts are not supported on GFX10+";
4302       return false;
4303     }
4304     if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
4305         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4306       ErrInfo = "Invalid dpp_ctrl value: "
4307                 "broadcasts are not supported on GFX10+";
4308       return false;
4309     }
4310     if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
4311         ST.getGeneration() < AMDGPUSubtarget::GFX10) {
4312       if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
4313           DC <= DppCtrl::ROW_NEWBCAST_LAST &&
4314           !ST.hasGFX90AInsts()) {
4315         ErrInfo = "Invalid dpp_ctrl value: "
4316                   "row_newbroadcast/row_share is not supported before "
4317                   "GFX90A/GFX10";
4318         return false;
4319       } else if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
4320         ErrInfo = "Invalid dpp_ctrl value: "
4321                   "row_share and row_xmask are not supported before GFX10";
4322         return false;
4323       }
4324     }
4325 
4326     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4327     int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
4328 
4329     if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
4330         ((DstIdx >= 0 &&
4331           (Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64RegClassID ||
4332            Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64_Align2RegClassID)) ||
4333          ((Src0Idx >= 0 &&
4334            (Desc.OpInfo[Src0Idx].RegClass == AMDGPU::VReg_64RegClassID ||
4335             Desc.OpInfo[Src0Idx].RegClass ==
4336                 AMDGPU::VReg_64_Align2RegClassID)))) &&
4337         !AMDGPU::isLegal64BitDPPControl(DC)) {
4338       ErrInfo = "Invalid dpp_ctrl value: "
4339                 "64 bit dpp only support row_newbcast";
4340       return false;
4341     }
4342   }
4343 
4344   if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
4345     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4346     uint16_t DataNameIdx = isDS(Opcode) ? AMDGPU::OpName::data0
4347                                         : AMDGPU::OpName::vdata;
4348     const MachineOperand *Data = getNamedOperand(MI, DataNameIdx);
4349     const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
4350     if (Data && !Data->isReg())
4351       Data = nullptr;
4352 
4353     if (ST.hasGFX90AInsts()) {
4354       if (Dst && Data &&
4355           (RI.isAGPR(MRI, Dst->getReg()) != RI.isAGPR(MRI, Data->getReg()))) {
4356         ErrInfo = "Invalid register class: "
4357                   "vdata and vdst should be both VGPR or AGPR";
4358         return false;
4359       }
4360       if (Data && Data2 &&
4361           (RI.isAGPR(MRI, Data->getReg()) != RI.isAGPR(MRI, Data2->getReg()))) {
4362         ErrInfo = "Invalid register class: "
4363                   "both data operands should be VGPR or AGPR";
4364         return false;
4365       }
4366     } else {
4367       if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
4368           (Data && RI.isAGPR(MRI, Data->getReg())) ||
4369           (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
4370         ErrInfo = "Invalid register class: "
4371                   "agpr loads and stores not supported on this GPU";
4372         return false;
4373       }
4374     }
4375   }
4376 
4377   return true;
4378 }
4379 
4380 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
4381   switch (MI.getOpcode()) {
4382   default: return AMDGPU::INSTRUCTION_LIST_END;
4383   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
4384   case AMDGPU::COPY: return AMDGPU::COPY;
4385   case AMDGPU::PHI: return AMDGPU::PHI;
4386   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
4387   case AMDGPU::WQM: return AMDGPU::WQM;
4388   case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
4389   case AMDGPU::STRICT_WWM: return AMDGPU::STRICT_WWM;
4390   case AMDGPU::STRICT_WQM: return AMDGPU::STRICT_WQM;
4391   case AMDGPU::S_MOV_B32: {
4392     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4393     return MI.getOperand(1).isReg() ||
4394            RI.isAGPR(MRI, MI.getOperand(0).getReg()) ?
4395            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
4396   }
4397   case AMDGPU::S_ADD_I32:
4398     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
4399   case AMDGPU::S_ADDC_U32:
4400     return AMDGPU::V_ADDC_U32_e32;
4401   case AMDGPU::S_SUB_I32:
4402     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
4403     // FIXME: These are not consistently handled, and selected when the carry is
4404     // used.
4405   case AMDGPU::S_ADD_U32:
4406     return AMDGPU::V_ADD_CO_U32_e32;
4407   case AMDGPU::S_SUB_U32:
4408     return AMDGPU::V_SUB_CO_U32_e32;
4409   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
4410   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
4411   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
4412   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
4413   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
4414   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
4415   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
4416   case AMDGPU::S_XNOR_B32:
4417     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
4418   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
4419   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
4420   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
4421   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
4422   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
4423   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
4424   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
4425   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
4426   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
4427   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
4428   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
4429   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
4430   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
4431   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
4432   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
4433   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
4434   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
4435   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
4436   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
4437   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
4438   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
4439   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
4440   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
4441   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
4442   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
4443   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
4444   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
4445   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
4446   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
4447   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
4448   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
4449   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
4450   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
4451   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
4452   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
4453   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
4454   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
4455   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
4456   }
4457   llvm_unreachable(
4458       "Unexpected scalar opcode without corresponding vector one!");
4459 }
4460 
4461 static unsigned adjustAllocatableRegClass(const GCNSubtarget &ST,
4462                                           const MachineRegisterInfo &MRI,
4463                                           const MCInstrDesc &TID,
4464                                           unsigned RCID,
4465                                           bool IsAllocatable) {
4466   if ((IsAllocatable || !ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4467       (TID.mayLoad() || TID.mayStore() ||
4468       (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::MIMG)))) {
4469     switch (RCID) {
4470     case AMDGPU::AV_32RegClassID: return AMDGPU::VGPR_32RegClassID;
4471     case AMDGPU::AV_64RegClassID: return AMDGPU::VReg_64RegClassID;
4472     case AMDGPU::AV_96RegClassID: return AMDGPU::VReg_96RegClassID;
4473     case AMDGPU::AV_128RegClassID: return AMDGPU::VReg_128RegClassID;
4474     case AMDGPU::AV_160RegClassID: return AMDGPU::VReg_160RegClassID;
4475     default:
4476       break;
4477     }
4478   }
4479   return RCID;
4480 }
4481 
4482 const TargetRegisterClass *SIInstrInfo::getRegClass(const MCInstrDesc &TID,
4483     unsigned OpNum, const TargetRegisterInfo *TRI,
4484     const MachineFunction &MF)
4485   const {
4486   if (OpNum >= TID.getNumOperands())
4487     return nullptr;
4488   auto RegClass = TID.OpInfo[OpNum].RegClass;
4489   bool IsAllocatable = false;
4490   if (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::FLAT)) {
4491     // vdst and vdata should be both VGPR or AGPR, same for the DS instructions
4492     // with two data operands. Request register class constainted to VGPR only
4493     // of both operands present as Machine Copy Propagation can not check this
4494     // constraint and possibly other passes too.
4495     //
4496     // The check is limited to FLAT and DS because atomics in non-flat encoding
4497     // have their vdst and vdata tied to be the same register.
4498     const int VDstIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4499                                                    AMDGPU::OpName::vdst);
4500     const int DataIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4501         (TID.TSFlags & SIInstrFlags::DS) ? AMDGPU::OpName::data0
4502                                          : AMDGPU::OpName::vdata);
4503     if (DataIdx != -1) {
4504       IsAllocatable = VDstIdx != -1 ||
4505                       AMDGPU::getNamedOperandIdx(TID.Opcode,
4506                                                  AMDGPU::OpName::data1) != -1;
4507     }
4508   }
4509   RegClass = adjustAllocatableRegClass(ST, MF.getRegInfo(), TID, RegClass,
4510                                        IsAllocatable);
4511   return RI.getRegClass(RegClass);
4512 }
4513 
4514 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
4515                                                       unsigned OpNo) const {
4516   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4517   const MCInstrDesc &Desc = get(MI.getOpcode());
4518   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
4519       Desc.OpInfo[OpNo].RegClass == -1) {
4520     Register Reg = MI.getOperand(OpNo).getReg();
4521 
4522     if (Reg.isVirtual())
4523       return MRI.getRegClass(Reg);
4524     return RI.getPhysRegClass(Reg);
4525   }
4526 
4527   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
4528   RCID = adjustAllocatableRegClass(ST, MRI, Desc, RCID, true);
4529   return RI.getRegClass(RCID);
4530 }
4531 
4532 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
4533   MachineBasicBlock::iterator I = MI;
4534   MachineBasicBlock *MBB = MI.getParent();
4535   MachineOperand &MO = MI.getOperand(OpIdx);
4536   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4537   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
4538   const TargetRegisterClass *RC = RI.getRegClass(RCID);
4539   unsigned Size = RI.getRegSizeInBits(*RC);
4540   unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO : AMDGPU::V_MOV_B32_e32;
4541   if (MO.isReg())
4542     Opcode = AMDGPU::COPY;
4543   else if (RI.isSGPRClass(RC))
4544     Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
4545 
4546   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
4547   const TargetRegisterClass *VRC64 = RI.getVGPR64Class();
4548   if (RI.getCommonSubClass(VRC64, VRC))
4549     VRC = VRC64;
4550   else
4551     VRC = &AMDGPU::VGPR_32RegClass;
4552 
4553   Register Reg = MRI.createVirtualRegister(VRC);
4554   DebugLoc DL = MBB->findDebugLoc(I);
4555   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
4556   MO.ChangeToRegister(Reg, false);
4557 }
4558 
4559 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
4560                                          MachineRegisterInfo &MRI,
4561                                          MachineOperand &SuperReg,
4562                                          const TargetRegisterClass *SuperRC,
4563                                          unsigned SubIdx,
4564                                          const TargetRegisterClass *SubRC)
4565                                          const {
4566   MachineBasicBlock *MBB = MI->getParent();
4567   DebugLoc DL = MI->getDebugLoc();
4568   Register SubReg = MRI.createVirtualRegister(SubRC);
4569 
4570   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
4571     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4572       .addReg(SuperReg.getReg(), 0, SubIdx);
4573     return SubReg;
4574   }
4575 
4576   // Just in case the super register is itself a sub-register, copy it to a new
4577   // value so we don't need to worry about merging its subreg index with the
4578   // SubIdx passed to this function. The register coalescer should be able to
4579   // eliminate this extra copy.
4580   Register NewSuperReg = MRI.createVirtualRegister(SuperRC);
4581 
4582   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
4583     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
4584 
4585   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4586     .addReg(NewSuperReg, 0, SubIdx);
4587 
4588   return SubReg;
4589 }
4590 
4591 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
4592   MachineBasicBlock::iterator MII,
4593   MachineRegisterInfo &MRI,
4594   MachineOperand &Op,
4595   const TargetRegisterClass *SuperRC,
4596   unsigned SubIdx,
4597   const TargetRegisterClass *SubRC) const {
4598   if (Op.isImm()) {
4599     if (SubIdx == AMDGPU::sub0)
4600       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
4601     if (SubIdx == AMDGPU::sub1)
4602       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
4603 
4604     llvm_unreachable("Unhandled register index for immediate");
4605   }
4606 
4607   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
4608                                        SubIdx, SubRC);
4609   return MachineOperand::CreateReg(SubReg, false);
4610 }
4611 
4612 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
4613 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
4614   assert(Inst.getNumExplicitOperands() == 3);
4615   MachineOperand Op1 = Inst.getOperand(1);
4616   Inst.RemoveOperand(1);
4617   Inst.addOperand(Op1);
4618 }
4619 
4620 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
4621                                     const MCOperandInfo &OpInfo,
4622                                     const MachineOperand &MO) const {
4623   if (!MO.isReg())
4624     return false;
4625 
4626   Register Reg = MO.getReg();
4627 
4628   const TargetRegisterClass *DRC = RI.getRegClass(OpInfo.RegClass);
4629   if (Reg.isPhysical())
4630     return DRC->contains(Reg);
4631 
4632   const TargetRegisterClass *RC = MRI.getRegClass(Reg);
4633 
4634   if (MO.getSubReg()) {
4635     const MachineFunction *MF = MO.getParent()->getParent()->getParent();
4636     const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
4637     if (!SuperRC)
4638       return false;
4639 
4640     DRC = RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg());
4641     if (!DRC)
4642       return false;
4643   }
4644   return RC->hasSuperClassEq(DRC);
4645 }
4646 
4647 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
4648                                      const MCOperandInfo &OpInfo,
4649                                      const MachineOperand &MO) const {
4650   if (MO.isReg())
4651     return isLegalRegOperand(MRI, OpInfo, MO);
4652 
4653   // Handle non-register types that are treated like immediates.
4654   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
4655   return true;
4656 }
4657 
4658 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
4659                                  const MachineOperand *MO) const {
4660   const MachineFunction &MF = *MI.getParent()->getParent();
4661   const MachineRegisterInfo &MRI = MF.getRegInfo();
4662   const MCInstrDesc &InstDesc = MI.getDesc();
4663   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
4664   const TargetRegisterClass *DefinedRC =
4665       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
4666   if (!MO)
4667     MO = &MI.getOperand(OpIdx);
4668 
4669   int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
4670   int VOP3LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4671   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
4672     if (isVOP3(MI) && isLiteralConstantLike(*MO, OpInfo) && !VOP3LiteralLimit--)
4673       return false;
4674 
4675     SmallDenseSet<RegSubRegPair> SGPRsUsed;
4676     if (MO->isReg())
4677       SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
4678 
4679     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4680       if (i == OpIdx)
4681         continue;
4682       const MachineOperand &Op = MI.getOperand(i);
4683       if (Op.isReg()) {
4684         RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
4685         if (!SGPRsUsed.count(SGPR) &&
4686             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
4687           if (--ConstantBusLimit <= 0)
4688             return false;
4689           SGPRsUsed.insert(SGPR);
4690         }
4691       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
4692         if (--ConstantBusLimit <= 0)
4693           return false;
4694       } else if (isVOP3(MI) && AMDGPU::isSISrcOperand(InstDesc, i) &&
4695                  isLiteralConstantLike(Op, InstDesc.OpInfo[i])) {
4696         if (!VOP3LiteralLimit--)
4697           return false;
4698         if (--ConstantBusLimit <= 0)
4699           return false;
4700       }
4701     }
4702   }
4703 
4704   if (MO->isReg()) {
4705     assert(DefinedRC);
4706     if (!isLegalRegOperand(MRI, OpInfo, *MO))
4707       return false;
4708     bool IsAGPR = RI.isAGPR(MRI, MO->getReg());
4709     if (IsAGPR && !ST.hasMAIInsts())
4710       return false;
4711     unsigned Opc = MI.getOpcode();
4712     if (IsAGPR &&
4713         (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4714         (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
4715       return false;
4716     // Atomics should have both vdst and vdata either vgpr or agpr.
4717     const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
4718     const int DataIdx = AMDGPU::getNamedOperandIdx(Opc,
4719         isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
4720     if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
4721         MI.getOperand(DataIdx).isReg() &&
4722         RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
4723       return false;
4724     if ((int)OpIdx == DataIdx) {
4725       if (VDstIdx != -1 &&
4726           RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
4727         return false;
4728       // DS instructions with 2 src operands also must have tied RC.
4729       const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc,
4730                                                       AMDGPU::OpName::data1);
4731       if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
4732           RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
4733         return false;
4734     }
4735     if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 &&
4736         (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
4737         RI.isSGPRReg(MRI, MO->getReg()))
4738       return false;
4739     return true;
4740   }
4741 
4742   // Handle non-register types that are treated like immediates.
4743   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
4744 
4745   if (!DefinedRC) {
4746     // This operand expects an immediate.
4747     return true;
4748   }
4749 
4750   return isImmOperandLegal(MI, OpIdx, *MO);
4751 }
4752 
4753 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
4754                                        MachineInstr &MI) const {
4755   unsigned Opc = MI.getOpcode();
4756   const MCInstrDesc &InstrDesc = get(Opc);
4757 
4758   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
4759   MachineOperand &Src0 = MI.getOperand(Src0Idx);
4760 
4761   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
4762   MachineOperand &Src1 = MI.getOperand(Src1Idx);
4763 
4764   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
4765   // we need to only have one constant bus use before GFX10.
4766   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
4767   if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 &&
4768       Src0.isReg() && (RI.isSGPRReg(MRI, Src0.getReg()) ||
4769        isLiteralConstantLike(Src0, InstrDesc.OpInfo[Src0Idx])))
4770     legalizeOpWithMove(MI, Src0Idx);
4771 
4772   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
4773   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
4774   // src0/src1 with V_READFIRSTLANE.
4775   if (Opc == AMDGPU::V_WRITELANE_B32) {
4776     const DebugLoc &DL = MI.getDebugLoc();
4777     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
4778       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4779       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4780           .add(Src0);
4781       Src0.ChangeToRegister(Reg, false);
4782     }
4783     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
4784       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4785       const DebugLoc &DL = MI.getDebugLoc();
4786       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4787           .add(Src1);
4788       Src1.ChangeToRegister(Reg, false);
4789     }
4790     return;
4791   }
4792 
4793   // No VOP2 instructions support AGPRs.
4794   if (Src0.isReg() && RI.isAGPR(MRI, Src0.getReg()))
4795     legalizeOpWithMove(MI, Src0Idx);
4796 
4797   if (Src1.isReg() && RI.isAGPR(MRI, Src1.getReg()))
4798     legalizeOpWithMove(MI, Src1Idx);
4799 
4800   // VOP2 src0 instructions support all operand types, so we don't need to check
4801   // their legality. If src1 is already legal, we don't need to do anything.
4802   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
4803     return;
4804 
4805   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
4806   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
4807   // select is uniform.
4808   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
4809       RI.isVGPR(MRI, Src1.getReg())) {
4810     Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4811     const DebugLoc &DL = MI.getDebugLoc();
4812     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4813         .add(Src1);
4814     Src1.ChangeToRegister(Reg, false);
4815     return;
4816   }
4817 
4818   // We do not use commuteInstruction here because it is too aggressive and will
4819   // commute if it is possible. We only want to commute here if it improves
4820   // legality. This can be called a fairly large number of times so don't waste
4821   // compile time pointlessly swapping and checking legality again.
4822   if (HasImplicitSGPR || !MI.isCommutable()) {
4823     legalizeOpWithMove(MI, Src1Idx);
4824     return;
4825   }
4826 
4827   // If src0 can be used as src1, commuting will make the operands legal.
4828   // Otherwise we have to give up and insert a move.
4829   //
4830   // TODO: Other immediate-like operand kinds could be commuted if there was a
4831   // MachineOperand::ChangeTo* for them.
4832   if ((!Src1.isImm() && !Src1.isReg()) ||
4833       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
4834     legalizeOpWithMove(MI, Src1Idx);
4835     return;
4836   }
4837 
4838   int CommutedOpc = commuteOpcode(MI);
4839   if (CommutedOpc == -1) {
4840     legalizeOpWithMove(MI, Src1Idx);
4841     return;
4842   }
4843 
4844   MI.setDesc(get(CommutedOpc));
4845 
4846   Register Src0Reg = Src0.getReg();
4847   unsigned Src0SubReg = Src0.getSubReg();
4848   bool Src0Kill = Src0.isKill();
4849 
4850   if (Src1.isImm())
4851     Src0.ChangeToImmediate(Src1.getImm());
4852   else if (Src1.isReg()) {
4853     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
4854     Src0.setSubReg(Src1.getSubReg());
4855   } else
4856     llvm_unreachable("Should only have register or immediate operands");
4857 
4858   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
4859   Src1.setSubReg(Src0SubReg);
4860   fixImplicitOperands(MI);
4861 }
4862 
4863 // Legalize VOP3 operands. All operand types are supported for any operand
4864 // but only one literal constant and only starting from GFX10.
4865 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
4866                                        MachineInstr &MI) const {
4867   unsigned Opc = MI.getOpcode();
4868 
4869   int VOP3Idx[3] = {
4870     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
4871     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
4872     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
4873   };
4874 
4875   if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
4876       Opc == AMDGPU::V_PERMLANEX16_B32_e64) {
4877     // src1 and src2 must be scalar
4878     MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
4879     MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
4880     const DebugLoc &DL = MI.getDebugLoc();
4881     if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
4882       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4883       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4884         .add(Src1);
4885       Src1.ChangeToRegister(Reg, false);
4886     }
4887     if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
4888       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4889       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
4890         .add(Src2);
4891       Src2.ChangeToRegister(Reg, false);
4892     }
4893   }
4894 
4895   // Find the one SGPR operand we are allowed to use.
4896   int ConstantBusLimit = ST.getConstantBusLimit(Opc);
4897   int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4898   SmallDenseSet<unsigned> SGPRsUsed;
4899   Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
4900   if (SGPRReg != AMDGPU::NoRegister) {
4901     SGPRsUsed.insert(SGPRReg);
4902     --ConstantBusLimit;
4903   }
4904 
4905   for (unsigned i = 0; i < 3; ++i) {
4906     int Idx = VOP3Idx[i];
4907     if (Idx == -1)
4908       break;
4909     MachineOperand &MO = MI.getOperand(Idx);
4910 
4911     if (!MO.isReg()) {
4912       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
4913         continue;
4914 
4915       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
4916         --LiteralLimit;
4917         --ConstantBusLimit;
4918         continue;
4919       }
4920 
4921       --LiteralLimit;
4922       --ConstantBusLimit;
4923       legalizeOpWithMove(MI, Idx);
4924       continue;
4925     }
4926 
4927     if (RI.hasAGPRs(MRI.getRegClass(MO.getReg())) &&
4928         !isOperandLegal(MI, Idx, &MO)) {
4929       legalizeOpWithMove(MI, Idx);
4930       continue;
4931     }
4932 
4933     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
4934       continue; // VGPRs are legal
4935 
4936     // We can use one SGPR in each VOP3 instruction prior to GFX10
4937     // and two starting from GFX10.
4938     if (SGPRsUsed.count(MO.getReg()))
4939       continue;
4940     if (ConstantBusLimit > 0) {
4941       SGPRsUsed.insert(MO.getReg());
4942       --ConstantBusLimit;
4943       continue;
4944     }
4945 
4946     // If we make it this far, then the operand is not legal and we must
4947     // legalize it.
4948     legalizeOpWithMove(MI, Idx);
4949   }
4950 }
4951 
4952 Register SIInstrInfo::readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI,
4953                                          MachineRegisterInfo &MRI) const {
4954   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
4955   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
4956   Register DstReg = MRI.createVirtualRegister(SRC);
4957   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
4958 
4959   if (RI.hasAGPRs(VRC)) {
4960     VRC = RI.getEquivalentVGPRClass(VRC);
4961     Register NewSrcReg = MRI.createVirtualRegister(VRC);
4962     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4963             get(TargetOpcode::COPY), NewSrcReg)
4964         .addReg(SrcReg);
4965     SrcReg = NewSrcReg;
4966   }
4967 
4968   if (SubRegs == 1) {
4969     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4970             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
4971         .addReg(SrcReg);
4972     return DstReg;
4973   }
4974 
4975   SmallVector<unsigned, 8> SRegs;
4976   for (unsigned i = 0; i < SubRegs; ++i) {
4977     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4978     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4979             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
4980         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
4981     SRegs.push_back(SGPR);
4982   }
4983 
4984   MachineInstrBuilder MIB =
4985       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
4986               get(AMDGPU::REG_SEQUENCE), DstReg);
4987   for (unsigned i = 0; i < SubRegs; ++i) {
4988     MIB.addReg(SRegs[i]);
4989     MIB.addImm(RI.getSubRegFromChannel(i));
4990   }
4991   return DstReg;
4992 }
4993 
4994 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
4995                                        MachineInstr &MI) const {
4996 
4997   // If the pointer is store in VGPRs, then we need to move them to
4998   // SGPRs using v_readfirstlane.  This is safe because we only select
4999   // loads with uniform pointers to SMRD instruction so we know the
5000   // pointer value is uniform.
5001   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
5002   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
5003     Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
5004     SBase->setReg(SGPR);
5005   }
5006   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
5007   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
5008     Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
5009     SOff->setReg(SGPR);
5010   }
5011 }
5012 
5013 // FIXME: Remove this when SelectionDAG is obsoleted.
5014 void SIInstrInfo::legalizeOperandsFLAT(MachineRegisterInfo &MRI,
5015                                        MachineInstr &MI) const {
5016   if (!isSegmentSpecificFLAT(MI))
5017     return;
5018 
5019   // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
5020   // thinks they are uniform, so a readfirstlane should be valid.
5021   MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
5022   if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
5023     return;
5024 
5025   Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI);
5026   SAddr->setReg(ToSGPR);
5027 }
5028 
5029 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
5030                                          MachineBasicBlock::iterator I,
5031                                          const TargetRegisterClass *DstRC,
5032                                          MachineOperand &Op,
5033                                          MachineRegisterInfo &MRI,
5034                                          const DebugLoc &DL) const {
5035   Register OpReg = Op.getReg();
5036   unsigned OpSubReg = Op.getSubReg();
5037 
5038   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
5039       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
5040 
5041   // Check if operand is already the correct register class.
5042   if (DstRC == OpRC)
5043     return;
5044 
5045   Register DstReg = MRI.createVirtualRegister(DstRC);
5046   MachineInstr *Copy =
5047       BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
5048 
5049   Op.setReg(DstReg);
5050   Op.setSubReg(0);
5051 
5052   MachineInstr *Def = MRI.getVRegDef(OpReg);
5053   if (!Def)
5054     return;
5055 
5056   // Try to eliminate the copy if it is copying an immediate value.
5057   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
5058     FoldImmediate(*Copy, *Def, OpReg, &MRI);
5059 
5060   bool ImpDef = Def->isImplicitDef();
5061   while (!ImpDef && Def && Def->isCopy()) {
5062     if (Def->getOperand(1).getReg().isPhysical())
5063       break;
5064     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
5065     ImpDef = Def && Def->isImplicitDef();
5066   }
5067   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
5068       !ImpDef)
5069     Copy->addOperand(MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
5070 }
5071 
5072 // Emit the actual waterfall loop, executing the wrapped instruction for each
5073 // unique value of \p Rsrc across all lanes. In the best case we execute 1
5074 // iteration, in the worst case we execute 64 (once per lane).
5075 static void
5076 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
5077                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5078                           const DebugLoc &DL, MachineOperand &Rsrc) {
5079   MachineFunction &MF = *OrigBB.getParent();
5080   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5081   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5082   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5083   unsigned SaveExecOpc =
5084       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
5085   unsigned XorTermOpc =
5086       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
5087   unsigned AndOpc =
5088       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
5089   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5090 
5091   MachineBasicBlock::iterator I = LoopBB.begin();
5092 
5093   SmallVector<Register, 8> ReadlanePieces;
5094   Register CondReg = AMDGPU::NoRegister;
5095 
5096   Register VRsrc = Rsrc.getReg();
5097   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
5098 
5099   unsigned RegSize = TRI->getRegSizeInBits(Rsrc.getReg(), MRI);
5100   unsigned NumSubRegs =  RegSize / 32;
5101   assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 && "Unhandled register size");
5102 
5103   for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
5104 
5105     Register CurRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5106     Register CurRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5107 
5108     // Read the next variant <- also loop target.
5109     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
5110             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx));
5111 
5112     // Read the next variant <- also loop target.
5113     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
5114             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx + 1));
5115 
5116     ReadlanePieces.push_back(CurRegLo);
5117     ReadlanePieces.push_back(CurRegHi);
5118 
5119     // Comparison is to be done as 64-bit.
5120     Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
5121     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
5122             .addReg(CurRegLo)
5123             .addImm(AMDGPU::sub0)
5124             .addReg(CurRegHi)
5125             .addImm(AMDGPU::sub1);
5126 
5127     Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
5128     auto Cmp =
5129         BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
5130             .addReg(CurReg);
5131     if (NumSubRegs <= 2)
5132       Cmp.addReg(VRsrc);
5133     else
5134       Cmp.addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx, 2));
5135 
5136     // Combine the comparision results with AND.
5137     if (CondReg == AMDGPU::NoRegister) // First.
5138       CondReg = NewCondReg;
5139     else { // If not the first, we create an AND.
5140       Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
5141       BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndReg)
5142               .addReg(CondReg)
5143               .addReg(NewCondReg);
5144       CondReg = AndReg;
5145     }
5146   } // End for loop.
5147 
5148   auto SRsrcRC = TRI->getEquivalentSGPRClass(MRI.getRegClass(VRsrc));
5149   Register SRsrc = MRI.createVirtualRegister(SRsrcRC);
5150 
5151   // Build scalar Rsrc.
5152   auto Merge = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc);
5153   unsigned Channel = 0;
5154   for (Register Piece : ReadlanePieces) {
5155     Merge.addReg(Piece)
5156          .addImm(TRI->getSubRegFromChannel(Channel++));
5157   }
5158 
5159   // Update Rsrc operand to use the SGPR Rsrc.
5160   Rsrc.setReg(SRsrc);
5161   Rsrc.setIsKill(true);
5162 
5163   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5164   MRI.setSimpleHint(SaveExec, CondReg);
5165 
5166   // Update EXEC to matching lanes, saving original to SaveExec.
5167   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
5168       .addReg(CondReg, RegState::Kill);
5169 
5170   // The original instruction is here; we insert the terminators after it.
5171   I = LoopBB.end();
5172 
5173   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5174   BuildMI(LoopBB, I, DL, TII.get(XorTermOpc), Exec)
5175       .addReg(Exec)
5176       .addReg(SaveExec);
5177 
5178   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(&LoopBB);
5179 }
5180 
5181 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
5182 // with SGPRs by iterating over all unique values across all lanes.
5183 // Returns the loop basic block that now contains \p MI.
5184 static MachineBasicBlock *
5185 loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
5186                   MachineOperand &Rsrc, MachineDominatorTree *MDT,
5187                   MachineBasicBlock::iterator Begin = nullptr,
5188                   MachineBasicBlock::iterator End = nullptr) {
5189   MachineBasicBlock &MBB = *MI.getParent();
5190   MachineFunction &MF = *MBB.getParent();
5191   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5192   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5193   MachineRegisterInfo &MRI = MF.getRegInfo();
5194   if (!Begin.isValid())
5195     Begin = &MI;
5196   if (!End.isValid()) {
5197     End = &MI;
5198     ++End;
5199   }
5200   const DebugLoc &DL = MI.getDebugLoc();
5201   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5202   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
5203   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5204 
5205   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5206 
5207   // Save the EXEC mask
5208   BuildMI(MBB, Begin, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
5209 
5210   // Killed uses in the instruction we are waterfalling around will be
5211   // incorrect due to the added control-flow.
5212   MachineBasicBlock::iterator AfterMI = MI;
5213   ++AfterMI;
5214   for (auto I = Begin; I != AfterMI; I++) {
5215     for (auto &MO : I->uses()) {
5216       if (MO.isReg() && MO.isUse()) {
5217         MRI.clearKillFlags(MO.getReg());
5218       }
5219     }
5220   }
5221 
5222   // To insert the loop we need to split the block. Move everything after this
5223   // point to a new block, and insert a new empty block between the two.
5224   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
5225   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
5226   MachineFunction::iterator MBBI(MBB);
5227   ++MBBI;
5228 
5229   MF.insert(MBBI, LoopBB);
5230   MF.insert(MBBI, RemainderBB);
5231 
5232   LoopBB->addSuccessor(LoopBB);
5233   LoopBB->addSuccessor(RemainderBB);
5234 
5235   // Move Begin to MI to the LoopBB, and the remainder of the block to
5236   // RemainderBB.
5237   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5238   RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
5239   LoopBB->splice(LoopBB->begin(), &MBB, Begin, MBB.end());
5240 
5241   MBB.addSuccessor(LoopBB);
5242 
5243   // Update dominators. We know that MBB immediately dominates LoopBB, that
5244   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
5245   // dominates all of the successors transferred to it from MBB that MBB used
5246   // to properly dominate.
5247   if (MDT) {
5248     MDT->addNewBlock(LoopBB, &MBB);
5249     MDT->addNewBlock(RemainderBB, LoopBB);
5250     for (auto &Succ : RemainderBB->successors()) {
5251       if (MDT->properlyDominates(&MBB, Succ)) {
5252         MDT->changeImmediateDominator(Succ, RemainderBB);
5253       }
5254     }
5255   }
5256 
5257   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
5258 
5259   // Restore the EXEC mask
5260   MachineBasicBlock::iterator First = RemainderBB->begin();
5261   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
5262   return LoopBB;
5263 }
5264 
5265 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
5266 static std::tuple<unsigned, unsigned>
5267 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
5268   MachineBasicBlock &MBB = *MI.getParent();
5269   MachineFunction &MF = *MBB.getParent();
5270   MachineRegisterInfo &MRI = MF.getRegInfo();
5271 
5272   // Extract the ptr from the resource descriptor.
5273   unsigned RsrcPtr =
5274       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
5275                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
5276 
5277   // Create an empty resource descriptor
5278   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5279   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5280   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5281   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
5282   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
5283 
5284   // Zero64 = 0
5285   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
5286       .addImm(0);
5287 
5288   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
5289   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
5290       .addImm(RsrcDataFormat & 0xFFFFFFFF);
5291 
5292   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
5293   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
5294       .addImm(RsrcDataFormat >> 32);
5295 
5296   // NewSRsrc = {Zero64, SRsrcFormat}
5297   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
5298       .addReg(Zero64)
5299       .addImm(AMDGPU::sub0_sub1)
5300       .addReg(SRsrcFormatLo)
5301       .addImm(AMDGPU::sub2)
5302       .addReg(SRsrcFormatHi)
5303       .addImm(AMDGPU::sub3);
5304 
5305   return std::make_tuple(RsrcPtr, NewSRsrc);
5306 }
5307 
5308 MachineBasicBlock *
5309 SIInstrInfo::legalizeOperands(MachineInstr &MI,
5310                               MachineDominatorTree *MDT) const {
5311   MachineFunction &MF = *MI.getParent()->getParent();
5312   MachineRegisterInfo &MRI = MF.getRegInfo();
5313   MachineBasicBlock *CreatedBB = nullptr;
5314 
5315   // Legalize VOP2
5316   if (isVOP2(MI) || isVOPC(MI)) {
5317     legalizeOperandsVOP2(MRI, MI);
5318     return CreatedBB;
5319   }
5320 
5321   // Legalize VOP3
5322   if (isVOP3(MI)) {
5323     legalizeOperandsVOP3(MRI, MI);
5324     return CreatedBB;
5325   }
5326 
5327   // Legalize SMRD
5328   if (isSMRD(MI)) {
5329     legalizeOperandsSMRD(MRI, MI);
5330     return CreatedBB;
5331   }
5332 
5333   // Legalize FLAT
5334   if (isFLAT(MI)) {
5335     legalizeOperandsFLAT(MRI, MI);
5336     return CreatedBB;
5337   }
5338 
5339   // Legalize REG_SEQUENCE and PHI
5340   // The register class of the operands much be the same type as the register
5341   // class of the output.
5342   if (MI.getOpcode() == AMDGPU::PHI) {
5343     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
5344     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
5345       if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
5346         continue;
5347       const TargetRegisterClass *OpRC =
5348           MRI.getRegClass(MI.getOperand(i).getReg());
5349       if (RI.hasVectorRegisters(OpRC)) {
5350         VRC = OpRC;
5351       } else {
5352         SRC = OpRC;
5353       }
5354     }
5355 
5356     // If any of the operands are VGPR registers, then they all most be
5357     // otherwise we will create illegal VGPR->SGPR copies when legalizing
5358     // them.
5359     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
5360       if (!VRC) {
5361         assert(SRC);
5362         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
5363           VRC = &AMDGPU::VReg_1RegClass;
5364         } else
5365           VRC = RI.hasAGPRs(getOpRegClass(MI, 0))
5366                     ? RI.getEquivalentAGPRClass(SRC)
5367                     : RI.getEquivalentVGPRClass(SRC);
5368       } else {
5369           VRC = RI.hasAGPRs(getOpRegClass(MI, 0))
5370                     ? RI.getEquivalentAGPRClass(VRC)
5371                     : RI.getEquivalentVGPRClass(VRC);
5372       }
5373       RC = VRC;
5374     } else {
5375       RC = SRC;
5376     }
5377 
5378     // Update all the operands so they have the same type.
5379     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5380       MachineOperand &Op = MI.getOperand(I);
5381       if (!Op.isReg() || !Op.getReg().isVirtual())
5382         continue;
5383 
5384       // MI is a PHI instruction.
5385       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
5386       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
5387 
5388       // Avoid creating no-op copies with the same src and dst reg class.  These
5389       // confuse some of the machine passes.
5390       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
5391     }
5392   }
5393 
5394   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
5395   // VGPR dest type and SGPR sources, insert copies so all operands are
5396   // VGPRs. This seems to help operand folding / the register coalescer.
5397   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
5398     MachineBasicBlock *MBB = MI.getParent();
5399     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
5400     if (RI.hasVGPRs(DstRC)) {
5401       // Update all the operands so they are VGPR register classes. These may
5402       // not be the same register class because REG_SEQUENCE supports mixing
5403       // subregister index types e.g. sub0_sub1 + sub2 + sub3
5404       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5405         MachineOperand &Op = MI.getOperand(I);
5406         if (!Op.isReg() || !Op.getReg().isVirtual())
5407           continue;
5408 
5409         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
5410         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
5411         if (VRC == OpRC)
5412           continue;
5413 
5414         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
5415         Op.setIsKill();
5416       }
5417     }
5418 
5419     return CreatedBB;
5420   }
5421 
5422   // Legalize INSERT_SUBREG
5423   // src0 must have the same register class as dst
5424   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
5425     Register Dst = MI.getOperand(0).getReg();
5426     Register Src0 = MI.getOperand(1).getReg();
5427     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
5428     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
5429     if (DstRC != Src0RC) {
5430       MachineBasicBlock *MBB = MI.getParent();
5431       MachineOperand &Op = MI.getOperand(1);
5432       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
5433     }
5434     return CreatedBB;
5435   }
5436 
5437   // Legalize SI_INIT_M0
5438   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
5439     MachineOperand &Src = MI.getOperand(0);
5440     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
5441       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
5442     return CreatedBB;
5443   }
5444 
5445   // Legalize MIMG and MUBUF/MTBUF for shaders.
5446   //
5447   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
5448   // scratch memory access. In both cases, the legalization never involves
5449   // conversion to the addr64 form.
5450   if (isMIMG(MI) || (AMDGPU::isGraphics(MF.getFunction().getCallingConv()) &&
5451                      (isMUBUF(MI) || isMTBUF(MI)))) {
5452     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
5453     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
5454       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SRsrc, MDT);
5455 
5456     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
5457     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
5458       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SSamp, MDT);
5459 
5460     return CreatedBB;
5461   }
5462 
5463   // Legalize SI_CALL
5464   if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
5465     MachineOperand *Dest = &MI.getOperand(0);
5466     if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
5467       // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
5468       // following copies, we also need to move copies from and to physical
5469       // registers into the loop block.
5470       unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
5471       unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
5472 
5473       // Also move the copies to physical registers into the loop block
5474       MachineBasicBlock &MBB = *MI.getParent();
5475       MachineBasicBlock::iterator Start(&MI);
5476       while (Start->getOpcode() != FrameSetupOpcode)
5477         --Start;
5478       MachineBasicBlock::iterator End(&MI);
5479       while (End->getOpcode() != FrameDestroyOpcode)
5480         ++End;
5481       // Also include following copies of the return value
5482       ++End;
5483       while (End != MBB.end() && End->isCopy() && End->getOperand(1).isReg() &&
5484              MI.definesRegister(End->getOperand(1).getReg()))
5485         ++End;
5486       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Dest, MDT, Start, End);
5487     }
5488   }
5489 
5490   // Legalize MUBUF* instructions.
5491   int RsrcIdx =
5492       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
5493   if (RsrcIdx != -1) {
5494     // We have an MUBUF instruction
5495     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
5496     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
5497     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
5498                              RI.getRegClass(RsrcRC))) {
5499       // The operands are legal.
5500       // FIXME: We may need to legalize operands besided srsrc.
5501       return CreatedBB;
5502     }
5503 
5504     // Legalize a VGPR Rsrc.
5505     //
5506     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
5507     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
5508     // a zero-value SRsrc.
5509     //
5510     // If the instruction is _OFFSET (both idxen and offen disabled), and we
5511     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
5512     // above.
5513     //
5514     // Otherwise we are on non-ADDR64 hardware, and/or we have
5515     // idxen/offen/bothen and we fall back to a waterfall loop.
5516 
5517     MachineBasicBlock &MBB = *MI.getParent();
5518 
5519     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5520     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
5521       // This is already an ADDR64 instruction so we need to add the pointer
5522       // extracted from the resource descriptor to the current value of VAddr.
5523       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5524       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5525       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5526 
5527       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5528       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
5529       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
5530 
5531       unsigned RsrcPtr, NewSRsrc;
5532       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5533 
5534       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
5535       const DebugLoc &DL = MI.getDebugLoc();
5536       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
5537         .addDef(CondReg0)
5538         .addReg(RsrcPtr, 0, AMDGPU::sub0)
5539         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
5540         .addImm(0);
5541 
5542       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
5543       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
5544         .addDef(CondReg1, RegState::Dead)
5545         .addReg(RsrcPtr, 0, AMDGPU::sub1)
5546         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
5547         .addReg(CondReg0, RegState::Kill)
5548         .addImm(0);
5549 
5550       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5551       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
5552           .addReg(NewVAddrLo)
5553           .addImm(AMDGPU::sub0)
5554           .addReg(NewVAddrHi)
5555           .addImm(AMDGPU::sub1);
5556 
5557       VAddr->setReg(NewVAddr);
5558       Rsrc->setReg(NewSRsrc);
5559     } else if (!VAddr && ST.hasAddr64()) {
5560       // This instructions is the _OFFSET variant, so we need to convert it to
5561       // ADDR64.
5562       assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5563              "FIXME: Need to emit flat atomics here");
5564 
5565       unsigned RsrcPtr, NewSRsrc;
5566       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5567 
5568       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5569       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
5570       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5571       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
5572       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
5573 
5574       // Atomics rith return have have an additional tied operand and are
5575       // missing some of the special bits.
5576       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
5577       MachineInstr *Addr64;
5578 
5579       if (!VDataIn) {
5580         // Regular buffer load / store.
5581         MachineInstrBuilder MIB =
5582             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5583                 .add(*VData)
5584                 .addReg(NewVAddr)
5585                 .addReg(NewSRsrc)
5586                 .add(*SOffset)
5587                 .add(*Offset);
5588 
5589         if (const MachineOperand *CPol =
5590                 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
5591           MIB.addImm(CPol->getImm());
5592         }
5593 
5594         if (const MachineOperand *TFE =
5595                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
5596           MIB.addImm(TFE->getImm());
5597         }
5598 
5599         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
5600 
5601         MIB.cloneMemRefs(MI);
5602         Addr64 = MIB;
5603       } else {
5604         // Atomics with return.
5605         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5606                      .add(*VData)
5607                      .add(*VDataIn)
5608                      .addReg(NewVAddr)
5609                      .addReg(NewSRsrc)
5610                      .add(*SOffset)
5611                      .add(*Offset)
5612                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
5613                      .cloneMemRefs(MI);
5614       }
5615 
5616       MI.removeFromParent();
5617 
5618       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5619       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
5620               NewVAddr)
5621           .addReg(RsrcPtr, 0, AMDGPU::sub0)
5622           .addImm(AMDGPU::sub0)
5623           .addReg(RsrcPtr, 0, AMDGPU::sub1)
5624           .addImm(AMDGPU::sub1);
5625     } else {
5626       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
5627       // to SGPRs.
5628       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
5629       return CreatedBB;
5630     }
5631   }
5632   return CreatedBB;
5633 }
5634 
5635 MachineBasicBlock *SIInstrInfo::moveToVALU(MachineInstr &TopInst,
5636                                            MachineDominatorTree *MDT) const {
5637   SetVectorType Worklist;
5638   Worklist.insert(&TopInst);
5639   MachineBasicBlock *CreatedBB = nullptr;
5640   MachineBasicBlock *CreatedBBTmp = nullptr;
5641 
5642   while (!Worklist.empty()) {
5643     MachineInstr &Inst = *Worklist.pop_back_val();
5644     MachineBasicBlock *MBB = Inst.getParent();
5645     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
5646 
5647     unsigned Opcode = Inst.getOpcode();
5648     unsigned NewOpcode = getVALUOp(Inst);
5649 
5650     // Handle some special cases
5651     switch (Opcode) {
5652     default:
5653       break;
5654     case AMDGPU::S_ADD_U64_PSEUDO:
5655     case AMDGPU::S_SUB_U64_PSEUDO:
5656       splitScalar64BitAddSub(Worklist, Inst, MDT);
5657       Inst.eraseFromParent();
5658       continue;
5659     case AMDGPU::S_ADD_I32:
5660     case AMDGPU::S_SUB_I32: {
5661       // FIXME: The u32 versions currently selected use the carry.
5662       bool Changed;
5663       std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
5664       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5665         CreatedBB = CreatedBBTmp;
5666       if (Changed)
5667         continue;
5668 
5669       // Default handling
5670       break;
5671     }
5672     case AMDGPU::S_AND_B64:
5673       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
5674       Inst.eraseFromParent();
5675       continue;
5676 
5677     case AMDGPU::S_OR_B64:
5678       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
5679       Inst.eraseFromParent();
5680       continue;
5681 
5682     case AMDGPU::S_XOR_B64:
5683       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
5684       Inst.eraseFromParent();
5685       continue;
5686 
5687     case AMDGPU::S_NAND_B64:
5688       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
5689       Inst.eraseFromParent();
5690       continue;
5691 
5692     case AMDGPU::S_NOR_B64:
5693       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
5694       Inst.eraseFromParent();
5695       continue;
5696 
5697     case AMDGPU::S_XNOR_B64:
5698       if (ST.hasDLInsts())
5699         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
5700       else
5701         splitScalar64BitXnor(Worklist, Inst, MDT);
5702       Inst.eraseFromParent();
5703       continue;
5704 
5705     case AMDGPU::S_ANDN2_B64:
5706       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
5707       Inst.eraseFromParent();
5708       continue;
5709 
5710     case AMDGPU::S_ORN2_B64:
5711       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
5712       Inst.eraseFromParent();
5713       continue;
5714 
5715     case AMDGPU::S_BREV_B64:
5716       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
5717       Inst.eraseFromParent();
5718       continue;
5719 
5720     case AMDGPU::S_NOT_B64:
5721       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
5722       Inst.eraseFromParent();
5723       continue;
5724 
5725     case AMDGPU::S_BCNT1_I32_B64:
5726       splitScalar64BitBCNT(Worklist, Inst);
5727       Inst.eraseFromParent();
5728       continue;
5729 
5730     case AMDGPU::S_BFE_I64:
5731       splitScalar64BitBFE(Worklist, Inst);
5732       Inst.eraseFromParent();
5733       continue;
5734 
5735     case AMDGPU::S_LSHL_B32:
5736       if (ST.hasOnlyRevVALUShifts()) {
5737         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
5738         swapOperands(Inst);
5739       }
5740       break;
5741     case AMDGPU::S_ASHR_I32:
5742       if (ST.hasOnlyRevVALUShifts()) {
5743         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
5744         swapOperands(Inst);
5745       }
5746       break;
5747     case AMDGPU::S_LSHR_B32:
5748       if (ST.hasOnlyRevVALUShifts()) {
5749         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
5750         swapOperands(Inst);
5751       }
5752       break;
5753     case AMDGPU::S_LSHL_B64:
5754       if (ST.hasOnlyRevVALUShifts()) {
5755         NewOpcode = AMDGPU::V_LSHLREV_B64_e64;
5756         swapOperands(Inst);
5757       }
5758       break;
5759     case AMDGPU::S_ASHR_I64:
5760       if (ST.hasOnlyRevVALUShifts()) {
5761         NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
5762         swapOperands(Inst);
5763       }
5764       break;
5765     case AMDGPU::S_LSHR_B64:
5766       if (ST.hasOnlyRevVALUShifts()) {
5767         NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
5768         swapOperands(Inst);
5769       }
5770       break;
5771 
5772     case AMDGPU::S_ABS_I32:
5773       lowerScalarAbs(Worklist, Inst);
5774       Inst.eraseFromParent();
5775       continue;
5776 
5777     case AMDGPU::S_CBRANCH_SCC0:
5778     case AMDGPU::S_CBRANCH_SCC1:
5779       // Clear unused bits of vcc
5780       if (ST.isWave32())
5781         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B32),
5782                 AMDGPU::VCC_LO)
5783             .addReg(AMDGPU::EXEC_LO)
5784             .addReg(AMDGPU::VCC_LO);
5785       else
5786         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
5787                 AMDGPU::VCC)
5788             .addReg(AMDGPU::EXEC)
5789             .addReg(AMDGPU::VCC);
5790       break;
5791 
5792     case AMDGPU::S_BFE_U64:
5793     case AMDGPU::S_BFM_B64:
5794       llvm_unreachable("Moving this op to VALU not implemented");
5795 
5796     case AMDGPU::S_PACK_LL_B32_B16:
5797     case AMDGPU::S_PACK_LH_B32_B16:
5798     case AMDGPU::S_PACK_HH_B32_B16:
5799       movePackToVALU(Worklist, MRI, Inst);
5800       Inst.eraseFromParent();
5801       continue;
5802 
5803     case AMDGPU::S_XNOR_B32:
5804       lowerScalarXnor(Worklist, Inst);
5805       Inst.eraseFromParent();
5806       continue;
5807 
5808     case AMDGPU::S_NAND_B32:
5809       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
5810       Inst.eraseFromParent();
5811       continue;
5812 
5813     case AMDGPU::S_NOR_B32:
5814       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
5815       Inst.eraseFromParent();
5816       continue;
5817 
5818     case AMDGPU::S_ANDN2_B32:
5819       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
5820       Inst.eraseFromParent();
5821       continue;
5822 
5823     case AMDGPU::S_ORN2_B32:
5824       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
5825       Inst.eraseFromParent();
5826       continue;
5827 
5828     // TODO: remove as soon as everything is ready
5829     // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
5830     // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
5831     // can only be selected from the uniform SDNode.
5832     case AMDGPU::S_ADD_CO_PSEUDO:
5833     case AMDGPU::S_SUB_CO_PSEUDO: {
5834       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
5835                          ? AMDGPU::V_ADDC_U32_e64
5836                          : AMDGPU::V_SUBB_U32_e64;
5837       const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5838 
5839       Register CarryInReg = Inst.getOperand(4).getReg();
5840       if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
5841         Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
5842         BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
5843             .addReg(CarryInReg);
5844       }
5845 
5846       Register CarryOutReg = Inst.getOperand(1).getReg();
5847 
5848       Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
5849           MRI.getRegClass(Inst.getOperand(0).getReg())));
5850       MachineInstr *CarryOp =
5851           BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
5852               .addReg(CarryOutReg, RegState::Define)
5853               .add(Inst.getOperand(2))
5854               .add(Inst.getOperand(3))
5855               .addReg(CarryInReg)
5856               .addImm(0);
5857       CreatedBBTmp = legalizeOperands(*CarryOp);
5858       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5859         CreatedBB = CreatedBBTmp;
5860       MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
5861       addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
5862       Inst.eraseFromParent();
5863     }
5864       continue;
5865     case AMDGPU::S_UADDO_PSEUDO:
5866     case AMDGPU::S_USUBO_PSEUDO: {
5867       const DebugLoc &DL = Inst.getDebugLoc();
5868       MachineOperand &Dest0 = Inst.getOperand(0);
5869       MachineOperand &Dest1 = Inst.getOperand(1);
5870       MachineOperand &Src0 = Inst.getOperand(2);
5871       MachineOperand &Src1 = Inst.getOperand(3);
5872 
5873       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
5874                          ? AMDGPU::V_ADD_CO_U32_e64
5875                          : AMDGPU::V_SUB_CO_U32_e64;
5876       const TargetRegisterClass *NewRC =
5877           RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
5878       Register DestReg = MRI.createVirtualRegister(NewRC);
5879       MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
5880                                    .addReg(Dest1.getReg(), RegState::Define)
5881                                    .add(Src0)
5882                                    .add(Src1)
5883                                    .addImm(0); // clamp bit
5884 
5885       CreatedBBTmp = legalizeOperands(*NewInstr, MDT);
5886       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5887         CreatedBB = CreatedBBTmp;
5888 
5889       MRI.replaceRegWith(Dest0.getReg(), DestReg);
5890       addUsersToMoveToVALUWorklist(NewInstr->getOperand(0).getReg(), MRI,
5891                                    Worklist);
5892       Inst.eraseFromParent();
5893     }
5894       continue;
5895 
5896     case AMDGPU::S_CSELECT_B32:
5897     case AMDGPU::S_CSELECT_B64:
5898       lowerSelect(Worklist, Inst, MDT);
5899       Inst.eraseFromParent();
5900       continue;
5901     }
5902 
5903     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
5904       // We cannot move this instruction to the VALU, so we should try to
5905       // legalize its operands instead.
5906       CreatedBBTmp = legalizeOperands(Inst, MDT);
5907       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5908         CreatedBB = CreatedBBTmp;
5909       continue;
5910     }
5911 
5912     // Use the new VALU Opcode.
5913     const MCInstrDesc &NewDesc = get(NewOpcode);
5914     Inst.setDesc(NewDesc);
5915 
5916     // Remove any references to SCC. Vector instructions can't read from it, and
5917     // We're just about to add the implicit use / defs of VCC, and we don't want
5918     // both.
5919     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
5920       MachineOperand &Op = Inst.getOperand(i);
5921       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
5922         // Only propagate through live-def of SCC.
5923         if (Op.isDef() && !Op.isDead())
5924           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
5925         Inst.RemoveOperand(i);
5926       }
5927     }
5928 
5929     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
5930       // We are converting these to a BFE, so we need to add the missing
5931       // operands for the size and offset.
5932       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
5933       Inst.addOperand(MachineOperand::CreateImm(0));
5934       Inst.addOperand(MachineOperand::CreateImm(Size));
5935 
5936     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
5937       // The VALU version adds the second operand to the result, so insert an
5938       // extra 0 operand.
5939       Inst.addOperand(MachineOperand::CreateImm(0));
5940     }
5941 
5942     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
5943     fixImplicitOperands(Inst);
5944 
5945     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
5946       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
5947       // If we need to move this to VGPRs, we need to unpack the second operand
5948       // back into the 2 separate ones for bit offset and width.
5949       assert(OffsetWidthOp.isImm() &&
5950              "Scalar BFE is only implemented for constant width and offset");
5951       uint32_t Imm = OffsetWidthOp.getImm();
5952 
5953       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
5954       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
5955       Inst.RemoveOperand(2);                     // Remove old immediate.
5956       Inst.addOperand(MachineOperand::CreateImm(Offset));
5957       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
5958     }
5959 
5960     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
5961     unsigned NewDstReg = AMDGPU::NoRegister;
5962     if (HasDst) {
5963       Register DstReg = Inst.getOperand(0).getReg();
5964       if (DstReg.isPhysical())
5965         continue;
5966 
5967       // Update the destination register class.
5968       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
5969       if (!NewDstRC)
5970         continue;
5971 
5972       if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual() &&
5973           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
5974         // Instead of creating a copy where src and dst are the same register
5975         // class, we just replace all uses of dst with src.  These kinds of
5976         // copies interfere with the heuristics MachineSink uses to decide
5977         // whether or not to split a critical edge.  Since the pass assumes
5978         // that copies will end up as machine instructions and not be
5979         // eliminated.
5980         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
5981         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
5982         MRI.clearKillFlags(Inst.getOperand(1).getReg());
5983         Inst.getOperand(0).setReg(DstReg);
5984 
5985         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
5986         // these are deleted later, but at -O0 it would leave a suspicious
5987         // looking illegal copy of an undef register.
5988         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
5989           Inst.RemoveOperand(I);
5990         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
5991         continue;
5992       }
5993 
5994       NewDstReg = MRI.createVirtualRegister(NewDstRC);
5995       MRI.replaceRegWith(DstReg, NewDstReg);
5996     }
5997 
5998     // Legalize the operands
5999     CreatedBBTmp = legalizeOperands(Inst, MDT);
6000     if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6001       CreatedBB = CreatedBBTmp;
6002 
6003     if (HasDst)
6004      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
6005   }
6006   return CreatedBB;
6007 }
6008 
6009 // Add/sub require special handling to deal with carry outs.
6010 std::pair<bool, MachineBasicBlock *>
6011 SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
6012                               MachineDominatorTree *MDT) const {
6013   if (ST.hasAddNoCarry()) {
6014     // Assume there is no user of scc since we don't select this in that case.
6015     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
6016     // is used.
6017 
6018     MachineBasicBlock &MBB = *Inst.getParent();
6019     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6020 
6021     Register OldDstReg = Inst.getOperand(0).getReg();
6022     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6023 
6024     unsigned Opc = Inst.getOpcode();
6025     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
6026 
6027     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
6028       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
6029 
6030     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
6031     Inst.RemoveOperand(3);
6032 
6033     Inst.setDesc(get(NewOpc));
6034     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
6035     Inst.addImplicitDefUseOperands(*MBB.getParent());
6036     MRI.replaceRegWith(OldDstReg, ResultReg);
6037     MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
6038 
6039     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6040     return std::make_pair(true, NewBB);
6041   }
6042 
6043   return std::make_pair(false, nullptr);
6044 }
6045 
6046 void SIInstrInfo::lowerSelect(SetVectorType &Worklist, MachineInstr &Inst,
6047                               MachineDominatorTree *MDT) const {
6048 
6049   MachineBasicBlock &MBB = *Inst.getParent();
6050   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6051   MachineBasicBlock::iterator MII = Inst;
6052   DebugLoc DL = Inst.getDebugLoc();
6053 
6054   MachineOperand &Dest = Inst.getOperand(0);
6055   MachineOperand &Src0 = Inst.getOperand(1);
6056   MachineOperand &Src1 = Inst.getOperand(2);
6057   MachineOperand &Cond = Inst.getOperand(3);
6058 
6059   Register SCCSource = Cond.getReg();
6060   // Find SCC def, and if that is a copy (SCC = COPY reg) then use reg instead.
6061   if (!Cond.isUndef()) {
6062     for (MachineInstr &CandI :
6063          make_range(std::next(MachineBasicBlock::reverse_iterator(Inst)),
6064                     Inst.getParent()->rend())) {
6065       if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) !=
6066           -1) {
6067         if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
6068           SCCSource = CandI.getOperand(1).getReg();
6069         }
6070         break;
6071       }
6072     }
6073   }
6074 
6075   // If this is a trivial select where the condition is effectively not SCC
6076   // (SCCSource is a source of copy to SCC), then the select is semantically
6077   // equivalent to copying SCCSource. Hence, there is no need to create
6078   // V_CNDMASK, we can just use that and bail out.
6079   if ((SCCSource != AMDGPU::SCC) && Src0.isImm() && (Src0.getImm() == -1) &&
6080       Src1.isImm() && (Src1.getImm() == 0)) {
6081     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6082     return;
6083   }
6084 
6085   const TargetRegisterClass *TC = ST.getWavefrontSize() == 64
6086                                       ? &AMDGPU::SReg_64_XEXECRegClass
6087                                       : &AMDGPU::SReg_32_XM0_XEXECRegClass;
6088   Register CopySCC = MRI.createVirtualRegister(TC);
6089 
6090   if (SCCSource == AMDGPU::SCC) {
6091     // Insert a trivial select instead of creating a copy, because a copy from
6092     // SCC would semantically mean just copying a single bit, but we may need
6093     // the result to be a vector condition mask that needs preserving.
6094     unsigned Opcode = (ST.getWavefrontSize() == 64) ? AMDGPU::S_CSELECT_B64
6095                                                     : AMDGPU::S_CSELECT_B32;
6096     auto NewSelect =
6097         BuildMI(MBB, MII, DL, get(Opcode), CopySCC).addImm(-1).addImm(0);
6098     NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
6099   } else {
6100     BuildMI(MBB, MII, DL, get(AMDGPU::COPY), CopySCC).addReg(SCCSource);
6101   }
6102 
6103   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6104 
6105   auto UpdatedInst =
6106       BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), ResultReg)
6107           .addImm(0)
6108           .add(Src1) // False
6109           .addImm(0)
6110           .add(Src0) // True
6111           .addReg(CopySCC);
6112 
6113   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6114   legalizeOperands(*UpdatedInst, MDT);
6115   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6116 }
6117 
6118 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
6119                                  MachineInstr &Inst) const {
6120   MachineBasicBlock &MBB = *Inst.getParent();
6121   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6122   MachineBasicBlock::iterator MII = Inst;
6123   DebugLoc DL = Inst.getDebugLoc();
6124 
6125   MachineOperand &Dest = Inst.getOperand(0);
6126   MachineOperand &Src = Inst.getOperand(1);
6127   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6128   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6129 
6130   unsigned SubOp = ST.hasAddNoCarry() ?
6131     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_CO_U32_e32;
6132 
6133   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
6134     .addImm(0)
6135     .addReg(Src.getReg());
6136 
6137   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
6138     .addReg(Src.getReg())
6139     .addReg(TmpReg);
6140 
6141   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6142   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6143 }
6144 
6145 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
6146                                   MachineInstr &Inst) const {
6147   MachineBasicBlock &MBB = *Inst.getParent();
6148   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6149   MachineBasicBlock::iterator MII = Inst;
6150   const DebugLoc &DL = Inst.getDebugLoc();
6151 
6152   MachineOperand &Dest = Inst.getOperand(0);
6153   MachineOperand &Src0 = Inst.getOperand(1);
6154   MachineOperand &Src1 = Inst.getOperand(2);
6155 
6156   if (ST.hasDLInsts()) {
6157     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6158     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
6159     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
6160 
6161     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
6162       .add(Src0)
6163       .add(Src1);
6164 
6165     MRI.replaceRegWith(Dest.getReg(), NewDest);
6166     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6167   } else {
6168     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
6169     // invert either source and then perform the XOR. If either source is a
6170     // scalar register, then we can leave the inversion on the scalar unit to
6171     // acheive a better distrubution of scalar and vector instructions.
6172     bool Src0IsSGPR = Src0.isReg() &&
6173                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
6174     bool Src1IsSGPR = Src1.isReg() &&
6175                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
6176     MachineInstr *Xor;
6177     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6178     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6179 
6180     // Build a pair of scalar instructions and add them to the work list.
6181     // The next iteration over the work list will lower these to the vector
6182     // unit as necessary.
6183     if (Src0IsSGPR) {
6184       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
6185       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6186       .addReg(Temp)
6187       .add(Src1);
6188     } else if (Src1IsSGPR) {
6189       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
6190       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6191       .add(Src0)
6192       .addReg(Temp);
6193     } else {
6194       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
6195         .add(Src0)
6196         .add(Src1);
6197       MachineInstr *Not =
6198           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
6199       Worklist.insert(Not);
6200     }
6201 
6202     MRI.replaceRegWith(Dest.getReg(), NewDest);
6203 
6204     Worklist.insert(Xor);
6205 
6206     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6207   }
6208 }
6209 
6210 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
6211                                       MachineInstr &Inst,
6212                                       unsigned Opcode) const {
6213   MachineBasicBlock &MBB = *Inst.getParent();
6214   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6215   MachineBasicBlock::iterator MII = Inst;
6216   const DebugLoc &DL = Inst.getDebugLoc();
6217 
6218   MachineOperand &Dest = Inst.getOperand(0);
6219   MachineOperand &Src0 = Inst.getOperand(1);
6220   MachineOperand &Src1 = Inst.getOperand(2);
6221 
6222   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6223   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6224 
6225   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
6226     .add(Src0)
6227     .add(Src1);
6228 
6229   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
6230     .addReg(Interm);
6231 
6232   Worklist.insert(&Op);
6233   Worklist.insert(&Not);
6234 
6235   MRI.replaceRegWith(Dest.getReg(), NewDest);
6236   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6237 }
6238 
6239 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
6240                                      MachineInstr &Inst,
6241                                      unsigned Opcode) const {
6242   MachineBasicBlock &MBB = *Inst.getParent();
6243   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6244   MachineBasicBlock::iterator MII = Inst;
6245   const DebugLoc &DL = Inst.getDebugLoc();
6246 
6247   MachineOperand &Dest = Inst.getOperand(0);
6248   MachineOperand &Src0 = Inst.getOperand(1);
6249   MachineOperand &Src1 = Inst.getOperand(2);
6250 
6251   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6252   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6253 
6254   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
6255     .add(Src1);
6256 
6257   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
6258     .add(Src0)
6259     .addReg(Interm);
6260 
6261   Worklist.insert(&Not);
6262   Worklist.insert(&Op);
6263 
6264   MRI.replaceRegWith(Dest.getReg(), NewDest);
6265   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6266 }
6267 
6268 void SIInstrInfo::splitScalar64BitUnaryOp(
6269     SetVectorType &Worklist, MachineInstr &Inst,
6270     unsigned Opcode, bool Swap) const {
6271   MachineBasicBlock &MBB = *Inst.getParent();
6272   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6273 
6274   MachineOperand &Dest = Inst.getOperand(0);
6275   MachineOperand &Src0 = Inst.getOperand(1);
6276   DebugLoc DL = Inst.getDebugLoc();
6277 
6278   MachineBasicBlock::iterator MII = Inst;
6279 
6280   const MCInstrDesc &InstDesc = get(Opcode);
6281   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6282     MRI.getRegClass(Src0.getReg()) :
6283     &AMDGPU::SGPR_32RegClass;
6284 
6285   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6286 
6287   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6288                                                        AMDGPU::sub0, Src0SubRC);
6289 
6290   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6291   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6292   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6293 
6294   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6295   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
6296 
6297   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6298                                                        AMDGPU::sub1, Src0SubRC);
6299 
6300   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6301   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
6302 
6303   if (Swap)
6304     std::swap(DestSub0, DestSub1);
6305 
6306   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6307   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6308     .addReg(DestSub0)
6309     .addImm(AMDGPU::sub0)
6310     .addReg(DestSub1)
6311     .addImm(AMDGPU::sub1);
6312 
6313   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6314 
6315   Worklist.insert(&LoHalf);
6316   Worklist.insert(&HiHalf);
6317 
6318   // We don't need to legalizeOperands here because for a single operand, src0
6319   // will support any kind of input.
6320 
6321   // Move all users of this moved value.
6322   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6323 }
6324 
6325 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
6326                                          MachineInstr &Inst,
6327                                          MachineDominatorTree *MDT) const {
6328   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
6329 
6330   MachineBasicBlock &MBB = *Inst.getParent();
6331   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6332   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6333 
6334   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6335   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6336   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6337 
6338   Register CarryReg = MRI.createVirtualRegister(CarryRC);
6339   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
6340 
6341   MachineOperand &Dest = Inst.getOperand(0);
6342   MachineOperand &Src0 = Inst.getOperand(1);
6343   MachineOperand &Src1 = Inst.getOperand(2);
6344   const DebugLoc &DL = Inst.getDebugLoc();
6345   MachineBasicBlock::iterator MII = Inst;
6346 
6347   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
6348   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
6349   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6350   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6351 
6352   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6353                                                        AMDGPU::sub0, Src0SubRC);
6354   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6355                                                        AMDGPU::sub0, Src1SubRC);
6356 
6357 
6358   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6359                                                        AMDGPU::sub1, Src0SubRC);
6360   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6361                                                        AMDGPU::sub1, Src1SubRC);
6362 
6363   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
6364   MachineInstr *LoHalf =
6365     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
6366     .addReg(CarryReg, RegState::Define)
6367     .add(SrcReg0Sub0)
6368     .add(SrcReg1Sub0)
6369     .addImm(0); // clamp bit
6370 
6371   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
6372   MachineInstr *HiHalf =
6373     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
6374     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
6375     .add(SrcReg0Sub1)
6376     .add(SrcReg1Sub1)
6377     .addReg(CarryReg, RegState::Kill)
6378     .addImm(0); // clamp bit
6379 
6380   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6381     .addReg(DestSub0)
6382     .addImm(AMDGPU::sub0)
6383     .addReg(DestSub1)
6384     .addImm(AMDGPU::sub1);
6385 
6386   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6387 
6388   // Try to legalize the operands in case we need to swap the order to keep it
6389   // valid.
6390   legalizeOperands(*LoHalf, MDT);
6391   legalizeOperands(*HiHalf, MDT);
6392 
6393   // Move all users of this moved vlaue.
6394   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6395 }
6396 
6397 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
6398                                            MachineInstr &Inst, unsigned Opcode,
6399                                            MachineDominatorTree *MDT) const {
6400   MachineBasicBlock &MBB = *Inst.getParent();
6401   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6402 
6403   MachineOperand &Dest = Inst.getOperand(0);
6404   MachineOperand &Src0 = Inst.getOperand(1);
6405   MachineOperand &Src1 = Inst.getOperand(2);
6406   DebugLoc DL = Inst.getDebugLoc();
6407 
6408   MachineBasicBlock::iterator MII = Inst;
6409 
6410   const MCInstrDesc &InstDesc = get(Opcode);
6411   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6412     MRI.getRegClass(Src0.getReg()) :
6413     &AMDGPU::SGPR_32RegClass;
6414 
6415   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6416   const TargetRegisterClass *Src1RC = Src1.isReg() ?
6417     MRI.getRegClass(Src1.getReg()) :
6418     &AMDGPU::SGPR_32RegClass;
6419 
6420   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6421 
6422   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6423                                                        AMDGPU::sub0, Src0SubRC);
6424   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6425                                                        AMDGPU::sub0, Src1SubRC);
6426   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6427                                                        AMDGPU::sub1, Src0SubRC);
6428   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6429                                                        AMDGPU::sub1, Src1SubRC);
6430 
6431   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6432   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6433   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6434 
6435   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6436   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
6437                               .add(SrcReg0Sub0)
6438                               .add(SrcReg1Sub0);
6439 
6440   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6441   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
6442                               .add(SrcReg0Sub1)
6443                               .add(SrcReg1Sub1);
6444 
6445   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6446   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6447     .addReg(DestSub0)
6448     .addImm(AMDGPU::sub0)
6449     .addReg(DestSub1)
6450     .addImm(AMDGPU::sub1);
6451 
6452   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6453 
6454   Worklist.insert(&LoHalf);
6455   Worklist.insert(&HiHalf);
6456 
6457   // Move all users of this moved vlaue.
6458   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6459 }
6460 
6461 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
6462                                        MachineInstr &Inst,
6463                                        MachineDominatorTree *MDT) const {
6464   MachineBasicBlock &MBB = *Inst.getParent();
6465   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6466 
6467   MachineOperand &Dest = Inst.getOperand(0);
6468   MachineOperand &Src0 = Inst.getOperand(1);
6469   MachineOperand &Src1 = Inst.getOperand(2);
6470   const DebugLoc &DL = Inst.getDebugLoc();
6471 
6472   MachineBasicBlock::iterator MII = Inst;
6473 
6474   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6475 
6476   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6477 
6478   MachineOperand* Op0;
6479   MachineOperand* Op1;
6480 
6481   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
6482     Op0 = &Src0;
6483     Op1 = &Src1;
6484   } else {
6485     Op0 = &Src1;
6486     Op1 = &Src0;
6487   }
6488 
6489   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
6490     .add(*Op0);
6491 
6492   Register NewDest = MRI.createVirtualRegister(DestRC);
6493 
6494   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
6495     .addReg(Interm)
6496     .add(*Op1);
6497 
6498   MRI.replaceRegWith(Dest.getReg(), NewDest);
6499 
6500   Worklist.insert(&Xor);
6501 }
6502 
6503 void SIInstrInfo::splitScalar64BitBCNT(
6504     SetVectorType &Worklist, MachineInstr &Inst) const {
6505   MachineBasicBlock &MBB = *Inst.getParent();
6506   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6507 
6508   MachineBasicBlock::iterator MII = Inst;
6509   const DebugLoc &DL = Inst.getDebugLoc();
6510 
6511   MachineOperand &Dest = Inst.getOperand(0);
6512   MachineOperand &Src = Inst.getOperand(1);
6513 
6514   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
6515   const TargetRegisterClass *SrcRC = Src.isReg() ?
6516     MRI.getRegClass(Src.getReg()) :
6517     &AMDGPU::SGPR_32RegClass;
6518 
6519   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6520   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6521 
6522   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
6523 
6524   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6525                                                       AMDGPU::sub0, SrcSubRC);
6526   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6527                                                       AMDGPU::sub1, SrcSubRC);
6528 
6529   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
6530 
6531   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
6532 
6533   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6534 
6535   // We don't need to legalize operands here. src0 for etiher instruction can be
6536   // an SGPR, and the second input is unused or determined here.
6537   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6538 }
6539 
6540 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
6541                                       MachineInstr &Inst) const {
6542   MachineBasicBlock &MBB = *Inst.getParent();
6543   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6544   MachineBasicBlock::iterator MII = Inst;
6545   const DebugLoc &DL = Inst.getDebugLoc();
6546 
6547   MachineOperand &Dest = Inst.getOperand(0);
6548   uint32_t Imm = Inst.getOperand(2).getImm();
6549   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6550   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6551 
6552   (void) Offset;
6553 
6554   // Only sext_inreg cases handled.
6555   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
6556          Offset == 0 && "Not implemented");
6557 
6558   if (BitWidth < 32) {
6559     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6560     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6561     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6562 
6563     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
6564         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
6565         .addImm(0)
6566         .addImm(BitWidth);
6567 
6568     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
6569       .addImm(31)
6570       .addReg(MidRegLo);
6571 
6572     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6573       .addReg(MidRegLo)
6574       .addImm(AMDGPU::sub0)
6575       .addReg(MidRegHi)
6576       .addImm(AMDGPU::sub1);
6577 
6578     MRI.replaceRegWith(Dest.getReg(), ResultReg);
6579     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6580     return;
6581   }
6582 
6583   MachineOperand &Src = Inst.getOperand(1);
6584   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6585   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6586 
6587   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
6588     .addImm(31)
6589     .addReg(Src.getReg(), 0, AMDGPU::sub0);
6590 
6591   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6592     .addReg(Src.getReg(), 0, AMDGPU::sub0)
6593     .addImm(AMDGPU::sub0)
6594     .addReg(TmpReg)
6595     .addImm(AMDGPU::sub1);
6596 
6597   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6598   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6599 }
6600 
6601 void SIInstrInfo::addUsersToMoveToVALUWorklist(
6602   Register DstReg,
6603   MachineRegisterInfo &MRI,
6604   SetVectorType &Worklist) const {
6605   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
6606          E = MRI.use_end(); I != E;) {
6607     MachineInstr &UseMI = *I->getParent();
6608 
6609     unsigned OpNo = 0;
6610 
6611     switch (UseMI.getOpcode()) {
6612     case AMDGPU::COPY:
6613     case AMDGPU::WQM:
6614     case AMDGPU::SOFT_WQM:
6615     case AMDGPU::STRICT_WWM:
6616     case AMDGPU::STRICT_WQM:
6617     case AMDGPU::REG_SEQUENCE:
6618     case AMDGPU::PHI:
6619     case AMDGPU::INSERT_SUBREG:
6620       break;
6621     default:
6622       OpNo = I.getOperandNo();
6623       break;
6624     }
6625 
6626     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
6627       Worklist.insert(&UseMI);
6628 
6629       do {
6630         ++I;
6631       } while (I != E && I->getParent() == &UseMI);
6632     } else {
6633       ++I;
6634     }
6635   }
6636 }
6637 
6638 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
6639                                  MachineRegisterInfo &MRI,
6640                                  MachineInstr &Inst) const {
6641   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6642   MachineBasicBlock *MBB = Inst.getParent();
6643   MachineOperand &Src0 = Inst.getOperand(1);
6644   MachineOperand &Src1 = Inst.getOperand(2);
6645   const DebugLoc &DL = Inst.getDebugLoc();
6646 
6647   switch (Inst.getOpcode()) {
6648   case AMDGPU::S_PACK_LL_B32_B16: {
6649     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6650     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6651 
6652     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
6653     // 0.
6654     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
6655       .addImm(0xffff);
6656 
6657     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
6658       .addReg(ImmReg, RegState::Kill)
6659       .add(Src0);
6660 
6661     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
6662       .add(Src1)
6663       .addImm(16)
6664       .addReg(TmpReg, RegState::Kill);
6665     break;
6666   }
6667   case AMDGPU::S_PACK_LH_B32_B16: {
6668     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6669     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
6670       .addImm(0xffff);
6671     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
6672       .addReg(ImmReg, RegState::Kill)
6673       .add(Src0)
6674       .add(Src1);
6675     break;
6676   }
6677   case AMDGPU::S_PACK_HH_B32_B16: {
6678     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6679     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6680     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
6681       .addImm(16)
6682       .add(Src0);
6683     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
6684       .addImm(0xffff0000);
6685     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
6686       .add(Src1)
6687       .addReg(ImmReg, RegState::Kill)
6688       .addReg(TmpReg, RegState::Kill);
6689     break;
6690   }
6691   default:
6692     llvm_unreachable("unhandled s_pack_* instruction");
6693   }
6694 
6695   MachineOperand &Dest = Inst.getOperand(0);
6696   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6697   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6698 }
6699 
6700 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
6701                                                MachineInstr &SCCDefInst,
6702                                                SetVectorType &Worklist) const {
6703   bool SCCUsedImplicitly = false;
6704 
6705   // Ensure that def inst defines SCC, which is still live.
6706   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
6707          !Op.isDead() && Op.getParent() == &SCCDefInst);
6708   SmallVector<MachineInstr *, 4> CopyToDelete;
6709   // This assumes that all the users of SCC are in the same block
6710   // as the SCC def.
6711   for (MachineInstr &MI : // Skip the def inst itself.
6712        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
6713                   SCCDefInst.getParent()->end())) {
6714     // Check if SCC is used first.
6715     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI) != -1) {
6716       if (MI.isCopy()) {
6717         MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6718         Register DestReg = MI.getOperand(0).getReg();
6719 
6720         for (auto &User : MRI.use_nodbg_instructions(DestReg)) {
6721           if ((User.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) ||
6722               (User.getOpcode() == AMDGPU::S_SUB_CO_PSEUDO)) {
6723             User.getOperand(4).setReg(RI.getVCC());
6724             Worklist.insert(&User);
6725           } else if (User.getOpcode() == AMDGPU::V_CNDMASK_B32_e64) {
6726             User.getOperand(5).setReg(RI.getVCC());
6727             // No need to add to Worklist.
6728           }
6729         }
6730         CopyToDelete.push_back(&MI);
6731       } else {
6732         if (MI.getOpcode() == AMDGPU::S_CSELECT_B32 ||
6733             MI.getOpcode() == AMDGPU::S_CSELECT_B64) {
6734           // This is an implicit use of SCC and it is really expected by
6735           // the SCC users to handle.
6736           // We cannot preserve the edge to the user so add the explicit
6737           // copy: SCC = COPY VCC.
6738           // The copy will be cleaned up during the processing of the user
6739           // in lowerSelect.
6740           SCCUsedImplicitly = true;
6741         }
6742 
6743         Worklist.insert(&MI);
6744       }
6745     }
6746     // Exit if we find another SCC def.
6747     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
6748       break;
6749   }
6750   for (auto &Copy : CopyToDelete)
6751     Copy->eraseFromParent();
6752 
6753   if (SCCUsedImplicitly) {
6754     BuildMI(*SCCDefInst.getParent(), std::next(SCCDefInst.getIterator()),
6755             SCCDefInst.getDebugLoc(), get(AMDGPU::COPY), AMDGPU::SCC)
6756         .addReg(RI.getVCC());
6757   }
6758 }
6759 
6760 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
6761   const MachineInstr &Inst) const {
6762   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
6763 
6764   switch (Inst.getOpcode()) {
6765   // For target instructions, getOpRegClass just returns the virtual register
6766   // class associated with the operand, so we need to find an equivalent VGPR
6767   // register class in order to move the instruction to the VALU.
6768   case AMDGPU::COPY:
6769   case AMDGPU::PHI:
6770   case AMDGPU::REG_SEQUENCE:
6771   case AMDGPU::INSERT_SUBREG:
6772   case AMDGPU::WQM:
6773   case AMDGPU::SOFT_WQM:
6774   case AMDGPU::STRICT_WWM:
6775   case AMDGPU::STRICT_WQM: {
6776     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
6777     if (RI.hasAGPRs(SrcRC)) {
6778       if (RI.hasAGPRs(NewDstRC))
6779         return nullptr;
6780 
6781       switch (Inst.getOpcode()) {
6782       case AMDGPU::PHI:
6783       case AMDGPU::REG_SEQUENCE:
6784       case AMDGPU::INSERT_SUBREG:
6785         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
6786         break;
6787       default:
6788         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
6789       }
6790 
6791       if (!NewDstRC)
6792         return nullptr;
6793     } else {
6794       if (RI.hasVGPRs(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
6795         return nullptr;
6796 
6797       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
6798       if (!NewDstRC)
6799         return nullptr;
6800     }
6801 
6802     return NewDstRC;
6803   }
6804   default:
6805     return NewDstRC;
6806   }
6807 }
6808 
6809 // Find the one SGPR operand we are allowed to use.
6810 Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
6811                                    int OpIndices[3]) const {
6812   const MCInstrDesc &Desc = MI.getDesc();
6813 
6814   // Find the one SGPR operand we are allowed to use.
6815   //
6816   // First we need to consider the instruction's operand requirements before
6817   // legalizing. Some operands are required to be SGPRs, such as implicit uses
6818   // of VCC, but we are still bound by the constant bus requirement to only use
6819   // one.
6820   //
6821   // If the operand's class is an SGPR, we can never move it.
6822 
6823   Register SGPRReg = findImplicitSGPRRead(MI);
6824   if (SGPRReg != AMDGPU::NoRegister)
6825     return SGPRReg;
6826 
6827   Register UsedSGPRs[3] = { AMDGPU::NoRegister };
6828   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
6829 
6830   for (unsigned i = 0; i < 3; ++i) {
6831     int Idx = OpIndices[i];
6832     if (Idx == -1)
6833       break;
6834 
6835     const MachineOperand &MO = MI.getOperand(Idx);
6836     if (!MO.isReg())
6837       continue;
6838 
6839     // Is this operand statically required to be an SGPR based on the operand
6840     // constraints?
6841     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
6842     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
6843     if (IsRequiredSGPR)
6844       return MO.getReg();
6845 
6846     // If this could be a VGPR or an SGPR, Check the dynamic register class.
6847     Register Reg = MO.getReg();
6848     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
6849     if (RI.isSGPRClass(RegRC))
6850       UsedSGPRs[i] = Reg;
6851   }
6852 
6853   // We don't have a required SGPR operand, so we have a bit more freedom in
6854   // selecting operands to move.
6855 
6856   // Try to select the most used SGPR. If an SGPR is equal to one of the
6857   // others, we choose that.
6858   //
6859   // e.g.
6860   // V_FMA_F32 v0, s0, s0, s0 -> No moves
6861   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
6862 
6863   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
6864   // prefer those.
6865 
6866   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
6867     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
6868       SGPRReg = UsedSGPRs[0];
6869   }
6870 
6871   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
6872     if (UsedSGPRs[1] == UsedSGPRs[2])
6873       SGPRReg = UsedSGPRs[1];
6874   }
6875 
6876   return SGPRReg;
6877 }
6878 
6879 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
6880                                              unsigned OperandName) const {
6881   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
6882   if (Idx == -1)
6883     return nullptr;
6884 
6885   return &MI.getOperand(Idx);
6886 }
6887 
6888 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
6889   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
6890     return (AMDGPU::MTBUFFormat::UFMT_32_FLOAT << 44) |
6891            (1ULL << 56) | // RESOURCE_LEVEL = 1
6892            (3ULL << 60); // OOB_SELECT = 3
6893   }
6894 
6895   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
6896   if (ST.isAmdHsaOS()) {
6897     // Set ATC = 1. GFX9 doesn't have this bit.
6898     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6899       RsrcDataFormat |= (1ULL << 56);
6900 
6901     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
6902     // BTW, it disables TC L2 and therefore decreases performance.
6903     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
6904       RsrcDataFormat |= (2ULL << 59);
6905   }
6906 
6907   return RsrcDataFormat;
6908 }
6909 
6910 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
6911   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
6912                     AMDGPU::RSRC_TID_ENABLE |
6913                     0xffffffff; // Size;
6914 
6915   // GFX9 doesn't have ELEMENT_SIZE.
6916   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
6917     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
6918     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
6919   }
6920 
6921   // IndexStride = 64 / 32.
6922   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
6923   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
6924 
6925   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
6926   // Clear them unless we want a huge stride.
6927   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
6928       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
6929     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
6930 
6931   return Rsrc23;
6932 }
6933 
6934 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
6935   unsigned Opc = MI.getOpcode();
6936 
6937   return isSMRD(Opc);
6938 }
6939 
6940 bool SIInstrInfo::isHighLatencyDef(int Opc) const {
6941   return get(Opc).mayLoad() &&
6942          (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
6943 }
6944 
6945 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
6946                                     int &FrameIndex) const {
6947   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
6948   if (!Addr || !Addr->isFI())
6949     return AMDGPU::NoRegister;
6950 
6951   assert(!MI.memoperands_empty() &&
6952          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
6953 
6954   FrameIndex = Addr->getIndex();
6955   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
6956 }
6957 
6958 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
6959                                         int &FrameIndex) const {
6960   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
6961   assert(Addr && Addr->isFI());
6962   FrameIndex = Addr->getIndex();
6963   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
6964 }
6965 
6966 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
6967                                           int &FrameIndex) const {
6968   if (!MI.mayLoad())
6969     return AMDGPU::NoRegister;
6970 
6971   if (isMUBUF(MI) || isVGPRSpill(MI))
6972     return isStackAccess(MI, FrameIndex);
6973 
6974   if (isSGPRSpill(MI))
6975     return isSGPRStackAccess(MI, FrameIndex);
6976 
6977   return AMDGPU::NoRegister;
6978 }
6979 
6980 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
6981                                          int &FrameIndex) const {
6982   if (!MI.mayStore())
6983     return AMDGPU::NoRegister;
6984 
6985   if (isMUBUF(MI) || isVGPRSpill(MI))
6986     return isStackAccess(MI, FrameIndex);
6987 
6988   if (isSGPRSpill(MI))
6989     return isSGPRStackAccess(MI, FrameIndex);
6990 
6991   return AMDGPU::NoRegister;
6992 }
6993 
6994 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
6995   unsigned Size = 0;
6996   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
6997   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
6998   while (++I != E && I->isInsideBundle()) {
6999     assert(!I->isBundle() && "No nested bundle!");
7000     Size += getInstSizeInBytes(*I);
7001   }
7002 
7003   return Size;
7004 }
7005 
7006 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
7007   unsigned Opc = MI.getOpcode();
7008   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
7009   unsigned DescSize = Desc.getSize();
7010 
7011   // If we have a definitive size, we can use it. Otherwise we need to inspect
7012   // the operands to know the size.
7013   if (isFixedSize(MI)) {
7014     unsigned Size = DescSize;
7015 
7016     // If we hit the buggy offset, an extra nop will be inserted in MC so
7017     // estimate the worst case.
7018     if (MI.isBranch() && ST.hasOffset3fBug())
7019       Size += 4;
7020 
7021     return Size;
7022   }
7023 
7024   // 4-byte instructions may have a 32-bit literal encoded after them. Check
7025   // operands that coud ever be literals.
7026   if (isVALU(MI) || isSALU(MI)) {
7027     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
7028     if (Src0Idx == -1)
7029       return DescSize; // No operands.
7030 
7031     if (isLiteralConstantLike(MI.getOperand(Src0Idx), Desc.OpInfo[Src0Idx]))
7032       return isVOP3(MI) ? 12 : (DescSize + 4);
7033 
7034     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
7035     if (Src1Idx == -1)
7036       return DescSize;
7037 
7038     if (isLiteralConstantLike(MI.getOperand(Src1Idx), Desc.OpInfo[Src1Idx]))
7039       return isVOP3(MI) ? 12 : (DescSize + 4);
7040 
7041     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
7042     if (Src2Idx == -1)
7043       return DescSize;
7044 
7045     if (isLiteralConstantLike(MI.getOperand(Src2Idx), Desc.OpInfo[Src2Idx]))
7046       return isVOP3(MI) ? 12 : (DescSize + 4);
7047 
7048     return DescSize;
7049   }
7050 
7051   // Check whether we have extra NSA words.
7052   if (isMIMG(MI)) {
7053     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
7054     if (VAddr0Idx < 0)
7055       return 8;
7056 
7057     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
7058     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
7059   }
7060 
7061   switch (Opc) {
7062   case TargetOpcode::IMPLICIT_DEF:
7063   case TargetOpcode::KILL:
7064   case TargetOpcode::DBG_VALUE:
7065   case TargetOpcode::EH_LABEL:
7066     return 0;
7067   case TargetOpcode::BUNDLE:
7068     return getInstBundleSize(MI);
7069   case TargetOpcode::INLINEASM:
7070   case TargetOpcode::INLINEASM_BR: {
7071     const MachineFunction *MF = MI.getParent()->getParent();
7072     const char *AsmStr = MI.getOperand(0).getSymbolName();
7073     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(), &ST);
7074   }
7075   default:
7076     return DescSize;
7077   }
7078 }
7079 
7080 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
7081   if (!isFLAT(MI))
7082     return false;
7083 
7084   if (MI.memoperands_empty())
7085     return true;
7086 
7087   for (const MachineMemOperand *MMO : MI.memoperands()) {
7088     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
7089       return true;
7090   }
7091   return false;
7092 }
7093 
7094 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
7095   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
7096 }
7097 
7098 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
7099                                             MachineBasicBlock *IfEnd) const {
7100   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
7101   assert(TI != IfEntry->end());
7102 
7103   MachineInstr *Branch = &(*TI);
7104   MachineFunction *MF = IfEntry->getParent();
7105   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
7106 
7107   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7108     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7109     MachineInstr *SIIF =
7110         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
7111             .add(Branch->getOperand(0))
7112             .add(Branch->getOperand(1));
7113     MachineInstr *SIEND =
7114         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
7115             .addReg(DstReg);
7116 
7117     IfEntry->erase(TI);
7118     IfEntry->insert(IfEntry->end(), SIIF);
7119     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
7120   }
7121 }
7122 
7123 void SIInstrInfo::convertNonUniformLoopRegion(
7124     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
7125   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
7126   // We expect 2 terminators, one conditional and one unconditional.
7127   assert(TI != LoopEnd->end());
7128 
7129   MachineInstr *Branch = &(*TI);
7130   MachineFunction *MF = LoopEnd->getParent();
7131   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
7132 
7133   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7134 
7135     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7136     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
7137     MachineInstrBuilder HeaderPHIBuilder =
7138         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
7139     for (MachineBasicBlock::pred_iterator PI = LoopEntry->pred_begin(),
7140                                           E = LoopEntry->pred_end();
7141          PI != E; ++PI) {
7142       if (*PI == LoopEnd) {
7143         HeaderPHIBuilder.addReg(BackEdgeReg);
7144       } else {
7145         MachineBasicBlock *PMBB = *PI;
7146         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
7147         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
7148                              ZeroReg, 0);
7149         HeaderPHIBuilder.addReg(ZeroReg);
7150       }
7151       HeaderPHIBuilder.addMBB(*PI);
7152     }
7153     MachineInstr *HeaderPhi = HeaderPHIBuilder;
7154     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
7155                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
7156                                   .addReg(DstReg)
7157                                   .add(Branch->getOperand(0));
7158     MachineInstr *SILOOP =
7159         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
7160             .addReg(BackEdgeReg)
7161             .addMBB(LoopEntry);
7162 
7163     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
7164     LoopEnd->erase(TI);
7165     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
7166     LoopEnd->insert(LoopEnd->end(), SILOOP);
7167   }
7168 }
7169 
7170 ArrayRef<std::pair<int, const char *>>
7171 SIInstrInfo::getSerializableTargetIndices() const {
7172   static const std::pair<int, const char *> TargetIndices[] = {
7173       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
7174       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
7175       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
7176       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
7177       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
7178   return makeArrayRef(TargetIndices);
7179 }
7180 
7181 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
7182 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
7183 ScheduleHazardRecognizer *
7184 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
7185                                             const ScheduleDAG *DAG) const {
7186   return new GCNHazardRecognizer(DAG->MF);
7187 }
7188 
7189 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
7190 /// pass.
7191 ScheduleHazardRecognizer *
7192 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
7193   return new GCNHazardRecognizer(MF);
7194 }
7195 
7196 std::pair<unsigned, unsigned>
7197 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7198   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
7199 }
7200 
7201 ArrayRef<std::pair<unsigned, const char *>>
7202 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7203   static const std::pair<unsigned, const char *> TargetFlags[] = {
7204     { MO_GOTPCREL, "amdgpu-gotprel" },
7205     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
7206     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
7207     { MO_REL32_LO, "amdgpu-rel32-lo" },
7208     { MO_REL32_HI, "amdgpu-rel32-hi" },
7209     { MO_ABS32_LO, "amdgpu-abs32-lo" },
7210     { MO_ABS32_HI, "amdgpu-abs32-hi" },
7211   };
7212 
7213   return makeArrayRef(TargetFlags);
7214 }
7215 
7216 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
7217   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
7218          MI.modifiesRegister(AMDGPU::EXEC, &RI);
7219 }
7220 
7221 MachineInstrBuilder
7222 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7223                            MachineBasicBlock::iterator I,
7224                            const DebugLoc &DL,
7225                            Register DestReg) const {
7226   if (ST.hasAddNoCarry())
7227     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
7228 
7229   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7230   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
7231   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
7232 
7233   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7234            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7235 }
7236 
7237 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7238                                                MachineBasicBlock::iterator I,
7239                                                const DebugLoc &DL,
7240                                                Register DestReg,
7241                                                RegScavenger &RS) const {
7242   if (ST.hasAddNoCarry())
7243     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
7244 
7245   // If available, prefer to use vcc.
7246   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
7247                              ? Register(RI.getVCC())
7248                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
7249 
7250   // TODO: Users need to deal with this.
7251   if (!UnusedCarry.isValid())
7252     return MachineInstrBuilder();
7253 
7254   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7255            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7256 }
7257 
7258 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
7259   switch (Opcode) {
7260   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
7261   case AMDGPU::SI_KILL_I1_TERMINATOR:
7262     return true;
7263   default:
7264     return false;
7265   }
7266 }
7267 
7268 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
7269   switch (Opcode) {
7270   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7271     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
7272   case AMDGPU::SI_KILL_I1_PSEUDO:
7273     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
7274   default:
7275     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
7276   }
7277 }
7278 
7279 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
7280   if (!ST.isWave32())
7281     return;
7282 
7283   for (auto &Op : MI.implicit_operands()) {
7284     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
7285       Op.setReg(AMDGPU::VCC_LO);
7286   }
7287 }
7288 
7289 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
7290   if (!isSMRD(MI))
7291     return false;
7292 
7293   // Check that it is using a buffer resource.
7294   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
7295   if (Idx == -1) // e.g. s_memtime
7296     return false;
7297 
7298   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
7299   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
7300 }
7301 
7302 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
7303                                     bool Signed) const {
7304   // TODO: Should 0 be special cased?
7305   if (!ST.hasFlatInstOffsets())
7306     return false;
7307 
7308   if (ST.hasFlatSegmentOffsetBug() && AddrSpace == AMDGPUAS::FLAT_ADDRESS)
7309     return false;
7310 
7311   unsigned N = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7312   return Signed ? isIntN(N, Offset) : isUIntN(N, Offset);
7313 }
7314 
7315 std::pair<int64_t, int64_t> SIInstrInfo::splitFlatOffset(int64_t COffsetVal,
7316                                                          unsigned AddrSpace,
7317                                                          bool IsSigned) const {
7318   int64_t RemainderOffset = COffsetVal;
7319   int64_t ImmField = 0;
7320   const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST, IsSigned);
7321   if (IsSigned) {
7322     // Use signed division by a power of two to truncate towards 0.
7323     int64_t D = 1LL << (NumBits - 1);
7324     RemainderOffset = (COffsetVal / D) * D;
7325     ImmField = COffsetVal - RemainderOffset;
7326   } else if (COffsetVal >= 0) {
7327     ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
7328     RemainderOffset = COffsetVal - ImmField;
7329   }
7330 
7331   assert(isLegalFLATOffset(ImmField, AddrSpace, IsSigned));
7332   assert(RemainderOffset + ImmField == COffsetVal);
7333   return {ImmField, RemainderOffset};
7334 }
7335 
7336 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
7337 enum SIEncodingFamily {
7338   SI = 0,
7339   VI = 1,
7340   SDWA = 2,
7341   SDWA9 = 3,
7342   GFX80 = 4,
7343   GFX9 = 5,
7344   GFX10 = 6,
7345   SDWA10 = 7,
7346   GFX90A = 8
7347 };
7348 
7349 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
7350   switch (ST.getGeneration()) {
7351   default:
7352     break;
7353   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
7354   case AMDGPUSubtarget::SEA_ISLANDS:
7355     return SIEncodingFamily::SI;
7356   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
7357   case AMDGPUSubtarget::GFX9:
7358     return SIEncodingFamily::VI;
7359   case AMDGPUSubtarget::GFX10:
7360     return SIEncodingFamily::GFX10;
7361   }
7362   llvm_unreachable("Unknown subtarget generation!");
7363 }
7364 
7365 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
7366   switch(MCOp) {
7367   // These opcodes use indirect register addressing so
7368   // they need special handling by codegen (currently missing).
7369   // Therefore it is too risky to allow these opcodes
7370   // to be selected by dpp combiner or sdwa peepholer.
7371   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
7372   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
7373   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
7374   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
7375   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
7376   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
7377   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
7378   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
7379     return true;
7380   default:
7381     return false;
7382   }
7383 }
7384 
7385 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
7386   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
7387 
7388   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
7389     ST.getGeneration() == AMDGPUSubtarget::GFX9)
7390     Gen = SIEncodingFamily::GFX9;
7391 
7392   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
7393   // subtarget has UnpackedD16VMem feature.
7394   // TODO: remove this when we discard GFX80 encoding.
7395   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
7396     Gen = SIEncodingFamily::GFX80;
7397 
7398   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
7399     switch (ST.getGeneration()) {
7400     default:
7401       Gen = SIEncodingFamily::SDWA;
7402       break;
7403     case AMDGPUSubtarget::GFX9:
7404       Gen = SIEncodingFamily::SDWA9;
7405       break;
7406     case AMDGPUSubtarget::GFX10:
7407       Gen = SIEncodingFamily::SDWA10;
7408       break;
7409     }
7410   }
7411 
7412   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
7413 
7414   // -1 means that Opcode is already a native instruction.
7415   if (MCOp == -1)
7416     return Opcode;
7417 
7418   if (ST.hasGFX90AInsts()) {
7419     uint16_t NMCOp = (uint16_t)-1;
7420       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX90A);
7421     if (NMCOp == (uint16_t)-1)
7422       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX9);
7423     if (NMCOp != (uint16_t)-1)
7424       MCOp = NMCOp;
7425   }
7426 
7427   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
7428   // no encoding in the given subtarget generation.
7429   if (MCOp == (uint16_t)-1)
7430     return -1;
7431 
7432   if (isAsmOnlyOpcode(MCOp))
7433     return -1;
7434 
7435   return MCOp;
7436 }
7437 
7438 static
7439 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
7440   assert(RegOpnd.isReg());
7441   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
7442                              getRegSubRegPair(RegOpnd);
7443 }
7444 
7445 TargetInstrInfo::RegSubRegPair
7446 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
7447   assert(MI.isRegSequence());
7448   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
7449     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
7450       auto &RegOp = MI.getOperand(1 + 2 * I);
7451       return getRegOrUndef(RegOp);
7452     }
7453   return TargetInstrInfo::RegSubRegPair();
7454 }
7455 
7456 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
7457 // Following a subreg of reg:subreg isn't supported
7458 static bool followSubRegDef(MachineInstr &MI,
7459                             TargetInstrInfo::RegSubRegPair &RSR) {
7460   if (!RSR.SubReg)
7461     return false;
7462   switch (MI.getOpcode()) {
7463   default: break;
7464   case AMDGPU::REG_SEQUENCE:
7465     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
7466     return true;
7467   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
7468   case AMDGPU::INSERT_SUBREG:
7469     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
7470       // inserted the subreg we're looking for
7471       RSR = getRegOrUndef(MI.getOperand(2));
7472     else { // the subreg in the rest of the reg
7473       auto R1 = getRegOrUndef(MI.getOperand(1));
7474       if (R1.SubReg) // subreg of subreg isn't supported
7475         return false;
7476       RSR.Reg = R1.Reg;
7477     }
7478     return true;
7479   }
7480   return false;
7481 }
7482 
7483 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
7484                                      MachineRegisterInfo &MRI) {
7485   assert(MRI.isSSA());
7486   if (!P.Reg.isVirtual())
7487     return nullptr;
7488 
7489   auto RSR = P;
7490   auto *DefInst = MRI.getVRegDef(RSR.Reg);
7491   while (auto *MI = DefInst) {
7492     DefInst = nullptr;
7493     switch (MI->getOpcode()) {
7494     case AMDGPU::COPY:
7495     case AMDGPU::V_MOV_B32_e32: {
7496       auto &Op1 = MI->getOperand(1);
7497       if (Op1.isReg() && Op1.getReg().isVirtual()) {
7498         if (Op1.isUndef())
7499           return nullptr;
7500         RSR = getRegSubRegPair(Op1);
7501         DefInst = MRI.getVRegDef(RSR.Reg);
7502       }
7503       break;
7504     }
7505     default:
7506       if (followSubRegDef(*MI, RSR)) {
7507         if (!RSR.Reg)
7508           return nullptr;
7509         DefInst = MRI.getVRegDef(RSR.Reg);
7510       }
7511     }
7512     if (!DefInst)
7513       return MI;
7514   }
7515   return nullptr;
7516 }
7517 
7518 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
7519                                       Register VReg,
7520                                       const MachineInstr &DefMI,
7521                                       const MachineInstr &UseMI) {
7522   assert(MRI.isSSA() && "Must be run on SSA");
7523 
7524   auto *TRI = MRI.getTargetRegisterInfo();
7525   auto *DefBB = DefMI.getParent();
7526 
7527   // Don't bother searching between blocks, although it is possible this block
7528   // doesn't modify exec.
7529   if (UseMI.getParent() != DefBB)
7530     return true;
7531 
7532   const int MaxInstScan = 20;
7533   int NumInst = 0;
7534 
7535   // Stop scan at the use.
7536   auto E = UseMI.getIterator();
7537   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
7538     if (I->isDebugInstr())
7539       continue;
7540 
7541     if (++NumInst > MaxInstScan)
7542       return true;
7543 
7544     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
7545       return true;
7546   }
7547 
7548   return false;
7549 }
7550 
7551 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
7552                                          Register VReg,
7553                                          const MachineInstr &DefMI) {
7554   assert(MRI.isSSA() && "Must be run on SSA");
7555 
7556   auto *TRI = MRI.getTargetRegisterInfo();
7557   auto *DefBB = DefMI.getParent();
7558 
7559   const int MaxUseScan = 10;
7560   int NumUse = 0;
7561 
7562   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
7563     auto &UseInst = *Use.getParent();
7564     // Don't bother searching between blocks, although it is possible this block
7565     // doesn't modify exec.
7566     if (UseInst.getParent() != DefBB)
7567       return true;
7568 
7569     if (++NumUse > MaxUseScan)
7570       return true;
7571   }
7572 
7573   if (NumUse == 0)
7574     return false;
7575 
7576   const int MaxInstScan = 20;
7577   int NumInst = 0;
7578 
7579   // Stop scan when we have seen all the uses.
7580   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
7581     assert(I != DefBB->end());
7582 
7583     if (I->isDebugInstr())
7584       continue;
7585 
7586     if (++NumInst > MaxInstScan)
7587       return true;
7588 
7589     for (const MachineOperand &Op : I->operands()) {
7590       // We don't check reg masks here as they're used only on calls:
7591       // 1. EXEC is only considered const within one BB
7592       // 2. Call should be a terminator instruction if present in a BB
7593 
7594       if (!Op.isReg())
7595         continue;
7596 
7597       Register Reg = Op.getReg();
7598       if (Op.isUse()) {
7599         if (Reg == VReg && --NumUse == 0)
7600           return false;
7601       } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
7602         return true;
7603     }
7604   }
7605 }
7606 
7607 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
7608     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
7609     const DebugLoc &DL, Register Src, Register Dst) const {
7610   auto Cur = MBB.begin();
7611   if (Cur != MBB.end())
7612     do {
7613       if (!Cur->isPHI() && Cur->readsRegister(Dst))
7614         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
7615       ++Cur;
7616     } while (Cur != MBB.end() && Cur != LastPHIIt);
7617 
7618   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
7619                                                    Dst);
7620 }
7621 
7622 MachineInstr *SIInstrInfo::createPHISourceCopy(
7623     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
7624     const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
7625   if (InsPt != MBB.end() &&
7626       (InsPt->getOpcode() == AMDGPU::SI_IF ||
7627        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
7628        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
7629       InsPt->definesRegister(Src)) {
7630     InsPt++;
7631     return BuildMI(MBB, InsPt, DL,
7632                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
7633                                      : AMDGPU::S_MOV_B64_term),
7634                    Dst)
7635         .addReg(Src, 0, SrcSubReg)
7636         .addReg(AMDGPU::EXEC, RegState::Implicit);
7637   }
7638   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
7639                                               Dst);
7640 }
7641 
7642 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
7643 
7644 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
7645     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
7646     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
7647     VirtRegMap *VRM) const {
7648   // This is a bit of a hack (copied from AArch64). Consider this instruction:
7649   //
7650   //   %0:sreg_32 = COPY $m0
7651   //
7652   // We explicitly chose SReg_32 for the virtual register so such a copy might
7653   // be eliminated by RegisterCoalescer. However, that may not be possible, and
7654   // %0 may even spill. We can't spill $m0 normally (it would require copying to
7655   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
7656   // TargetInstrInfo::foldMemoryOperand() is going to try.
7657   // A similar issue also exists with spilling and reloading $exec registers.
7658   //
7659   // To prevent that, constrain the %0 register class here.
7660   if (MI.isFullCopy()) {
7661     Register DstReg = MI.getOperand(0).getReg();
7662     Register SrcReg = MI.getOperand(1).getReg();
7663     if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
7664         (DstReg.isVirtual() != SrcReg.isVirtual())) {
7665       MachineRegisterInfo &MRI = MF.getRegInfo();
7666       Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
7667       const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
7668       if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
7669         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
7670         return nullptr;
7671       } else if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
7672         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
7673         return nullptr;
7674       }
7675     }
7676   }
7677 
7678   return nullptr;
7679 }
7680 
7681 unsigned SIInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
7682                                       const MachineInstr &MI,
7683                                       unsigned *PredCost) const {
7684   if (MI.isBundle()) {
7685     MachineBasicBlock::const_instr_iterator I(MI.getIterator());
7686     MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
7687     unsigned Lat = 0, Count = 0;
7688     for (++I; I != E && I->isBundledWithPred(); ++I) {
7689       ++Count;
7690       Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
7691     }
7692     return Lat + Count - 1;
7693   }
7694 
7695   return SchedModel.computeInstrLatency(&MI);
7696 }
7697 
7698 unsigned SIInstrInfo::getDSShaderTypeValue(const MachineFunction &MF) {
7699   switch (MF.getFunction().getCallingConv()) {
7700   case CallingConv::AMDGPU_PS:
7701     return 1;
7702   case CallingConv::AMDGPU_VS:
7703     return 2;
7704   case CallingConv::AMDGPU_GS:
7705     return 3;
7706   case CallingConv::AMDGPU_HS:
7707   case CallingConv::AMDGPU_LS:
7708   case CallingConv::AMDGPU_ES:
7709     report_fatal_error("ds_ordered_count unsupported for this calling conv");
7710   case CallingConv::AMDGPU_CS:
7711   case CallingConv::AMDGPU_KERNEL:
7712   case CallingConv::C:
7713   case CallingConv::Fast:
7714   default:
7715     // Assume other calling conventions are various compute callable functions
7716     return 0;
7717   }
7718 }
7719