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