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