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   bool Src0Literal = false;
3259 
3260   switch (Opc) {
3261   default:
3262     return nullptr;
3263   case AMDGPU::V_MAC_F16_e64:
3264   case AMDGPU::V_FMAC_F16_e64:
3265   case AMDGPU::V_MAC_F32_e64:
3266   case AMDGPU::V_MAC_LEGACY_F32_e64:
3267   case AMDGPU::V_FMAC_F32_e64:
3268   case AMDGPU::V_FMAC_LEGACY_F32_e64:
3269   case AMDGPU::V_FMAC_F64_e64:
3270     break;
3271   case AMDGPU::V_MAC_F16_e32:
3272   case AMDGPU::V_FMAC_F16_e32:
3273   case AMDGPU::V_MAC_F32_e32:
3274   case AMDGPU::V_MAC_LEGACY_F32_e32:
3275   case AMDGPU::V_FMAC_F32_e32:
3276   case AMDGPU::V_FMAC_LEGACY_F32_e32:
3277   case AMDGPU::V_FMAC_F64_e32: {
3278     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
3279                                              AMDGPU::OpName::src0);
3280     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
3281     if (!Src0->isReg() && !Src0->isImm())
3282       return nullptr;
3283 
3284     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
3285       Src0Literal = true;
3286 
3287     break;
3288   }
3289   }
3290 
3291   MachineInstrBuilder MIB;
3292   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
3293   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
3294   const MachineOperand *Src0Mods =
3295     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
3296   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3297   const MachineOperand *Src1Mods =
3298     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
3299   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3300   const MachineOperand *Src2Mods =
3301       getNamedOperand(MI, AMDGPU::OpName::src2_modifiers);
3302   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
3303   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
3304 
3305   if (!Src0Mods && !Src1Mods && !Src2Mods && !Clamp && !Omod && !IsF64 &&
3306       !IsLegacy &&
3307       // If we have an SGPR input, we will violate the constant bus restriction.
3308       (ST.getConstantBusLimit(Opc) > 1 || !Src0->isReg() ||
3309        !RI.isSGPRReg(MBB.getParent()->getRegInfo(), Src0->getReg()))) {
3310     MachineInstr *DefMI;
3311     const auto killDef = [&DefMI, &MBB, this]() -> void {
3312       const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3313       // The only user is the instruction which will be killed.
3314       if (!MRI.hasOneNonDBGUse(DefMI->getOperand(0).getReg()))
3315         return;
3316       // We cannot just remove the DefMI here, calling pass will crash.
3317       DefMI->setDesc(get(AMDGPU::IMPLICIT_DEF));
3318       for (unsigned I = DefMI->getNumOperands() - 1; I != 0; --I)
3319         DefMI->RemoveOperand(I);
3320     };
3321 
3322     int64_t Imm;
3323     if (!Src0Literal && getFoldableImm(Src2, Imm, &DefMI)) {
3324       unsigned NewOpc =
3325           IsFMA ? (IsF16 ? AMDGPU::V_FMAAK_F16 : AMDGPU::V_FMAAK_F32)
3326                 : (IsF16 ? AMDGPU::V_MADAK_F16 : AMDGPU::V_MADAK_F32);
3327       if (pseudoToMCOpcode(NewOpc) != -1) {
3328         MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
3329                   .add(*Dst)
3330                   .add(*Src0)
3331                   .add(*Src1)
3332                   .addImm(Imm);
3333         updateLiveVariables(LV, MI, *MIB);
3334         if (LIS)
3335           LIS->ReplaceMachineInstrInMaps(MI, *MIB);
3336         killDef();
3337         return MIB;
3338       }
3339     }
3340     unsigned NewOpc = IsFMA
3341                           ? (IsF16 ? AMDGPU::V_FMAMK_F16 : AMDGPU::V_FMAMK_F32)
3342                           : (IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32);
3343     if (!Src0Literal && getFoldableImm(Src1, Imm, &DefMI)) {
3344       if (pseudoToMCOpcode(NewOpc) != -1) {
3345         MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
3346                   .add(*Dst)
3347                   .add(*Src0)
3348                   .addImm(Imm)
3349                   .add(*Src2);
3350         updateLiveVariables(LV, MI, *MIB);
3351         if (LIS)
3352           LIS->ReplaceMachineInstrInMaps(MI, *MIB);
3353         killDef();
3354         return MIB;
3355       }
3356     }
3357     if (Src0Literal || getFoldableImm(Src0, Imm, &DefMI)) {
3358       if (Src0Literal) {
3359         Imm = Src0->getImm();
3360         DefMI = nullptr;
3361       }
3362       if (pseudoToMCOpcode(NewOpc) != -1 &&
3363           isOperandLegal(
3364               MI, AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::src0),
3365               Src1)) {
3366         MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
3367                   .add(*Dst)
3368                   .add(*Src1)
3369                   .addImm(Imm)
3370                   .add(*Src2);
3371         updateLiveVariables(LV, MI, *MIB);
3372         if (LIS)
3373           LIS->ReplaceMachineInstrInMaps(MI, *MIB);
3374         if (DefMI)
3375           killDef();
3376         return MIB;
3377       }
3378     }
3379   }
3380 
3381   // VOP2 mac/fmac with a literal operand cannot be converted to VOP3 mad/fma
3382   // because VOP3 does not allow a literal operand.
3383   // TODO: Remove this restriction for GFX10.
3384   if (Src0Literal)
3385     return nullptr;
3386 
3387   unsigned NewOpc = IsFMA ? IsF16 ? AMDGPU::V_FMA_F16_gfx9_e64
3388                                   : IsF64 ? AMDGPU::V_FMA_F64_e64
3389                                           : IsLegacy
3390                                                 ? AMDGPU::V_FMA_LEGACY_F32_e64
3391                                                 : AMDGPU::V_FMA_F32_e64
3392                           : IsF16 ? AMDGPU::V_MAD_F16_e64
3393                                   : IsLegacy ? AMDGPU::V_MAD_LEGACY_F32_e64
3394                                              : AMDGPU::V_MAD_F32_e64;
3395   if (pseudoToMCOpcode(NewOpc) == -1)
3396     return nullptr;
3397 
3398   MIB = BuildMI(MBB, MI, MI.getDebugLoc(), get(NewOpc))
3399             .add(*Dst)
3400             .addImm(Src0Mods ? Src0Mods->getImm() : 0)
3401             .add(*Src0)
3402             .addImm(Src1Mods ? Src1Mods->getImm() : 0)
3403             .add(*Src1)
3404             .addImm(Src2Mods ? Src2Mods->getImm() : 0)
3405             .add(*Src2)
3406             .addImm(Clamp ? Clamp->getImm() : 0)
3407             .addImm(Omod ? Omod->getImm() : 0);
3408   updateLiveVariables(LV, MI, *MIB);
3409   if (LIS)
3410     LIS->ReplaceMachineInstrInMaps(MI, *MIB);
3411   return MIB;
3412 }
3413 
3414 // It's not generally safe to move VALU instructions across these since it will
3415 // start using the register as a base index rather than directly.
3416 // XXX - Why isn't hasSideEffects sufficient for these?
3417 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
3418   switch (MI.getOpcode()) {
3419   case AMDGPU::S_SET_GPR_IDX_ON:
3420   case AMDGPU::S_SET_GPR_IDX_MODE:
3421   case AMDGPU::S_SET_GPR_IDX_OFF:
3422     return true;
3423   default:
3424     return false;
3425   }
3426 }
3427 
3428 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
3429                                        const MachineBasicBlock *MBB,
3430                                        const MachineFunction &MF) const {
3431   // Skipping the check for SP writes in the base implementation. The reason it
3432   // was added was apparently due to compile time concerns.
3433   //
3434   // TODO: Do we really want this barrier? It triggers unnecessary hazard nops
3435   // but is probably avoidable.
3436 
3437   // Copied from base implementation.
3438   // Terminators and labels can't be scheduled around.
3439   if (MI.isTerminator() || MI.isPosition())
3440     return true;
3441 
3442   // INLINEASM_BR can jump to another block
3443   if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
3444     return true;
3445 
3446   // Target-independent instructions do not have an implicit-use of EXEC, even
3447   // when they operate on VGPRs. Treating EXEC modifications as scheduling
3448   // boundaries prevents incorrect movements of such instructions.
3449   return MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
3450          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
3451          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
3452          changesVGPRIndexingMode(MI);
3453 }
3454 
3455 bool SIInstrInfo::isAlwaysGDS(uint16_t Opcode) const {
3456   return Opcode == AMDGPU::DS_ORDERED_COUNT ||
3457          Opcode == AMDGPU::DS_GWS_INIT ||
3458          Opcode == AMDGPU::DS_GWS_SEMA_V ||
3459          Opcode == AMDGPU::DS_GWS_SEMA_BR ||
3460          Opcode == AMDGPU::DS_GWS_SEMA_P ||
3461          Opcode == AMDGPU::DS_GWS_SEMA_RELEASE_ALL ||
3462          Opcode == AMDGPU::DS_GWS_BARRIER;
3463 }
3464 
3465 bool SIInstrInfo::modifiesModeRegister(const MachineInstr &MI) {
3466   // Skip the full operand and register alias search modifiesRegister
3467   // does. There's only a handful of instructions that touch this, it's only an
3468   // implicit def, and doesn't alias any other registers.
3469   if (const MCPhysReg *ImpDef = MI.getDesc().getImplicitDefs()) {
3470     for (; ImpDef && *ImpDef; ++ImpDef) {
3471       if (*ImpDef == AMDGPU::MODE)
3472         return true;
3473     }
3474   }
3475 
3476   return false;
3477 }
3478 
3479 bool SIInstrInfo::hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const {
3480   unsigned Opcode = MI.getOpcode();
3481 
3482   if (MI.mayStore() && isSMRD(MI))
3483     return true; // scalar store or atomic
3484 
3485   // This will terminate the function when other lanes may need to continue.
3486   if (MI.isReturn())
3487     return true;
3488 
3489   // These instructions cause shader I/O that may cause hardware lockups
3490   // when executed with an empty EXEC mask.
3491   //
3492   // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
3493   //       EXEC = 0, but checking for that case here seems not worth it
3494   //       given the typical code patterns.
3495   if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
3496       isEXP(Opcode) ||
3497       Opcode == AMDGPU::DS_ORDERED_COUNT || Opcode == AMDGPU::S_TRAP ||
3498       Opcode == AMDGPU::DS_GWS_INIT || Opcode == AMDGPU::DS_GWS_BARRIER)
3499     return true;
3500 
3501   if (MI.isCall() || MI.isInlineAsm())
3502     return true; // conservative assumption
3503 
3504   // A mode change is a scalar operation that influences vector instructions.
3505   if (modifiesModeRegister(MI))
3506     return true;
3507 
3508   // These are like SALU instructions in terms of effects, so it's questionable
3509   // whether we should return true for those.
3510   //
3511   // However, executing them with EXEC = 0 causes them to operate on undefined
3512   // data, which we avoid by returning true here.
3513   if (Opcode == AMDGPU::V_READFIRSTLANE_B32 ||
3514       Opcode == AMDGPU::V_READLANE_B32 || Opcode == AMDGPU::V_WRITELANE_B32)
3515     return true;
3516 
3517   return false;
3518 }
3519 
3520 bool SIInstrInfo::mayReadEXEC(const MachineRegisterInfo &MRI,
3521                               const MachineInstr &MI) const {
3522   if (MI.isMetaInstruction())
3523     return false;
3524 
3525   // This won't read exec if this is an SGPR->SGPR copy.
3526   if (MI.isCopyLike()) {
3527     if (!RI.isSGPRReg(MRI, MI.getOperand(0).getReg()))
3528       return true;
3529 
3530     // Make sure this isn't copying exec as a normal operand
3531     return MI.readsRegister(AMDGPU::EXEC, &RI);
3532   }
3533 
3534   // Make a conservative assumption about the callee.
3535   if (MI.isCall())
3536     return true;
3537 
3538   // Be conservative with any unhandled generic opcodes.
3539   if (!isTargetSpecificOpcode(MI.getOpcode()))
3540     return true;
3541 
3542   return !isSALU(MI) || MI.readsRegister(AMDGPU::EXEC, &RI);
3543 }
3544 
3545 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
3546   switch (Imm.getBitWidth()) {
3547   case 1: // This likely will be a condition code mask.
3548     return true;
3549 
3550   case 32:
3551     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
3552                                         ST.hasInv2PiInlineImm());
3553   case 64:
3554     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
3555                                         ST.hasInv2PiInlineImm());
3556   case 16:
3557     return ST.has16BitInsts() &&
3558            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
3559                                         ST.hasInv2PiInlineImm());
3560   default:
3561     llvm_unreachable("invalid bitwidth");
3562   }
3563 }
3564 
3565 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
3566                                    uint8_t OperandType) const {
3567   if (!MO.isImm() ||
3568       OperandType < AMDGPU::OPERAND_SRC_FIRST ||
3569       OperandType > AMDGPU::OPERAND_SRC_LAST)
3570     return false;
3571 
3572   // MachineOperand provides no way to tell the true operand size, since it only
3573   // records a 64-bit value. We need to know the size to determine if a 32-bit
3574   // floating point immediate bit pattern is legal for an integer immediate. It
3575   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
3576 
3577   int64_t Imm = MO.getImm();
3578   switch (OperandType) {
3579   case AMDGPU::OPERAND_REG_IMM_INT32:
3580   case AMDGPU::OPERAND_REG_IMM_FP32:
3581   case AMDGPU::OPERAND_REG_IMM_FP32_DEFERRED:
3582   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
3583   case AMDGPU::OPERAND_REG_INLINE_C_FP32:
3584   case AMDGPU::OPERAND_REG_IMM_V2FP32:
3585   case AMDGPU::OPERAND_REG_INLINE_C_V2FP32:
3586   case AMDGPU::OPERAND_REG_IMM_V2INT32:
3587   case AMDGPU::OPERAND_REG_INLINE_C_V2INT32:
3588   case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
3589   case AMDGPU::OPERAND_REG_INLINE_AC_FP32: {
3590     int32_t Trunc = static_cast<int32_t>(Imm);
3591     return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
3592   }
3593   case AMDGPU::OPERAND_REG_IMM_INT64:
3594   case AMDGPU::OPERAND_REG_IMM_FP64:
3595   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
3596   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
3597   case AMDGPU::OPERAND_REG_INLINE_AC_FP64:
3598     return AMDGPU::isInlinableLiteral64(MO.getImm(),
3599                                         ST.hasInv2PiInlineImm());
3600   case AMDGPU::OPERAND_REG_IMM_INT16:
3601   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
3602   case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
3603     // We would expect inline immediates to not be concerned with an integer/fp
3604     // distinction. However, in the case of 16-bit integer operations, the
3605     // "floating point" values appear to not work. It seems read the low 16-bits
3606     // of 32-bit immediates, which happens to always work for the integer
3607     // values.
3608     //
3609     // See llvm bugzilla 46302.
3610     //
3611     // TODO: Theoretically we could use op-sel to use the high bits of the
3612     // 32-bit FP values.
3613     return AMDGPU::isInlinableIntLiteral(Imm);
3614   case AMDGPU::OPERAND_REG_IMM_V2INT16:
3615   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
3616   case AMDGPU::OPERAND_REG_INLINE_AC_V2INT16:
3617     // This suffers the same problem as the scalar 16-bit cases.
3618     return AMDGPU::isInlinableIntLiteralV216(Imm);
3619   case AMDGPU::OPERAND_REG_IMM_FP16:
3620   case AMDGPU::OPERAND_REG_IMM_FP16_DEFERRED:
3621   case AMDGPU::OPERAND_REG_INLINE_C_FP16:
3622   case AMDGPU::OPERAND_REG_INLINE_AC_FP16: {
3623     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
3624       // A few special case instructions have 16-bit operands on subtargets
3625       // where 16-bit instructions are not legal.
3626       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
3627       // constants in these cases
3628       int16_t Trunc = static_cast<int16_t>(Imm);
3629       return ST.has16BitInsts() &&
3630              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
3631     }
3632 
3633     return false;
3634   }
3635   case AMDGPU::OPERAND_REG_IMM_V2FP16:
3636   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
3637   case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: {
3638     uint32_t Trunc = static_cast<uint32_t>(Imm);
3639     return AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
3640   }
3641   case AMDGPU::OPERAND_KIMM32:
3642   case AMDGPU::OPERAND_KIMM16:
3643     return false;
3644   default:
3645     llvm_unreachable("invalid bitwidth");
3646   }
3647 }
3648 
3649 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
3650                                         const MCOperandInfo &OpInfo) const {
3651   switch (MO.getType()) {
3652   case MachineOperand::MO_Register:
3653     return false;
3654   case MachineOperand::MO_Immediate:
3655     return !isInlineConstant(MO, OpInfo);
3656   case MachineOperand::MO_FrameIndex:
3657   case MachineOperand::MO_MachineBasicBlock:
3658   case MachineOperand::MO_ExternalSymbol:
3659   case MachineOperand::MO_GlobalAddress:
3660   case MachineOperand::MO_MCSymbol:
3661     return true;
3662   default:
3663     llvm_unreachable("unexpected operand type");
3664   }
3665 }
3666 
3667 static bool compareMachineOp(const MachineOperand &Op0,
3668                              const MachineOperand &Op1) {
3669   if (Op0.getType() != Op1.getType())
3670     return false;
3671 
3672   switch (Op0.getType()) {
3673   case MachineOperand::MO_Register:
3674     return Op0.getReg() == Op1.getReg();
3675   case MachineOperand::MO_Immediate:
3676     return Op0.getImm() == Op1.getImm();
3677   default:
3678     llvm_unreachable("Didn't expect to be comparing these operand types");
3679   }
3680 }
3681 
3682 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
3683                                     const MachineOperand &MO) const {
3684   const MCInstrDesc &InstDesc = MI.getDesc();
3685   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo];
3686 
3687   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
3688 
3689   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
3690     return true;
3691 
3692   if (OpInfo.RegClass < 0)
3693     return false;
3694 
3695   if (MO.isImm() && isInlineConstant(MO, OpInfo)) {
3696     if (isMAI(MI) && ST.hasMFMAInlineLiteralBug() &&
3697         OpNo ==(unsigned)AMDGPU::getNamedOperandIdx(MI.getOpcode(),
3698                                                     AMDGPU::OpName::src2))
3699       return false;
3700     return RI.opCanUseInlineConstant(OpInfo.OperandType);
3701   }
3702 
3703   if (!RI.opCanUseLiteralConstant(OpInfo.OperandType))
3704     return false;
3705 
3706   if (!isVOP3(MI) || !AMDGPU::isSISrcOperand(InstDesc, OpNo))
3707     return true;
3708 
3709   return ST.hasVOP3Literal();
3710 }
3711 
3712 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
3713   // GFX90A does not have V_MUL_LEGACY_F32_e32.
3714   if (Opcode == AMDGPU::V_MUL_LEGACY_F32_e64 && ST.hasGFX90AInsts())
3715     return false;
3716 
3717   int Op32 = AMDGPU::getVOPe32(Opcode);
3718   if (Op32 == -1)
3719     return false;
3720 
3721   return pseudoToMCOpcode(Op32) != -1;
3722 }
3723 
3724 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
3725   // The src0_modifier operand is present on all instructions
3726   // that have modifiers.
3727 
3728   return AMDGPU::getNamedOperandIdx(Opcode,
3729                                     AMDGPU::OpName::src0_modifiers) != -1;
3730 }
3731 
3732 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
3733                                   unsigned OpName) const {
3734   const MachineOperand *Mods = getNamedOperand(MI, OpName);
3735   return Mods && Mods->getImm();
3736 }
3737 
3738 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
3739   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
3740          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
3741          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
3742          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
3743          hasModifiersSet(MI, AMDGPU::OpName::omod);
3744 }
3745 
3746 bool SIInstrInfo::canShrink(const MachineInstr &MI,
3747                             const MachineRegisterInfo &MRI) const {
3748   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3749   // Can't shrink instruction with three operands.
3750   if (Src2) {
3751     switch (MI.getOpcode()) {
3752       default: return false;
3753 
3754       case AMDGPU::V_ADDC_U32_e64:
3755       case AMDGPU::V_SUBB_U32_e64:
3756       case AMDGPU::V_SUBBREV_U32_e64: {
3757         const MachineOperand *Src1
3758           = getNamedOperand(MI, AMDGPU::OpName::src1);
3759         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
3760           return false;
3761         // Additional verification is needed for sdst/src2.
3762         return true;
3763       }
3764       case AMDGPU::V_MAC_F16_e64:
3765       case AMDGPU::V_MAC_F32_e64:
3766       case AMDGPU::V_MAC_LEGACY_F32_e64:
3767       case AMDGPU::V_FMAC_F16_e64:
3768       case AMDGPU::V_FMAC_F32_e64:
3769       case AMDGPU::V_FMAC_F64_e64:
3770       case AMDGPU::V_FMAC_LEGACY_F32_e64:
3771         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
3772             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
3773           return false;
3774         break;
3775 
3776       case AMDGPU::V_CNDMASK_B32_e64:
3777         break;
3778     }
3779   }
3780 
3781   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3782   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
3783                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
3784     return false;
3785 
3786   // We don't need to check src0, all input types are legal, so just make sure
3787   // src0 isn't using any modifiers.
3788   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
3789     return false;
3790 
3791   // Can it be shrunk to a valid 32 bit opcode?
3792   if (!hasVALU32BitEncoding(MI.getOpcode()))
3793     return false;
3794 
3795   // Check output modifiers
3796   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
3797          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
3798 }
3799 
3800 // Set VCC operand with all flags from \p Orig, except for setting it as
3801 // implicit.
3802 static void copyFlagsToImplicitVCC(MachineInstr &MI,
3803                                    const MachineOperand &Orig) {
3804 
3805   for (MachineOperand &Use : MI.implicit_operands()) {
3806     if (Use.isUse() &&
3807         (Use.getReg() == AMDGPU::VCC || Use.getReg() == AMDGPU::VCC_LO)) {
3808       Use.setIsUndef(Orig.isUndef());
3809       Use.setIsKill(Orig.isKill());
3810       return;
3811     }
3812   }
3813 }
3814 
3815 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
3816                                            unsigned Op32) const {
3817   MachineBasicBlock *MBB = MI.getParent();;
3818   MachineInstrBuilder Inst32 =
3819     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32))
3820     .setMIFlags(MI.getFlags());
3821 
3822   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
3823   // For VOPC instructions, this is replaced by an implicit def of vcc.
3824   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
3825   if (Op32DstIdx != -1) {
3826     // dst
3827     Inst32.add(MI.getOperand(0));
3828   } else {
3829     assert(((MI.getOperand(0).getReg() == AMDGPU::VCC) ||
3830             (MI.getOperand(0).getReg() == AMDGPU::VCC_LO)) &&
3831            "Unexpected case");
3832   }
3833 
3834   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
3835 
3836   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
3837   if (Src1)
3838     Inst32.add(*Src1);
3839 
3840   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
3841 
3842   if (Src2) {
3843     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
3844     if (Op32Src2Idx != -1) {
3845       Inst32.add(*Src2);
3846     } else {
3847       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
3848       // replaced with an implicit read of vcc or vcc_lo. The implicit read
3849       // of vcc was already added during the initial BuildMI, but we
3850       // 1) may need to change vcc to vcc_lo to preserve the original register
3851       // 2) have to preserve the original flags.
3852       fixImplicitOperands(*Inst32);
3853       copyFlagsToImplicitVCC(*Inst32, *Src2);
3854     }
3855   }
3856 
3857   return Inst32;
3858 }
3859 
3860 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
3861                                   const MachineOperand &MO,
3862                                   const MCOperandInfo &OpInfo) const {
3863   // Literal constants use the constant bus.
3864   //if (isLiteralConstantLike(MO, OpInfo))
3865   // return true;
3866   if (MO.isImm())
3867     return !isInlineConstant(MO, OpInfo);
3868 
3869   if (!MO.isReg())
3870     return true; // Misc other operands like FrameIndex
3871 
3872   if (!MO.isUse())
3873     return false;
3874 
3875   if (MO.getReg().isVirtual())
3876     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
3877 
3878   // Null is free
3879   if (MO.getReg() == AMDGPU::SGPR_NULL)
3880     return false;
3881 
3882   // SGPRs use the constant bus
3883   if (MO.isImplicit()) {
3884     return MO.getReg() == AMDGPU::M0 ||
3885            MO.getReg() == AMDGPU::VCC ||
3886            MO.getReg() == AMDGPU::VCC_LO;
3887   } else {
3888     return AMDGPU::SReg_32RegClass.contains(MO.getReg()) ||
3889            AMDGPU::SReg_64RegClass.contains(MO.getReg());
3890   }
3891 }
3892 
3893 static Register findImplicitSGPRRead(const MachineInstr &MI) {
3894   for (const MachineOperand &MO : MI.implicit_operands()) {
3895     // We only care about reads.
3896     if (MO.isDef())
3897       continue;
3898 
3899     switch (MO.getReg()) {
3900     case AMDGPU::VCC:
3901     case AMDGPU::VCC_LO:
3902     case AMDGPU::VCC_HI:
3903     case AMDGPU::M0:
3904     case AMDGPU::FLAT_SCR:
3905       return MO.getReg();
3906 
3907     default:
3908       break;
3909     }
3910   }
3911 
3912   return AMDGPU::NoRegister;
3913 }
3914 
3915 static bool shouldReadExec(const MachineInstr &MI) {
3916   if (SIInstrInfo::isVALU(MI)) {
3917     switch (MI.getOpcode()) {
3918     case AMDGPU::V_READLANE_B32:
3919     case AMDGPU::V_WRITELANE_B32:
3920       return false;
3921     }
3922 
3923     return true;
3924   }
3925 
3926   if (MI.isPreISelOpcode() ||
3927       SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
3928       SIInstrInfo::isSALU(MI) ||
3929       SIInstrInfo::isSMRD(MI))
3930     return false;
3931 
3932   return true;
3933 }
3934 
3935 static bool isSubRegOf(const SIRegisterInfo &TRI,
3936                        const MachineOperand &SuperVec,
3937                        const MachineOperand &SubReg) {
3938   if (SubReg.getReg().isPhysical())
3939     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
3940 
3941   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
3942          SubReg.getReg() == SuperVec.getReg();
3943 }
3944 
3945 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
3946                                     StringRef &ErrInfo) const {
3947   uint16_t Opcode = MI.getOpcode();
3948   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
3949     return true;
3950 
3951   const MachineFunction *MF = MI.getParent()->getParent();
3952   const MachineRegisterInfo &MRI = MF->getRegInfo();
3953 
3954   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
3955   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
3956   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
3957 
3958   // Make sure the number of operands is correct.
3959   const MCInstrDesc &Desc = get(Opcode);
3960   if (!Desc.isVariadic() &&
3961       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
3962     ErrInfo = "Instruction has wrong number of operands.";
3963     return false;
3964   }
3965 
3966   if (MI.isInlineAsm()) {
3967     // Verify register classes for inlineasm constraints.
3968     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
3969          I != E; ++I) {
3970       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
3971       if (!RC)
3972         continue;
3973 
3974       const MachineOperand &Op = MI.getOperand(I);
3975       if (!Op.isReg())
3976         continue;
3977 
3978       Register Reg = Op.getReg();
3979       if (!Reg.isVirtual() && !RC->contains(Reg)) {
3980         ErrInfo = "inlineasm operand has incorrect register class.";
3981         return false;
3982       }
3983     }
3984 
3985     return true;
3986   }
3987 
3988   if (isMIMG(MI) && MI.memoperands_empty() && MI.mayLoadOrStore()) {
3989     ErrInfo = "missing memory operand from MIMG instruction.";
3990     return false;
3991   }
3992 
3993   // Make sure the register classes are correct.
3994   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
3995     const MachineOperand &MO = MI.getOperand(i);
3996     if (MO.isFPImm()) {
3997       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
3998                 "all fp values to integers.";
3999       return false;
4000     }
4001 
4002     int RegClass = Desc.OpInfo[i].RegClass;
4003 
4004     switch (Desc.OpInfo[i].OperandType) {
4005     case MCOI::OPERAND_REGISTER:
4006       if (MI.getOperand(i).isImm() || MI.getOperand(i).isGlobal()) {
4007         ErrInfo = "Illegal immediate value for operand.";
4008         return false;
4009       }
4010       break;
4011     case AMDGPU::OPERAND_REG_IMM_INT32:
4012     case AMDGPU::OPERAND_REG_IMM_FP32:
4013     case AMDGPU::OPERAND_REG_IMM_FP32_DEFERRED:
4014       break;
4015     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
4016     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
4017     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
4018     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
4019     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
4020     case AMDGPU::OPERAND_REG_INLINE_C_FP16:
4021     case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
4022     case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
4023     case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
4024     case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
4025     case AMDGPU::OPERAND_REG_INLINE_AC_FP64: {
4026       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
4027         ErrInfo = "Illegal immediate value for operand.";
4028         return false;
4029       }
4030       break;
4031     }
4032     case MCOI::OPERAND_IMMEDIATE:
4033     case AMDGPU::OPERAND_KIMM32:
4034       // Check if this operand is an immediate.
4035       // FrameIndex operands will be replaced by immediates, so they are
4036       // allowed.
4037       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
4038         ErrInfo = "Expected immediate, but got non-immediate";
4039         return false;
4040       }
4041       LLVM_FALLTHROUGH;
4042     default:
4043       continue;
4044     }
4045 
4046     if (!MO.isReg())
4047       continue;
4048     Register Reg = MO.getReg();
4049     if (!Reg)
4050       continue;
4051 
4052     // FIXME: Ideally we would have separate instruction definitions with the
4053     // aligned register constraint.
4054     // FIXME: We do not verify inline asm operands, but custom inline asm
4055     // verification is broken anyway
4056     if (ST.needsAlignedVGPRs()) {
4057       const TargetRegisterClass *RC = RI.getRegClassForReg(MRI, Reg);
4058       if (RI.hasVectorRegisters(RC) && MO.getSubReg()) {
4059         const TargetRegisterClass *SubRC =
4060             RI.getSubRegClass(RC, MO.getSubReg());
4061         RC = RI.getCompatibleSubRegClass(RC, SubRC, MO.getSubReg());
4062         if (RC)
4063           RC = SubRC;
4064       }
4065 
4066       // Check that this is the aligned version of the class.
4067       if (!RC || !RI.isProperlyAlignedRC(*RC)) {
4068         ErrInfo = "Subtarget requires even aligned vector registers";
4069         return false;
4070       }
4071     }
4072 
4073     if (RegClass != -1) {
4074       if (Reg.isVirtual())
4075         continue;
4076 
4077       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
4078       if (!RC->contains(Reg)) {
4079         ErrInfo = "Operand has incorrect register class.";
4080         return false;
4081       }
4082     }
4083   }
4084 
4085   // Verify SDWA
4086   if (isSDWA(MI)) {
4087     if (!ST.hasSDWA()) {
4088       ErrInfo = "SDWA is not supported on this target";
4089       return false;
4090     }
4091 
4092     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4093 
4094     const int OpIndices[] = {DstIdx, Src0Idx, Src1Idx, Src2Idx};
4095 
4096     for (int OpIdx : OpIndices) {
4097       if (OpIdx == -1)
4098         continue;
4099       const MachineOperand &MO = MI.getOperand(OpIdx);
4100 
4101       if (!ST.hasSDWAScalar()) {
4102         // Only VGPRS on VI
4103         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
4104           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
4105           return false;
4106         }
4107       } else {
4108         // No immediates on GFX9
4109         if (!MO.isReg()) {
4110           ErrInfo =
4111             "Only reg allowed as operands in SDWA instructions on GFX9+";
4112           return false;
4113         }
4114       }
4115     }
4116 
4117     if (!ST.hasSDWAOmod()) {
4118       // No omod allowed on VI
4119       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
4120       if (OMod != nullptr &&
4121         (!OMod->isImm() || OMod->getImm() != 0)) {
4122         ErrInfo = "OMod not allowed in SDWA instructions on VI";
4123         return false;
4124       }
4125     }
4126 
4127     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
4128     if (isVOPC(BasicOpcode)) {
4129       if (!ST.hasSDWASdst() && DstIdx != -1) {
4130         // Only vcc allowed as dst on VI for VOPC
4131         const MachineOperand &Dst = MI.getOperand(DstIdx);
4132         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
4133           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
4134           return false;
4135         }
4136       } else if (!ST.hasSDWAOutModsVOPC()) {
4137         // No clamp allowed on GFX9 for VOPC
4138         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
4139         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
4140           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
4141           return false;
4142         }
4143 
4144         // No omod allowed on GFX9 for VOPC
4145         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
4146         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
4147           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
4148           return false;
4149         }
4150       }
4151     }
4152 
4153     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
4154     if (DstUnused && DstUnused->isImm() &&
4155         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
4156       const MachineOperand &Dst = MI.getOperand(DstIdx);
4157       if (!Dst.isReg() || !Dst.isTied()) {
4158         ErrInfo = "Dst register should have tied register";
4159         return false;
4160       }
4161 
4162       const MachineOperand &TiedMO =
4163           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
4164       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
4165         ErrInfo =
4166             "Dst register should be tied to implicit use of preserved register";
4167         return false;
4168       } else if (TiedMO.getReg().isPhysical() &&
4169                  Dst.getReg() != TiedMO.getReg()) {
4170         ErrInfo = "Dst register should use same physical register as preserved";
4171         return false;
4172       }
4173     }
4174   }
4175 
4176   // Verify MIMG
4177   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
4178     // Ensure that the return type used is large enough for all the options
4179     // being used TFE/LWE require an extra result register.
4180     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
4181     if (DMask) {
4182       uint64_t DMaskImm = DMask->getImm();
4183       uint32_t RegCount =
4184           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
4185       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
4186       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
4187       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
4188 
4189       // Adjust for packed 16 bit values
4190       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
4191         RegCount >>= 1;
4192 
4193       // Adjust if using LWE or TFE
4194       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
4195         RegCount += 1;
4196 
4197       const uint32_t DstIdx =
4198           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
4199       const MachineOperand &Dst = MI.getOperand(DstIdx);
4200       if (Dst.isReg()) {
4201         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
4202         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
4203         if (RegCount > DstSize) {
4204           ErrInfo = "MIMG instruction returns too many registers for dst "
4205                     "register class";
4206           return false;
4207         }
4208       }
4209     }
4210   }
4211 
4212   // Verify VOP*. Ignore multiple sgpr operands on writelane.
4213   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
4214       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
4215     // Only look at the true operands. Only a real operand can use the constant
4216     // bus, and we don't want to check pseudo-operands like the source modifier
4217     // flags.
4218     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
4219 
4220     unsigned ConstantBusCount = 0;
4221     bool UsesLiteral = false;
4222     const MachineOperand *LiteralVal = nullptr;
4223 
4224     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
4225       ++ConstantBusCount;
4226 
4227     SmallVector<Register, 2> SGPRsUsed;
4228     Register SGPRUsed;
4229 
4230     for (int OpIdx : OpIndices) {
4231       if (OpIdx == -1)
4232         break;
4233       const MachineOperand &MO = MI.getOperand(OpIdx);
4234       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4235         if (MO.isReg()) {
4236           SGPRUsed = MO.getReg();
4237           if (llvm::all_of(SGPRsUsed, [SGPRUsed](unsigned SGPR) {
4238                 return SGPRUsed != SGPR;
4239               })) {
4240             ++ConstantBusCount;
4241             SGPRsUsed.push_back(SGPRUsed);
4242           }
4243         } else {
4244           if (!UsesLiteral) {
4245             ++ConstantBusCount;
4246             UsesLiteral = true;
4247             LiteralVal = &MO;
4248           } else if (!MO.isIdenticalTo(*LiteralVal)) {
4249             assert(isVOP3(MI));
4250             ErrInfo = "VOP3 instruction uses more than one literal";
4251             return false;
4252           }
4253         }
4254       }
4255     }
4256 
4257     SGPRUsed = findImplicitSGPRRead(MI);
4258     if (SGPRUsed != AMDGPU::NoRegister) {
4259       // Implicit uses may safely overlap true operands
4260       if (llvm::all_of(SGPRsUsed, [this, SGPRUsed](unsigned SGPR) {
4261             return !RI.regsOverlap(SGPRUsed, SGPR);
4262           })) {
4263         ++ConstantBusCount;
4264         SGPRsUsed.push_back(SGPRUsed);
4265       }
4266     }
4267 
4268     // v_writelane_b32 is an exception from constant bus restriction:
4269     // vsrc0 can be sgpr, const or m0 and lane select sgpr, m0 or inline-const
4270     if (ConstantBusCount > ST.getConstantBusLimit(Opcode) &&
4271         Opcode != AMDGPU::V_WRITELANE_B32) {
4272       ErrInfo = "VOP* instruction violates constant bus restriction";
4273       return false;
4274     }
4275 
4276     if (isVOP3(MI) && UsesLiteral && !ST.hasVOP3Literal()) {
4277       ErrInfo = "VOP3 instruction uses literal";
4278       return false;
4279     }
4280   }
4281 
4282   // Special case for writelane - this can break the multiple constant bus rule,
4283   // but still can't use more than one SGPR register
4284   if (Desc.getOpcode() == AMDGPU::V_WRITELANE_B32) {
4285     unsigned SGPRCount = 0;
4286     Register SGPRUsed = AMDGPU::NoRegister;
4287 
4288     for (int OpIdx : {Src0Idx, Src1Idx, Src2Idx}) {
4289       if (OpIdx == -1)
4290         break;
4291 
4292       const MachineOperand &MO = MI.getOperand(OpIdx);
4293 
4294       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
4295         if (MO.isReg() && MO.getReg() != AMDGPU::M0) {
4296           if (MO.getReg() != SGPRUsed)
4297             ++SGPRCount;
4298           SGPRUsed = MO.getReg();
4299         }
4300       }
4301       if (SGPRCount > ST.getConstantBusLimit(Opcode)) {
4302         ErrInfo = "WRITELANE instruction violates constant bus restriction";
4303         return false;
4304       }
4305     }
4306   }
4307 
4308   // Verify misc. restrictions on specific instructions.
4309   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32_e64 ||
4310       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64_e64) {
4311     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4312     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4313     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
4314     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
4315       if (!compareMachineOp(Src0, Src1) &&
4316           !compareMachineOp(Src0, Src2)) {
4317         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
4318         return false;
4319       }
4320     }
4321     if ((getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm() &
4322          SISrcMods::ABS) ||
4323         (getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm() &
4324          SISrcMods::ABS) ||
4325         (getNamedOperand(MI, AMDGPU::OpName::src2_modifiers)->getImm() &
4326          SISrcMods::ABS)) {
4327       ErrInfo = "ABS not allowed in VOP3B instructions";
4328       return false;
4329     }
4330   }
4331 
4332   if (isSOP2(MI) || isSOPC(MI)) {
4333     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4334     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
4335     unsigned Immediates = 0;
4336 
4337     if (!Src0.isReg() &&
4338         !isInlineConstant(Src0, Desc.OpInfo[Src0Idx].OperandType))
4339       Immediates++;
4340     if (!Src1.isReg() &&
4341         !isInlineConstant(Src1, Desc.OpInfo[Src1Idx].OperandType))
4342       Immediates++;
4343 
4344     if (Immediates > 1) {
4345       ErrInfo = "SOP2/SOPC instruction requires too many immediate constants";
4346       return false;
4347     }
4348   }
4349 
4350   if (isSOPK(MI)) {
4351     auto Op = getNamedOperand(MI, AMDGPU::OpName::simm16);
4352     if (Desc.isBranch()) {
4353       if (!Op->isMBB()) {
4354         ErrInfo = "invalid branch target for SOPK instruction";
4355         return false;
4356       }
4357     } else {
4358       uint64_t Imm = Op->getImm();
4359       if (sopkIsZext(MI)) {
4360         if (!isUInt<16>(Imm)) {
4361           ErrInfo = "invalid immediate for SOPK instruction";
4362           return false;
4363         }
4364       } else {
4365         if (!isInt<16>(Imm)) {
4366           ErrInfo = "invalid immediate for SOPK instruction";
4367           return false;
4368         }
4369       }
4370     }
4371   }
4372 
4373   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
4374       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
4375       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4376       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
4377     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
4378                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
4379 
4380     const unsigned StaticNumOps = Desc.getNumOperands() +
4381       Desc.getNumImplicitUses();
4382     const unsigned NumImplicitOps = IsDst ? 2 : 1;
4383 
4384     // Allow additional implicit operands. This allows a fixup done by the post
4385     // RA scheduler where the main implicit operand is killed and implicit-defs
4386     // are added for sub-registers that remain live after this instruction.
4387     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
4388       ErrInfo = "missing implicit register operands";
4389       return false;
4390     }
4391 
4392     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4393     if (IsDst) {
4394       if (!Dst->isUse()) {
4395         ErrInfo = "v_movreld_b32 vdst should be a use operand";
4396         return false;
4397       }
4398 
4399       unsigned UseOpIdx;
4400       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
4401           UseOpIdx != StaticNumOps + 1) {
4402         ErrInfo = "movrel implicit operands should be tied";
4403         return false;
4404       }
4405     }
4406 
4407     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
4408     const MachineOperand &ImpUse
4409       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
4410     if (!ImpUse.isReg() || !ImpUse.isUse() ||
4411         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
4412       ErrInfo = "src0 should be subreg of implicit vector use";
4413       return false;
4414     }
4415   }
4416 
4417   // Make sure we aren't losing exec uses in the td files. This mostly requires
4418   // being careful when using let Uses to try to add other use registers.
4419   if (shouldReadExec(MI)) {
4420     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
4421       ErrInfo = "VALU instruction does not implicitly read exec mask";
4422       return false;
4423     }
4424   }
4425 
4426   if (isSMRD(MI)) {
4427     if (MI.mayStore()) {
4428       // The register offset form of scalar stores may only use m0 as the
4429       // soffset register.
4430       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
4431       if (Soff && Soff->getReg() != AMDGPU::M0) {
4432         ErrInfo = "scalar stores must use m0 as offset register";
4433         return false;
4434       }
4435     }
4436   }
4437 
4438   if (isFLAT(MI) && !ST.hasFlatInstOffsets()) {
4439     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4440     if (Offset->getImm() != 0) {
4441       ErrInfo = "subtarget does not support offsets in flat instructions";
4442       return false;
4443     }
4444   }
4445 
4446   if (isMIMG(MI)) {
4447     const MachineOperand *DimOp = getNamedOperand(MI, AMDGPU::OpName::dim);
4448     if (DimOp) {
4449       int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opcode,
4450                                                  AMDGPU::OpName::vaddr0);
4451       int SRsrcIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::srsrc);
4452       const AMDGPU::MIMGInfo *Info = AMDGPU::getMIMGInfo(Opcode);
4453       const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4454           AMDGPU::getMIMGBaseOpcodeInfo(Info->BaseOpcode);
4455       const AMDGPU::MIMGDimInfo *Dim =
4456           AMDGPU::getMIMGDimInfoByEncoding(DimOp->getImm());
4457 
4458       if (!Dim) {
4459         ErrInfo = "dim is out of range";
4460         return false;
4461       }
4462 
4463       bool IsA16 = false;
4464       if (ST.hasR128A16()) {
4465         const MachineOperand *R128A16 = getNamedOperand(MI, AMDGPU::OpName::r128);
4466         IsA16 = R128A16->getImm() != 0;
4467       } else if (ST.hasGFX10A16()) {
4468         const MachineOperand *A16 = getNamedOperand(MI, AMDGPU::OpName::a16);
4469         IsA16 = A16->getImm() != 0;
4470       }
4471 
4472       bool IsNSA = SRsrcIdx - VAddr0Idx > 1;
4473 
4474       unsigned AddrWords =
4475           AMDGPU::getAddrSizeMIMGOp(BaseOpcode, Dim, IsA16, ST.hasG16());
4476 
4477       unsigned VAddrWords;
4478       if (IsNSA) {
4479         VAddrWords = SRsrcIdx - VAddr0Idx;
4480       } else {
4481         const TargetRegisterClass *RC = getOpRegClass(MI, VAddr0Idx);
4482         VAddrWords = MRI.getTargetRegisterInfo()->getRegSizeInBits(*RC) / 32;
4483         if (AddrWords > 8)
4484           AddrWords = 16;
4485       }
4486 
4487       if (VAddrWords != AddrWords) {
4488         LLVM_DEBUG(dbgs() << "bad vaddr size, expected " << AddrWords
4489                           << " but got " << VAddrWords << "\n");
4490         ErrInfo = "bad vaddr size";
4491         return false;
4492       }
4493     }
4494   }
4495 
4496   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
4497   if (DppCt) {
4498     using namespace AMDGPU::DPP;
4499 
4500     unsigned DC = DppCt->getImm();
4501     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
4502         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
4503         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
4504         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
4505         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
4506         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST) ||
4507         (DC >= DppCtrl::DPP_UNUSED8_FIRST && DC <= DppCtrl::DPP_UNUSED8_LAST)) {
4508       ErrInfo = "Invalid dpp_ctrl value";
4509       return false;
4510     }
4511     if (DC >= DppCtrl::WAVE_SHL1 && DC <= DppCtrl::WAVE_ROR1 &&
4512         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4513       ErrInfo = "Invalid dpp_ctrl value: "
4514                 "wavefront shifts are not supported on GFX10+";
4515       return false;
4516     }
4517     if (DC >= DppCtrl::BCAST15 && DC <= DppCtrl::BCAST31 &&
4518         ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
4519       ErrInfo = "Invalid dpp_ctrl value: "
4520                 "broadcasts are not supported on GFX10+";
4521       return false;
4522     }
4523     if (DC >= DppCtrl::ROW_SHARE_FIRST && DC <= DppCtrl::ROW_XMASK_LAST &&
4524         ST.getGeneration() < AMDGPUSubtarget::GFX10) {
4525       if (DC >= DppCtrl::ROW_NEWBCAST_FIRST &&
4526           DC <= DppCtrl::ROW_NEWBCAST_LAST &&
4527           !ST.hasGFX90AInsts()) {
4528         ErrInfo = "Invalid dpp_ctrl value: "
4529                   "row_newbroadcast/row_share is not supported before "
4530                   "GFX90A/GFX10";
4531         return false;
4532       } else if (DC > DppCtrl::ROW_NEWBCAST_LAST || !ST.hasGFX90AInsts()) {
4533         ErrInfo = "Invalid dpp_ctrl value: "
4534                   "row_share and row_xmask are not supported before GFX10";
4535         return false;
4536       }
4537     }
4538 
4539     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
4540     int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
4541 
4542     if (Opcode != AMDGPU::V_MOV_B64_DPP_PSEUDO &&
4543         ((DstIdx >= 0 &&
4544           (Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64RegClassID ||
4545            Desc.OpInfo[DstIdx].RegClass == AMDGPU::VReg_64_Align2RegClassID)) ||
4546          ((Src0Idx >= 0 &&
4547            (Desc.OpInfo[Src0Idx].RegClass == AMDGPU::VReg_64RegClassID ||
4548             Desc.OpInfo[Src0Idx].RegClass ==
4549                 AMDGPU::VReg_64_Align2RegClassID)))) &&
4550         !AMDGPU::isLegal64BitDPPControl(DC)) {
4551       ErrInfo = "Invalid dpp_ctrl value: "
4552                 "64 bit dpp only support row_newbcast";
4553       return false;
4554     }
4555   }
4556 
4557   if ((MI.mayStore() || MI.mayLoad()) && !isVGPRSpill(MI)) {
4558     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
4559     uint16_t DataNameIdx = isDS(Opcode) ? AMDGPU::OpName::data0
4560                                         : AMDGPU::OpName::vdata;
4561     const MachineOperand *Data = getNamedOperand(MI, DataNameIdx);
4562     const MachineOperand *Data2 = getNamedOperand(MI, AMDGPU::OpName::data1);
4563     if (Data && !Data->isReg())
4564       Data = nullptr;
4565 
4566     if (ST.hasGFX90AInsts()) {
4567       if (Dst && Data &&
4568           (RI.isAGPR(MRI, Dst->getReg()) != RI.isAGPR(MRI, Data->getReg()))) {
4569         ErrInfo = "Invalid register class: "
4570                   "vdata and vdst should be both VGPR or AGPR";
4571         return false;
4572       }
4573       if (Data && Data2 &&
4574           (RI.isAGPR(MRI, Data->getReg()) != RI.isAGPR(MRI, Data2->getReg()))) {
4575         ErrInfo = "Invalid register class: "
4576                   "both data operands should be VGPR or AGPR";
4577         return false;
4578       }
4579     } else {
4580       if ((Dst && RI.isAGPR(MRI, Dst->getReg())) ||
4581           (Data && RI.isAGPR(MRI, Data->getReg())) ||
4582           (Data2 && RI.isAGPR(MRI, Data2->getReg()))) {
4583         ErrInfo = "Invalid register class: "
4584                   "agpr loads and stores not supported on this GPU";
4585         return false;
4586       }
4587     }
4588   }
4589 
4590   if (ST.needsAlignedVGPRs() &&
4591       (MI.getOpcode() == AMDGPU::DS_GWS_INIT ||
4592        MI.getOpcode() == AMDGPU::DS_GWS_SEMA_BR ||
4593        MI.getOpcode() == AMDGPU::DS_GWS_BARRIER)) {
4594     const MachineOperand *Op = getNamedOperand(MI, AMDGPU::OpName::data0);
4595     Register Reg = Op->getReg();
4596     bool Aligned = true;
4597     if (Reg.isPhysical()) {
4598       Aligned = !(RI.getHWRegIndex(Reg) & 1);
4599     } else {
4600       const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
4601       Aligned = RI.getRegSizeInBits(RC) > 32 && RI.isProperlyAlignedRC(RC) &&
4602                 !(RI.getChannelFromSubReg(Op->getSubReg()) & 1);
4603     }
4604 
4605     if (!Aligned) {
4606       ErrInfo = "Subtarget requires even aligned vector registers "
4607                 "for DS_GWS instructions";
4608       return false;
4609     }
4610   }
4611 
4612   if (Desc.getOpcode() == AMDGPU::G_AMDGPU_WAVE_ADDRESS) {
4613     const MachineOperand &SrcOp = MI.getOperand(1);
4614     if (!SrcOp.isReg() || SrcOp.getReg().isVirtual()) {
4615       ErrInfo = "pseudo expects only physical SGPRs";
4616       return false;
4617     }
4618   }
4619 
4620   return true;
4621 }
4622 
4623 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
4624   switch (MI.getOpcode()) {
4625   default: return AMDGPU::INSTRUCTION_LIST_END;
4626   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
4627   case AMDGPU::COPY: return AMDGPU::COPY;
4628   case AMDGPU::PHI: return AMDGPU::PHI;
4629   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
4630   case AMDGPU::WQM: return AMDGPU::WQM;
4631   case AMDGPU::SOFT_WQM: return AMDGPU::SOFT_WQM;
4632   case AMDGPU::STRICT_WWM: return AMDGPU::STRICT_WWM;
4633   case AMDGPU::STRICT_WQM: return AMDGPU::STRICT_WQM;
4634   case AMDGPU::S_MOV_B32: {
4635     const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4636     return MI.getOperand(1).isReg() ||
4637            RI.isAGPR(MRI, MI.getOperand(0).getReg()) ?
4638            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
4639   }
4640   case AMDGPU::S_ADD_I32:
4641     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
4642   case AMDGPU::S_ADDC_U32:
4643     return AMDGPU::V_ADDC_U32_e32;
4644   case AMDGPU::S_SUB_I32:
4645     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_CO_U32_e32;
4646     // FIXME: These are not consistently handled, and selected when the carry is
4647     // used.
4648   case AMDGPU::S_ADD_U32:
4649     return AMDGPU::V_ADD_CO_U32_e32;
4650   case AMDGPU::S_SUB_U32:
4651     return AMDGPU::V_SUB_CO_U32_e32;
4652   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
4653   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_U32_e64;
4654   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32_e64;
4655   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32_e64;
4656   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
4657   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
4658   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
4659   case AMDGPU::S_XNOR_B32:
4660     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
4661   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
4662   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
4663   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
4664   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
4665   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
4666   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64_e64;
4667   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
4668   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64_e64;
4669   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
4670   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64_e64;
4671   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32_e64;
4672   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32_e64;
4673   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32_e64;
4674   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32_e64;
4675   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
4676   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
4677   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
4678   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
4679   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e64;
4680   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e64;
4681   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e64;
4682   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e64;
4683   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e64;
4684   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e64;
4685   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e64;
4686   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e64;
4687   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e64;
4688   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e64;
4689   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e64;
4690   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e64;
4691   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e64;
4692   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e64;
4693   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
4694   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
4695   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
4696   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
4697   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
4698   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
4699   }
4700   llvm_unreachable(
4701       "Unexpected scalar opcode without corresponding vector one!");
4702 }
4703 
4704 static unsigned adjustAllocatableRegClass(const GCNSubtarget &ST,
4705                                           const MachineRegisterInfo &MRI,
4706                                           const MCInstrDesc &TID,
4707                                           unsigned RCID,
4708                                           bool IsAllocatable) {
4709   if ((IsAllocatable || !ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4710       (((TID.mayLoad() || TID.mayStore()) &&
4711         !(TID.TSFlags & SIInstrFlags::VGPRSpill)) ||
4712        (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::MIMG)))) {
4713     switch (RCID) {
4714     case AMDGPU::AV_32RegClassID: return AMDGPU::VGPR_32RegClassID;
4715     case AMDGPU::AV_64RegClassID: return AMDGPU::VReg_64RegClassID;
4716     case AMDGPU::AV_96RegClassID: return AMDGPU::VReg_96RegClassID;
4717     case AMDGPU::AV_128RegClassID: return AMDGPU::VReg_128RegClassID;
4718     case AMDGPU::AV_160RegClassID: return AMDGPU::VReg_160RegClassID;
4719     default:
4720       break;
4721     }
4722   }
4723   return RCID;
4724 }
4725 
4726 const TargetRegisterClass *SIInstrInfo::getRegClass(const MCInstrDesc &TID,
4727     unsigned OpNum, const TargetRegisterInfo *TRI,
4728     const MachineFunction &MF)
4729   const {
4730   if (OpNum >= TID.getNumOperands())
4731     return nullptr;
4732   auto RegClass = TID.OpInfo[OpNum].RegClass;
4733   bool IsAllocatable = false;
4734   if (TID.TSFlags & (SIInstrFlags::DS | SIInstrFlags::FLAT)) {
4735     // vdst and vdata should be both VGPR or AGPR, same for the DS instructions
4736     // with two data operands. Request register class constrained to VGPR only
4737     // of both operands present as Machine Copy Propagation can not check this
4738     // constraint and possibly other passes too.
4739     //
4740     // The check is limited to FLAT and DS because atomics in non-flat encoding
4741     // have their vdst and vdata tied to be the same register.
4742     const int VDstIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4743                                                    AMDGPU::OpName::vdst);
4744     const int DataIdx = AMDGPU::getNamedOperandIdx(TID.Opcode,
4745         (TID.TSFlags & SIInstrFlags::DS) ? AMDGPU::OpName::data0
4746                                          : AMDGPU::OpName::vdata);
4747     if (DataIdx != -1) {
4748       IsAllocatable = VDstIdx != -1 ||
4749                       AMDGPU::getNamedOperandIdx(TID.Opcode,
4750                                                  AMDGPU::OpName::data1) != -1;
4751     }
4752   }
4753   RegClass = adjustAllocatableRegClass(ST, MF.getRegInfo(), TID, RegClass,
4754                                        IsAllocatable);
4755   return RI.getRegClass(RegClass);
4756 }
4757 
4758 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
4759                                                       unsigned OpNo) const {
4760   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4761   const MCInstrDesc &Desc = get(MI.getOpcode());
4762   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
4763       Desc.OpInfo[OpNo].RegClass == -1) {
4764     Register Reg = MI.getOperand(OpNo).getReg();
4765 
4766     if (Reg.isVirtual())
4767       return MRI.getRegClass(Reg);
4768     return RI.getPhysRegClass(Reg);
4769   }
4770 
4771   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
4772   RCID = adjustAllocatableRegClass(ST, MRI, Desc, RCID, true);
4773   return RI.getRegClass(RCID);
4774 }
4775 
4776 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
4777   MachineBasicBlock::iterator I = MI;
4778   MachineBasicBlock *MBB = MI.getParent();
4779   MachineOperand &MO = MI.getOperand(OpIdx);
4780   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4781   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
4782   const TargetRegisterClass *RC = RI.getRegClass(RCID);
4783   unsigned Size = RI.getRegSizeInBits(*RC);
4784   unsigned Opcode = (Size == 64) ? AMDGPU::V_MOV_B64_PSEUDO : AMDGPU::V_MOV_B32_e32;
4785   if (MO.isReg())
4786     Opcode = AMDGPU::COPY;
4787   else if (RI.isSGPRClass(RC))
4788     Opcode = (Size == 64) ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
4789 
4790   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
4791   const TargetRegisterClass *VRC64 = RI.getVGPR64Class();
4792   if (RI.getCommonSubClass(VRC64, VRC))
4793     VRC = VRC64;
4794   else
4795     VRC = &AMDGPU::VGPR_32RegClass;
4796 
4797   Register Reg = MRI.createVirtualRegister(VRC);
4798   DebugLoc DL = MBB->findDebugLoc(I);
4799   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
4800   MO.ChangeToRegister(Reg, false);
4801 }
4802 
4803 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
4804                                          MachineRegisterInfo &MRI,
4805                                          MachineOperand &SuperReg,
4806                                          const TargetRegisterClass *SuperRC,
4807                                          unsigned SubIdx,
4808                                          const TargetRegisterClass *SubRC)
4809                                          const {
4810   MachineBasicBlock *MBB = MI->getParent();
4811   DebugLoc DL = MI->getDebugLoc();
4812   Register SubReg = MRI.createVirtualRegister(SubRC);
4813 
4814   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
4815     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4816       .addReg(SuperReg.getReg(), 0, SubIdx);
4817     return SubReg;
4818   }
4819 
4820   // Just in case the super register is itself a sub-register, copy it to a new
4821   // value so we don't need to worry about merging its subreg index with the
4822   // SubIdx passed to this function. The register coalescer should be able to
4823   // eliminate this extra copy.
4824   Register NewSuperReg = MRI.createVirtualRegister(SuperRC);
4825 
4826   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
4827     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
4828 
4829   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
4830     .addReg(NewSuperReg, 0, SubIdx);
4831 
4832   return SubReg;
4833 }
4834 
4835 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
4836   MachineBasicBlock::iterator MII,
4837   MachineRegisterInfo &MRI,
4838   MachineOperand &Op,
4839   const TargetRegisterClass *SuperRC,
4840   unsigned SubIdx,
4841   const TargetRegisterClass *SubRC) const {
4842   if (Op.isImm()) {
4843     if (SubIdx == AMDGPU::sub0)
4844       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
4845     if (SubIdx == AMDGPU::sub1)
4846       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
4847 
4848     llvm_unreachable("Unhandled register index for immediate");
4849   }
4850 
4851   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
4852                                        SubIdx, SubRC);
4853   return MachineOperand::CreateReg(SubReg, false);
4854 }
4855 
4856 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
4857 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
4858   assert(Inst.getNumExplicitOperands() == 3);
4859   MachineOperand Op1 = Inst.getOperand(1);
4860   Inst.RemoveOperand(1);
4861   Inst.addOperand(Op1);
4862 }
4863 
4864 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
4865                                     const MCOperandInfo &OpInfo,
4866                                     const MachineOperand &MO) const {
4867   if (!MO.isReg())
4868     return false;
4869 
4870   Register Reg = MO.getReg();
4871 
4872   const TargetRegisterClass *DRC = RI.getRegClass(OpInfo.RegClass);
4873   if (Reg.isPhysical())
4874     return DRC->contains(Reg);
4875 
4876   const TargetRegisterClass *RC = MRI.getRegClass(Reg);
4877 
4878   if (MO.getSubReg()) {
4879     const MachineFunction *MF = MO.getParent()->getParent()->getParent();
4880     const TargetRegisterClass *SuperRC = RI.getLargestLegalSuperClass(RC, *MF);
4881     if (!SuperRC)
4882       return false;
4883 
4884     DRC = RI.getMatchingSuperRegClass(SuperRC, DRC, MO.getSubReg());
4885     if (!DRC)
4886       return false;
4887   }
4888   return RC->hasSuperClassEq(DRC);
4889 }
4890 
4891 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
4892                                      const MCOperandInfo &OpInfo,
4893                                      const MachineOperand &MO) const {
4894   if (MO.isReg())
4895     return isLegalRegOperand(MRI, OpInfo, MO);
4896 
4897   // Handle non-register types that are treated like immediates.
4898   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI() || MO.isGlobal());
4899   return true;
4900 }
4901 
4902 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
4903                                  const MachineOperand *MO) const {
4904   const MachineFunction &MF = *MI.getParent()->getParent();
4905   const MachineRegisterInfo &MRI = MF.getRegInfo();
4906   const MCInstrDesc &InstDesc = MI.getDesc();
4907   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
4908   const TargetRegisterClass *DefinedRC =
4909       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
4910   if (!MO)
4911     MO = &MI.getOperand(OpIdx);
4912 
4913   int ConstantBusLimit = ST.getConstantBusLimit(MI.getOpcode());
4914   int VOP3LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
4915   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
4916     if (isVOP3(MI) && isLiteralConstantLike(*MO, OpInfo) && !VOP3LiteralLimit--)
4917       return false;
4918 
4919     SmallDenseSet<RegSubRegPair> SGPRsUsed;
4920     if (MO->isReg())
4921       SGPRsUsed.insert(RegSubRegPair(MO->getReg(), MO->getSubReg()));
4922 
4923     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
4924       if (i == OpIdx)
4925         continue;
4926       const MachineOperand &Op = MI.getOperand(i);
4927       if (Op.isReg()) {
4928         RegSubRegPair SGPR(Op.getReg(), Op.getSubReg());
4929         if (!SGPRsUsed.count(SGPR) &&
4930             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
4931           if (--ConstantBusLimit <= 0)
4932             return false;
4933           SGPRsUsed.insert(SGPR);
4934         }
4935       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
4936         if (--ConstantBusLimit <= 0)
4937           return false;
4938       } else if (isVOP3(MI) && AMDGPU::isSISrcOperand(InstDesc, i) &&
4939                  isLiteralConstantLike(Op, InstDesc.OpInfo[i])) {
4940         if (!VOP3LiteralLimit--)
4941           return false;
4942         if (--ConstantBusLimit <= 0)
4943           return false;
4944       }
4945     }
4946   }
4947 
4948   if (MO->isReg()) {
4949     assert(DefinedRC);
4950     if (!isLegalRegOperand(MRI, OpInfo, *MO))
4951       return false;
4952     bool IsAGPR = RI.isAGPR(MRI, MO->getReg());
4953     if (IsAGPR && !ST.hasMAIInsts())
4954       return false;
4955     unsigned Opc = MI.getOpcode();
4956     if (IsAGPR &&
4957         (!ST.hasGFX90AInsts() || !MRI.reservedRegsFrozen()) &&
4958         (MI.mayLoad() || MI.mayStore() || isDS(Opc) || isMIMG(Opc)))
4959       return false;
4960     // Atomics should have both vdst and vdata either vgpr or agpr.
4961     const int VDstIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst);
4962     const int DataIdx = AMDGPU::getNamedOperandIdx(Opc,
4963         isDS(Opc) ? AMDGPU::OpName::data0 : AMDGPU::OpName::vdata);
4964     if ((int)OpIdx == VDstIdx && DataIdx != -1 &&
4965         MI.getOperand(DataIdx).isReg() &&
4966         RI.isAGPR(MRI, MI.getOperand(DataIdx).getReg()) != IsAGPR)
4967       return false;
4968     if ((int)OpIdx == DataIdx) {
4969       if (VDstIdx != -1 &&
4970           RI.isAGPR(MRI, MI.getOperand(VDstIdx).getReg()) != IsAGPR)
4971         return false;
4972       // DS instructions with 2 src operands also must have tied RC.
4973       const int Data1Idx = AMDGPU::getNamedOperandIdx(Opc,
4974                                                       AMDGPU::OpName::data1);
4975       if (Data1Idx != -1 && MI.getOperand(Data1Idx).isReg() &&
4976           RI.isAGPR(MRI, MI.getOperand(Data1Idx).getReg()) != IsAGPR)
4977         return false;
4978     }
4979     if (Opc == AMDGPU::V_ACCVGPR_WRITE_B32_e64 &&
4980         (int)OpIdx == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) &&
4981         RI.isSGPRReg(MRI, MO->getReg()))
4982       return false;
4983     return true;
4984   }
4985 
4986   // Handle non-register types that are treated like immediates.
4987   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI() || MO->isGlobal());
4988 
4989   if (!DefinedRC) {
4990     // This operand expects an immediate.
4991     return true;
4992   }
4993 
4994   return isImmOperandLegal(MI, OpIdx, *MO);
4995 }
4996 
4997 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
4998                                        MachineInstr &MI) const {
4999   unsigned Opc = MI.getOpcode();
5000   const MCInstrDesc &InstrDesc = get(Opc);
5001 
5002   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
5003   MachineOperand &Src0 = MI.getOperand(Src0Idx);
5004 
5005   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5006   MachineOperand &Src1 = MI.getOperand(Src1Idx);
5007 
5008   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
5009   // we need to only have one constant bus use before GFX10.
5010   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
5011   if (HasImplicitSGPR && ST.getConstantBusLimit(Opc) <= 1 &&
5012       Src0.isReg() && (RI.isSGPRReg(MRI, Src0.getReg()) ||
5013        isLiteralConstantLike(Src0, InstrDesc.OpInfo[Src0Idx])))
5014     legalizeOpWithMove(MI, Src0Idx);
5015 
5016   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
5017   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
5018   // src0/src1 with V_READFIRSTLANE.
5019   if (Opc == AMDGPU::V_WRITELANE_B32) {
5020     const DebugLoc &DL = MI.getDebugLoc();
5021     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
5022       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5023       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5024           .add(Src0);
5025       Src0.ChangeToRegister(Reg, false);
5026     }
5027     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
5028       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5029       const DebugLoc &DL = MI.getDebugLoc();
5030       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5031           .add(Src1);
5032       Src1.ChangeToRegister(Reg, false);
5033     }
5034     return;
5035   }
5036 
5037   // No VOP2 instructions support AGPRs.
5038   if (Src0.isReg() && RI.isAGPR(MRI, Src0.getReg()))
5039     legalizeOpWithMove(MI, Src0Idx);
5040 
5041   if (Src1.isReg() && RI.isAGPR(MRI, Src1.getReg()))
5042     legalizeOpWithMove(MI, Src1Idx);
5043 
5044   // VOP2 src0 instructions support all operand types, so we don't need to check
5045   // their legality. If src1 is already legal, we don't need to do anything.
5046   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
5047     return;
5048 
5049   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
5050   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
5051   // select is uniform.
5052   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
5053       RI.isVGPR(MRI, Src1.getReg())) {
5054     Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5055     const DebugLoc &DL = MI.getDebugLoc();
5056     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5057         .add(Src1);
5058     Src1.ChangeToRegister(Reg, false);
5059     return;
5060   }
5061 
5062   // We do not use commuteInstruction here because it is too aggressive and will
5063   // commute if it is possible. We only want to commute here if it improves
5064   // legality. This can be called a fairly large number of times so don't waste
5065   // compile time pointlessly swapping and checking legality again.
5066   if (HasImplicitSGPR || !MI.isCommutable()) {
5067     legalizeOpWithMove(MI, Src1Idx);
5068     return;
5069   }
5070 
5071   // If src0 can be used as src1, commuting will make the operands legal.
5072   // Otherwise we have to give up and insert a move.
5073   //
5074   // TODO: Other immediate-like operand kinds could be commuted if there was a
5075   // MachineOperand::ChangeTo* for them.
5076   if ((!Src1.isImm() && !Src1.isReg()) ||
5077       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
5078     legalizeOpWithMove(MI, Src1Idx);
5079     return;
5080   }
5081 
5082   int CommutedOpc = commuteOpcode(MI);
5083   if (CommutedOpc == -1) {
5084     legalizeOpWithMove(MI, Src1Idx);
5085     return;
5086   }
5087 
5088   MI.setDesc(get(CommutedOpc));
5089 
5090   Register Src0Reg = Src0.getReg();
5091   unsigned Src0SubReg = Src0.getSubReg();
5092   bool Src0Kill = Src0.isKill();
5093 
5094   if (Src1.isImm())
5095     Src0.ChangeToImmediate(Src1.getImm());
5096   else if (Src1.isReg()) {
5097     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
5098     Src0.setSubReg(Src1.getSubReg());
5099   } else
5100     llvm_unreachable("Should only have register or immediate operands");
5101 
5102   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
5103   Src1.setSubReg(Src0SubReg);
5104   fixImplicitOperands(MI);
5105 }
5106 
5107 // Legalize VOP3 operands. All operand types are supported for any operand
5108 // but only one literal constant and only starting from GFX10.
5109 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
5110                                        MachineInstr &MI) const {
5111   unsigned Opc = MI.getOpcode();
5112 
5113   int VOP3Idx[3] = {
5114     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
5115     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
5116     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
5117   };
5118 
5119   if (Opc == AMDGPU::V_PERMLANE16_B32_e64 ||
5120       Opc == AMDGPU::V_PERMLANEX16_B32_e64) {
5121     // src1 and src2 must be scalar
5122     MachineOperand &Src1 = MI.getOperand(VOP3Idx[1]);
5123     MachineOperand &Src2 = MI.getOperand(VOP3Idx[2]);
5124     const DebugLoc &DL = MI.getDebugLoc();
5125     if (Src1.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
5126       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5127       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5128         .add(Src1);
5129       Src1.ChangeToRegister(Reg, false);
5130     }
5131     if (Src2.isReg() && !RI.isSGPRClass(MRI.getRegClass(Src2.getReg()))) {
5132       Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
5133       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
5134         .add(Src2);
5135       Src2.ChangeToRegister(Reg, false);
5136     }
5137   }
5138 
5139   // Find the one SGPR operand we are allowed to use.
5140   int ConstantBusLimit = ST.getConstantBusLimit(Opc);
5141   int LiteralLimit = ST.hasVOP3Literal() ? 1 : 0;
5142   SmallDenseSet<unsigned> SGPRsUsed;
5143   Register SGPRReg = findUsedSGPR(MI, VOP3Idx);
5144   if (SGPRReg != AMDGPU::NoRegister) {
5145     SGPRsUsed.insert(SGPRReg);
5146     --ConstantBusLimit;
5147   }
5148 
5149   for (int Idx : VOP3Idx) {
5150     if (Idx == -1)
5151       break;
5152     MachineOperand &MO = MI.getOperand(Idx);
5153 
5154     if (!MO.isReg()) {
5155       if (!isLiteralConstantLike(MO, get(Opc).OpInfo[Idx]))
5156         continue;
5157 
5158       if (LiteralLimit > 0 && ConstantBusLimit > 0) {
5159         --LiteralLimit;
5160         --ConstantBusLimit;
5161         continue;
5162       }
5163 
5164       --LiteralLimit;
5165       --ConstantBusLimit;
5166       legalizeOpWithMove(MI, Idx);
5167       continue;
5168     }
5169 
5170     if (RI.hasAGPRs(RI.getRegClassForReg(MRI, MO.getReg())) &&
5171         !isOperandLegal(MI, Idx, &MO)) {
5172       legalizeOpWithMove(MI, Idx);
5173       continue;
5174     }
5175 
5176     if (!RI.isSGPRClass(RI.getRegClassForReg(MRI, MO.getReg())))
5177       continue; // VGPRs are legal
5178 
5179     // We can use one SGPR in each VOP3 instruction prior to GFX10
5180     // and two starting from GFX10.
5181     if (SGPRsUsed.count(MO.getReg()))
5182       continue;
5183     if (ConstantBusLimit > 0) {
5184       SGPRsUsed.insert(MO.getReg());
5185       --ConstantBusLimit;
5186       continue;
5187     }
5188 
5189     // If we make it this far, then the operand is not legal and we must
5190     // legalize it.
5191     legalizeOpWithMove(MI, Idx);
5192   }
5193 }
5194 
5195 Register SIInstrInfo::readlaneVGPRToSGPR(Register SrcReg, MachineInstr &UseMI,
5196                                          MachineRegisterInfo &MRI) const {
5197   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
5198   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
5199   Register DstReg = MRI.createVirtualRegister(SRC);
5200   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
5201 
5202   if (RI.hasAGPRs(VRC)) {
5203     VRC = RI.getEquivalentVGPRClass(VRC);
5204     Register NewSrcReg = MRI.createVirtualRegister(VRC);
5205     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5206             get(TargetOpcode::COPY), NewSrcReg)
5207         .addReg(SrcReg);
5208     SrcReg = NewSrcReg;
5209   }
5210 
5211   if (SubRegs == 1) {
5212     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5213             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
5214         .addReg(SrcReg);
5215     return DstReg;
5216   }
5217 
5218   SmallVector<unsigned, 8> SRegs;
5219   for (unsigned i = 0; i < SubRegs; ++i) {
5220     Register SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5221     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5222             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
5223         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
5224     SRegs.push_back(SGPR);
5225   }
5226 
5227   MachineInstrBuilder MIB =
5228       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
5229               get(AMDGPU::REG_SEQUENCE), DstReg);
5230   for (unsigned i = 0; i < SubRegs; ++i) {
5231     MIB.addReg(SRegs[i]);
5232     MIB.addImm(RI.getSubRegFromChannel(i));
5233   }
5234   return DstReg;
5235 }
5236 
5237 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
5238                                        MachineInstr &MI) const {
5239 
5240   // If the pointer is store in VGPRs, then we need to move them to
5241   // SGPRs using v_readfirstlane.  This is safe because we only select
5242   // loads with uniform pointers to SMRD instruction so we know the
5243   // pointer value is uniform.
5244   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
5245   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
5246     Register SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
5247     SBase->setReg(SGPR);
5248   }
5249   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
5250   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
5251     Register SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
5252     SOff->setReg(SGPR);
5253   }
5254 }
5255 
5256 bool SIInstrInfo::moveFlatAddrToVGPR(MachineInstr &Inst) const {
5257   unsigned Opc = Inst.getOpcode();
5258   int OldSAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
5259   if (OldSAddrIdx < 0)
5260     return false;
5261 
5262   assert(isSegmentSpecificFLAT(Inst));
5263 
5264   int NewOpc = AMDGPU::getGlobalVaddrOp(Opc);
5265   if (NewOpc < 0)
5266     NewOpc = AMDGPU::getFlatScratchInstSVfromSS(Opc);
5267   if (NewOpc < 0)
5268     return false;
5269 
5270   MachineRegisterInfo &MRI = Inst.getMF()->getRegInfo();
5271   MachineOperand &SAddr = Inst.getOperand(OldSAddrIdx);
5272   if (RI.isSGPRReg(MRI, SAddr.getReg()))
5273     return false;
5274 
5275   int NewVAddrIdx = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vaddr);
5276   if (NewVAddrIdx < 0)
5277     return false;
5278 
5279   int OldVAddrIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
5280 
5281   // Check vaddr, it shall be zero or absent.
5282   MachineInstr *VAddrDef = nullptr;
5283   if (OldVAddrIdx >= 0) {
5284     MachineOperand &VAddr = Inst.getOperand(OldVAddrIdx);
5285     VAddrDef = MRI.getUniqueVRegDef(VAddr.getReg());
5286     if (!VAddrDef || VAddrDef->getOpcode() != AMDGPU::V_MOV_B32_e32 ||
5287         !VAddrDef->getOperand(1).isImm() ||
5288         VAddrDef->getOperand(1).getImm() != 0)
5289       return false;
5290   }
5291 
5292   const MCInstrDesc &NewDesc = get(NewOpc);
5293   Inst.setDesc(NewDesc);
5294 
5295   // Callers expect iterator to be valid after this call, so modify the
5296   // instruction in place.
5297   if (OldVAddrIdx == NewVAddrIdx) {
5298     MachineOperand &NewVAddr = Inst.getOperand(NewVAddrIdx);
5299     // Clear use list from the old vaddr holding a zero register.
5300     MRI.removeRegOperandFromUseList(&NewVAddr);
5301     MRI.moveOperands(&NewVAddr, &SAddr, 1);
5302     Inst.RemoveOperand(OldSAddrIdx);
5303     // Update the use list with the pointer we have just moved from vaddr to
5304     // saddr position. Otherwise new vaddr will be missing from the use list.
5305     MRI.removeRegOperandFromUseList(&NewVAddr);
5306     MRI.addRegOperandToUseList(&NewVAddr);
5307   } else {
5308     assert(OldSAddrIdx == NewVAddrIdx);
5309 
5310     if (OldVAddrIdx >= 0) {
5311       int NewVDstIn = AMDGPU::getNamedOperandIdx(NewOpc,
5312                                                  AMDGPU::OpName::vdst_in);
5313 
5314       // RemoveOperand doesn't try to fixup tied operand indexes at it goes, so
5315       // it asserts. Untie the operands for now and retie them afterwards.
5316       if (NewVDstIn != -1) {
5317         int OldVDstIn = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in);
5318         Inst.untieRegOperand(OldVDstIn);
5319       }
5320 
5321       Inst.RemoveOperand(OldVAddrIdx);
5322 
5323       if (NewVDstIn != -1) {
5324         int NewVDst = AMDGPU::getNamedOperandIdx(NewOpc, AMDGPU::OpName::vdst);
5325         Inst.tieOperands(NewVDst, NewVDstIn);
5326       }
5327     }
5328   }
5329 
5330   if (VAddrDef && MRI.use_nodbg_empty(VAddrDef->getOperand(0).getReg()))
5331     VAddrDef->eraseFromParent();
5332 
5333   return true;
5334 }
5335 
5336 // FIXME: Remove this when SelectionDAG is obsoleted.
5337 void SIInstrInfo::legalizeOperandsFLAT(MachineRegisterInfo &MRI,
5338                                        MachineInstr &MI) const {
5339   if (!isSegmentSpecificFLAT(MI))
5340     return;
5341 
5342   // Fixup SGPR operands in VGPRs. We only select these when the DAG divergence
5343   // thinks they are uniform, so a readfirstlane should be valid.
5344   MachineOperand *SAddr = getNamedOperand(MI, AMDGPU::OpName::saddr);
5345   if (!SAddr || RI.isSGPRClass(MRI.getRegClass(SAddr->getReg())))
5346     return;
5347 
5348   if (moveFlatAddrToVGPR(MI))
5349     return;
5350 
5351   Register ToSGPR = readlaneVGPRToSGPR(SAddr->getReg(), MI, MRI);
5352   SAddr->setReg(ToSGPR);
5353 }
5354 
5355 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
5356                                          MachineBasicBlock::iterator I,
5357                                          const TargetRegisterClass *DstRC,
5358                                          MachineOperand &Op,
5359                                          MachineRegisterInfo &MRI,
5360                                          const DebugLoc &DL) const {
5361   Register OpReg = Op.getReg();
5362   unsigned OpSubReg = Op.getSubReg();
5363 
5364   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
5365       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
5366 
5367   // Check if operand is already the correct register class.
5368   if (DstRC == OpRC)
5369     return;
5370 
5371   Register DstReg = MRI.createVirtualRegister(DstRC);
5372   auto Copy = BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
5373 
5374   Op.setReg(DstReg);
5375   Op.setSubReg(0);
5376 
5377   MachineInstr *Def = MRI.getVRegDef(OpReg);
5378   if (!Def)
5379     return;
5380 
5381   // Try to eliminate the copy if it is copying an immediate value.
5382   if (Def->isMoveImmediate() && DstRC != &AMDGPU::VReg_1RegClass)
5383     FoldImmediate(*Copy, *Def, OpReg, &MRI);
5384 
5385   bool ImpDef = Def->isImplicitDef();
5386   while (!ImpDef && Def && Def->isCopy()) {
5387     if (Def->getOperand(1).getReg().isPhysical())
5388       break;
5389     Def = MRI.getUniqueVRegDef(Def->getOperand(1).getReg());
5390     ImpDef = Def && Def->isImplicitDef();
5391   }
5392   if (!RI.isSGPRClass(DstRC) && !Copy->readsRegister(AMDGPU::EXEC, &RI) &&
5393       !ImpDef)
5394     Copy.addReg(AMDGPU::EXEC, RegState::Implicit);
5395 }
5396 
5397 // Emit the actual waterfall loop, executing the wrapped instruction for each
5398 // unique value of \p Rsrc across all lanes. In the best case we execute 1
5399 // iteration, in the worst case we execute 64 (once per lane).
5400 static void
5401 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
5402                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
5403                           const DebugLoc &DL, MachineOperand &Rsrc) {
5404   MachineFunction &MF = *OrigBB.getParent();
5405   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5406   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5407   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5408   unsigned SaveExecOpc =
5409       ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 : AMDGPU::S_AND_SAVEEXEC_B64;
5410   unsigned XorTermOpc =
5411       ST.isWave32() ? AMDGPU::S_XOR_B32_term : AMDGPU::S_XOR_B64_term;
5412   unsigned AndOpc =
5413       ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
5414   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5415 
5416   MachineBasicBlock::iterator I = LoopBB.begin();
5417 
5418   SmallVector<Register, 8> ReadlanePieces;
5419   Register CondReg = AMDGPU::NoRegister;
5420 
5421   Register VRsrc = Rsrc.getReg();
5422   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
5423 
5424   unsigned RegSize = TRI->getRegSizeInBits(Rsrc.getReg(), MRI);
5425   unsigned NumSubRegs =  RegSize / 32;
5426   assert(NumSubRegs % 2 == 0 && NumSubRegs <= 32 && "Unhandled register size");
5427 
5428   for (unsigned Idx = 0; Idx < NumSubRegs; Idx += 2) {
5429 
5430     Register CurRegLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5431     Register CurRegHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5432 
5433     // Read the next variant <- also loop target.
5434     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegLo)
5435             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx));
5436 
5437     // Read the next variant <- also loop target.
5438     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), CurRegHi)
5439             .addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx + 1));
5440 
5441     ReadlanePieces.push_back(CurRegLo);
5442     ReadlanePieces.push_back(CurRegHi);
5443 
5444     // Comparison is to be done as 64-bit.
5445     Register CurReg = MRI.createVirtualRegister(&AMDGPU::SGPR_64RegClass);
5446     BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), CurReg)
5447             .addReg(CurRegLo)
5448             .addImm(AMDGPU::sub0)
5449             .addReg(CurRegHi)
5450             .addImm(AMDGPU::sub1);
5451 
5452     Register NewCondReg = MRI.createVirtualRegister(BoolXExecRC);
5453     auto Cmp =
5454         BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), NewCondReg)
5455             .addReg(CurReg);
5456     if (NumSubRegs <= 2)
5457       Cmp.addReg(VRsrc);
5458     else
5459       Cmp.addReg(VRsrc, VRsrcUndef, TRI->getSubRegFromChannel(Idx, 2));
5460 
5461     // Combine the comparison results with AND.
5462     if (CondReg == AMDGPU::NoRegister) // First.
5463       CondReg = NewCondReg;
5464     else { // If not the first, we create an AND.
5465       Register AndReg = MRI.createVirtualRegister(BoolXExecRC);
5466       BuildMI(LoopBB, I, DL, TII.get(AndOpc), AndReg)
5467               .addReg(CondReg)
5468               .addReg(NewCondReg);
5469       CondReg = AndReg;
5470     }
5471   } // End for loop.
5472 
5473   auto SRsrcRC = TRI->getEquivalentSGPRClass(MRI.getRegClass(VRsrc));
5474   Register SRsrc = MRI.createVirtualRegister(SRsrcRC);
5475 
5476   // Build scalar Rsrc.
5477   auto Merge = BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc);
5478   unsigned Channel = 0;
5479   for (Register Piece : ReadlanePieces) {
5480     Merge.addReg(Piece)
5481          .addImm(TRI->getSubRegFromChannel(Channel++));
5482   }
5483 
5484   // Update Rsrc operand to use the SGPR Rsrc.
5485   Rsrc.setReg(SRsrc);
5486   Rsrc.setIsKill(true);
5487 
5488   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5489   MRI.setSimpleHint(SaveExec, CondReg);
5490 
5491   // Update EXEC to matching lanes, saving original to SaveExec.
5492   BuildMI(LoopBB, I, DL, TII.get(SaveExecOpc), SaveExec)
5493       .addReg(CondReg, RegState::Kill);
5494 
5495   // The original instruction is here; we insert the terminators after it.
5496   I = LoopBB.end();
5497 
5498   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
5499   BuildMI(LoopBB, I, DL, TII.get(XorTermOpc), Exec)
5500       .addReg(Exec)
5501       .addReg(SaveExec);
5502 
5503   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::SI_WATERFALL_LOOP)).addMBB(&LoopBB);
5504 }
5505 
5506 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
5507 // with SGPRs by iterating over all unique values across all lanes.
5508 // Returns the loop basic block that now contains \p MI.
5509 static MachineBasicBlock *
5510 loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
5511                   MachineOperand &Rsrc, MachineDominatorTree *MDT,
5512                   MachineBasicBlock::iterator Begin = nullptr,
5513                   MachineBasicBlock::iterator End = nullptr) {
5514   MachineBasicBlock &MBB = *MI.getParent();
5515   MachineFunction &MF = *MBB.getParent();
5516   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
5517   const SIRegisterInfo *TRI = ST.getRegisterInfo();
5518   MachineRegisterInfo &MRI = MF.getRegInfo();
5519   if (!Begin.isValid())
5520     Begin = &MI;
5521   if (!End.isValid()) {
5522     End = &MI;
5523     ++End;
5524   }
5525   const DebugLoc &DL = MI.getDebugLoc();
5526   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
5527   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
5528   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5529 
5530   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
5531 
5532   // Save the EXEC mask
5533   BuildMI(MBB, Begin, DL, TII.get(MovExecOpc), SaveExec).addReg(Exec);
5534 
5535   // Killed uses in the instruction we are waterfalling around will be
5536   // incorrect due to the added control-flow.
5537   MachineBasicBlock::iterator AfterMI = MI;
5538   ++AfterMI;
5539   for (auto I = Begin; I != AfterMI; I++) {
5540     for (auto &MO : I->uses()) {
5541       if (MO.isReg() && MO.isUse()) {
5542         MRI.clearKillFlags(MO.getReg());
5543       }
5544     }
5545   }
5546 
5547   // To insert the loop we need to split the block. Move everything after this
5548   // point to a new block, and insert a new empty block between the two.
5549   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
5550   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
5551   MachineFunction::iterator MBBI(MBB);
5552   ++MBBI;
5553 
5554   MF.insert(MBBI, LoopBB);
5555   MF.insert(MBBI, RemainderBB);
5556 
5557   LoopBB->addSuccessor(LoopBB);
5558   LoopBB->addSuccessor(RemainderBB);
5559 
5560   // Move Begin to MI to the LoopBB, and the remainder of the block to
5561   // RemainderBB.
5562   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
5563   RemainderBB->splice(RemainderBB->begin(), &MBB, End, MBB.end());
5564   LoopBB->splice(LoopBB->begin(), &MBB, Begin, MBB.end());
5565 
5566   MBB.addSuccessor(LoopBB);
5567 
5568   // Update dominators. We know that MBB immediately dominates LoopBB, that
5569   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
5570   // dominates all of the successors transferred to it from MBB that MBB used
5571   // to properly dominate.
5572   if (MDT) {
5573     MDT->addNewBlock(LoopBB, &MBB);
5574     MDT->addNewBlock(RemainderBB, LoopBB);
5575     for (auto &Succ : RemainderBB->successors()) {
5576       if (MDT->properlyDominates(&MBB, Succ)) {
5577         MDT->changeImmediateDominator(Succ, RemainderBB);
5578       }
5579     }
5580   }
5581 
5582   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
5583 
5584   // Restore the EXEC mask
5585   MachineBasicBlock::iterator First = RemainderBB->begin();
5586   BuildMI(*RemainderBB, First, DL, TII.get(MovExecOpc), Exec).addReg(SaveExec);
5587   return LoopBB;
5588 }
5589 
5590 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
5591 static std::tuple<unsigned, unsigned>
5592 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
5593   MachineBasicBlock &MBB = *MI.getParent();
5594   MachineFunction &MF = *MBB.getParent();
5595   MachineRegisterInfo &MRI = MF.getRegInfo();
5596 
5597   // Extract the ptr from the resource descriptor.
5598   unsigned RsrcPtr =
5599       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
5600                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
5601 
5602   // Create an empty resource descriptor
5603   Register Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5604   Register SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5605   Register SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
5606   Register NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
5607   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
5608 
5609   // Zero64 = 0
5610   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
5611       .addImm(0);
5612 
5613   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
5614   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
5615       .addImm(RsrcDataFormat & 0xFFFFFFFF);
5616 
5617   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
5618   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
5619       .addImm(RsrcDataFormat >> 32);
5620 
5621   // NewSRsrc = {Zero64, SRsrcFormat}
5622   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
5623       .addReg(Zero64)
5624       .addImm(AMDGPU::sub0_sub1)
5625       .addReg(SRsrcFormatLo)
5626       .addImm(AMDGPU::sub2)
5627       .addReg(SRsrcFormatHi)
5628       .addImm(AMDGPU::sub3);
5629 
5630   return std::make_tuple(RsrcPtr, NewSRsrc);
5631 }
5632 
5633 MachineBasicBlock *
5634 SIInstrInfo::legalizeOperands(MachineInstr &MI,
5635                               MachineDominatorTree *MDT) const {
5636   MachineFunction &MF = *MI.getParent()->getParent();
5637   MachineRegisterInfo &MRI = MF.getRegInfo();
5638   MachineBasicBlock *CreatedBB = nullptr;
5639 
5640   // Legalize VOP2
5641   if (isVOP2(MI) || isVOPC(MI)) {
5642     legalizeOperandsVOP2(MRI, MI);
5643     return CreatedBB;
5644   }
5645 
5646   // Legalize VOP3
5647   if (isVOP3(MI)) {
5648     legalizeOperandsVOP3(MRI, MI);
5649     return CreatedBB;
5650   }
5651 
5652   // Legalize SMRD
5653   if (isSMRD(MI)) {
5654     legalizeOperandsSMRD(MRI, MI);
5655     return CreatedBB;
5656   }
5657 
5658   // Legalize FLAT
5659   if (isFLAT(MI)) {
5660     legalizeOperandsFLAT(MRI, MI);
5661     return CreatedBB;
5662   }
5663 
5664   // Legalize REG_SEQUENCE and PHI
5665   // The register class of the operands much be the same type as the register
5666   // class of the output.
5667   if (MI.getOpcode() == AMDGPU::PHI) {
5668     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
5669     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
5670       if (!MI.getOperand(i).isReg() || !MI.getOperand(i).getReg().isVirtual())
5671         continue;
5672       const TargetRegisterClass *OpRC =
5673           MRI.getRegClass(MI.getOperand(i).getReg());
5674       if (RI.hasVectorRegisters(OpRC)) {
5675         VRC = OpRC;
5676       } else {
5677         SRC = OpRC;
5678       }
5679     }
5680 
5681     // If any of the operands are VGPR registers, then they all most be
5682     // otherwise we will create illegal VGPR->SGPR copies when legalizing
5683     // them.
5684     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
5685       if (!VRC) {
5686         assert(SRC);
5687         if (getOpRegClass(MI, 0) == &AMDGPU::VReg_1RegClass) {
5688           VRC = &AMDGPU::VReg_1RegClass;
5689         } else
5690           VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5691                     ? RI.getEquivalentAGPRClass(SRC)
5692                     : RI.getEquivalentVGPRClass(SRC);
5693       } else {
5694         VRC = RI.isAGPRClass(getOpRegClass(MI, 0))
5695                   ? RI.getEquivalentAGPRClass(VRC)
5696                   : RI.getEquivalentVGPRClass(VRC);
5697       }
5698       RC = VRC;
5699     } else {
5700       RC = SRC;
5701     }
5702 
5703     // Update all the operands so they have the same type.
5704     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5705       MachineOperand &Op = MI.getOperand(I);
5706       if (!Op.isReg() || !Op.getReg().isVirtual())
5707         continue;
5708 
5709       // MI is a PHI instruction.
5710       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
5711       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
5712 
5713       // Avoid creating no-op copies with the same src and dst reg class.  These
5714       // confuse some of the machine passes.
5715       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
5716     }
5717   }
5718 
5719   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
5720   // VGPR dest type and SGPR sources, insert copies so all operands are
5721   // VGPRs. This seems to help operand folding / the register coalescer.
5722   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
5723     MachineBasicBlock *MBB = MI.getParent();
5724     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
5725     if (RI.hasVGPRs(DstRC)) {
5726       // Update all the operands so they are VGPR register classes. These may
5727       // not be the same register class because REG_SEQUENCE supports mixing
5728       // subregister index types e.g. sub0_sub1 + sub2 + sub3
5729       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
5730         MachineOperand &Op = MI.getOperand(I);
5731         if (!Op.isReg() || !Op.getReg().isVirtual())
5732           continue;
5733 
5734         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
5735         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
5736         if (VRC == OpRC)
5737           continue;
5738 
5739         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
5740         Op.setIsKill();
5741       }
5742     }
5743 
5744     return CreatedBB;
5745   }
5746 
5747   // Legalize INSERT_SUBREG
5748   // src0 must have the same register class as dst
5749   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
5750     Register Dst = MI.getOperand(0).getReg();
5751     Register Src0 = MI.getOperand(1).getReg();
5752     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
5753     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
5754     if (DstRC != Src0RC) {
5755       MachineBasicBlock *MBB = MI.getParent();
5756       MachineOperand &Op = MI.getOperand(1);
5757       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
5758     }
5759     return CreatedBB;
5760   }
5761 
5762   // Legalize SI_INIT_M0
5763   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
5764     MachineOperand &Src = MI.getOperand(0);
5765     if (Src.isReg() && RI.hasVectorRegisters(MRI.getRegClass(Src.getReg())))
5766       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
5767     return CreatedBB;
5768   }
5769 
5770   // Legalize MIMG and MUBUF/MTBUF for shaders.
5771   //
5772   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
5773   // scratch memory access. In both cases, the legalization never involves
5774   // conversion to the addr64 form.
5775   if (isMIMG(MI) || (AMDGPU::isGraphics(MF.getFunction().getCallingConv()) &&
5776                      (isMUBUF(MI) || isMTBUF(MI)))) {
5777     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
5778     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg())))
5779       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SRsrc, MDT);
5780 
5781     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
5782     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg())))
5783       CreatedBB = loadSRsrcFromVGPR(*this, MI, *SSamp, MDT);
5784 
5785     return CreatedBB;
5786   }
5787 
5788   // Legalize SI_CALL
5789   if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
5790     MachineOperand *Dest = &MI.getOperand(0);
5791     if (!RI.isSGPRClass(MRI.getRegClass(Dest->getReg()))) {
5792       // Move everything between ADJCALLSTACKUP and ADJCALLSTACKDOWN and
5793       // following copies, we also need to move copies from and to physical
5794       // registers into the loop block.
5795       unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
5796       unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
5797 
5798       // Also move the copies to physical registers into the loop block
5799       MachineBasicBlock &MBB = *MI.getParent();
5800       MachineBasicBlock::iterator Start(&MI);
5801       while (Start->getOpcode() != FrameSetupOpcode)
5802         --Start;
5803       MachineBasicBlock::iterator End(&MI);
5804       while (End->getOpcode() != FrameDestroyOpcode)
5805         ++End;
5806       // Also include following copies of the return value
5807       ++End;
5808       while (End != MBB.end() && End->isCopy() && End->getOperand(1).isReg() &&
5809              MI.definesRegister(End->getOperand(1).getReg()))
5810         ++End;
5811       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Dest, MDT, Start, End);
5812     }
5813   }
5814 
5815   // Legalize MUBUF* instructions.
5816   int RsrcIdx =
5817       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
5818   if (RsrcIdx != -1) {
5819     // We have an MUBUF instruction
5820     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
5821     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
5822     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
5823                              RI.getRegClass(RsrcRC))) {
5824       // The operands are legal.
5825       // FIXME: We may need to legalize operands besides srsrc.
5826       return CreatedBB;
5827     }
5828 
5829     // Legalize a VGPR Rsrc.
5830     //
5831     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
5832     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
5833     // a zero-value SRsrc.
5834     //
5835     // If the instruction is _OFFSET (both idxen and offen disabled), and we
5836     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
5837     // above.
5838     //
5839     // Otherwise we are on non-ADDR64 hardware, and/or we have
5840     // idxen/offen/bothen and we fall back to a waterfall loop.
5841 
5842     MachineBasicBlock &MBB = *MI.getParent();
5843 
5844     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5845     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
5846       // This is already an ADDR64 instruction so we need to add the pointer
5847       // extracted from the resource descriptor to the current value of VAddr.
5848       Register NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5849       Register NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5850       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5851 
5852       const auto *BoolXExecRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5853       Register CondReg0 = MRI.createVirtualRegister(BoolXExecRC);
5854       Register CondReg1 = MRI.createVirtualRegister(BoolXExecRC);
5855 
5856       unsigned RsrcPtr, NewSRsrc;
5857       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5858 
5859       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
5860       const DebugLoc &DL = MI.getDebugLoc();
5861       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_CO_U32_e64), NewVAddrLo)
5862         .addDef(CondReg0)
5863         .addReg(RsrcPtr, 0, AMDGPU::sub0)
5864         .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
5865         .addImm(0);
5866 
5867       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
5868       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e64), NewVAddrHi)
5869         .addDef(CondReg1, RegState::Dead)
5870         .addReg(RsrcPtr, 0, AMDGPU::sub1)
5871         .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
5872         .addReg(CondReg0, RegState::Kill)
5873         .addImm(0);
5874 
5875       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5876       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
5877           .addReg(NewVAddrLo)
5878           .addImm(AMDGPU::sub0)
5879           .addReg(NewVAddrHi)
5880           .addImm(AMDGPU::sub1);
5881 
5882       VAddr->setReg(NewVAddr);
5883       Rsrc->setReg(NewSRsrc);
5884     } else if (!VAddr && ST.hasAddr64()) {
5885       // This instructions is the _OFFSET variant, so we need to convert it to
5886       // ADDR64.
5887       assert(ST.getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
5888              "FIXME: Need to emit flat atomics here");
5889 
5890       unsigned RsrcPtr, NewSRsrc;
5891       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
5892 
5893       Register NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
5894       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
5895       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
5896       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
5897       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
5898 
5899       // Atomics with return have an additional tied operand and are
5900       // missing some of the special bits.
5901       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
5902       MachineInstr *Addr64;
5903 
5904       if (!VDataIn) {
5905         // Regular buffer load / store.
5906         MachineInstrBuilder MIB =
5907             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5908                 .add(*VData)
5909                 .addReg(NewVAddr)
5910                 .addReg(NewSRsrc)
5911                 .add(*SOffset)
5912                 .add(*Offset);
5913 
5914         if (const MachineOperand *CPol =
5915                 getNamedOperand(MI, AMDGPU::OpName::cpol)) {
5916           MIB.addImm(CPol->getImm());
5917         }
5918 
5919         if (const MachineOperand *TFE =
5920                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
5921           MIB.addImm(TFE->getImm());
5922         }
5923 
5924         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::swz));
5925 
5926         MIB.cloneMemRefs(MI);
5927         Addr64 = MIB;
5928       } else {
5929         // Atomics with return.
5930         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
5931                      .add(*VData)
5932                      .add(*VDataIn)
5933                      .addReg(NewVAddr)
5934                      .addReg(NewSRsrc)
5935                      .add(*SOffset)
5936                      .add(*Offset)
5937                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::cpol))
5938                      .cloneMemRefs(MI);
5939       }
5940 
5941       MI.removeFromParent();
5942 
5943       // NewVaddr = {NewVaddrHi, NewVaddrLo}
5944       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
5945               NewVAddr)
5946           .addReg(RsrcPtr, 0, AMDGPU::sub0)
5947           .addImm(AMDGPU::sub0)
5948           .addReg(RsrcPtr, 0, AMDGPU::sub1)
5949           .addImm(AMDGPU::sub1);
5950     } else {
5951       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
5952       // to SGPRs.
5953       CreatedBB = loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
5954       return CreatedBB;
5955     }
5956   }
5957   return CreatedBB;
5958 }
5959 
5960 MachineBasicBlock *SIInstrInfo::moveToVALU(MachineInstr &TopInst,
5961                                            MachineDominatorTree *MDT) const {
5962   SetVectorType Worklist;
5963   Worklist.insert(&TopInst);
5964   MachineBasicBlock *CreatedBB = nullptr;
5965   MachineBasicBlock *CreatedBBTmp = nullptr;
5966 
5967   while (!Worklist.empty()) {
5968     MachineInstr &Inst = *Worklist.pop_back_val();
5969     MachineBasicBlock *MBB = Inst.getParent();
5970     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
5971 
5972     unsigned Opcode = Inst.getOpcode();
5973     unsigned NewOpcode = getVALUOp(Inst);
5974 
5975     // Handle some special cases
5976     switch (Opcode) {
5977     default:
5978       break;
5979     case AMDGPU::S_ADD_U64_PSEUDO:
5980     case AMDGPU::S_SUB_U64_PSEUDO:
5981       splitScalar64BitAddSub(Worklist, Inst, MDT);
5982       Inst.eraseFromParent();
5983       continue;
5984     case AMDGPU::S_ADD_I32:
5985     case AMDGPU::S_SUB_I32: {
5986       // FIXME: The u32 versions currently selected use the carry.
5987       bool Changed;
5988       std::tie(Changed, CreatedBBTmp) = moveScalarAddSub(Worklist, Inst, MDT);
5989       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
5990         CreatedBB = CreatedBBTmp;
5991       if (Changed)
5992         continue;
5993 
5994       // Default handling
5995       break;
5996     }
5997     case AMDGPU::S_AND_B64:
5998       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
5999       Inst.eraseFromParent();
6000       continue;
6001 
6002     case AMDGPU::S_OR_B64:
6003       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
6004       Inst.eraseFromParent();
6005       continue;
6006 
6007     case AMDGPU::S_XOR_B64:
6008       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
6009       Inst.eraseFromParent();
6010       continue;
6011 
6012     case AMDGPU::S_NAND_B64:
6013       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
6014       Inst.eraseFromParent();
6015       continue;
6016 
6017     case AMDGPU::S_NOR_B64:
6018       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
6019       Inst.eraseFromParent();
6020       continue;
6021 
6022     case AMDGPU::S_XNOR_B64:
6023       if (ST.hasDLInsts())
6024         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
6025       else
6026         splitScalar64BitXnor(Worklist, Inst, MDT);
6027       Inst.eraseFromParent();
6028       continue;
6029 
6030     case AMDGPU::S_ANDN2_B64:
6031       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
6032       Inst.eraseFromParent();
6033       continue;
6034 
6035     case AMDGPU::S_ORN2_B64:
6036       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
6037       Inst.eraseFromParent();
6038       continue;
6039 
6040     case AMDGPU::S_BREV_B64:
6041       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_BREV_B32, true);
6042       Inst.eraseFromParent();
6043       continue;
6044 
6045     case AMDGPU::S_NOT_B64:
6046       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
6047       Inst.eraseFromParent();
6048       continue;
6049 
6050     case AMDGPU::S_BCNT1_I32_B64:
6051       splitScalar64BitBCNT(Worklist, Inst);
6052       Inst.eraseFromParent();
6053       continue;
6054 
6055     case AMDGPU::S_BFE_I64:
6056       splitScalar64BitBFE(Worklist, Inst);
6057       Inst.eraseFromParent();
6058       continue;
6059 
6060     case AMDGPU::S_LSHL_B32:
6061       if (ST.hasOnlyRevVALUShifts()) {
6062         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
6063         swapOperands(Inst);
6064       }
6065       break;
6066     case AMDGPU::S_ASHR_I32:
6067       if (ST.hasOnlyRevVALUShifts()) {
6068         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
6069         swapOperands(Inst);
6070       }
6071       break;
6072     case AMDGPU::S_LSHR_B32:
6073       if (ST.hasOnlyRevVALUShifts()) {
6074         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
6075         swapOperands(Inst);
6076       }
6077       break;
6078     case AMDGPU::S_LSHL_B64:
6079       if (ST.hasOnlyRevVALUShifts()) {
6080         NewOpcode = AMDGPU::V_LSHLREV_B64_e64;
6081         swapOperands(Inst);
6082       }
6083       break;
6084     case AMDGPU::S_ASHR_I64:
6085       if (ST.hasOnlyRevVALUShifts()) {
6086         NewOpcode = AMDGPU::V_ASHRREV_I64_e64;
6087         swapOperands(Inst);
6088       }
6089       break;
6090     case AMDGPU::S_LSHR_B64:
6091       if (ST.hasOnlyRevVALUShifts()) {
6092         NewOpcode = AMDGPU::V_LSHRREV_B64_e64;
6093         swapOperands(Inst);
6094       }
6095       break;
6096 
6097     case AMDGPU::S_ABS_I32:
6098       lowerScalarAbs(Worklist, Inst);
6099       Inst.eraseFromParent();
6100       continue;
6101 
6102     case AMDGPU::S_CBRANCH_SCC0:
6103     case AMDGPU::S_CBRANCH_SCC1: {
6104         // Clear unused bits of vcc
6105         Register CondReg = Inst.getOperand(1).getReg();
6106         bool IsSCC = CondReg == AMDGPU::SCC;
6107         Register VCC = RI.getVCC();
6108         Register EXEC = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
6109         unsigned Opc = ST.isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64;
6110         BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(Opc), VCC)
6111             .addReg(EXEC)
6112             .addReg(IsSCC ? VCC : CondReg);
6113         Inst.RemoveOperand(1);
6114       }
6115       break;
6116 
6117     case AMDGPU::S_BFE_U64:
6118     case AMDGPU::S_BFM_B64:
6119       llvm_unreachable("Moving this op to VALU not implemented");
6120 
6121     case AMDGPU::S_PACK_LL_B32_B16:
6122     case AMDGPU::S_PACK_LH_B32_B16:
6123     case AMDGPU::S_PACK_HH_B32_B16:
6124       movePackToVALU(Worklist, MRI, Inst);
6125       Inst.eraseFromParent();
6126       continue;
6127 
6128     case AMDGPU::S_XNOR_B32:
6129       lowerScalarXnor(Worklist, Inst);
6130       Inst.eraseFromParent();
6131       continue;
6132 
6133     case AMDGPU::S_NAND_B32:
6134       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
6135       Inst.eraseFromParent();
6136       continue;
6137 
6138     case AMDGPU::S_NOR_B32:
6139       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
6140       Inst.eraseFromParent();
6141       continue;
6142 
6143     case AMDGPU::S_ANDN2_B32:
6144       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
6145       Inst.eraseFromParent();
6146       continue;
6147 
6148     case AMDGPU::S_ORN2_B32:
6149       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
6150       Inst.eraseFromParent();
6151       continue;
6152 
6153     // TODO: remove as soon as everything is ready
6154     // to replace VGPR to SGPR copy with V_READFIRSTLANEs.
6155     // S_ADD/SUB_CO_PSEUDO as well as S_UADDO/USUBO_PSEUDO
6156     // can only be selected from the uniform SDNode.
6157     case AMDGPU::S_ADD_CO_PSEUDO:
6158     case AMDGPU::S_SUB_CO_PSEUDO: {
6159       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
6160                          ? AMDGPU::V_ADDC_U32_e64
6161                          : AMDGPU::V_SUBB_U32_e64;
6162       const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6163 
6164       Register CarryInReg = Inst.getOperand(4).getReg();
6165       if (!MRI.constrainRegClass(CarryInReg, CarryRC)) {
6166         Register NewCarryReg = MRI.createVirtualRegister(CarryRC);
6167         BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(AMDGPU::COPY), NewCarryReg)
6168             .addReg(CarryInReg);
6169       }
6170 
6171       Register CarryOutReg = Inst.getOperand(1).getReg();
6172 
6173       Register DestReg = MRI.createVirtualRegister(RI.getEquivalentVGPRClass(
6174           MRI.getRegClass(Inst.getOperand(0).getReg())));
6175       MachineInstr *CarryOp =
6176           BuildMI(*MBB, &Inst, Inst.getDebugLoc(), get(Opc), DestReg)
6177               .addReg(CarryOutReg, RegState::Define)
6178               .add(Inst.getOperand(2))
6179               .add(Inst.getOperand(3))
6180               .addReg(CarryInReg)
6181               .addImm(0);
6182       CreatedBBTmp = legalizeOperands(*CarryOp);
6183       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6184         CreatedBB = CreatedBBTmp;
6185       MRI.replaceRegWith(Inst.getOperand(0).getReg(), DestReg);
6186       addUsersToMoveToVALUWorklist(DestReg, MRI, Worklist);
6187       Inst.eraseFromParent();
6188     }
6189       continue;
6190     case AMDGPU::S_UADDO_PSEUDO:
6191     case AMDGPU::S_USUBO_PSEUDO: {
6192       const DebugLoc &DL = Inst.getDebugLoc();
6193       MachineOperand &Dest0 = Inst.getOperand(0);
6194       MachineOperand &Dest1 = Inst.getOperand(1);
6195       MachineOperand &Src0 = Inst.getOperand(2);
6196       MachineOperand &Src1 = Inst.getOperand(3);
6197 
6198       unsigned Opc = (Inst.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
6199                          ? AMDGPU::V_ADD_CO_U32_e64
6200                          : AMDGPU::V_SUB_CO_U32_e64;
6201       const TargetRegisterClass *NewRC =
6202           RI.getEquivalentVGPRClass(MRI.getRegClass(Dest0.getReg()));
6203       Register DestReg = MRI.createVirtualRegister(NewRC);
6204       MachineInstr *NewInstr = BuildMI(*MBB, &Inst, DL, get(Opc), DestReg)
6205                                    .addReg(Dest1.getReg(), RegState::Define)
6206                                    .add(Src0)
6207                                    .add(Src1)
6208                                    .addImm(0); // clamp bit
6209 
6210       CreatedBBTmp = legalizeOperands(*NewInstr, MDT);
6211       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6212         CreatedBB = CreatedBBTmp;
6213 
6214       MRI.replaceRegWith(Dest0.getReg(), DestReg);
6215       addUsersToMoveToVALUWorklist(NewInstr->getOperand(0).getReg(), MRI,
6216                                    Worklist);
6217       Inst.eraseFromParent();
6218     }
6219       continue;
6220 
6221     case AMDGPU::S_CSELECT_B32:
6222     case AMDGPU::S_CSELECT_B64:
6223       lowerSelect(Worklist, Inst, MDT);
6224       Inst.eraseFromParent();
6225       continue;
6226     case AMDGPU::S_CMP_EQ_I32:
6227     case AMDGPU::S_CMP_LG_I32:
6228     case AMDGPU::S_CMP_GT_I32:
6229     case AMDGPU::S_CMP_GE_I32:
6230     case AMDGPU::S_CMP_LT_I32:
6231     case AMDGPU::S_CMP_LE_I32:
6232     case AMDGPU::S_CMP_EQ_U32:
6233     case AMDGPU::S_CMP_LG_U32:
6234     case AMDGPU::S_CMP_GT_U32:
6235     case AMDGPU::S_CMP_GE_U32:
6236     case AMDGPU::S_CMP_LT_U32:
6237     case AMDGPU::S_CMP_LE_U32:
6238     case AMDGPU::S_CMP_EQ_U64:
6239     case AMDGPU::S_CMP_LG_U64: {
6240         const MCInstrDesc &NewDesc = get(NewOpcode);
6241         Register CondReg = MRI.createVirtualRegister(RI.getWaveMaskRegClass());
6242         MachineInstr *NewInstr =
6243             BuildMI(*MBB, Inst, Inst.getDebugLoc(), NewDesc, CondReg)
6244                 .add(Inst.getOperand(0))
6245                 .add(Inst.getOperand(1));
6246         legalizeOperands(*NewInstr, MDT);
6247         int SCCIdx = Inst.findRegisterDefOperandIdx(AMDGPU::SCC);
6248         MachineOperand SCCOp = Inst.getOperand(SCCIdx);
6249         addSCCDefUsersToVALUWorklist(SCCOp, Inst, Worklist, CondReg);
6250         Inst.eraseFromParent();
6251       }
6252       continue;
6253     }
6254 
6255 
6256     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
6257       // We cannot move this instruction to the VALU, so we should try to
6258       // legalize its operands instead.
6259       CreatedBBTmp = legalizeOperands(Inst, MDT);
6260       if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6261         CreatedBB = CreatedBBTmp;
6262       continue;
6263     }
6264 
6265     // Use the new VALU Opcode.
6266     const MCInstrDesc &NewDesc = get(NewOpcode);
6267     Inst.setDesc(NewDesc);
6268 
6269     // Remove any references to SCC. Vector instructions can't read from it, and
6270     // We're just about to add the implicit use / defs of VCC, and we don't want
6271     // both.
6272     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
6273       MachineOperand &Op = Inst.getOperand(i);
6274       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
6275         // Only propagate through live-def of SCC.
6276         if (Op.isDef() && !Op.isDead())
6277           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
6278         if (Op.isUse())
6279           addSCCDefsToVALUWorklist(Op, Worklist);
6280         Inst.RemoveOperand(i);
6281       }
6282     }
6283 
6284     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
6285       // We are converting these to a BFE, so we need to add the missing
6286       // operands for the size and offset.
6287       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
6288       Inst.addOperand(MachineOperand::CreateImm(0));
6289       Inst.addOperand(MachineOperand::CreateImm(Size));
6290 
6291     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
6292       // The VALU version adds the second operand to the result, so insert an
6293       // extra 0 operand.
6294       Inst.addOperand(MachineOperand::CreateImm(0));
6295     }
6296 
6297     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
6298     fixImplicitOperands(Inst);
6299 
6300     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
6301       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
6302       // If we need to move this to VGPRs, we need to unpack the second operand
6303       // back into the 2 separate ones for bit offset and width.
6304       assert(OffsetWidthOp.isImm() &&
6305              "Scalar BFE is only implemented for constant width and offset");
6306       uint32_t Imm = OffsetWidthOp.getImm();
6307 
6308       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6309       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6310       Inst.RemoveOperand(2);                     // Remove old immediate.
6311       Inst.addOperand(MachineOperand::CreateImm(Offset));
6312       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
6313     }
6314 
6315     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
6316     unsigned NewDstReg = AMDGPU::NoRegister;
6317     if (HasDst) {
6318       Register DstReg = Inst.getOperand(0).getReg();
6319       if (DstReg.isPhysical())
6320         continue;
6321 
6322       // Update the destination register class.
6323       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
6324       if (!NewDstRC)
6325         continue;
6326 
6327       if (Inst.isCopy() && Inst.getOperand(1).getReg().isVirtual() &&
6328           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
6329         // Instead of creating a copy where src and dst are the same register
6330         // class, we just replace all uses of dst with src.  These kinds of
6331         // copies interfere with the heuristics MachineSink uses to decide
6332         // whether or not to split a critical edge.  Since the pass assumes
6333         // that copies will end up as machine instructions and not be
6334         // eliminated.
6335         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
6336         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
6337         MRI.clearKillFlags(Inst.getOperand(1).getReg());
6338         Inst.getOperand(0).setReg(DstReg);
6339 
6340         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
6341         // these are deleted later, but at -O0 it would leave a suspicious
6342         // looking illegal copy of an undef register.
6343         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
6344           Inst.RemoveOperand(I);
6345         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
6346         continue;
6347       }
6348 
6349       NewDstReg = MRI.createVirtualRegister(NewDstRC);
6350       MRI.replaceRegWith(DstReg, NewDstReg);
6351     }
6352 
6353     // Legalize the operands
6354     CreatedBBTmp = legalizeOperands(Inst, MDT);
6355     if (CreatedBBTmp && TopInst.getParent() == CreatedBBTmp)
6356       CreatedBB = CreatedBBTmp;
6357 
6358     if (HasDst)
6359      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
6360   }
6361   return CreatedBB;
6362 }
6363 
6364 // Add/sub require special handling to deal with carry outs.
6365 std::pair<bool, MachineBasicBlock *>
6366 SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
6367                               MachineDominatorTree *MDT) const {
6368   if (ST.hasAddNoCarry()) {
6369     // Assume there is no user of scc since we don't select this in that case.
6370     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
6371     // is used.
6372 
6373     MachineBasicBlock &MBB = *Inst.getParent();
6374     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6375 
6376     Register OldDstReg = Inst.getOperand(0).getReg();
6377     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6378 
6379     unsigned Opc = Inst.getOpcode();
6380     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
6381 
6382     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
6383       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
6384 
6385     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
6386     Inst.RemoveOperand(3);
6387 
6388     Inst.setDesc(get(NewOpc));
6389     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
6390     Inst.addImplicitDefUseOperands(*MBB.getParent());
6391     MRI.replaceRegWith(OldDstReg, ResultReg);
6392     MachineBasicBlock *NewBB = legalizeOperands(Inst, MDT);
6393 
6394     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6395     return std::make_pair(true, NewBB);
6396   }
6397 
6398   return std::make_pair(false, nullptr);
6399 }
6400 
6401 void SIInstrInfo::lowerSelect(SetVectorType &Worklist, MachineInstr &Inst,
6402                               MachineDominatorTree *MDT) const {
6403 
6404   MachineBasicBlock &MBB = *Inst.getParent();
6405   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6406   MachineBasicBlock::iterator MII = Inst;
6407   DebugLoc DL = Inst.getDebugLoc();
6408 
6409   MachineOperand &Dest = Inst.getOperand(0);
6410   MachineOperand &Src0 = Inst.getOperand(1);
6411   MachineOperand &Src1 = Inst.getOperand(2);
6412   MachineOperand &Cond = Inst.getOperand(3);
6413 
6414   Register SCCSource = Cond.getReg();
6415   bool IsSCC = (SCCSource == AMDGPU::SCC);
6416 
6417   // If this is a trivial select where the condition is effectively not SCC
6418   // (SCCSource is a source of copy to SCC), then the select is semantically
6419   // equivalent to copying SCCSource. Hence, there is no need to create
6420   // V_CNDMASK, we can just use that and bail out.
6421   if (!IsSCC && Src0.isImm() && (Src0.getImm() == -1) && Src1.isImm() &&
6422       (Src1.getImm() == 0)) {
6423     MRI.replaceRegWith(Dest.getReg(), SCCSource);
6424     return;
6425   }
6426 
6427   const TargetRegisterClass *TC =
6428       RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6429 
6430   Register CopySCC = MRI.createVirtualRegister(TC);
6431 
6432   if (IsSCC) {
6433     // Now look for the closest SCC def if it is a copy
6434     // replacing the SCCSource with the COPY source register
6435     bool CopyFound = false;
6436     for (MachineInstr &CandI :
6437          make_range(std::next(MachineBasicBlock::reverse_iterator(Inst)),
6438                     Inst.getParent()->rend())) {
6439       if (CandI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) !=
6440           -1) {
6441         if (CandI.isCopy() && CandI.getOperand(0).getReg() == AMDGPU::SCC) {
6442           BuildMI(MBB, MII, DL, get(AMDGPU::COPY), CopySCC)
6443               .addReg(CandI.getOperand(1).getReg());
6444           CopyFound = true;
6445         }
6446         break;
6447       }
6448     }
6449     if (!CopyFound) {
6450       // SCC def is not a copy
6451       // Insert a trivial select instead of creating a copy, because a copy from
6452       // SCC would semantically mean just copying a single bit, but we may need
6453       // the result to be a vector condition mask that needs preserving.
6454       unsigned Opcode = (ST.getWavefrontSize() == 64) ? AMDGPU::S_CSELECT_B64
6455                                                       : AMDGPU::S_CSELECT_B32;
6456       auto NewSelect =
6457           BuildMI(MBB, MII, DL, get(Opcode), CopySCC).addImm(-1).addImm(0);
6458       NewSelect->getOperand(3).setIsUndef(Cond.isUndef());
6459     }
6460   }
6461 
6462   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6463 
6464   auto UpdatedInst =
6465       BuildMI(MBB, MII, DL, get(AMDGPU::V_CNDMASK_B32_e64), ResultReg)
6466           .addImm(0)
6467           .add(Src1) // False
6468           .addImm(0)
6469           .add(Src0) // True
6470           .addReg(IsSCC ? CopySCC : SCCSource);
6471 
6472   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6473   legalizeOperands(*UpdatedInst, MDT);
6474   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6475 }
6476 
6477 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
6478                                  MachineInstr &Inst) const {
6479   MachineBasicBlock &MBB = *Inst.getParent();
6480   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6481   MachineBasicBlock::iterator MII = Inst;
6482   DebugLoc DL = Inst.getDebugLoc();
6483 
6484   MachineOperand &Dest = Inst.getOperand(0);
6485   MachineOperand &Src = Inst.getOperand(1);
6486   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6487   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6488 
6489   unsigned SubOp = ST.hasAddNoCarry() ?
6490     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_CO_U32_e32;
6491 
6492   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
6493     .addImm(0)
6494     .addReg(Src.getReg());
6495 
6496   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
6497     .addReg(Src.getReg())
6498     .addReg(TmpReg);
6499 
6500   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6501   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6502 }
6503 
6504 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
6505                                   MachineInstr &Inst) const {
6506   MachineBasicBlock &MBB = *Inst.getParent();
6507   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6508   MachineBasicBlock::iterator MII = Inst;
6509   const DebugLoc &DL = Inst.getDebugLoc();
6510 
6511   MachineOperand &Dest = Inst.getOperand(0);
6512   MachineOperand &Src0 = Inst.getOperand(1);
6513   MachineOperand &Src1 = Inst.getOperand(2);
6514 
6515   if (ST.hasDLInsts()) {
6516     Register NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6517     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
6518     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
6519 
6520     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
6521       .add(Src0)
6522       .add(Src1);
6523 
6524     MRI.replaceRegWith(Dest.getReg(), NewDest);
6525     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6526   } else {
6527     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
6528     // invert either source and then perform the XOR. If either source is a
6529     // scalar register, then we can leave the inversion on the scalar unit to
6530     // achieve a better distribution of scalar and vector instructions.
6531     bool Src0IsSGPR = Src0.isReg() &&
6532                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
6533     bool Src1IsSGPR = Src1.isReg() &&
6534                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
6535     MachineInstr *Xor;
6536     Register Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6537     Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6538 
6539     // Build a pair of scalar instructions and add them to the work list.
6540     // The next iteration over the work list will lower these to the vector
6541     // unit as necessary.
6542     if (Src0IsSGPR) {
6543       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src0);
6544       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6545       .addReg(Temp)
6546       .add(Src1);
6547     } else if (Src1IsSGPR) {
6548       BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp).add(Src1);
6549       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
6550       .add(Src0)
6551       .addReg(Temp);
6552     } else {
6553       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
6554         .add(Src0)
6555         .add(Src1);
6556       MachineInstr *Not =
6557           BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest).addReg(Temp);
6558       Worklist.insert(Not);
6559     }
6560 
6561     MRI.replaceRegWith(Dest.getReg(), NewDest);
6562 
6563     Worklist.insert(Xor);
6564 
6565     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6566   }
6567 }
6568 
6569 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
6570                                       MachineInstr &Inst,
6571                                       unsigned Opcode) const {
6572   MachineBasicBlock &MBB = *Inst.getParent();
6573   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6574   MachineBasicBlock::iterator MII = Inst;
6575   const DebugLoc &DL = Inst.getDebugLoc();
6576 
6577   MachineOperand &Dest = Inst.getOperand(0);
6578   MachineOperand &Src0 = Inst.getOperand(1);
6579   MachineOperand &Src1 = Inst.getOperand(2);
6580 
6581   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6582   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6583 
6584   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
6585     .add(Src0)
6586     .add(Src1);
6587 
6588   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
6589     .addReg(Interm);
6590 
6591   Worklist.insert(&Op);
6592   Worklist.insert(&Not);
6593 
6594   MRI.replaceRegWith(Dest.getReg(), NewDest);
6595   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6596 }
6597 
6598 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
6599                                      MachineInstr &Inst,
6600                                      unsigned Opcode) const {
6601   MachineBasicBlock &MBB = *Inst.getParent();
6602   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6603   MachineBasicBlock::iterator MII = Inst;
6604   const DebugLoc &DL = Inst.getDebugLoc();
6605 
6606   MachineOperand &Dest = Inst.getOperand(0);
6607   MachineOperand &Src0 = Inst.getOperand(1);
6608   MachineOperand &Src1 = Inst.getOperand(2);
6609 
6610   Register NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6611   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
6612 
6613   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
6614     .add(Src1);
6615 
6616   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
6617     .add(Src0)
6618     .addReg(Interm);
6619 
6620   Worklist.insert(&Not);
6621   Worklist.insert(&Op);
6622 
6623   MRI.replaceRegWith(Dest.getReg(), NewDest);
6624   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
6625 }
6626 
6627 void SIInstrInfo::splitScalar64BitUnaryOp(
6628     SetVectorType &Worklist, MachineInstr &Inst,
6629     unsigned Opcode, bool Swap) const {
6630   MachineBasicBlock &MBB = *Inst.getParent();
6631   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6632 
6633   MachineOperand &Dest = Inst.getOperand(0);
6634   MachineOperand &Src0 = Inst.getOperand(1);
6635   DebugLoc DL = Inst.getDebugLoc();
6636 
6637   MachineBasicBlock::iterator MII = Inst;
6638 
6639   const MCInstrDesc &InstDesc = get(Opcode);
6640   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6641     MRI.getRegClass(Src0.getReg()) :
6642     &AMDGPU::SGPR_32RegClass;
6643 
6644   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6645 
6646   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6647                                                        AMDGPU::sub0, Src0SubRC);
6648 
6649   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6650   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6651   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6652 
6653   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6654   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
6655 
6656   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6657                                                        AMDGPU::sub1, Src0SubRC);
6658 
6659   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6660   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
6661 
6662   if (Swap)
6663     std::swap(DestSub0, DestSub1);
6664 
6665   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6666   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6667     .addReg(DestSub0)
6668     .addImm(AMDGPU::sub0)
6669     .addReg(DestSub1)
6670     .addImm(AMDGPU::sub1);
6671 
6672   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6673 
6674   Worklist.insert(&LoHalf);
6675   Worklist.insert(&HiHalf);
6676 
6677   // We don't need to legalizeOperands here because for a single operand, src0
6678   // will support any kind of input.
6679 
6680   // Move all users of this moved value.
6681   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6682 }
6683 
6684 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
6685                                          MachineInstr &Inst,
6686                                          MachineDominatorTree *MDT) const {
6687   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
6688 
6689   MachineBasicBlock &MBB = *Inst.getParent();
6690   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6691   const auto *CarryRC = RI.getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
6692 
6693   Register FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6694   Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6695   Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6696 
6697   Register CarryReg = MRI.createVirtualRegister(CarryRC);
6698   Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
6699 
6700   MachineOperand &Dest = Inst.getOperand(0);
6701   MachineOperand &Src0 = Inst.getOperand(1);
6702   MachineOperand &Src1 = Inst.getOperand(2);
6703   const DebugLoc &DL = Inst.getDebugLoc();
6704   MachineBasicBlock::iterator MII = Inst;
6705 
6706   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
6707   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
6708   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6709   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6710 
6711   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6712                                                        AMDGPU::sub0, Src0SubRC);
6713   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6714                                                        AMDGPU::sub0, Src1SubRC);
6715 
6716 
6717   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6718                                                        AMDGPU::sub1, Src0SubRC);
6719   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6720                                                        AMDGPU::sub1, Src1SubRC);
6721 
6722   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
6723   MachineInstr *LoHalf =
6724     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
6725     .addReg(CarryReg, RegState::Define)
6726     .add(SrcReg0Sub0)
6727     .add(SrcReg1Sub0)
6728     .addImm(0); // clamp bit
6729 
6730   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
6731   MachineInstr *HiHalf =
6732     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
6733     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
6734     .add(SrcReg0Sub1)
6735     .add(SrcReg1Sub1)
6736     .addReg(CarryReg, RegState::Kill)
6737     .addImm(0); // clamp bit
6738 
6739   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6740     .addReg(DestSub0)
6741     .addImm(AMDGPU::sub0)
6742     .addReg(DestSub1)
6743     .addImm(AMDGPU::sub1);
6744 
6745   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6746 
6747   // Try to legalize the operands in case we need to swap the order to keep it
6748   // valid.
6749   legalizeOperands(*LoHalf, MDT);
6750   legalizeOperands(*HiHalf, MDT);
6751 
6752   // Move all users of this moved value.
6753   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6754 }
6755 
6756 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
6757                                            MachineInstr &Inst, unsigned Opcode,
6758                                            MachineDominatorTree *MDT) const {
6759   MachineBasicBlock &MBB = *Inst.getParent();
6760   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6761 
6762   MachineOperand &Dest = Inst.getOperand(0);
6763   MachineOperand &Src0 = Inst.getOperand(1);
6764   MachineOperand &Src1 = Inst.getOperand(2);
6765   DebugLoc DL = Inst.getDebugLoc();
6766 
6767   MachineBasicBlock::iterator MII = Inst;
6768 
6769   const MCInstrDesc &InstDesc = get(Opcode);
6770   const TargetRegisterClass *Src0RC = Src0.isReg() ?
6771     MRI.getRegClass(Src0.getReg()) :
6772     &AMDGPU::SGPR_32RegClass;
6773 
6774   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
6775   const TargetRegisterClass *Src1RC = Src1.isReg() ?
6776     MRI.getRegClass(Src1.getReg()) :
6777     &AMDGPU::SGPR_32RegClass;
6778 
6779   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
6780 
6781   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6782                                                        AMDGPU::sub0, Src0SubRC);
6783   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6784                                                        AMDGPU::sub0, Src1SubRC);
6785   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
6786                                                        AMDGPU::sub1, Src0SubRC);
6787   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
6788                                                        AMDGPU::sub1, Src1SubRC);
6789 
6790   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6791   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
6792   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
6793 
6794   Register DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
6795   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
6796                               .add(SrcReg0Sub0)
6797                               .add(SrcReg1Sub0);
6798 
6799   Register DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
6800   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
6801                               .add(SrcReg0Sub1)
6802                               .add(SrcReg1Sub1);
6803 
6804   Register FullDestReg = MRI.createVirtualRegister(NewDestRC);
6805   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
6806     .addReg(DestSub0)
6807     .addImm(AMDGPU::sub0)
6808     .addReg(DestSub1)
6809     .addImm(AMDGPU::sub1);
6810 
6811   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
6812 
6813   Worklist.insert(&LoHalf);
6814   Worklist.insert(&HiHalf);
6815 
6816   // Move all users of this moved value.
6817   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
6818 }
6819 
6820 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
6821                                        MachineInstr &Inst,
6822                                        MachineDominatorTree *MDT) const {
6823   MachineBasicBlock &MBB = *Inst.getParent();
6824   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6825 
6826   MachineOperand &Dest = Inst.getOperand(0);
6827   MachineOperand &Src0 = Inst.getOperand(1);
6828   MachineOperand &Src1 = Inst.getOperand(2);
6829   const DebugLoc &DL = Inst.getDebugLoc();
6830 
6831   MachineBasicBlock::iterator MII = Inst;
6832 
6833   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
6834 
6835   Register Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6836 
6837   MachineOperand* Op0;
6838   MachineOperand* Op1;
6839 
6840   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
6841     Op0 = &Src0;
6842     Op1 = &Src1;
6843   } else {
6844     Op0 = &Src1;
6845     Op1 = &Src0;
6846   }
6847 
6848   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
6849     .add(*Op0);
6850 
6851   Register NewDest = MRI.createVirtualRegister(DestRC);
6852 
6853   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
6854     .addReg(Interm)
6855     .add(*Op1);
6856 
6857   MRI.replaceRegWith(Dest.getReg(), NewDest);
6858 
6859   Worklist.insert(&Xor);
6860 }
6861 
6862 void SIInstrInfo::splitScalar64BitBCNT(
6863     SetVectorType &Worklist, MachineInstr &Inst) const {
6864   MachineBasicBlock &MBB = *Inst.getParent();
6865   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6866 
6867   MachineBasicBlock::iterator MII = Inst;
6868   const DebugLoc &DL = Inst.getDebugLoc();
6869 
6870   MachineOperand &Dest = Inst.getOperand(0);
6871   MachineOperand &Src = Inst.getOperand(1);
6872 
6873   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
6874   const TargetRegisterClass *SrcRC = Src.isReg() ?
6875     MRI.getRegClass(Src.getReg()) :
6876     &AMDGPU::SGPR_32RegClass;
6877 
6878   Register MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6879   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6880 
6881   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
6882 
6883   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6884                                                       AMDGPU::sub0, SrcSubRC);
6885   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
6886                                                       AMDGPU::sub1, SrcSubRC);
6887 
6888   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
6889 
6890   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
6891 
6892   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6893 
6894   // We don't need to legalize operands here. src0 for either instruction can be
6895   // an SGPR, and the second input is unused or determined here.
6896   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6897 }
6898 
6899 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
6900                                       MachineInstr &Inst) const {
6901   MachineBasicBlock &MBB = *Inst.getParent();
6902   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
6903   MachineBasicBlock::iterator MII = Inst;
6904   const DebugLoc &DL = Inst.getDebugLoc();
6905 
6906   MachineOperand &Dest = Inst.getOperand(0);
6907   uint32_t Imm = Inst.getOperand(2).getImm();
6908   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
6909   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
6910 
6911   (void) Offset;
6912 
6913   // Only sext_inreg cases handled.
6914   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
6915          Offset == 0 && "Not implemented");
6916 
6917   if (BitWidth < 32) {
6918     Register MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6919     Register MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6920     Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6921 
6922     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32_e64), MidRegLo)
6923         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
6924         .addImm(0)
6925         .addImm(BitWidth);
6926 
6927     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
6928       .addImm(31)
6929       .addReg(MidRegLo);
6930 
6931     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6932       .addReg(MidRegLo)
6933       .addImm(AMDGPU::sub0)
6934       .addReg(MidRegHi)
6935       .addImm(AMDGPU::sub1);
6936 
6937     MRI.replaceRegWith(Dest.getReg(), ResultReg);
6938     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6939     return;
6940   }
6941 
6942   MachineOperand &Src = Inst.getOperand(1);
6943   Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6944   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
6945 
6946   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
6947     .addImm(31)
6948     .addReg(Src.getReg(), 0, AMDGPU::sub0);
6949 
6950   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
6951     .addReg(Src.getReg(), 0, AMDGPU::sub0)
6952     .addImm(AMDGPU::sub0)
6953     .addReg(TmpReg)
6954     .addImm(AMDGPU::sub1);
6955 
6956   MRI.replaceRegWith(Dest.getReg(), ResultReg);
6957   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
6958 }
6959 
6960 void SIInstrInfo::addUsersToMoveToVALUWorklist(
6961   Register DstReg,
6962   MachineRegisterInfo &MRI,
6963   SetVectorType &Worklist) const {
6964   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
6965          E = MRI.use_end(); I != E;) {
6966     MachineInstr &UseMI = *I->getParent();
6967 
6968     unsigned OpNo = 0;
6969 
6970     switch (UseMI.getOpcode()) {
6971     case AMDGPU::COPY:
6972     case AMDGPU::WQM:
6973     case AMDGPU::SOFT_WQM:
6974     case AMDGPU::STRICT_WWM:
6975     case AMDGPU::STRICT_WQM:
6976     case AMDGPU::REG_SEQUENCE:
6977     case AMDGPU::PHI:
6978     case AMDGPU::INSERT_SUBREG:
6979       break;
6980     default:
6981       OpNo = I.getOperandNo();
6982       break;
6983     }
6984 
6985     if (!RI.hasVectorRegisters(getOpRegClass(UseMI, OpNo))) {
6986       Worklist.insert(&UseMI);
6987 
6988       do {
6989         ++I;
6990       } while (I != E && I->getParent() == &UseMI);
6991     } else {
6992       ++I;
6993     }
6994   }
6995 }
6996 
6997 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
6998                                  MachineRegisterInfo &MRI,
6999                                  MachineInstr &Inst) const {
7000   Register ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7001   MachineBasicBlock *MBB = Inst.getParent();
7002   MachineOperand &Src0 = Inst.getOperand(1);
7003   MachineOperand &Src1 = Inst.getOperand(2);
7004   const DebugLoc &DL = Inst.getDebugLoc();
7005 
7006   switch (Inst.getOpcode()) {
7007   case AMDGPU::S_PACK_LL_B32_B16: {
7008     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7009     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7010 
7011     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
7012     // 0.
7013     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7014       .addImm(0xffff);
7015 
7016     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
7017       .addReg(ImmReg, RegState::Kill)
7018       .add(Src0);
7019 
7020     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32_e64), ResultReg)
7021       .add(Src1)
7022       .addImm(16)
7023       .addReg(TmpReg, RegState::Kill);
7024     break;
7025   }
7026   case AMDGPU::S_PACK_LH_B32_B16: {
7027     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7028     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7029       .addImm(0xffff);
7030     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32_e64), ResultReg)
7031       .addReg(ImmReg, RegState::Kill)
7032       .add(Src0)
7033       .add(Src1);
7034     break;
7035   }
7036   case AMDGPU::S_PACK_HH_B32_B16: {
7037     Register ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7038     Register TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
7039     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
7040       .addImm(16)
7041       .add(Src0);
7042     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
7043       .addImm(0xffff0000);
7044     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32_e64), ResultReg)
7045       .add(Src1)
7046       .addReg(ImmReg, RegState::Kill)
7047       .addReg(TmpReg, RegState::Kill);
7048     break;
7049   }
7050   default:
7051     llvm_unreachable("unhandled s_pack_* instruction");
7052   }
7053 
7054   MachineOperand &Dest = Inst.getOperand(0);
7055   MRI.replaceRegWith(Dest.getReg(), ResultReg);
7056   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
7057 }
7058 
7059 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
7060                                                MachineInstr &SCCDefInst,
7061                                                SetVectorType &Worklist,
7062                                                Register NewCond) const {
7063 
7064   // Ensure that def inst defines SCC, which is still live.
7065   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
7066          !Op.isDead() && Op.getParent() == &SCCDefInst);
7067   SmallVector<MachineInstr *, 4> CopyToDelete;
7068   // This assumes that all the users of SCC are in the same block
7069   // as the SCC def.
7070   for (MachineInstr &MI : // Skip the def inst itself.
7071        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
7072                   SCCDefInst.getParent()->end())) {
7073     // Check if SCC is used first.
7074     int SCCIdx = MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI);
7075     if (SCCIdx != -1) {
7076       if (MI.isCopy()) {
7077         MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7078         Register DestReg = MI.getOperand(0).getReg();
7079 
7080         MRI.replaceRegWith(DestReg, NewCond);
7081         CopyToDelete.push_back(&MI);
7082       } else {
7083 
7084         if (NewCond.isValid())
7085           MI.getOperand(SCCIdx).setReg(NewCond);
7086 
7087         Worklist.insert(&MI);
7088       }
7089     }
7090     // Exit if we find another SCC def.
7091     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
7092       break;
7093   }
7094   for (auto &Copy : CopyToDelete)
7095     Copy->eraseFromParent();
7096 }
7097 
7098 // Instructions that use SCC may be converted to VALU instructions. When that
7099 // happens, the SCC register is changed to VCC_LO. The instruction that defines
7100 // SCC must be changed to an instruction that defines VCC. This function makes
7101 // sure that the instruction that defines SCC is added to the moveToVALU
7102 // worklist.
7103 void SIInstrInfo::addSCCDefsToVALUWorklist(MachineOperand &Op,
7104                                            SetVectorType &Worklist) const {
7105   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isUse());
7106 
7107   MachineInstr *SCCUseInst = Op.getParent();
7108   // Look for a preceding instruction that either defines VCC or SCC. If VCC
7109   // then there is nothing to do because the defining instruction has been
7110   // converted to a VALU already. If SCC then that instruction needs to be
7111   // converted to a VALU.
7112   for (MachineInstr &MI :
7113        make_range(std::next(MachineBasicBlock::reverse_iterator(SCCUseInst)),
7114                   SCCUseInst->getParent()->rend())) {
7115     if (MI.modifiesRegister(AMDGPU::VCC, &RI))
7116       break;
7117     if (MI.definesRegister(AMDGPU::SCC, &RI)) {
7118       Worklist.insert(&MI);
7119       break;
7120     }
7121   }
7122 }
7123 
7124 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
7125   const MachineInstr &Inst) const {
7126   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
7127 
7128   switch (Inst.getOpcode()) {
7129   // For target instructions, getOpRegClass just returns the virtual register
7130   // class associated with the operand, so we need to find an equivalent VGPR
7131   // register class in order to move the instruction to the VALU.
7132   case AMDGPU::COPY:
7133   case AMDGPU::PHI:
7134   case AMDGPU::REG_SEQUENCE:
7135   case AMDGPU::INSERT_SUBREG:
7136   case AMDGPU::WQM:
7137   case AMDGPU::SOFT_WQM:
7138   case AMDGPU::STRICT_WWM:
7139   case AMDGPU::STRICT_WQM: {
7140     const TargetRegisterClass *SrcRC = getOpRegClass(Inst, 1);
7141     if (RI.isAGPRClass(SrcRC)) {
7142       if (RI.isAGPRClass(NewDstRC))
7143         return nullptr;
7144 
7145       switch (Inst.getOpcode()) {
7146       case AMDGPU::PHI:
7147       case AMDGPU::REG_SEQUENCE:
7148       case AMDGPU::INSERT_SUBREG:
7149         NewDstRC = RI.getEquivalentAGPRClass(NewDstRC);
7150         break;
7151       default:
7152         NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7153       }
7154 
7155       if (!NewDstRC)
7156         return nullptr;
7157     } else {
7158       if (RI.isVGPRClass(NewDstRC) || NewDstRC == &AMDGPU::VReg_1RegClass)
7159         return nullptr;
7160 
7161       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
7162       if (!NewDstRC)
7163         return nullptr;
7164     }
7165 
7166     return NewDstRC;
7167   }
7168   default:
7169     return NewDstRC;
7170   }
7171 }
7172 
7173 // Find the one SGPR operand we are allowed to use.
7174 Register SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
7175                                    int OpIndices[3]) const {
7176   const MCInstrDesc &Desc = MI.getDesc();
7177 
7178   // Find the one SGPR operand we are allowed to use.
7179   //
7180   // First we need to consider the instruction's operand requirements before
7181   // legalizing. Some operands are required to be SGPRs, such as implicit uses
7182   // of VCC, but we are still bound by the constant bus requirement to only use
7183   // one.
7184   //
7185   // If the operand's class is an SGPR, we can never move it.
7186 
7187   Register SGPRReg = findImplicitSGPRRead(MI);
7188   if (SGPRReg != AMDGPU::NoRegister)
7189     return SGPRReg;
7190 
7191   Register UsedSGPRs[3] = { AMDGPU::NoRegister };
7192   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7193 
7194   for (unsigned i = 0; i < 3; ++i) {
7195     int Idx = OpIndices[i];
7196     if (Idx == -1)
7197       break;
7198 
7199     const MachineOperand &MO = MI.getOperand(Idx);
7200     if (!MO.isReg())
7201       continue;
7202 
7203     // Is this operand statically required to be an SGPR based on the operand
7204     // constraints?
7205     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
7206     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
7207     if (IsRequiredSGPR)
7208       return MO.getReg();
7209 
7210     // If this could be a VGPR or an SGPR, Check the dynamic register class.
7211     Register Reg = MO.getReg();
7212     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
7213     if (RI.isSGPRClass(RegRC))
7214       UsedSGPRs[i] = Reg;
7215   }
7216 
7217   // We don't have a required SGPR operand, so we have a bit more freedom in
7218   // selecting operands to move.
7219 
7220   // Try to select the most used SGPR. If an SGPR is equal to one of the
7221   // others, we choose that.
7222   //
7223   // e.g.
7224   // V_FMA_F32 v0, s0, s0, s0 -> No moves
7225   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
7226 
7227   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
7228   // prefer those.
7229 
7230   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
7231     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
7232       SGPRReg = UsedSGPRs[0];
7233   }
7234 
7235   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
7236     if (UsedSGPRs[1] == UsedSGPRs[2])
7237       SGPRReg = UsedSGPRs[1];
7238   }
7239 
7240   return SGPRReg;
7241 }
7242 
7243 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
7244                                              unsigned OperandName) const {
7245   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
7246   if (Idx == -1)
7247     return nullptr;
7248 
7249   return &MI.getOperand(Idx);
7250 }
7251 
7252 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
7253   if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
7254     return (AMDGPU::MTBUFFormat::UFMT_32_FLOAT << 44) |
7255            (1ULL << 56) | // RESOURCE_LEVEL = 1
7256            (3ULL << 60); // OOB_SELECT = 3
7257   }
7258 
7259   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
7260   if (ST.isAmdHsaOS()) {
7261     // Set ATC = 1. GFX9 doesn't have this bit.
7262     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7263       RsrcDataFormat |= (1ULL << 56);
7264 
7265     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
7266     // BTW, it disables TC L2 and therefore decreases performance.
7267     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
7268       RsrcDataFormat |= (2ULL << 59);
7269   }
7270 
7271   return RsrcDataFormat;
7272 }
7273 
7274 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
7275   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
7276                     AMDGPU::RSRC_TID_ENABLE |
7277                     0xffffffff; // Size;
7278 
7279   // GFX9 doesn't have ELEMENT_SIZE.
7280   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
7281     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize(true)) - 1;
7282     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
7283   }
7284 
7285   // IndexStride = 64 / 32.
7286   uint64_t IndexStride = ST.getWavefrontSize() == 64 ? 3 : 2;
7287   Rsrc23 |= IndexStride << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
7288 
7289   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
7290   // Clear them unless we want a huge stride.
7291   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
7292       ST.getGeneration() <= AMDGPUSubtarget::GFX9)
7293     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
7294 
7295   return Rsrc23;
7296 }
7297 
7298 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
7299   unsigned Opc = MI.getOpcode();
7300 
7301   return isSMRD(Opc);
7302 }
7303 
7304 bool SIInstrInfo::isHighLatencyDef(int Opc) const {
7305   return get(Opc).mayLoad() &&
7306          (isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc) || isFLAT(Opc));
7307 }
7308 
7309 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
7310                                     int &FrameIndex) const {
7311   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
7312   if (!Addr || !Addr->isFI())
7313     return AMDGPU::NoRegister;
7314 
7315   assert(!MI.memoperands_empty() &&
7316          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
7317 
7318   FrameIndex = Addr->getIndex();
7319   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
7320 }
7321 
7322 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
7323                                         int &FrameIndex) const {
7324   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
7325   assert(Addr && Addr->isFI());
7326   FrameIndex = Addr->getIndex();
7327   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
7328 }
7329 
7330 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
7331                                           int &FrameIndex) const {
7332   if (!MI.mayLoad())
7333     return AMDGPU::NoRegister;
7334 
7335   if (isMUBUF(MI) || isVGPRSpill(MI))
7336     return isStackAccess(MI, FrameIndex);
7337 
7338   if (isSGPRSpill(MI))
7339     return isSGPRStackAccess(MI, FrameIndex);
7340 
7341   return AMDGPU::NoRegister;
7342 }
7343 
7344 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
7345                                          int &FrameIndex) const {
7346   if (!MI.mayStore())
7347     return AMDGPU::NoRegister;
7348 
7349   if (isMUBUF(MI) || isVGPRSpill(MI))
7350     return isStackAccess(MI, FrameIndex);
7351 
7352   if (isSGPRSpill(MI))
7353     return isSGPRStackAccess(MI, FrameIndex);
7354 
7355   return AMDGPU::NoRegister;
7356 }
7357 
7358 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
7359   unsigned Size = 0;
7360   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
7361   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
7362   while (++I != E && I->isInsideBundle()) {
7363     assert(!I->isBundle() && "No nested bundle!");
7364     Size += getInstSizeInBytes(*I);
7365   }
7366 
7367   return Size;
7368 }
7369 
7370 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
7371   unsigned Opc = MI.getOpcode();
7372   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
7373   unsigned DescSize = Desc.getSize();
7374 
7375   // If we have a definitive size, we can use it. Otherwise we need to inspect
7376   // the operands to know the size.
7377   if (isFixedSize(MI)) {
7378     unsigned Size = DescSize;
7379 
7380     // If we hit the buggy offset, an extra nop will be inserted in MC so
7381     // estimate the worst case.
7382     if (MI.isBranch() && ST.hasOffset3fBug())
7383       Size += 4;
7384 
7385     return Size;
7386   }
7387 
7388   // Instructions may have a 32-bit literal encoded after them. Check
7389   // operands that could ever be literals.
7390   if (isVALU(MI) || isSALU(MI)) {
7391     if (isDPP(MI))
7392       return DescSize;
7393     bool HasLiteral = false;
7394     for (int I = 0, E = MI.getNumExplicitOperands(); I != E; ++I) {
7395       if (isLiteralConstant(MI, I)) {
7396         HasLiteral = true;
7397         break;
7398       }
7399     }
7400     return HasLiteral ? DescSize + 4 : DescSize;
7401   }
7402 
7403   // Check whether we have extra NSA words.
7404   if (isMIMG(MI)) {
7405     int VAddr0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr0);
7406     if (VAddr0Idx < 0)
7407       return 8;
7408 
7409     int RSrcIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::srsrc);
7410     return 8 + 4 * ((RSrcIdx - VAddr0Idx + 2) / 4);
7411   }
7412 
7413   switch (Opc) {
7414   case TargetOpcode::BUNDLE:
7415     return getInstBundleSize(MI);
7416   case TargetOpcode::INLINEASM:
7417   case TargetOpcode::INLINEASM_BR: {
7418     const MachineFunction *MF = MI.getParent()->getParent();
7419     const char *AsmStr = MI.getOperand(0).getSymbolName();
7420     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo(), &ST);
7421   }
7422   default:
7423     if (MI.isMetaInstruction())
7424       return 0;
7425     return DescSize;
7426   }
7427 }
7428 
7429 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
7430   if (!isFLAT(MI))
7431     return false;
7432 
7433   if (MI.memoperands_empty())
7434     return true;
7435 
7436   for (const MachineMemOperand *MMO : MI.memoperands()) {
7437     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
7438       return true;
7439   }
7440   return false;
7441 }
7442 
7443 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
7444   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
7445 }
7446 
7447 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
7448                                             MachineBasicBlock *IfEnd) const {
7449   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
7450   assert(TI != IfEntry->end());
7451 
7452   MachineInstr *Branch = &(*TI);
7453   MachineFunction *MF = IfEntry->getParent();
7454   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
7455 
7456   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7457     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7458     MachineInstr *SIIF =
7459         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
7460             .add(Branch->getOperand(0))
7461             .add(Branch->getOperand(1));
7462     MachineInstr *SIEND =
7463         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
7464             .addReg(DstReg);
7465 
7466     IfEntry->erase(TI);
7467     IfEntry->insert(IfEntry->end(), SIIF);
7468     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
7469   }
7470 }
7471 
7472 void SIInstrInfo::convertNonUniformLoopRegion(
7473     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
7474   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
7475   // We expect 2 terminators, one conditional and one unconditional.
7476   assert(TI != LoopEnd->end());
7477 
7478   MachineInstr *Branch = &(*TI);
7479   MachineFunction *MF = LoopEnd->getParent();
7480   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
7481 
7482   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
7483 
7484     Register DstReg = MRI.createVirtualRegister(RI.getBoolRC());
7485     Register BackEdgeReg = MRI.createVirtualRegister(RI.getBoolRC());
7486     MachineInstrBuilder HeaderPHIBuilder =
7487         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
7488     for (MachineBasicBlock *PMBB : LoopEntry->predecessors()) {
7489       if (PMBB == LoopEnd) {
7490         HeaderPHIBuilder.addReg(BackEdgeReg);
7491       } else {
7492         Register ZeroReg = MRI.createVirtualRegister(RI.getBoolRC());
7493         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
7494                              ZeroReg, 0);
7495         HeaderPHIBuilder.addReg(ZeroReg);
7496       }
7497       HeaderPHIBuilder.addMBB(PMBB);
7498     }
7499     MachineInstr *HeaderPhi = HeaderPHIBuilder;
7500     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
7501                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
7502                                   .addReg(DstReg)
7503                                   .add(Branch->getOperand(0));
7504     MachineInstr *SILOOP =
7505         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
7506             .addReg(BackEdgeReg)
7507             .addMBB(LoopEntry);
7508 
7509     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
7510     LoopEnd->erase(TI);
7511     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
7512     LoopEnd->insert(LoopEnd->end(), SILOOP);
7513   }
7514 }
7515 
7516 ArrayRef<std::pair<int, const char *>>
7517 SIInstrInfo::getSerializableTargetIndices() const {
7518   static const std::pair<int, const char *> TargetIndices[] = {
7519       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
7520       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
7521       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
7522       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
7523       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
7524   return makeArrayRef(TargetIndices);
7525 }
7526 
7527 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
7528 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
7529 ScheduleHazardRecognizer *
7530 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
7531                                             const ScheduleDAG *DAG) const {
7532   return new GCNHazardRecognizer(DAG->MF);
7533 }
7534 
7535 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
7536 /// pass.
7537 ScheduleHazardRecognizer *
7538 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
7539   return new GCNHazardRecognizer(MF);
7540 }
7541 
7542 // Called during:
7543 // - pre-RA scheduling and post-RA scheduling
7544 ScheduleHazardRecognizer *
7545 SIInstrInfo::CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
7546                                             const ScheduleDAGMI *DAG) const {
7547   // Borrowed from Arm Target
7548   // We would like to restrict this hazard recognizer to only
7549   // post-RA scheduling; we can tell that we're post-RA because we don't
7550   // track VRegLiveness.
7551   if (!DAG->hasVRegLiveness())
7552     return new GCNHazardRecognizer(DAG->MF);
7553   return TargetInstrInfo::CreateTargetMIHazardRecognizer(II, DAG);
7554 }
7555 
7556 std::pair<unsigned, unsigned>
7557 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
7558   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
7559 }
7560 
7561 ArrayRef<std::pair<unsigned, const char *>>
7562 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
7563   static const std::pair<unsigned, const char *> TargetFlags[] = {
7564     { MO_GOTPCREL, "amdgpu-gotprel" },
7565     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
7566     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
7567     { MO_REL32_LO, "amdgpu-rel32-lo" },
7568     { MO_REL32_HI, "amdgpu-rel32-hi" },
7569     { MO_ABS32_LO, "amdgpu-abs32-lo" },
7570     { MO_ABS32_HI, "amdgpu-abs32-hi" },
7571   };
7572 
7573   return makeArrayRef(TargetFlags);
7574 }
7575 
7576 ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
7577 SIInstrInfo::getSerializableMachineMemOperandTargetFlags() const {
7578   static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
7579       {
7580           {MONoClobber, "amdgpu-noclobber"},
7581       };
7582 
7583   return makeArrayRef(TargetFlags);
7584 }
7585 
7586 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
7587   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
7588          MI.modifiesRegister(AMDGPU::EXEC, &RI);
7589 }
7590 
7591 MachineInstrBuilder
7592 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7593                            MachineBasicBlock::iterator I,
7594                            const DebugLoc &DL,
7595                            Register DestReg) const {
7596   if (ST.hasAddNoCarry())
7597     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
7598 
7599   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
7600   Register UnusedCarry = MRI.createVirtualRegister(RI.getBoolRC());
7601   MRI.setRegAllocationHint(UnusedCarry, 0, RI.getVCC());
7602 
7603   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7604            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7605 }
7606 
7607 MachineInstrBuilder SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
7608                                                MachineBasicBlock::iterator I,
7609                                                const DebugLoc &DL,
7610                                                Register DestReg,
7611                                                RegScavenger &RS) const {
7612   if (ST.hasAddNoCarry())
7613     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e32), DestReg);
7614 
7615   // If available, prefer to use vcc.
7616   Register UnusedCarry = !RS.isRegUsed(AMDGPU::VCC)
7617                              ? Register(RI.getVCC())
7618                              : RS.scavengeRegister(RI.getBoolRC(), I, 0, false);
7619 
7620   // TODO: Users need to deal with this.
7621   if (!UnusedCarry.isValid())
7622     return MachineInstrBuilder();
7623 
7624   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_CO_U32_e64), DestReg)
7625            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
7626 }
7627 
7628 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
7629   switch (Opcode) {
7630   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
7631   case AMDGPU::SI_KILL_I1_TERMINATOR:
7632     return true;
7633   default:
7634     return false;
7635   }
7636 }
7637 
7638 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
7639   switch (Opcode) {
7640   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
7641     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
7642   case AMDGPU::SI_KILL_I1_PSEUDO:
7643     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
7644   default:
7645     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
7646   }
7647 }
7648 
7649 void SIInstrInfo::fixImplicitOperands(MachineInstr &MI) const {
7650   if (!ST.isWave32())
7651     return;
7652 
7653   for (auto &Op : MI.implicit_operands()) {
7654     if (Op.isReg() && Op.getReg() == AMDGPU::VCC)
7655       Op.setReg(AMDGPU::VCC_LO);
7656   }
7657 }
7658 
7659 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
7660   if (!isSMRD(MI))
7661     return false;
7662 
7663   // Check that it is using a buffer resource.
7664   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
7665   if (Idx == -1) // e.g. s_memtime
7666     return false;
7667 
7668   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
7669   return RI.getRegClass(RCID)->hasSubClassEq(&AMDGPU::SGPR_128RegClass);
7670 }
7671 
7672 // Depending on the used address space and instructions, some immediate offsets
7673 // are allowed and some are not.
7674 // In general, flat instruction offsets can only be non-negative, global and
7675 // scratch instruction offsets can also be negative.
7676 //
7677 // There are several bugs related to these offsets:
7678 // On gfx10.1, flat instructions that go into the global address space cannot
7679 // use an offset.
7680 //
7681 // For scratch instructions, the address can be either an SGPR or a VGPR.
7682 // The following offsets can be used, depending on the architecture (x means
7683 // cannot be used):
7684 // +----------------------------+------+------+
7685 // | Address-Mode               | SGPR | VGPR |
7686 // +----------------------------+------+------+
7687 // | gfx9                       |      |      |
7688 // | negative, 4-aligned offset | x    | ok   |
7689 // | negative, unaligned offset | x    | ok   |
7690 // +----------------------------+------+------+
7691 // | gfx10                      |      |      |
7692 // | negative, 4-aligned offset | ok   | ok   |
7693 // | negative, unaligned offset | ok   | x    |
7694 // +----------------------------+------+------+
7695 // | gfx10.3                    |      |      |
7696 // | negative, 4-aligned offset | ok   | ok   |
7697 // | negative, unaligned offset | ok   | ok   |
7698 // +----------------------------+------+------+
7699 //
7700 // This function ignores the addressing mode, so if an offset cannot be used in
7701 // one addressing mode, it is considered illegal.
7702 bool SIInstrInfo::isLegalFLATOffset(int64_t Offset, unsigned AddrSpace,
7703                                     uint64_t FlatVariant) const {
7704   // TODO: Should 0 be special cased?
7705   if (!ST.hasFlatInstOffsets())
7706     return false;
7707 
7708   if (ST.hasFlatSegmentOffsetBug() && FlatVariant == SIInstrFlags::FLAT &&
7709       (AddrSpace == AMDGPUAS::FLAT_ADDRESS ||
7710        AddrSpace == AMDGPUAS::GLOBAL_ADDRESS))
7711     return false;
7712 
7713   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7714   if (ST.hasNegativeScratchOffsetBug() &&
7715       FlatVariant == SIInstrFlags::FlatScratch)
7716     Signed = false;
7717   if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7718       FlatVariant == SIInstrFlags::FlatScratch && Offset < 0 &&
7719       (Offset % 4) != 0) {
7720     return false;
7721   }
7722 
7723   unsigned N = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7724   return Signed ? isIntN(N, Offset) : isUIntN(N, Offset);
7725 }
7726 
7727 // See comment on SIInstrInfo::isLegalFLATOffset for what is legal and what not.
7728 std::pair<int64_t, int64_t>
7729 SIInstrInfo::splitFlatOffset(int64_t COffsetVal, unsigned AddrSpace,
7730                              uint64_t FlatVariant) const {
7731   int64_t RemainderOffset = COffsetVal;
7732   int64_t ImmField = 0;
7733   bool Signed = FlatVariant != SIInstrFlags::FLAT;
7734   if (ST.hasNegativeScratchOffsetBug() &&
7735       FlatVariant == SIInstrFlags::FlatScratch)
7736     Signed = false;
7737 
7738   const unsigned NumBits = AMDGPU::getNumFlatOffsetBits(ST, Signed);
7739   if (Signed) {
7740     // Use signed division by a power of two to truncate towards 0.
7741     int64_t D = 1LL << (NumBits - 1);
7742     RemainderOffset = (COffsetVal / D) * D;
7743     ImmField = COffsetVal - RemainderOffset;
7744 
7745     if (ST.hasNegativeUnalignedScratchOffsetBug() &&
7746         FlatVariant == SIInstrFlags::FlatScratch && ImmField < 0 &&
7747         (ImmField % 4) != 0) {
7748       // Make ImmField a multiple of 4
7749       RemainderOffset += ImmField % 4;
7750       ImmField -= ImmField % 4;
7751     }
7752   } else if (COffsetVal >= 0) {
7753     ImmField = COffsetVal & maskTrailingOnes<uint64_t>(NumBits);
7754     RemainderOffset = COffsetVal - ImmField;
7755   }
7756 
7757   assert(isLegalFLATOffset(ImmField, AddrSpace, FlatVariant));
7758   assert(RemainderOffset + ImmField == COffsetVal);
7759   return {ImmField, RemainderOffset};
7760 }
7761 
7762 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
7763 enum SIEncodingFamily {
7764   SI = 0,
7765   VI = 1,
7766   SDWA = 2,
7767   SDWA9 = 3,
7768   GFX80 = 4,
7769   GFX9 = 5,
7770   GFX10 = 6,
7771   SDWA10 = 7,
7772   GFX90A = 8
7773 };
7774 
7775 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
7776   switch (ST.getGeneration()) {
7777   default:
7778     break;
7779   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
7780   case AMDGPUSubtarget::SEA_ISLANDS:
7781     return SIEncodingFamily::SI;
7782   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
7783   case AMDGPUSubtarget::GFX9:
7784     return SIEncodingFamily::VI;
7785   case AMDGPUSubtarget::GFX10:
7786     return SIEncodingFamily::GFX10;
7787   }
7788   llvm_unreachable("Unknown subtarget generation!");
7789 }
7790 
7791 bool SIInstrInfo::isAsmOnlyOpcode(int MCOp) const {
7792   switch(MCOp) {
7793   // These opcodes use indirect register addressing so
7794   // they need special handling by codegen (currently missing).
7795   // Therefore it is too risky to allow these opcodes
7796   // to be selected by dpp combiner or sdwa peepholer.
7797   case AMDGPU::V_MOVRELS_B32_dpp_gfx10:
7798   case AMDGPU::V_MOVRELS_B32_sdwa_gfx10:
7799   case AMDGPU::V_MOVRELD_B32_dpp_gfx10:
7800   case AMDGPU::V_MOVRELD_B32_sdwa_gfx10:
7801   case AMDGPU::V_MOVRELSD_B32_dpp_gfx10:
7802   case AMDGPU::V_MOVRELSD_B32_sdwa_gfx10:
7803   case AMDGPU::V_MOVRELSD_2_B32_dpp_gfx10:
7804   case AMDGPU::V_MOVRELSD_2_B32_sdwa_gfx10:
7805     return true;
7806   default:
7807     return false;
7808   }
7809 }
7810 
7811 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
7812   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
7813 
7814   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
7815     ST.getGeneration() == AMDGPUSubtarget::GFX9)
7816     Gen = SIEncodingFamily::GFX9;
7817 
7818   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
7819   // subtarget has UnpackedD16VMem feature.
7820   // TODO: remove this when we discard GFX80 encoding.
7821   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
7822     Gen = SIEncodingFamily::GFX80;
7823 
7824   if (get(Opcode).TSFlags & SIInstrFlags::SDWA) {
7825     switch (ST.getGeneration()) {
7826     default:
7827       Gen = SIEncodingFamily::SDWA;
7828       break;
7829     case AMDGPUSubtarget::GFX9:
7830       Gen = SIEncodingFamily::SDWA9;
7831       break;
7832     case AMDGPUSubtarget::GFX10:
7833       Gen = SIEncodingFamily::SDWA10;
7834       break;
7835     }
7836   }
7837 
7838   if (isMAI(Opcode)) {
7839     int MFMAOp = AMDGPU::getMFMAEarlyClobberOp(Opcode);
7840     if (MFMAOp != -1)
7841       Opcode = MFMAOp;
7842   }
7843 
7844   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
7845 
7846   // -1 means that Opcode is already a native instruction.
7847   if (MCOp == -1)
7848     return Opcode;
7849 
7850   if (ST.hasGFX90AInsts()) {
7851     uint16_t NMCOp = (uint16_t)-1;
7852       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX90A);
7853     if (NMCOp == (uint16_t)-1)
7854       NMCOp = AMDGPU::getMCOpcode(Opcode, SIEncodingFamily::GFX9);
7855     if (NMCOp != (uint16_t)-1)
7856       MCOp = NMCOp;
7857   }
7858 
7859   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
7860   // no encoding in the given subtarget generation.
7861   if (MCOp == (uint16_t)-1)
7862     return -1;
7863 
7864   if (isAsmOnlyOpcode(MCOp))
7865     return -1;
7866 
7867   return MCOp;
7868 }
7869 
7870 static
7871 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
7872   assert(RegOpnd.isReg());
7873   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
7874                              getRegSubRegPair(RegOpnd);
7875 }
7876 
7877 TargetInstrInfo::RegSubRegPair
7878 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
7879   assert(MI.isRegSequence());
7880   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
7881     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
7882       auto &RegOp = MI.getOperand(1 + 2 * I);
7883       return getRegOrUndef(RegOp);
7884     }
7885   return TargetInstrInfo::RegSubRegPair();
7886 }
7887 
7888 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
7889 // Following a subreg of reg:subreg isn't supported
7890 static bool followSubRegDef(MachineInstr &MI,
7891                             TargetInstrInfo::RegSubRegPair &RSR) {
7892   if (!RSR.SubReg)
7893     return false;
7894   switch (MI.getOpcode()) {
7895   default: break;
7896   case AMDGPU::REG_SEQUENCE:
7897     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
7898     return true;
7899   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
7900   case AMDGPU::INSERT_SUBREG:
7901     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
7902       // inserted the subreg we're looking for
7903       RSR = getRegOrUndef(MI.getOperand(2));
7904     else { // the subreg in the rest of the reg
7905       auto R1 = getRegOrUndef(MI.getOperand(1));
7906       if (R1.SubReg) // subreg of subreg isn't supported
7907         return false;
7908       RSR.Reg = R1.Reg;
7909     }
7910     return true;
7911   }
7912   return false;
7913 }
7914 
7915 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
7916                                      MachineRegisterInfo &MRI) {
7917   assert(MRI.isSSA());
7918   if (!P.Reg.isVirtual())
7919     return nullptr;
7920 
7921   auto RSR = P;
7922   auto *DefInst = MRI.getVRegDef(RSR.Reg);
7923   while (auto *MI = DefInst) {
7924     DefInst = nullptr;
7925     switch (MI->getOpcode()) {
7926     case AMDGPU::COPY:
7927     case AMDGPU::V_MOV_B32_e32: {
7928       auto &Op1 = MI->getOperand(1);
7929       if (Op1.isReg() && Op1.getReg().isVirtual()) {
7930         if (Op1.isUndef())
7931           return nullptr;
7932         RSR = getRegSubRegPair(Op1);
7933         DefInst = MRI.getVRegDef(RSR.Reg);
7934       }
7935       break;
7936     }
7937     default:
7938       if (followSubRegDef(*MI, RSR)) {
7939         if (!RSR.Reg)
7940           return nullptr;
7941         DefInst = MRI.getVRegDef(RSR.Reg);
7942       }
7943     }
7944     if (!DefInst)
7945       return MI;
7946   }
7947   return nullptr;
7948 }
7949 
7950 bool llvm::execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI,
7951                                       Register VReg,
7952                                       const MachineInstr &DefMI,
7953                                       const MachineInstr &UseMI) {
7954   assert(MRI.isSSA() && "Must be run on SSA");
7955 
7956   auto *TRI = MRI.getTargetRegisterInfo();
7957   auto *DefBB = DefMI.getParent();
7958 
7959   // Don't bother searching between blocks, although it is possible this block
7960   // doesn't modify exec.
7961   if (UseMI.getParent() != DefBB)
7962     return true;
7963 
7964   const int MaxInstScan = 20;
7965   int NumInst = 0;
7966 
7967   // Stop scan at the use.
7968   auto E = UseMI.getIterator();
7969   for (auto I = std::next(DefMI.getIterator()); I != E; ++I) {
7970     if (I->isDebugInstr())
7971       continue;
7972 
7973     if (++NumInst > MaxInstScan)
7974       return true;
7975 
7976     if (I->modifiesRegister(AMDGPU::EXEC, TRI))
7977       return true;
7978   }
7979 
7980   return false;
7981 }
7982 
7983 bool llvm::execMayBeModifiedBeforeAnyUse(const MachineRegisterInfo &MRI,
7984                                          Register VReg,
7985                                          const MachineInstr &DefMI) {
7986   assert(MRI.isSSA() && "Must be run on SSA");
7987 
7988   auto *TRI = MRI.getTargetRegisterInfo();
7989   auto *DefBB = DefMI.getParent();
7990 
7991   const int MaxUseScan = 10;
7992   int NumUse = 0;
7993 
7994   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
7995     auto &UseInst = *Use.getParent();
7996     // Don't bother searching between blocks, although it is possible this block
7997     // doesn't modify exec.
7998     if (UseInst.getParent() != DefBB)
7999       return true;
8000 
8001     if (++NumUse > MaxUseScan)
8002       return true;
8003   }
8004 
8005   if (NumUse == 0)
8006     return false;
8007 
8008   const int MaxInstScan = 20;
8009   int NumInst = 0;
8010 
8011   // Stop scan when we have seen all the uses.
8012   for (auto I = std::next(DefMI.getIterator()); ; ++I) {
8013     assert(I != DefBB->end());
8014 
8015     if (I->isDebugInstr())
8016       continue;
8017 
8018     if (++NumInst > MaxInstScan)
8019       return true;
8020 
8021     for (const MachineOperand &Op : I->operands()) {
8022       // We don't check reg masks here as they're used only on calls:
8023       // 1. EXEC is only considered const within one BB
8024       // 2. Call should be a terminator instruction if present in a BB
8025 
8026       if (!Op.isReg())
8027         continue;
8028 
8029       Register Reg = Op.getReg();
8030       if (Op.isUse()) {
8031         if (Reg == VReg && --NumUse == 0)
8032           return false;
8033       } else if (TRI->regsOverlap(Reg, AMDGPU::EXEC))
8034         return true;
8035     }
8036   }
8037 }
8038 
8039 MachineInstr *SIInstrInfo::createPHIDestinationCopy(
8040     MachineBasicBlock &MBB, MachineBasicBlock::iterator LastPHIIt,
8041     const DebugLoc &DL, Register Src, Register Dst) const {
8042   auto Cur = MBB.begin();
8043   if (Cur != MBB.end())
8044     do {
8045       if (!Cur->isPHI() && Cur->readsRegister(Dst))
8046         return BuildMI(MBB, Cur, DL, get(TargetOpcode::COPY), Dst).addReg(Src);
8047       ++Cur;
8048     } while (Cur != MBB.end() && Cur != LastPHIIt);
8049 
8050   return TargetInstrInfo::createPHIDestinationCopy(MBB, LastPHIIt, DL, Src,
8051                                                    Dst);
8052 }
8053 
8054 MachineInstr *SIInstrInfo::createPHISourceCopy(
8055     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsPt,
8056     const DebugLoc &DL, Register Src, unsigned SrcSubReg, Register Dst) const {
8057   if (InsPt != MBB.end() &&
8058       (InsPt->getOpcode() == AMDGPU::SI_IF ||
8059        InsPt->getOpcode() == AMDGPU::SI_ELSE ||
8060        InsPt->getOpcode() == AMDGPU::SI_IF_BREAK) &&
8061       InsPt->definesRegister(Src)) {
8062     InsPt++;
8063     return BuildMI(MBB, InsPt, DL,
8064                    get(ST.isWave32() ? AMDGPU::S_MOV_B32_term
8065                                      : AMDGPU::S_MOV_B64_term),
8066                    Dst)
8067         .addReg(Src, 0, SrcSubReg)
8068         .addReg(AMDGPU::EXEC, RegState::Implicit);
8069   }
8070   return TargetInstrInfo::createPHISourceCopy(MBB, InsPt, DL, Src, SrcSubReg,
8071                                               Dst);
8072 }
8073 
8074 bool llvm::SIInstrInfo::isWave32() const { return ST.isWave32(); }
8075 
8076 MachineInstr *SIInstrInfo::foldMemoryOperandImpl(
8077     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
8078     MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS,
8079     VirtRegMap *VRM) const {
8080   // This is a bit of a hack (copied from AArch64). Consider this instruction:
8081   //
8082   //   %0:sreg_32 = COPY $m0
8083   //
8084   // We explicitly chose SReg_32 for the virtual register so such a copy might
8085   // be eliminated by RegisterCoalescer. However, that may not be possible, and
8086   // %0 may even spill. We can't spill $m0 normally (it would require copying to
8087   // a numbered SGPR anyway), and since it is in the SReg_32 register class,
8088   // TargetInstrInfo::foldMemoryOperand() is going to try.
8089   // A similar issue also exists with spilling and reloading $exec registers.
8090   //
8091   // To prevent that, constrain the %0 register class here.
8092   if (MI.isFullCopy()) {
8093     Register DstReg = MI.getOperand(0).getReg();
8094     Register SrcReg = MI.getOperand(1).getReg();
8095     if ((DstReg.isVirtual() || SrcReg.isVirtual()) &&
8096         (DstReg.isVirtual() != SrcReg.isVirtual())) {
8097       MachineRegisterInfo &MRI = MF.getRegInfo();
8098       Register VirtReg = DstReg.isVirtual() ? DstReg : SrcReg;
8099       const TargetRegisterClass *RC = MRI.getRegClass(VirtReg);
8100       if (RC->hasSuperClassEq(&AMDGPU::SReg_32RegClass)) {
8101         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_32_XM0_XEXECRegClass);
8102         return nullptr;
8103       } else if (RC->hasSuperClassEq(&AMDGPU::SReg_64RegClass)) {
8104         MRI.constrainRegClass(VirtReg, &AMDGPU::SReg_64_XEXECRegClass);
8105         return nullptr;
8106       }
8107     }
8108   }
8109 
8110   return nullptr;
8111 }
8112 
8113 unsigned SIInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
8114                                       const MachineInstr &MI,
8115                                       unsigned *PredCost) const {
8116   if (MI.isBundle()) {
8117     MachineBasicBlock::const_instr_iterator I(MI.getIterator());
8118     MachineBasicBlock::const_instr_iterator E(MI.getParent()->instr_end());
8119     unsigned Lat = 0, Count = 0;
8120     for (++I; I != E && I->isBundledWithPred(); ++I) {
8121       ++Count;
8122       Lat = std::max(Lat, SchedModel.computeInstrLatency(&*I));
8123     }
8124     return Lat + Count - 1;
8125   }
8126 
8127   return SchedModel.computeInstrLatency(&MI);
8128 }
8129 
8130 unsigned SIInstrInfo::getDSShaderTypeValue(const MachineFunction &MF) {
8131   switch (MF.getFunction().getCallingConv()) {
8132   case CallingConv::AMDGPU_PS:
8133     return 1;
8134   case CallingConv::AMDGPU_VS:
8135     return 2;
8136   case CallingConv::AMDGPU_GS:
8137     return 3;
8138   case CallingConv::AMDGPU_HS:
8139   case CallingConv::AMDGPU_LS:
8140   case CallingConv::AMDGPU_ES:
8141     report_fatal_error("ds_ordered_count unsupported for this calling conv");
8142   case CallingConv::AMDGPU_CS:
8143   case CallingConv::AMDGPU_KERNEL:
8144   case CallingConv::C:
8145   case CallingConv::Fast:
8146   default:
8147     // Assume other calling conventions are various compute callable functions
8148     return 0;
8149   }
8150 }
8151 
8152 bool SIInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
8153                                  Register &SrcReg2, int64_t &CmpMask,
8154                                  int64_t &CmpValue) const {
8155   if (!MI.getOperand(0).isReg() || MI.getOperand(0).getSubReg())
8156     return false;
8157 
8158   switch (MI.getOpcode()) {
8159   default:
8160     break;
8161   case AMDGPU::S_CMP_EQ_U32:
8162   case AMDGPU::S_CMP_EQ_I32:
8163   case AMDGPU::S_CMP_LG_U32:
8164   case AMDGPU::S_CMP_LG_I32:
8165   case AMDGPU::S_CMP_LT_U32:
8166   case AMDGPU::S_CMP_LT_I32:
8167   case AMDGPU::S_CMP_GT_U32:
8168   case AMDGPU::S_CMP_GT_I32:
8169   case AMDGPU::S_CMP_LE_U32:
8170   case AMDGPU::S_CMP_LE_I32:
8171   case AMDGPU::S_CMP_GE_U32:
8172   case AMDGPU::S_CMP_GE_I32:
8173   case AMDGPU::S_CMP_EQ_U64:
8174   case AMDGPU::S_CMP_LG_U64:
8175     SrcReg = MI.getOperand(0).getReg();
8176     if (MI.getOperand(1).isReg()) {
8177       if (MI.getOperand(1).getSubReg())
8178         return false;
8179       SrcReg2 = MI.getOperand(1).getReg();
8180       CmpValue = 0;
8181     } else if (MI.getOperand(1).isImm()) {
8182       SrcReg2 = Register();
8183       CmpValue = MI.getOperand(1).getImm();
8184     } else {
8185       return false;
8186     }
8187     CmpMask = ~0;
8188     return true;
8189   case AMDGPU::S_CMPK_EQ_U32:
8190   case AMDGPU::S_CMPK_EQ_I32:
8191   case AMDGPU::S_CMPK_LG_U32:
8192   case AMDGPU::S_CMPK_LG_I32:
8193   case AMDGPU::S_CMPK_LT_U32:
8194   case AMDGPU::S_CMPK_LT_I32:
8195   case AMDGPU::S_CMPK_GT_U32:
8196   case AMDGPU::S_CMPK_GT_I32:
8197   case AMDGPU::S_CMPK_LE_U32:
8198   case AMDGPU::S_CMPK_LE_I32:
8199   case AMDGPU::S_CMPK_GE_U32:
8200   case AMDGPU::S_CMPK_GE_I32:
8201     SrcReg = MI.getOperand(0).getReg();
8202     SrcReg2 = Register();
8203     CmpValue = MI.getOperand(1).getImm();
8204     CmpMask = ~0;
8205     return true;
8206   }
8207 
8208   return false;
8209 }
8210 
8211 bool SIInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg,
8212                                        Register SrcReg2, int64_t CmpMask,
8213                                        int64_t CmpValue,
8214                                        const MachineRegisterInfo *MRI) const {
8215   if (!SrcReg || SrcReg.isPhysical())
8216     return false;
8217 
8218   if (SrcReg2 && !getFoldableImm(SrcReg2, *MRI, CmpValue))
8219     return false;
8220 
8221   const auto optimizeCmpAnd = [&CmpInstr, SrcReg, CmpValue, MRI,
8222                                this](int64_t ExpectedValue, unsigned SrcSize,
8223                                      bool IsReversible, bool IsSigned) -> bool {
8224     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8225     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8226     // s_cmp_ge_u32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8227     // s_cmp_ge_i32 (s_and_b32 $src, 1 << n), 1 << n => s_and_b32 $src, 1 << n
8228     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 1 << n => s_and_b64 $src, 1 << n
8229     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8230     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8231     // s_cmp_gt_u32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8232     // s_cmp_gt_i32 (s_and_b32 $src, 1 << n), 0 => s_and_b32 $src, 1 << n
8233     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 0 => s_and_b64 $src, 1 << n
8234     //
8235     // Signed ge/gt are not used for the sign bit.
8236     //
8237     // If result of the AND is unused except in the compare:
8238     // s_and_b(32|64) $src, 1 << n => s_bitcmp1_b(32|64) $src, n
8239     //
8240     // s_cmp_eq_u32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8241     // s_cmp_eq_i32 (s_and_b32 $src, 1 << n), 0 => s_bitcmp0_b32 $src, n
8242     // s_cmp_eq_u64 (s_and_b64 $src, 1 << n), 0 => s_bitcmp0_b64 $src, n
8243     // s_cmp_lg_u32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8244     // s_cmp_lg_i32 (s_and_b32 $src, 1 << n), 1 << n => s_bitcmp0_b32 $src, n
8245     // s_cmp_lg_u64 (s_and_b64 $src, 1 << n), 1 << n => s_bitcmp0_b64 $src, n
8246 
8247     MachineInstr *Def = MRI->getUniqueVRegDef(SrcReg);
8248     if (!Def || Def->getParent() != CmpInstr.getParent())
8249       return false;
8250 
8251     if (Def->getOpcode() != AMDGPU::S_AND_B32 &&
8252         Def->getOpcode() != AMDGPU::S_AND_B64)
8253       return false;
8254 
8255     int64_t Mask;
8256     const auto isMask = [&Mask, SrcSize](const MachineOperand *MO) -> bool {
8257       if (MO->isImm())
8258         Mask = MO->getImm();
8259       else if (!getFoldableImm(MO, Mask))
8260         return false;
8261       Mask &= maxUIntN(SrcSize);
8262       return isPowerOf2_64(Mask);
8263     };
8264 
8265     MachineOperand *SrcOp = &Def->getOperand(1);
8266     if (isMask(SrcOp))
8267       SrcOp = &Def->getOperand(2);
8268     else if (isMask(&Def->getOperand(2)))
8269       SrcOp = &Def->getOperand(1);
8270     else
8271       return false;
8272 
8273     unsigned BitNo = countTrailingZeros((uint64_t)Mask);
8274     if (IsSigned && BitNo == SrcSize - 1)
8275       return false;
8276 
8277     ExpectedValue <<= BitNo;
8278 
8279     bool IsReversedCC = false;
8280     if (CmpValue != ExpectedValue) {
8281       if (!IsReversible)
8282         return false;
8283       IsReversedCC = CmpValue == (ExpectedValue ^ Mask);
8284       if (!IsReversedCC)
8285         return false;
8286     }
8287 
8288     Register DefReg = Def->getOperand(0).getReg();
8289     if (IsReversedCC && !MRI->hasOneNonDBGUse(DefReg))
8290       return false;
8291 
8292     for (auto I = std::next(Def->getIterator()), E = CmpInstr.getIterator();
8293          I != E; ++I) {
8294       if (I->modifiesRegister(AMDGPU::SCC, &RI) ||
8295           I->killsRegister(AMDGPU::SCC, &RI))
8296         return false;
8297     }
8298 
8299     MachineOperand *SccDef = Def->findRegisterDefOperand(AMDGPU::SCC);
8300     SccDef->setIsDead(false);
8301     CmpInstr.eraseFromParent();
8302 
8303     if (!MRI->use_nodbg_empty(DefReg)) {
8304       assert(!IsReversedCC);
8305       return true;
8306     }
8307 
8308     // Replace AND with unused result with a S_BITCMP.
8309     MachineBasicBlock *MBB = Def->getParent();
8310 
8311     unsigned NewOpc = (SrcSize == 32) ? IsReversedCC ? AMDGPU::S_BITCMP0_B32
8312                                                      : AMDGPU::S_BITCMP1_B32
8313                                       : IsReversedCC ? AMDGPU::S_BITCMP0_B64
8314                                                      : AMDGPU::S_BITCMP1_B64;
8315 
8316     BuildMI(*MBB, Def, Def->getDebugLoc(), get(NewOpc))
8317       .add(*SrcOp)
8318       .addImm(BitNo);
8319     Def->eraseFromParent();
8320 
8321     return true;
8322   };
8323 
8324   switch (CmpInstr.getOpcode()) {
8325   default:
8326     break;
8327   case AMDGPU::S_CMP_EQ_U32:
8328   case AMDGPU::S_CMP_EQ_I32:
8329   case AMDGPU::S_CMPK_EQ_U32:
8330   case AMDGPU::S_CMPK_EQ_I32:
8331     return optimizeCmpAnd(1, 32, true, false);
8332   case AMDGPU::S_CMP_GE_U32:
8333   case AMDGPU::S_CMPK_GE_U32:
8334     return optimizeCmpAnd(1, 32, false, false);
8335   case AMDGPU::S_CMP_GE_I32:
8336   case AMDGPU::S_CMPK_GE_I32:
8337     return optimizeCmpAnd(1, 32, false, true);
8338   case AMDGPU::S_CMP_EQ_U64:
8339     return optimizeCmpAnd(1, 64, true, false);
8340   case AMDGPU::S_CMP_LG_U32:
8341   case AMDGPU::S_CMP_LG_I32:
8342   case AMDGPU::S_CMPK_LG_U32:
8343   case AMDGPU::S_CMPK_LG_I32:
8344     return optimizeCmpAnd(0, 32, true, false);
8345   case AMDGPU::S_CMP_GT_U32:
8346   case AMDGPU::S_CMPK_GT_U32:
8347     return optimizeCmpAnd(0, 32, false, false);
8348   case AMDGPU::S_CMP_GT_I32:
8349   case AMDGPU::S_CMPK_GT_I32:
8350     return optimizeCmpAnd(0, 32, false, true);
8351   case AMDGPU::S_CMP_LG_U64:
8352     return optimizeCmpAnd(0, 64, true, false);
8353   }
8354 
8355   return false;
8356 }
8357