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