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