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 "AMDGPUSubtarget.h"
17 #include "GCNHazardRecognizer.h"
18 #include "SIDefines.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Analysis/AliasAnalysis.h"
29 #include "llvm/Analysis/MemoryLocation.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineInstrBundle.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/RegisterScavenging.h"
42 #include "llvm/CodeGen/ScheduleDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetOpcodes.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/IR/DebugLoc.h"
47 #include "llvm/IR/DiagnosticInfo.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/InlineAsm.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/MC/MCInstrDesc.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MachineValueType.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Target/TargetMachine.h"
59 #include <cassert>
60 #include <cstdint>
61 #include <iterator>
62 #include <utility>
63 
64 using namespace llvm;
65 
66 #define GET_INSTRINFO_CTOR_DTOR
67 #include "AMDGPUGenInstrInfo.inc"
68 
69 namespace llvm {
70 namespace AMDGPU {
71 #define GET_D16ImageDimIntrinsics_IMPL
72 #define GET_ImageDimIntrinsicTable_IMPL
73 #define GET_RsrcIntrinsics_IMPL
74 #include "AMDGPUGenSearchableTables.inc"
75 }
76 }
77 
78 
79 // Must be at least 4 to be able to branch over minimum unconditional branch
80 // code. This is only for making it possible to write reasonably small tests for
81 // long branches.
82 static cl::opt<unsigned>
83 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
84                  cl::desc("Restrict range of branch instructions (DEBUG)"));
85 
86 SIInstrInfo::SIInstrInfo(const GCNSubtarget &ST)
87   : AMDGPUGenInstrInfo(AMDGPU::ADJCALLSTACKUP, AMDGPU::ADJCALLSTACKDOWN),
88     RI(ST), ST(ST) {}
89 
90 //===----------------------------------------------------------------------===//
91 // TargetInstrInfo callbacks
92 //===----------------------------------------------------------------------===//
93 
94 static unsigned getNumOperandsNoGlue(SDNode *Node) {
95   unsigned N = Node->getNumOperands();
96   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
97     --N;
98   return N;
99 }
100 
101 /// Returns true if both nodes have the same value for the given
102 ///        operand \p Op, or if both nodes do not have this operand.
103 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
104   unsigned Opc0 = N0->getMachineOpcode();
105   unsigned Opc1 = N1->getMachineOpcode();
106 
107   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
108   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
109 
110   if (Op0Idx == -1 && Op1Idx == -1)
111     return true;
112 
113 
114   if ((Op0Idx == -1 && Op1Idx != -1) ||
115       (Op1Idx == -1 && Op0Idx != -1))
116     return false;
117 
118   // getNamedOperandIdx returns the index for the MachineInstr's operands,
119   // which includes the result as the first operand. We are indexing into the
120   // MachineSDNode's operands, so we need to skip the result operand to get
121   // the real index.
122   --Op0Idx;
123   --Op1Idx;
124 
125   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
126 }
127 
128 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
129                                                     AliasAnalysis *AA) const {
130   // TODO: The generic check fails for VALU instructions that should be
131   // rematerializable due to implicit reads of exec. We really want all of the
132   // generic logic for this except for this.
133   switch (MI.getOpcode()) {
134   case AMDGPU::V_MOV_B32_e32:
135   case AMDGPU::V_MOV_B32_e64:
136   case AMDGPU::V_MOV_B64_PSEUDO:
137     // No implicit operands.
138     return MI.getNumOperands() == MI.getDesc().getNumOperands();
139   default:
140     return false;
141   }
142 }
143 
144 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
145                                           int64_t &Offset0,
146                                           int64_t &Offset1) const {
147   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
148     return false;
149 
150   unsigned Opc0 = Load0->getMachineOpcode();
151   unsigned Opc1 = Load1->getMachineOpcode();
152 
153   // Make sure both are actually loads.
154   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
155     return false;
156 
157   if (isDS(Opc0) && isDS(Opc1)) {
158 
159     // FIXME: Handle this case:
160     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
161       return false;
162 
163     // Check base reg.
164     if (Load0->getOperand(0) != Load1->getOperand(0))
165       return false;
166 
167     // Skip read2 / write2 variants for simplicity.
168     // TODO: We should report true if the used offsets are adjacent (excluded
169     // st64 versions).
170     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
171         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
172       return false;
173 
174     Offset0 = cast<ConstantSDNode>(Load0->getOperand(1))->getZExtValue();
175     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getZExtValue();
176     return true;
177   }
178 
179   if (isSMRD(Opc0) && isSMRD(Opc1)) {
180     // Skip time and cache invalidation instructions.
181     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::sbase) == -1 ||
182         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::sbase) == -1)
183       return false;
184 
185     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
186 
187     // Check base reg.
188     if (Load0->getOperand(0) != Load1->getOperand(0))
189       return false;
190 
191     const ConstantSDNode *Load0Offset =
192         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
193     const ConstantSDNode *Load1Offset =
194         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
195 
196     if (!Load0Offset || !Load1Offset)
197       return false;
198 
199     Offset0 = Load0Offset->getZExtValue();
200     Offset1 = Load1Offset->getZExtValue();
201     return true;
202   }
203 
204   // MUBUF and MTBUF can access the same addresses.
205   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
206 
207     // MUBUF and MTBUF have vaddr at different indices.
208     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
209         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
210         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
211       return false;
212 
213     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
214     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
215 
216     if (OffIdx0 == -1 || OffIdx1 == -1)
217       return false;
218 
219     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
220     // include the output in the operand list, but SDNodes don't, we need to
221     // subtract the index by one.
222     --OffIdx0;
223     --OffIdx1;
224 
225     SDValue Off0 = Load0->getOperand(OffIdx0);
226     SDValue Off1 = Load1->getOperand(OffIdx1);
227 
228     // The offset might be a FrameIndexSDNode.
229     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
230       return false;
231 
232     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
233     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
234     return true;
235   }
236 
237   return false;
238 }
239 
240 static bool isStride64(unsigned Opc) {
241   switch (Opc) {
242   case AMDGPU::DS_READ2ST64_B32:
243   case AMDGPU::DS_READ2ST64_B64:
244   case AMDGPU::DS_WRITE2ST64_B32:
245   case AMDGPU::DS_WRITE2ST64_B64:
246     return true;
247   default:
248     return false;
249   }
250 }
251 
252 bool SIInstrInfo::getMemOperandWithOffset(MachineInstr &LdSt,
253                                           MachineOperand *&BaseOp,
254                                           int64_t &Offset,
255                                           const TargetRegisterInfo *TRI) const {
256   unsigned Opc = LdSt.getOpcode();
257 
258   if (isDS(LdSt)) {
259     const MachineOperand *OffsetImm =
260         getNamedOperand(LdSt, AMDGPU::OpName::offset);
261     if (OffsetImm) {
262       // Normal, single offset LDS instruction.
263       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
264       // TODO: ds_consume/ds_append use M0 for the base address. Is it safe to
265       // report that here?
266       if (!BaseOp)
267         return false;
268 
269       Offset = OffsetImm->getImm();
270       assert(BaseOp->isReg() && "getMemOperandWithOffset only supports base "
271                                 "operands of type register.");
272       return true;
273     }
274 
275     // The 2 offset instructions use offset0 and offset1 instead. We can treat
276     // these as a load with a single offset if the 2 offsets are consecutive. We
277     // will use this for some partially aligned loads.
278     const MachineOperand *Offset0Imm =
279         getNamedOperand(LdSt, AMDGPU::OpName::offset0);
280     const MachineOperand *Offset1Imm =
281         getNamedOperand(LdSt, AMDGPU::OpName::offset1);
282 
283     uint8_t Offset0 = Offset0Imm->getImm();
284     uint8_t Offset1 = Offset1Imm->getImm();
285 
286     if (Offset1 > Offset0 && Offset1 - Offset0 == 1) {
287       // Each of these offsets is in element sized units, so we need to convert
288       // to bytes of the individual reads.
289 
290       unsigned EltSize;
291       if (LdSt.mayLoad())
292         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, 0)) / 16;
293       else {
294         assert(LdSt.mayStore());
295         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
296         EltSize = TRI->getRegSizeInBits(*getOpRegClass(LdSt, Data0Idx)) / 8;
297       }
298 
299       if (isStride64(Opc))
300         EltSize *= 64;
301 
302       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::addr);
303       Offset = EltSize * Offset0;
304       assert(BaseOp->isReg() && "getMemOperandWithOffset only supports base "
305                                 "operands of type register.");
306       return true;
307     }
308 
309     return false;
310   }
311 
312   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
313     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
314     if (SOffset && SOffset->isReg())
315       return false;
316 
317     MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
318     if (!AddrReg)
319       return false;
320 
321     const MachineOperand *OffsetImm =
322         getNamedOperand(LdSt, AMDGPU::OpName::offset);
323     BaseOp = AddrReg;
324     Offset = OffsetImm->getImm();
325 
326     if (SOffset) // soffset can be an inline immediate.
327       Offset += SOffset->getImm();
328 
329     assert(BaseOp->isReg() && "getMemOperandWithOffset only supports base "
330                               "operands of type register.");
331     return true;
332   }
333 
334   if (isSMRD(LdSt)) {
335     const MachineOperand *OffsetImm =
336         getNamedOperand(LdSt, AMDGPU::OpName::offset);
337     if (!OffsetImm)
338       return false;
339 
340     MachineOperand *SBaseReg = getNamedOperand(LdSt, AMDGPU::OpName::sbase);
341     BaseOp = SBaseReg;
342     Offset = OffsetImm->getImm();
343     assert(BaseOp->isReg() && "getMemOperandWithOffset only supports base "
344                               "operands of type register.");
345     return true;
346   }
347 
348   if (isFLAT(LdSt)) {
349     MachineOperand *VAddr = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
350     if (VAddr) {
351       // Can't analyze 2 offsets.
352       if (getNamedOperand(LdSt, AMDGPU::OpName::saddr))
353         return false;
354 
355       BaseOp = VAddr;
356     } else {
357       // scratch instructions have either vaddr or saddr.
358       BaseOp = getNamedOperand(LdSt, AMDGPU::OpName::saddr);
359     }
360 
361     Offset = getNamedOperand(LdSt, AMDGPU::OpName::offset)->getImm();
362     assert(BaseOp->isReg() && "getMemOperandWithOffset only supports base "
363                               "operands of type register.");
364     return true;
365   }
366 
367   return false;
368 }
369 
370 static bool memOpsHaveSameBasePtr(const MachineInstr &MI1,
371                                   const MachineOperand &BaseOp1,
372                                   const MachineInstr &MI2,
373                                   const MachineOperand &BaseOp2) {
374   // Support only base operands with base registers.
375   // Note: this could be extended to support FI operands.
376   if (!BaseOp1.isReg() || !BaseOp2.isReg())
377     return false;
378 
379   if (BaseOp1.isIdenticalTo(BaseOp2))
380     return true;
381 
382   if (!MI1.hasOneMemOperand() || !MI2.hasOneMemOperand())
383     return false;
384 
385   auto MO1 = *MI1.memoperands_begin();
386   auto MO2 = *MI2.memoperands_begin();
387   if (MO1->getAddrSpace() != MO2->getAddrSpace())
388     return false;
389 
390   auto Base1 = MO1->getValue();
391   auto Base2 = MO2->getValue();
392   if (!Base1 || !Base2)
393     return false;
394   const MachineFunction &MF = *MI1.getParent()->getParent();
395   const DataLayout &DL = MF.getFunction().getParent()->getDataLayout();
396   Base1 = GetUnderlyingObject(Base1, DL);
397   Base2 = GetUnderlyingObject(Base1, DL);
398 
399   if (isa<UndefValue>(Base1) || isa<UndefValue>(Base2))
400     return false;
401 
402   return Base1 == Base2;
403 }
404 
405 bool SIInstrInfo::shouldClusterMemOps(MachineOperand &BaseOp1,
406                                       MachineOperand &BaseOp2,
407                                       unsigned NumLoads) const {
408   MachineInstr &FirstLdSt = *BaseOp1.getParent();
409   MachineInstr &SecondLdSt = *BaseOp2.getParent();
410 
411   if (!memOpsHaveSameBasePtr(FirstLdSt, BaseOp1, SecondLdSt, BaseOp2))
412     return false;
413 
414   const MachineOperand *FirstDst = nullptr;
415   const MachineOperand *SecondDst = nullptr;
416 
417   if ((isMUBUF(FirstLdSt) && isMUBUF(SecondLdSt)) ||
418       (isMTBUF(FirstLdSt) && isMTBUF(SecondLdSt)) ||
419       (isFLAT(FirstLdSt) && isFLAT(SecondLdSt))) {
420     const unsigned MaxGlobalLoadCluster = 6;
421     if (NumLoads > MaxGlobalLoadCluster)
422       return false;
423 
424     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdata);
425     if (!FirstDst)
426       FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
427     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdata);
428     if (!SecondDst)
429       SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
430   } else if (isSMRD(FirstLdSt) && isSMRD(SecondLdSt)) {
431     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::sdst);
432     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::sdst);
433   } else if (isDS(FirstLdSt) && isDS(SecondLdSt)) {
434     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
435     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
436   }
437 
438   if (!FirstDst || !SecondDst)
439     return false;
440 
441   // Try to limit clustering based on the total number of bytes loaded
442   // rather than the number of instructions.  This is done to help reduce
443   // register pressure.  The method used is somewhat inexact, though,
444   // because it assumes that all loads in the cluster will load the
445   // same number of bytes as FirstLdSt.
446 
447   // The unit of this value is bytes.
448   // FIXME: This needs finer tuning.
449   unsigned LoadClusterThreshold = 16;
450 
451   const MachineRegisterInfo &MRI =
452       FirstLdSt.getParent()->getParent()->getRegInfo();
453   const TargetRegisterClass *DstRC = MRI.getRegClass(FirstDst->getReg());
454 
455   return (NumLoads * (RI.getRegSizeInBits(*DstRC) / 8)) <= LoadClusterThreshold;
456 }
457 
458 // FIXME: This behaves strangely. If, for example, you have 32 load + stores,
459 // the first 16 loads will be interleaved with the stores, and the next 16 will
460 // be clustered as expected. It should really split into 2 16 store batches.
461 //
462 // Loads are clustered until this returns false, rather than trying to schedule
463 // groups of stores. This also means we have to deal with saying different
464 // address space loads should be clustered, and ones which might cause bank
465 // conflicts.
466 //
467 // This might be deprecated so it might not be worth that much effort to fix.
468 bool SIInstrInfo::shouldScheduleLoadsNear(SDNode *Load0, SDNode *Load1,
469                                           int64_t Offset0, int64_t Offset1,
470                                           unsigned NumLoads) const {
471   assert(Offset1 > Offset0 &&
472          "Second offset should be larger than first offset!");
473   // If we have less than 16 loads in a row, and the offsets are within 64
474   // bytes, then schedule together.
475 
476   // A cacheline is 64 bytes (for global memory).
477   return (NumLoads <= 16 && (Offset1 - Offset0) < 64);
478 }
479 
480 static void reportIllegalCopy(const SIInstrInfo *TII, MachineBasicBlock &MBB,
481                               MachineBasicBlock::iterator MI,
482                               const DebugLoc &DL, unsigned DestReg,
483                               unsigned SrcReg, bool KillSrc) {
484   MachineFunction *MF = MBB.getParent();
485   DiagnosticInfoUnsupported IllegalCopy(MF->getFunction(),
486                                         "illegal SGPR to VGPR copy",
487                                         DL, DS_Error);
488   LLVMContext &C = MF->getFunction().getContext();
489   C.diagnose(IllegalCopy);
490 
491   BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_ILLEGAL_COPY), DestReg)
492     .addReg(SrcReg, getKillRegState(KillSrc));
493 }
494 
495 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
496                               MachineBasicBlock::iterator MI,
497                               const DebugLoc &DL, unsigned DestReg,
498                               unsigned SrcReg, bool KillSrc) const {
499   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
500 
501   if (RC == &AMDGPU::VGPR_32RegClass) {
502     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
503            AMDGPU::SReg_32RegClass.contains(SrcReg));
504     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
505       .addReg(SrcReg, getKillRegState(KillSrc));
506     return;
507   }
508 
509   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
510       RC == &AMDGPU::SReg_32RegClass) {
511     if (SrcReg == AMDGPU::SCC) {
512       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
513           .addImm(-1)
514           .addImm(0);
515       return;
516     }
517 
518     if (!AMDGPU::SReg_32RegClass.contains(SrcReg)) {
519       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
520       return;
521     }
522 
523     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
524             .addReg(SrcReg, getKillRegState(KillSrc));
525     return;
526   }
527 
528   if (RC == &AMDGPU::SReg_64RegClass) {
529     if (DestReg == AMDGPU::VCC) {
530       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
531         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
532           .addReg(SrcReg, getKillRegState(KillSrc));
533       } else {
534         // FIXME: Hack until VReg_1 removed.
535         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
536         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
537           .addImm(0)
538           .addReg(SrcReg, getKillRegState(KillSrc));
539       }
540 
541       return;
542     }
543 
544     if (!AMDGPU::SReg_64RegClass.contains(SrcReg)) {
545       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
546       return;
547     }
548 
549     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
550             .addReg(SrcReg, getKillRegState(KillSrc));
551     return;
552   }
553 
554   if (DestReg == AMDGPU::SCC) {
555     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
556     BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
557       .addReg(SrcReg, getKillRegState(KillSrc))
558       .addImm(0);
559     return;
560   }
561 
562   unsigned EltSize = 4;
563   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
564   if (RI.isSGPRClass(RC)) {
565     if (RI.getRegSizeInBits(*RC) > 32) {
566       Opcode =  AMDGPU::S_MOV_B64;
567       EltSize = 8;
568     } else {
569       Opcode = AMDGPU::S_MOV_B32;
570       EltSize = 4;
571     }
572 
573     if (!RI.isSGPRClass(RI.getPhysRegClass(SrcReg))) {
574       reportIllegalCopy(this, MBB, MI, DL, DestReg, SrcReg, KillSrc);
575       return;
576     }
577   }
578 
579   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
580   bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
581 
582   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
583     unsigned SubIdx;
584     if (Forward)
585       SubIdx = SubIndices[Idx];
586     else
587       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
588 
589     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
590       get(Opcode), RI.getSubReg(DestReg, SubIdx));
591 
592     Builder.addReg(RI.getSubReg(SrcReg, SubIdx));
593 
594     if (Idx == 0)
595       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
596 
597     bool UseKill = KillSrc && Idx == SubIndices.size() - 1;
598     Builder.addReg(SrcReg, getKillRegState(UseKill) | RegState::Implicit);
599   }
600 }
601 
602 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
603   int NewOpc;
604 
605   // Try to map original to commuted opcode
606   NewOpc = AMDGPU::getCommuteRev(Opcode);
607   if (NewOpc != -1)
608     // Check if the commuted (REV) opcode exists on the target.
609     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
610 
611   // Try to map commuted to original opcode
612   NewOpc = AMDGPU::getCommuteOrig(Opcode);
613   if (NewOpc != -1)
614     // Check if the original (non-REV) opcode exists on the target.
615     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
616 
617   return Opcode;
618 }
619 
620 void SIInstrInfo::materializeImmediate(MachineBasicBlock &MBB,
621                                        MachineBasicBlock::iterator MI,
622                                        const DebugLoc &DL, unsigned DestReg,
623                                        int64_t Value) const {
624   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
625   const TargetRegisterClass *RegClass = MRI.getRegClass(DestReg);
626   if (RegClass == &AMDGPU::SReg_32RegClass ||
627       RegClass == &AMDGPU::SGPR_32RegClass ||
628       RegClass == &AMDGPU::SReg_32_XM0RegClass ||
629       RegClass == &AMDGPU::SReg_32_XM0_XEXECRegClass) {
630     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
631       .addImm(Value);
632     return;
633   }
634 
635   if (RegClass == &AMDGPU::SReg_64RegClass ||
636       RegClass == &AMDGPU::SGPR_64RegClass ||
637       RegClass == &AMDGPU::SReg_64_XEXECRegClass) {
638     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
639       .addImm(Value);
640     return;
641   }
642 
643   if (RegClass == &AMDGPU::VGPR_32RegClass) {
644     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
645       .addImm(Value);
646     return;
647   }
648   if (RegClass == &AMDGPU::VReg_64RegClass) {
649     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO), DestReg)
650       .addImm(Value);
651     return;
652   }
653 
654   unsigned EltSize = 4;
655   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
656   if (RI.isSGPRClass(RegClass)) {
657     if (RI.getRegSizeInBits(*RegClass) > 32) {
658       Opcode =  AMDGPU::S_MOV_B64;
659       EltSize = 8;
660     } else {
661       Opcode = AMDGPU::S_MOV_B32;
662       EltSize = 4;
663     }
664   }
665 
666   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RegClass, EltSize);
667   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
668     int64_t IdxValue = Idx == 0 ? Value : 0;
669 
670     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
671       get(Opcode), RI.getSubReg(DestReg, Idx));
672     Builder.addImm(IdxValue);
673   }
674 }
675 
676 const TargetRegisterClass *
677 SIInstrInfo::getPreferredSelectRegClass(unsigned Size) const {
678   return &AMDGPU::VGPR_32RegClass;
679 }
680 
681 void SIInstrInfo::insertVectorSelect(MachineBasicBlock &MBB,
682                                      MachineBasicBlock::iterator I,
683                                      const DebugLoc &DL, unsigned DstReg,
684                                      ArrayRef<MachineOperand> Cond,
685                                      unsigned TrueReg,
686                                      unsigned FalseReg) const {
687   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
688   assert(MRI.getRegClass(DstReg) == &AMDGPU::VGPR_32RegClass &&
689          "Not a VGPR32 reg");
690 
691   if (Cond.size() == 1) {
692     unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
693     BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
694       .add(Cond[0]);
695     BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
696       .addImm(0)
697       .addReg(FalseReg)
698       .addImm(0)
699       .addReg(TrueReg)
700       .addReg(SReg);
701   } else if (Cond.size() == 2) {
702     assert(Cond[0].isImm() && "Cond[0] is not an immediate");
703     switch (Cond[0].getImm()) {
704     case SIInstrInfo::SCC_TRUE: {
705       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
706       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
707         .addImm(-1)
708         .addImm(0);
709       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
710         .addImm(0)
711         .addReg(FalseReg)
712         .addImm(0)
713         .addReg(TrueReg)
714         .addReg(SReg);
715       break;
716     }
717     case SIInstrInfo::SCC_FALSE: {
718       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
719       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
720         .addImm(0)
721         .addImm(-1);
722       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
723         .addImm(0)
724         .addReg(FalseReg)
725         .addImm(0)
726         .addReg(TrueReg)
727         .addReg(SReg);
728       break;
729     }
730     case SIInstrInfo::VCCNZ: {
731       MachineOperand RegOp = Cond[1];
732       RegOp.setImplicit(false);
733       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
734       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
735         .add(RegOp);
736       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
737           .addImm(0)
738           .addReg(FalseReg)
739           .addImm(0)
740           .addReg(TrueReg)
741           .addReg(SReg);
742       break;
743     }
744     case SIInstrInfo::VCCZ: {
745       MachineOperand RegOp = Cond[1];
746       RegOp.setImplicit(false);
747       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
748       BuildMI(MBB, I, DL, get(AMDGPU::COPY), SReg)
749         .add(RegOp);
750       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
751           .addImm(0)
752           .addReg(TrueReg)
753           .addImm(0)
754           .addReg(FalseReg)
755           .addReg(SReg);
756       break;
757     }
758     case SIInstrInfo::EXECNZ: {
759       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
760       unsigned SReg2 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
761       BuildMI(MBB, I, DL, get(AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
762         .addImm(0);
763       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
764         .addImm(-1)
765         .addImm(0);
766       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
767         .addImm(0)
768         .addReg(FalseReg)
769         .addImm(0)
770         .addReg(TrueReg)
771         .addReg(SReg);
772       break;
773     }
774     case SIInstrInfo::EXECZ: {
775       unsigned SReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
776       unsigned SReg2 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
777       BuildMI(MBB, I, DL, get(AMDGPU::S_OR_SAVEEXEC_B64), SReg2)
778         .addImm(0);
779       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), SReg)
780         .addImm(0)
781         .addImm(-1);
782       BuildMI(MBB, I, DL, get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
783         .addImm(0)
784         .addReg(FalseReg)
785         .addImm(0)
786         .addReg(TrueReg)
787         .addReg(SReg);
788       llvm_unreachable("Unhandled branch predicate EXECZ");
789       break;
790     }
791     default:
792       llvm_unreachable("invalid branch predicate");
793     }
794   } else {
795     llvm_unreachable("Can only handle Cond size 1 or 2");
796   }
797 }
798 
799 unsigned SIInstrInfo::insertEQ(MachineBasicBlock *MBB,
800                                MachineBasicBlock::iterator I,
801                                const DebugLoc &DL,
802                                unsigned SrcReg, int Value) const {
803   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
804   unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
805   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_EQ_I32_e64), Reg)
806     .addImm(Value)
807     .addReg(SrcReg);
808 
809   return Reg;
810 }
811 
812 unsigned SIInstrInfo::insertNE(MachineBasicBlock *MBB,
813                                MachineBasicBlock::iterator I,
814                                const DebugLoc &DL,
815                                unsigned SrcReg, int Value) const {
816   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
817   unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
818   BuildMI(*MBB, I, DL, get(AMDGPU::V_CMP_NE_I32_e64), Reg)
819     .addImm(Value)
820     .addReg(SrcReg);
821 
822   return Reg;
823 }
824 
825 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
826 
827   if (RI.getRegSizeInBits(*DstRC) == 32) {
828     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
829   } else if (RI.getRegSizeInBits(*DstRC) == 64 && RI.isSGPRClass(DstRC)) {
830     return AMDGPU::S_MOV_B64;
831   } else if (RI.getRegSizeInBits(*DstRC) == 64 && !RI.isSGPRClass(DstRC)) {
832     return  AMDGPU::V_MOV_B64_PSEUDO;
833   }
834   return AMDGPU::COPY;
835 }
836 
837 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
838   switch (Size) {
839   case 4:
840     return AMDGPU::SI_SPILL_S32_SAVE;
841   case 8:
842     return AMDGPU::SI_SPILL_S64_SAVE;
843   case 16:
844     return AMDGPU::SI_SPILL_S128_SAVE;
845   case 32:
846     return AMDGPU::SI_SPILL_S256_SAVE;
847   case 64:
848     return AMDGPU::SI_SPILL_S512_SAVE;
849   default:
850     llvm_unreachable("unknown register size");
851   }
852 }
853 
854 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
855   switch (Size) {
856   case 4:
857     return AMDGPU::SI_SPILL_V32_SAVE;
858   case 8:
859     return AMDGPU::SI_SPILL_V64_SAVE;
860   case 12:
861     return AMDGPU::SI_SPILL_V96_SAVE;
862   case 16:
863     return AMDGPU::SI_SPILL_V128_SAVE;
864   case 32:
865     return AMDGPU::SI_SPILL_V256_SAVE;
866   case 64:
867     return AMDGPU::SI_SPILL_V512_SAVE;
868   default:
869     llvm_unreachable("unknown register size");
870   }
871 }
872 
873 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
874                                       MachineBasicBlock::iterator MI,
875                                       unsigned SrcReg, bool isKill,
876                                       int FrameIndex,
877                                       const TargetRegisterClass *RC,
878                                       const TargetRegisterInfo *TRI) const {
879   MachineFunction *MF = MBB.getParent();
880   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
881   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
882   const DebugLoc &DL = MBB.findDebugLoc(MI);
883 
884   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
885   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
886   MachinePointerInfo PtrInfo
887     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
888   MachineMemOperand *MMO
889     = MF->getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
890                                Size, Align);
891   unsigned SpillSize = TRI->getSpillSize(*RC);
892 
893   if (RI.isSGPRClass(RC)) {
894     MFI->setHasSpilledSGPRs();
895 
896     // We are only allowed to create one new instruction when spilling
897     // registers, so we need to use pseudo instruction for spilling SGPRs.
898     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(SpillSize));
899 
900     // The SGPR spill/restore instructions only work on number sgprs, so we need
901     // to make sure we are using the correct register class.
902     if (TargetRegisterInfo::isVirtualRegister(SrcReg) && SpillSize == 4) {
903       MachineRegisterInfo &MRI = MF->getRegInfo();
904       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
905     }
906 
907     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc)
908       .addReg(SrcReg, getKillRegState(isKill)) // data
909       .addFrameIndex(FrameIndex)               // addr
910       .addMemOperand(MMO)
911       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
912       .addReg(MFI->getFrameOffsetReg(), RegState::Implicit);
913     // Add the scratch resource registers as implicit uses because we may end up
914     // needing them, and need to ensure that the reserved registers are
915     // correctly handled.
916 
917     FrameInfo.setStackID(FrameIndex, SIStackID::SGPR_SPILL);
918     if (ST.hasScalarStores()) {
919       // m0 is used for offset to scalar stores if used to spill.
920       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine | RegState::Dead);
921     }
922 
923     return;
924   }
925 
926   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
927 
928   unsigned Opcode = getVGPRSpillSaveOpcode(SpillSize);
929   MFI->setHasSpilledVGPRs();
930   BuildMI(MBB, MI, DL, get(Opcode))
931     .addReg(SrcReg, getKillRegState(isKill)) // data
932     .addFrameIndex(FrameIndex)               // addr
933     .addReg(MFI->getScratchRSrcReg())        // scratch_rsrc
934     .addReg(MFI->getFrameOffsetReg())        // scratch_offset
935     .addImm(0)                               // offset
936     .addMemOperand(MMO);
937 }
938 
939 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
940   switch (Size) {
941   case 4:
942     return AMDGPU::SI_SPILL_S32_RESTORE;
943   case 8:
944     return AMDGPU::SI_SPILL_S64_RESTORE;
945   case 16:
946     return AMDGPU::SI_SPILL_S128_RESTORE;
947   case 32:
948     return AMDGPU::SI_SPILL_S256_RESTORE;
949   case 64:
950     return AMDGPU::SI_SPILL_S512_RESTORE;
951   default:
952     llvm_unreachable("unknown register size");
953   }
954 }
955 
956 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
957   switch (Size) {
958   case 4:
959     return AMDGPU::SI_SPILL_V32_RESTORE;
960   case 8:
961     return AMDGPU::SI_SPILL_V64_RESTORE;
962   case 12:
963     return AMDGPU::SI_SPILL_V96_RESTORE;
964   case 16:
965     return AMDGPU::SI_SPILL_V128_RESTORE;
966   case 32:
967     return AMDGPU::SI_SPILL_V256_RESTORE;
968   case 64:
969     return AMDGPU::SI_SPILL_V512_RESTORE;
970   default:
971     llvm_unreachable("unknown register size");
972   }
973 }
974 
975 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
976                                        MachineBasicBlock::iterator MI,
977                                        unsigned DestReg, int FrameIndex,
978                                        const TargetRegisterClass *RC,
979                                        const TargetRegisterInfo *TRI) const {
980   MachineFunction *MF = MBB.getParent();
981   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
982   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
983   const DebugLoc &DL = MBB.findDebugLoc(MI);
984   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
985   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
986   unsigned SpillSize = TRI->getSpillSize(*RC);
987 
988   MachinePointerInfo PtrInfo
989     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
990 
991   MachineMemOperand *MMO = MF->getMachineMemOperand(
992     PtrInfo, MachineMemOperand::MOLoad, Size, Align);
993 
994   if (RI.isSGPRClass(RC)) {
995     MFI->setHasSpilledSGPRs();
996 
997     // FIXME: Maybe this should not include a memoperand because it will be
998     // lowered to non-memory instructions.
999     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(SpillSize));
1000     if (TargetRegisterInfo::isVirtualRegister(DestReg) && SpillSize == 4) {
1001       MachineRegisterInfo &MRI = MF->getRegInfo();
1002       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0RegClass);
1003     }
1004 
1005     FrameInfo.setStackID(FrameIndex, SIStackID::SGPR_SPILL);
1006     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc, DestReg)
1007       .addFrameIndex(FrameIndex) // addr
1008       .addMemOperand(MMO)
1009       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
1010       .addReg(MFI->getFrameOffsetReg(), RegState::Implicit);
1011 
1012     if (ST.hasScalarStores()) {
1013       // m0 is used for offset to scalar stores if used to spill.
1014       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine | RegState::Dead);
1015     }
1016 
1017     return;
1018   }
1019 
1020   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
1021 
1022   unsigned Opcode = getVGPRSpillRestoreOpcode(SpillSize);
1023   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
1024     .addFrameIndex(FrameIndex)        // vaddr
1025     .addReg(MFI->getScratchRSrcReg()) // scratch_rsrc
1026     .addReg(MFI->getFrameOffsetReg()) // scratch_offset
1027     .addImm(0)                        // offset
1028     .addMemOperand(MMO);
1029 }
1030 
1031 /// \param @Offset Offset in bytes of the FrameIndex being spilled
1032 unsigned SIInstrInfo::calculateLDSSpillAddress(
1033     MachineBasicBlock &MBB, MachineInstr &MI, RegScavenger *RS, unsigned TmpReg,
1034     unsigned FrameOffset, unsigned Size) const {
1035   MachineFunction *MF = MBB.getParent();
1036   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1037   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
1038   const DebugLoc &DL = MBB.findDebugLoc(MI);
1039   unsigned WorkGroupSize = MFI->getMaxFlatWorkGroupSize();
1040   unsigned WavefrontSize = ST.getWavefrontSize();
1041 
1042   unsigned TIDReg = MFI->getTIDReg();
1043   if (!MFI->hasCalculatedTID()) {
1044     MachineBasicBlock &Entry = MBB.getParent()->front();
1045     MachineBasicBlock::iterator Insert = Entry.front();
1046     const DebugLoc &DL = Insert->getDebugLoc();
1047 
1048     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass,
1049                                    *MF);
1050     if (TIDReg == AMDGPU::NoRegister)
1051       return TIDReg;
1052 
1053     if (!AMDGPU::isShader(MF->getFunction().getCallingConv()) &&
1054         WorkGroupSize > WavefrontSize) {
1055       unsigned TIDIGXReg
1056         = MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
1057       unsigned TIDIGYReg
1058         = MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
1059       unsigned TIDIGZReg
1060         = MFI->getPreloadedReg(AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
1061       unsigned InputPtrReg =
1062           MFI->getPreloadedReg(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1063       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
1064         if (!Entry.isLiveIn(Reg))
1065           Entry.addLiveIn(Reg);
1066       }
1067 
1068       RS->enterBasicBlock(Entry);
1069       // FIXME: Can we scavenge an SReg_64 and access the subregs?
1070       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
1071       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
1072       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
1073               .addReg(InputPtrReg)
1074               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
1075       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
1076               .addReg(InputPtrReg)
1077               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
1078 
1079       // NGROUPS.X * NGROUPS.Y
1080       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
1081               .addReg(STmp1)
1082               .addReg(STmp0);
1083       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
1084       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
1085               .addReg(STmp1)
1086               .addReg(TIDIGXReg);
1087       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
1088       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
1089               .addReg(STmp0)
1090               .addReg(TIDIGYReg)
1091               .addReg(TIDReg);
1092       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
1093       getAddNoCarry(Entry, Insert, DL, TIDReg)
1094         .addReg(TIDReg)
1095         .addReg(TIDIGZReg)
1096         .addImm(0); // clamp bit
1097     } else {
1098       // Get the wave id
1099       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
1100               TIDReg)
1101               .addImm(-1)
1102               .addImm(0);
1103 
1104       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
1105               TIDReg)
1106               .addImm(-1)
1107               .addReg(TIDReg);
1108     }
1109 
1110     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
1111             TIDReg)
1112             .addImm(2)
1113             .addReg(TIDReg);
1114     MFI->setTIDReg(TIDReg);
1115   }
1116 
1117   // Add FrameIndex to LDS offset
1118   unsigned LDSOffset = MFI->getLDSSize() + (FrameOffset * WorkGroupSize);
1119   getAddNoCarry(MBB, MI, DL, TmpReg)
1120     .addImm(LDSOffset)
1121     .addReg(TIDReg)
1122     .addImm(0); // clamp bit
1123 
1124   return TmpReg;
1125 }
1126 
1127 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
1128                                    MachineBasicBlock::iterator MI,
1129                                    int Count) const {
1130   DebugLoc DL = MBB.findDebugLoc(MI);
1131   while (Count > 0) {
1132     int Arg;
1133     if (Count >= 8)
1134       Arg = 7;
1135     else
1136       Arg = Count - 1;
1137     Count -= 8;
1138     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
1139             .addImm(Arg);
1140   }
1141 }
1142 
1143 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
1144                              MachineBasicBlock::iterator MI) const {
1145   insertWaitStates(MBB, MI, 1);
1146 }
1147 
1148 void SIInstrInfo::insertReturn(MachineBasicBlock &MBB) const {
1149   auto MF = MBB.getParent();
1150   SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1151 
1152   assert(Info->isEntryFunction());
1153 
1154   if (MBB.succ_empty()) {
1155     bool HasNoTerminator = MBB.getFirstTerminator() == MBB.end();
1156     if (HasNoTerminator) {
1157       if (Info->returnsVoid()) {
1158         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::S_ENDPGM)).addImm(0);
1159       } else {
1160         BuildMI(MBB, MBB.end(), DebugLoc(), get(AMDGPU::SI_RETURN_TO_EPILOG));
1161       }
1162     }
1163   }
1164 }
1165 
1166 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) {
1167   switch (MI.getOpcode()) {
1168   default: return 1; // FIXME: Do wait states equal cycles?
1169 
1170   case AMDGPU::S_NOP:
1171     return MI.getOperand(0).getImm() + 1;
1172   }
1173 }
1174 
1175 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1176   MachineBasicBlock &MBB = *MI.getParent();
1177   DebugLoc DL = MBB.findDebugLoc(MI);
1178   switch (MI.getOpcode()) {
1179   default: return TargetInstrInfo::expandPostRAPseudo(MI);
1180   case AMDGPU::S_MOV_B64_term:
1181     // This is only a terminator to get the correct spill code placement during
1182     // register allocation.
1183     MI.setDesc(get(AMDGPU::S_MOV_B64));
1184     break;
1185 
1186   case AMDGPU::S_XOR_B64_term:
1187     // This is only a terminator to get the correct spill code placement during
1188     // register allocation.
1189     MI.setDesc(get(AMDGPU::S_XOR_B64));
1190     break;
1191 
1192   case AMDGPU::S_ANDN2_B64_term:
1193     // This is only a terminator to get the correct spill code placement during
1194     // register allocation.
1195     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
1196     break;
1197 
1198   case AMDGPU::V_MOV_B64_PSEUDO: {
1199     unsigned Dst = MI.getOperand(0).getReg();
1200     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
1201     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
1202 
1203     const MachineOperand &SrcOp = MI.getOperand(1);
1204     // FIXME: Will this work for 64-bit floating point immediates?
1205     assert(!SrcOp.isFPImm());
1206     if (SrcOp.isImm()) {
1207       APInt Imm(64, SrcOp.getImm());
1208       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1209         .addImm(Imm.getLoBits(32).getZExtValue())
1210         .addReg(Dst, RegState::Implicit | RegState::Define);
1211       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1212         .addImm(Imm.getHiBits(32).getZExtValue())
1213         .addReg(Dst, RegState::Implicit | RegState::Define);
1214     } else {
1215       assert(SrcOp.isReg());
1216       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
1217         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
1218         .addReg(Dst, RegState::Implicit | RegState::Define);
1219       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
1220         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
1221         .addReg(Dst, RegState::Implicit | RegState::Define);
1222     }
1223     MI.eraseFromParent();
1224     break;
1225   }
1226   case AMDGPU::V_SET_INACTIVE_B32: {
1227     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1228       .addReg(AMDGPU::EXEC);
1229     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), MI.getOperand(0).getReg())
1230       .add(MI.getOperand(2));
1231     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1232       .addReg(AMDGPU::EXEC);
1233     MI.eraseFromParent();
1234     break;
1235   }
1236   case AMDGPU::V_SET_INACTIVE_B64: {
1237     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1238       .addReg(AMDGPU::EXEC);
1239     MachineInstr *Copy = BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B64_PSEUDO),
1240                                  MI.getOperand(0).getReg())
1241       .add(MI.getOperand(2));
1242     expandPostRAPseudo(*Copy);
1243     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOT_B64), AMDGPU::EXEC)
1244       .addReg(AMDGPU::EXEC);
1245     MI.eraseFromParent();
1246     break;
1247   }
1248   case AMDGPU::V_MOVRELD_B32_V1:
1249   case AMDGPU::V_MOVRELD_B32_V2:
1250   case AMDGPU::V_MOVRELD_B32_V4:
1251   case AMDGPU::V_MOVRELD_B32_V8:
1252   case AMDGPU::V_MOVRELD_B32_V16: {
1253     const MCInstrDesc &MovRelDesc = get(AMDGPU::V_MOVRELD_B32_e32);
1254     unsigned VecReg = MI.getOperand(0).getReg();
1255     bool IsUndef = MI.getOperand(1).isUndef();
1256     unsigned SubReg = AMDGPU::sub0 + MI.getOperand(3).getImm();
1257     assert(VecReg == MI.getOperand(1).getReg());
1258 
1259     MachineInstr *MovRel =
1260         BuildMI(MBB, MI, DL, MovRelDesc)
1261             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
1262             .add(MI.getOperand(2))
1263             .addReg(VecReg, RegState::ImplicitDefine)
1264             .addReg(VecReg,
1265                     RegState::Implicit | (IsUndef ? RegState::Undef : 0));
1266 
1267     const int ImpDefIdx =
1268         MovRelDesc.getNumOperands() + MovRelDesc.getNumImplicitUses();
1269     const int ImpUseIdx = ImpDefIdx + 1;
1270     MovRel->tieOperands(ImpDefIdx, ImpUseIdx);
1271 
1272     MI.eraseFromParent();
1273     break;
1274   }
1275   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
1276     MachineFunction &MF = *MBB.getParent();
1277     unsigned Reg = MI.getOperand(0).getReg();
1278     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
1279     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
1280 
1281     // Create a bundle so these instructions won't be re-ordered by the
1282     // post-RA scheduler.
1283     MIBundleBuilder Bundler(MBB, MI);
1284     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
1285 
1286     // Add 32-bit offset from this instruction to the start of the
1287     // constant data.
1288     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
1289                        .addReg(RegLo)
1290                        .add(MI.getOperand(1)));
1291 
1292     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
1293                                   .addReg(RegHi);
1294     if (MI.getOperand(2).getTargetFlags() == SIInstrInfo::MO_NONE)
1295       MIB.addImm(0);
1296     else
1297       MIB.add(MI.getOperand(2));
1298 
1299     Bundler.append(MIB);
1300     finalizeBundle(MBB, Bundler.begin());
1301 
1302     MI.eraseFromParent();
1303     break;
1304   }
1305   case AMDGPU::EXIT_WWM: {
1306     // This only gets its own opcode so that SIFixWWMLiveness can tell when WWM
1307     // is exited.
1308     MI.setDesc(get(AMDGPU::S_MOV_B64));
1309     break;
1310   }
1311   case TargetOpcode::BUNDLE: {
1312     if (!MI.mayLoad())
1313       return false;
1314 
1315     // If it is a load it must be a memory clause
1316     for (MachineBasicBlock::instr_iterator I = MI.getIterator();
1317          I->isBundledWithSucc(); ++I) {
1318       I->unbundleFromSucc();
1319       for (MachineOperand &MO : I->operands())
1320         if (MO.isReg())
1321           MO.setIsInternalRead(false);
1322     }
1323 
1324     MI.eraseFromParent();
1325     break;
1326   }
1327   }
1328   return true;
1329 }
1330 
1331 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
1332                                       MachineOperand &Src0,
1333                                       unsigned Src0OpName,
1334                                       MachineOperand &Src1,
1335                                       unsigned Src1OpName) const {
1336   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
1337   if (!Src0Mods)
1338     return false;
1339 
1340   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
1341   assert(Src1Mods &&
1342          "All commutable instructions have both src0 and src1 modifiers");
1343 
1344   int Src0ModsVal = Src0Mods->getImm();
1345   int Src1ModsVal = Src1Mods->getImm();
1346 
1347   Src1Mods->setImm(Src0ModsVal);
1348   Src0Mods->setImm(Src1ModsVal);
1349   return true;
1350 }
1351 
1352 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
1353                                              MachineOperand &RegOp,
1354                                              MachineOperand &NonRegOp) {
1355   unsigned Reg = RegOp.getReg();
1356   unsigned SubReg = RegOp.getSubReg();
1357   bool IsKill = RegOp.isKill();
1358   bool IsDead = RegOp.isDead();
1359   bool IsUndef = RegOp.isUndef();
1360   bool IsDebug = RegOp.isDebug();
1361 
1362   if (NonRegOp.isImm())
1363     RegOp.ChangeToImmediate(NonRegOp.getImm());
1364   else if (NonRegOp.isFI())
1365     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
1366   else
1367     return nullptr;
1368 
1369   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
1370   NonRegOp.setSubReg(SubReg);
1371 
1372   return &MI;
1373 }
1374 
1375 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
1376                                                   unsigned Src0Idx,
1377                                                   unsigned Src1Idx) const {
1378   assert(!NewMI && "this should never be used");
1379 
1380   unsigned Opc = MI.getOpcode();
1381   int CommutedOpcode = commuteOpcode(Opc);
1382   if (CommutedOpcode == -1)
1383     return nullptr;
1384 
1385   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
1386            static_cast<int>(Src0Idx) &&
1387          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
1388            static_cast<int>(Src1Idx) &&
1389          "inconsistency with findCommutedOpIndices");
1390 
1391   MachineOperand &Src0 = MI.getOperand(Src0Idx);
1392   MachineOperand &Src1 = MI.getOperand(Src1Idx);
1393 
1394   MachineInstr *CommutedMI = nullptr;
1395   if (Src0.isReg() && Src1.isReg()) {
1396     if (isOperandLegal(MI, Src1Idx, &Src0)) {
1397       // Be sure to copy the source modifiers to the right place.
1398       CommutedMI
1399         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
1400     }
1401 
1402   } else if (Src0.isReg() && !Src1.isReg()) {
1403     // src0 should always be able to support any operand type, so no need to
1404     // check operand legality.
1405     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
1406   } else if (!Src0.isReg() && Src1.isReg()) {
1407     if (isOperandLegal(MI, Src1Idx, &Src0))
1408       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
1409   } else {
1410     // FIXME: Found two non registers to commute. This does happen.
1411     return nullptr;
1412   }
1413 
1414   if (CommutedMI) {
1415     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
1416                         Src1, AMDGPU::OpName::src1_modifiers);
1417 
1418     CommutedMI->setDesc(get(CommutedOpcode));
1419   }
1420 
1421   return CommutedMI;
1422 }
1423 
1424 // This needs to be implemented because the source modifiers may be inserted
1425 // between the true commutable operands, and the base
1426 // TargetInstrInfo::commuteInstruction uses it.
1427 bool SIInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx0,
1428                                         unsigned &SrcOpIdx1) const {
1429   return findCommutedOpIndices(MI.getDesc(), SrcOpIdx0, SrcOpIdx1);
1430 }
1431 
1432 bool SIInstrInfo::findCommutedOpIndices(MCInstrDesc Desc, unsigned &SrcOpIdx0,
1433                                         unsigned &SrcOpIdx1) const {
1434   if (!Desc.isCommutable())
1435     return false;
1436 
1437   unsigned Opc = Desc.getOpcode();
1438   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1439   if (Src0Idx == -1)
1440     return false;
1441 
1442   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1443   if (Src1Idx == -1)
1444     return false;
1445 
1446   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1447 }
1448 
1449 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
1450                                         int64_t BrOffset) const {
1451   // BranchRelaxation should never have to check s_setpc_b64 because its dest
1452   // block is unanalyzable.
1453   assert(BranchOp != AMDGPU::S_SETPC_B64);
1454 
1455   // Convert to dwords.
1456   BrOffset /= 4;
1457 
1458   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
1459   // from the next instruction.
1460   BrOffset -= 1;
1461 
1462   return isIntN(BranchOffsetBits, BrOffset);
1463 }
1464 
1465 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
1466   const MachineInstr &MI) const {
1467   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
1468     // This would be a difficult analysis to perform, but can always be legal so
1469     // there's no need to analyze it.
1470     return nullptr;
1471   }
1472 
1473   return MI.getOperand(0).getMBB();
1474 }
1475 
1476 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
1477                                            MachineBasicBlock &DestBB,
1478                                            const DebugLoc &DL,
1479                                            int64_t BrOffset,
1480                                            RegScavenger *RS) const {
1481   assert(RS && "RegScavenger required for long branching");
1482   assert(MBB.empty() &&
1483          "new block should be inserted for expanding unconditional branch");
1484   assert(MBB.pred_size() == 1);
1485 
1486   MachineFunction *MF = MBB.getParent();
1487   MachineRegisterInfo &MRI = MF->getRegInfo();
1488 
1489   // FIXME: Virtual register workaround for RegScavenger not working with empty
1490   // blocks.
1491   unsigned PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1492 
1493   auto I = MBB.end();
1494 
1495   // We need to compute the offset relative to the instruction immediately after
1496   // s_getpc_b64. Insert pc arithmetic code before last terminator.
1497   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
1498 
1499   // TODO: Handle > 32-bit block address.
1500   if (BrOffset >= 0) {
1501     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
1502       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1503       .addReg(PCReg, 0, AMDGPU::sub0)
1504       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_FORWARD);
1505     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
1506       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1507       .addReg(PCReg, 0, AMDGPU::sub1)
1508       .addImm(0);
1509   } else {
1510     // Backwards branch.
1511     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
1512       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1513       .addReg(PCReg, 0, AMDGPU::sub0)
1514       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_BACKWARD);
1515     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
1516       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1517       .addReg(PCReg, 0, AMDGPU::sub1)
1518       .addImm(0);
1519   }
1520 
1521   // Insert the indirect branch after the other terminator.
1522   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
1523     .addReg(PCReg);
1524 
1525   // FIXME: If spilling is necessary, this will fail because this scavenger has
1526   // no emergency stack slots. It is non-trivial to spill in this situation,
1527   // because the restore code needs to be specially placed after the
1528   // jump. BranchRelaxation then needs to be made aware of the newly inserted
1529   // block.
1530   //
1531   // If a spill is needed for the pc register pair, we need to insert a spill
1532   // restore block right before the destination block, and insert a short branch
1533   // into the old destination block's fallthrough predecessor.
1534   // e.g.:
1535   //
1536   // s_cbranch_scc0 skip_long_branch:
1537   //
1538   // long_branch_bb:
1539   //   spill s[8:9]
1540   //   s_getpc_b64 s[8:9]
1541   //   s_add_u32 s8, s8, restore_bb
1542   //   s_addc_u32 s9, s9, 0
1543   //   s_setpc_b64 s[8:9]
1544   //
1545   // skip_long_branch:
1546   //   foo;
1547   //
1548   // .....
1549   //
1550   // dest_bb_fallthrough_predecessor:
1551   // bar;
1552   // s_branch dest_bb
1553   //
1554   // restore_bb:
1555   //  restore s[8:9]
1556   //  fallthrough dest_bb
1557   ///
1558   // dest_bb:
1559   //   buzz;
1560 
1561   RS->enterBasicBlockEnd(MBB);
1562   unsigned Scav = RS->scavengeRegisterBackwards(
1563     AMDGPU::SReg_64RegClass,
1564     MachineBasicBlock::iterator(GetPC), false, 0);
1565   MRI.replaceRegWith(PCReg, Scav);
1566   MRI.clearVirtRegs();
1567   RS->setRegUsed(Scav);
1568 
1569   return 4 + 8 + 4 + 4;
1570 }
1571 
1572 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1573   switch (Cond) {
1574   case SIInstrInfo::SCC_TRUE:
1575     return AMDGPU::S_CBRANCH_SCC1;
1576   case SIInstrInfo::SCC_FALSE:
1577     return AMDGPU::S_CBRANCH_SCC0;
1578   case SIInstrInfo::VCCNZ:
1579     return AMDGPU::S_CBRANCH_VCCNZ;
1580   case SIInstrInfo::VCCZ:
1581     return AMDGPU::S_CBRANCH_VCCZ;
1582   case SIInstrInfo::EXECNZ:
1583     return AMDGPU::S_CBRANCH_EXECNZ;
1584   case SIInstrInfo::EXECZ:
1585     return AMDGPU::S_CBRANCH_EXECZ;
1586   default:
1587     llvm_unreachable("invalid branch predicate");
1588   }
1589 }
1590 
1591 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1592   switch (Opcode) {
1593   case AMDGPU::S_CBRANCH_SCC0:
1594     return SCC_FALSE;
1595   case AMDGPU::S_CBRANCH_SCC1:
1596     return SCC_TRUE;
1597   case AMDGPU::S_CBRANCH_VCCNZ:
1598     return VCCNZ;
1599   case AMDGPU::S_CBRANCH_VCCZ:
1600     return VCCZ;
1601   case AMDGPU::S_CBRANCH_EXECNZ:
1602     return EXECNZ;
1603   case AMDGPU::S_CBRANCH_EXECZ:
1604     return EXECZ;
1605   default:
1606     return INVALID_BR;
1607   }
1608 }
1609 
1610 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
1611                                     MachineBasicBlock::iterator I,
1612                                     MachineBasicBlock *&TBB,
1613                                     MachineBasicBlock *&FBB,
1614                                     SmallVectorImpl<MachineOperand> &Cond,
1615                                     bool AllowModify) const {
1616   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1617     // Unconditional Branch
1618     TBB = I->getOperand(0).getMBB();
1619     return false;
1620   }
1621 
1622   MachineBasicBlock *CondBB = nullptr;
1623 
1624   if (I->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
1625     CondBB = I->getOperand(1).getMBB();
1626     Cond.push_back(I->getOperand(0));
1627   } else {
1628     BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1629     if (Pred == INVALID_BR)
1630       return true;
1631 
1632     CondBB = I->getOperand(0).getMBB();
1633     Cond.push_back(MachineOperand::CreateImm(Pred));
1634     Cond.push_back(I->getOperand(1)); // Save the branch register.
1635   }
1636   ++I;
1637 
1638   if (I == MBB.end()) {
1639     // Conditional branch followed by fall-through.
1640     TBB = CondBB;
1641     return false;
1642   }
1643 
1644   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1645     TBB = CondBB;
1646     FBB = I->getOperand(0).getMBB();
1647     return false;
1648   }
1649 
1650   return true;
1651 }
1652 
1653 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1654                                 MachineBasicBlock *&FBB,
1655                                 SmallVectorImpl<MachineOperand> &Cond,
1656                                 bool AllowModify) const {
1657   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1658   auto E = MBB.end();
1659   if (I == E)
1660     return false;
1661 
1662   // Skip over the instructions that are artificially terminators for special
1663   // exec management.
1664   while (I != E && !I->isBranch() && !I->isReturn() &&
1665          I->getOpcode() != AMDGPU::SI_MASK_BRANCH) {
1666     switch (I->getOpcode()) {
1667     case AMDGPU::SI_MASK_BRANCH:
1668     case AMDGPU::S_MOV_B64_term:
1669     case AMDGPU::S_XOR_B64_term:
1670     case AMDGPU::S_ANDN2_B64_term:
1671       break;
1672     case AMDGPU::SI_IF:
1673     case AMDGPU::SI_ELSE:
1674     case AMDGPU::SI_KILL_I1_TERMINATOR:
1675     case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
1676       // FIXME: It's messy that these need to be considered here at all.
1677       return true;
1678     default:
1679       llvm_unreachable("unexpected non-branch terminator inst");
1680     }
1681 
1682     ++I;
1683   }
1684 
1685   if (I == E)
1686     return false;
1687 
1688   if (I->getOpcode() != AMDGPU::SI_MASK_BRANCH)
1689     return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
1690 
1691   ++I;
1692 
1693   // TODO: Should be able to treat as fallthrough?
1694   if (I == MBB.end())
1695     return true;
1696 
1697   if (analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify))
1698     return true;
1699 
1700   MachineBasicBlock *MaskBrDest = I->getOperand(0).getMBB();
1701 
1702   // Specifically handle the case where the conditional branch is to the same
1703   // destination as the mask branch. e.g.
1704   //
1705   // si_mask_branch BB8
1706   // s_cbranch_execz BB8
1707   // s_cbranch BB9
1708   //
1709   // This is required to understand divergent loops which may need the branches
1710   // to be relaxed.
1711   if (TBB != MaskBrDest || Cond.empty())
1712     return true;
1713 
1714   auto Pred = Cond[0].getImm();
1715   return (Pred != EXECZ && Pred != EXECNZ);
1716 }
1717 
1718 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
1719                                    int *BytesRemoved) const {
1720   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1721 
1722   unsigned Count = 0;
1723   unsigned RemovedSize = 0;
1724   while (I != MBB.end()) {
1725     MachineBasicBlock::iterator Next = std::next(I);
1726     if (I->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
1727       I = Next;
1728       continue;
1729     }
1730 
1731     RemovedSize += getInstSizeInBytes(*I);
1732     I->eraseFromParent();
1733     ++Count;
1734     I = Next;
1735   }
1736 
1737   if (BytesRemoved)
1738     *BytesRemoved = RemovedSize;
1739 
1740   return Count;
1741 }
1742 
1743 // Copy the flags onto the implicit condition register operand.
1744 static void preserveCondRegFlags(MachineOperand &CondReg,
1745                                  const MachineOperand &OrigCond) {
1746   CondReg.setIsUndef(OrigCond.isUndef());
1747   CondReg.setIsKill(OrigCond.isKill());
1748 }
1749 
1750 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
1751                                    MachineBasicBlock *TBB,
1752                                    MachineBasicBlock *FBB,
1753                                    ArrayRef<MachineOperand> Cond,
1754                                    const DebugLoc &DL,
1755                                    int *BytesAdded) const {
1756   if (!FBB && Cond.empty()) {
1757     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1758       .addMBB(TBB);
1759     if (BytesAdded)
1760       *BytesAdded = 4;
1761     return 1;
1762   }
1763 
1764   if(Cond.size() == 1 && Cond[0].isReg()) {
1765      BuildMI(&MBB, DL, get(AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO))
1766        .add(Cond[0])
1767        .addMBB(TBB);
1768      return 1;
1769   }
1770 
1771   assert(TBB && Cond[0].isImm());
1772 
1773   unsigned Opcode
1774     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
1775 
1776   if (!FBB) {
1777     Cond[1].isUndef();
1778     MachineInstr *CondBr =
1779       BuildMI(&MBB, DL, get(Opcode))
1780       .addMBB(TBB);
1781 
1782     // Copy the flags onto the implicit condition register operand.
1783     preserveCondRegFlags(CondBr->getOperand(1), Cond[1]);
1784 
1785     if (BytesAdded)
1786       *BytesAdded = 4;
1787     return 1;
1788   }
1789 
1790   assert(TBB && FBB);
1791 
1792   MachineInstr *CondBr =
1793     BuildMI(&MBB, DL, get(Opcode))
1794     .addMBB(TBB);
1795   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1796     .addMBB(FBB);
1797 
1798   MachineOperand &CondReg = CondBr->getOperand(1);
1799   CondReg.setIsUndef(Cond[1].isUndef());
1800   CondReg.setIsKill(Cond[1].isKill());
1801 
1802   if (BytesAdded)
1803       *BytesAdded = 8;
1804 
1805   return 2;
1806 }
1807 
1808 bool SIInstrInfo::reverseBranchCondition(
1809   SmallVectorImpl<MachineOperand> &Cond) const {
1810   if (Cond.size() != 2) {
1811     return true;
1812   }
1813 
1814   if (Cond[0].isImm()) {
1815     Cond[0].setImm(-Cond[0].getImm());
1816     return false;
1817   }
1818 
1819   return true;
1820 }
1821 
1822 bool SIInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
1823                                   ArrayRef<MachineOperand> Cond,
1824                                   unsigned TrueReg, unsigned FalseReg,
1825                                   int &CondCycles,
1826                                   int &TrueCycles, int &FalseCycles) const {
1827   switch (Cond[0].getImm()) {
1828   case VCCNZ:
1829   case VCCZ: {
1830     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1831     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
1832     assert(MRI.getRegClass(FalseReg) == RC);
1833 
1834     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
1835     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
1836 
1837     // Limit to equal cost for branch vs. N v_cndmask_b32s.
1838     return !RI.isSGPRClass(RC) && NumInsts <= 6;
1839   }
1840   case SCC_TRUE:
1841   case SCC_FALSE: {
1842     // FIXME: We could insert for VGPRs if we could replace the original compare
1843     // with a vector one.
1844     const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1845     const TargetRegisterClass *RC = MRI.getRegClass(TrueReg);
1846     assert(MRI.getRegClass(FalseReg) == RC);
1847 
1848     int NumInsts = AMDGPU::getRegBitWidth(RC->getID()) / 32;
1849 
1850     // Multiples of 8 can do s_cselect_b64
1851     if (NumInsts % 2 == 0)
1852       NumInsts /= 2;
1853 
1854     CondCycles = TrueCycles = FalseCycles = NumInsts; // ???
1855     return RI.isSGPRClass(RC);
1856   }
1857   default:
1858     return false;
1859   }
1860 }
1861 
1862 void SIInstrInfo::insertSelect(MachineBasicBlock &MBB,
1863                                MachineBasicBlock::iterator I, const DebugLoc &DL,
1864                                unsigned DstReg, ArrayRef<MachineOperand> Cond,
1865                                unsigned TrueReg, unsigned FalseReg) const {
1866   BranchPredicate Pred = static_cast<BranchPredicate>(Cond[0].getImm());
1867   if (Pred == VCCZ || Pred == SCC_FALSE) {
1868     Pred = static_cast<BranchPredicate>(-Pred);
1869     std::swap(TrueReg, FalseReg);
1870   }
1871 
1872   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1873   const TargetRegisterClass *DstRC = MRI.getRegClass(DstReg);
1874   unsigned DstSize = RI.getRegSizeInBits(*DstRC);
1875 
1876   if (DstSize == 32) {
1877     unsigned SelOp = Pred == SCC_TRUE ?
1878       AMDGPU::S_CSELECT_B32 : AMDGPU::V_CNDMASK_B32_e32;
1879 
1880     // Instruction's operands are backwards from what is expected.
1881     MachineInstr *Select =
1882       BuildMI(MBB, I, DL, get(SelOp), DstReg)
1883       .addReg(FalseReg)
1884       .addReg(TrueReg);
1885 
1886     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1887     return;
1888   }
1889 
1890   if (DstSize == 64 && Pred == SCC_TRUE) {
1891     MachineInstr *Select =
1892       BuildMI(MBB, I, DL, get(AMDGPU::S_CSELECT_B64), DstReg)
1893       .addReg(FalseReg)
1894       .addReg(TrueReg);
1895 
1896     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1897     return;
1898   }
1899 
1900   static const int16_t Sub0_15[] = {
1901     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
1902     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
1903     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
1904     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15,
1905   };
1906 
1907   static const int16_t Sub0_15_64[] = {
1908     AMDGPU::sub0_sub1, AMDGPU::sub2_sub3,
1909     AMDGPU::sub4_sub5, AMDGPU::sub6_sub7,
1910     AMDGPU::sub8_sub9, AMDGPU::sub10_sub11,
1911     AMDGPU::sub12_sub13, AMDGPU::sub14_sub15,
1912   };
1913 
1914   unsigned SelOp = AMDGPU::V_CNDMASK_B32_e32;
1915   const TargetRegisterClass *EltRC = &AMDGPU::VGPR_32RegClass;
1916   const int16_t *SubIndices = Sub0_15;
1917   int NElts = DstSize / 32;
1918 
1919   // 64-bit select is only avaialble for SALU.
1920   if (Pred == SCC_TRUE) {
1921     SelOp = AMDGPU::S_CSELECT_B64;
1922     EltRC = &AMDGPU::SGPR_64RegClass;
1923     SubIndices = Sub0_15_64;
1924 
1925     assert(NElts % 2 == 0);
1926     NElts /= 2;
1927   }
1928 
1929   MachineInstrBuilder MIB = BuildMI(
1930     MBB, I, DL, get(AMDGPU::REG_SEQUENCE), DstReg);
1931 
1932   I = MIB->getIterator();
1933 
1934   SmallVector<unsigned, 8> Regs;
1935   for (int Idx = 0; Idx != NElts; ++Idx) {
1936     unsigned DstElt = MRI.createVirtualRegister(EltRC);
1937     Regs.push_back(DstElt);
1938 
1939     unsigned SubIdx = SubIndices[Idx];
1940 
1941     MachineInstr *Select =
1942       BuildMI(MBB, I, DL, get(SelOp), DstElt)
1943       .addReg(FalseReg, 0, SubIdx)
1944       .addReg(TrueReg, 0, SubIdx);
1945     preserveCondRegFlags(Select->getOperand(3), Cond[1]);
1946 
1947     MIB.addReg(DstElt)
1948        .addImm(SubIdx);
1949   }
1950 }
1951 
1952 bool SIInstrInfo::isFoldableCopy(const MachineInstr &MI) const {
1953   switch (MI.getOpcode()) {
1954   case AMDGPU::V_MOV_B32_e32:
1955   case AMDGPU::V_MOV_B32_e64:
1956   case AMDGPU::V_MOV_B64_PSEUDO: {
1957     // If there are additional implicit register operands, this may be used for
1958     // register indexing so the source register operand isn't simply copied.
1959     unsigned NumOps = MI.getDesc().getNumOperands() +
1960       MI.getDesc().getNumImplicitUses();
1961 
1962     return MI.getNumOperands() == NumOps;
1963   }
1964   case AMDGPU::S_MOV_B32:
1965   case AMDGPU::S_MOV_B64:
1966   case AMDGPU::COPY:
1967     return true;
1968   default:
1969     return false;
1970   }
1971 }
1972 
1973 unsigned SIInstrInfo::getAddressSpaceForPseudoSourceKind(
1974     unsigned Kind) const {
1975   switch(Kind) {
1976   case PseudoSourceValue::Stack:
1977   case PseudoSourceValue::FixedStack:
1978     return AMDGPUAS::PRIVATE_ADDRESS;
1979   case PseudoSourceValue::ConstantPool:
1980   case PseudoSourceValue::GOT:
1981   case PseudoSourceValue::JumpTable:
1982   case PseudoSourceValue::GlobalValueCallEntry:
1983   case PseudoSourceValue::ExternalSymbolCallEntry:
1984   case PseudoSourceValue::TargetCustom:
1985     return AMDGPUAS::CONSTANT_ADDRESS;
1986   }
1987   return AMDGPUAS::FLAT_ADDRESS;
1988 }
1989 
1990 static void removeModOperands(MachineInstr &MI) {
1991   unsigned Opc = MI.getOpcode();
1992   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1993                                               AMDGPU::OpName::src0_modifiers);
1994   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1995                                               AMDGPU::OpName::src1_modifiers);
1996   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1997                                               AMDGPU::OpName::src2_modifiers);
1998 
1999   MI.RemoveOperand(Src2ModIdx);
2000   MI.RemoveOperand(Src1ModIdx);
2001   MI.RemoveOperand(Src0ModIdx);
2002 }
2003 
2004 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
2005                                 unsigned Reg, MachineRegisterInfo *MRI) const {
2006   if (!MRI->hasOneNonDBGUse(Reg))
2007     return false;
2008 
2009   switch (DefMI.getOpcode()) {
2010   default:
2011     return false;
2012   case AMDGPU::S_MOV_B64:
2013     // TODO: We could fold 64-bit immediates, but this get compilicated
2014     // when there are sub-registers.
2015     return false;
2016 
2017   case AMDGPU::V_MOV_B32_e32:
2018   case AMDGPU::S_MOV_B32:
2019     break;
2020   }
2021 
2022   const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
2023   assert(ImmOp);
2024   // FIXME: We could handle FrameIndex values here.
2025   if (!ImmOp->isImm())
2026     return false;
2027 
2028   unsigned Opc = UseMI.getOpcode();
2029   if (Opc == AMDGPU::COPY) {
2030     bool isVGPRCopy = RI.isVGPR(*MRI, UseMI.getOperand(0).getReg());
2031     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
2032     UseMI.setDesc(get(NewOpc));
2033     UseMI.getOperand(1).ChangeToImmediate(ImmOp->getImm());
2034     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
2035     return true;
2036   }
2037 
2038   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64 ||
2039       Opc == AMDGPU::V_MAD_F16 || Opc == AMDGPU::V_MAC_F16_e64) {
2040     // Don't fold if we are using source or output modifiers. The new VOP2
2041     // instructions don't have them.
2042     if (hasAnyModifiersSet(UseMI))
2043       return false;
2044 
2045     // If this is a free constant, there's no reason to do this.
2046     // TODO: We could fold this here instead of letting SIFoldOperands do it
2047     // later.
2048     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
2049 
2050     // Any src operand can be used for the legality check.
2051     if (isInlineConstant(UseMI, *Src0, *ImmOp))
2052       return false;
2053 
2054     bool IsF32 = Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64;
2055     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
2056     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
2057 
2058     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
2059     // We should only expect these to be on src0 due to canonicalizations.
2060     if (Src0->isReg() && Src0->getReg() == Reg) {
2061       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
2062         return false;
2063 
2064       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
2065         return false;
2066 
2067       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
2068 
2069       const int64_t Imm = ImmOp->getImm();
2070 
2071       // FIXME: This would be a lot easier if we could return a new instruction
2072       // instead of having to modify in place.
2073 
2074       // Remove these first since they are at the end.
2075       UseMI.RemoveOperand(
2076           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2077       UseMI.RemoveOperand(
2078           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2079 
2080       unsigned Src1Reg = Src1->getReg();
2081       unsigned Src1SubReg = Src1->getSubReg();
2082       Src0->setReg(Src1Reg);
2083       Src0->setSubReg(Src1SubReg);
2084       Src0->setIsKill(Src1->isKill());
2085 
2086       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2087           Opc == AMDGPU::V_MAC_F16_e64)
2088         UseMI.untieRegOperand(
2089             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2090 
2091       Src1->ChangeToImmediate(Imm);
2092 
2093       removeModOperands(UseMI);
2094       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16));
2095 
2096       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2097       if (DeleteDef)
2098         DefMI.eraseFromParent();
2099 
2100       return true;
2101     }
2102 
2103     // Added part is the constant: Use v_madak_{f16, f32}.
2104     if (Src2->isReg() && Src2->getReg() == Reg) {
2105       // Not allowed to use constant bus for another operand.
2106       // We can however allow an inline immediate as src0.
2107       bool Src0Inlined = false;
2108       if (Src0->isReg()) {
2109         // Try to inline constant if possible.
2110         // If the Def moves immediate and the use is single
2111         // We are saving VGPR here.
2112         MachineInstr *Def = MRI->getUniqueVRegDef(Src0->getReg());
2113         if (Def && Def->isMoveImmediate() &&
2114           isInlineConstant(Def->getOperand(1)) &&
2115           MRI->hasOneUse(Src0->getReg())) {
2116           Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2117           Src0Inlined = true;
2118         } else if ((RI.isPhysicalRegister(Src0->getReg()) &&
2119             RI.isSGPRClass(RI.getPhysRegClass(Src0->getReg()))) ||
2120             (RI.isVirtualRegister(Src0->getReg()) &&
2121             RI.isSGPRClass(MRI->getRegClass(Src0->getReg()))))
2122           return false;
2123           // VGPR is okay as Src0 - fallthrough
2124       }
2125 
2126       if (Src1->isReg() && !Src0Inlined ) {
2127         // We have one slot for inlinable constant so far - try to fill it
2128         MachineInstr *Def = MRI->getUniqueVRegDef(Src1->getReg());
2129         if (Def && Def->isMoveImmediate() &&
2130             isInlineConstant(Def->getOperand(1)) &&
2131             MRI->hasOneUse(Src1->getReg()) &&
2132             commuteInstruction(UseMI)) {
2133             Src0->ChangeToImmediate(Def->getOperand(1).getImm());
2134         } else if ((RI.isPhysicalRegister(Src1->getReg()) &&
2135             RI.isSGPRClass(RI.getPhysRegClass(Src1->getReg()))) ||
2136             (RI.isVirtualRegister(Src1->getReg()) &&
2137             RI.isSGPRClass(MRI->getRegClass(Src1->getReg()))))
2138           return false;
2139           // VGPR is okay as Src1 - fallthrough
2140       }
2141 
2142       const int64_t Imm = ImmOp->getImm();
2143 
2144       // FIXME: This would be a lot easier if we could return a new instruction
2145       // instead of having to modify in place.
2146 
2147       // Remove these first since they are at the end.
2148       UseMI.RemoveOperand(
2149           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
2150       UseMI.RemoveOperand(
2151           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
2152 
2153       if (Opc == AMDGPU::V_MAC_F32_e64 ||
2154           Opc == AMDGPU::V_MAC_F16_e64)
2155         UseMI.untieRegOperand(
2156             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
2157 
2158       // ChangingToImmediate adds Src2 back to the instruction.
2159       Src2->ChangeToImmediate(Imm);
2160 
2161       // These come before src2.
2162       removeModOperands(UseMI);
2163       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16));
2164 
2165       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
2166       if (DeleteDef)
2167         DefMI.eraseFromParent();
2168 
2169       return true;
2170     }
2171   }
2172 
2173   return false;
2174 }
2175 
2176 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
2177                                 int WidthB, int OffsetB) {
2178   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
2179   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
2180   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
2181   return LowOffset + LowWidth <= HighOffset;
2182 }
2183 
2184 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr &MIa,
2185                                                MachineInstr &MIb) const {
2186   MachineOperand *BaseOp0, *BaseOp1;
2187   int64_t Offset0, Offset1;
2188 
2189   if (getMemOperandWithOffset(MIa, BaseOp0, Offset0, &RI) &&
2190       getMemOperandWithOffset(MIb, BaseOp1, Offset1, &RI)) {
2191     if (!BaseOp0->isIdenticalTo(*BaseOp1))
2192       return false;
2193 
2194     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
2195       // FIXME: Handle ds_read2 / ds_write2.
2196       return false;
2197     }
2198     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
2199     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
2200     if (offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
2201       return true;
2202     }
2203   }
2204 
2205   return false;
2206 }
2207 
2208 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr &MIa,
2209                                                   MachineInstr &MIb,
2210                                                   AliasAnalysis *AA) const {
2211   assert((MIa.mayLoad() || MIa.mayStore()) &&
2212          "MIa must load from or modify a memory location");
2213   assert((MIb.mayLoad() || MIb.mayStore()) &&
2214          "MIb must load from or modify a memory location");
2215 
2216   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
2217     return false;
2218 
2219   // XXX - Can we relax this between address spaces?
2220   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
2221     return false;
2222 
2223   // TODO: Should we check the address space from the MachineMemOperand? That
2224   // would allow us to distinguish objects we know don't alias based on the
2225   // underlying address space, even if it was lowered to a different one,
2226   // e.g. private accesses lowered to use MUBUF instructions on a scratch
2227   // buffer.
2228   if (isDS(MIa)) {
2229     if (isDS(MIb))
2230       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2231 
2232     return !isFLAT(MIb) || isSegmentSpecificFLAT(MIb);
2233   }
2234 
2235   if (isMUBUF(MIa) || isMTBUF(MIa)) {
2236     if (isMUBUF(MIb) || isMTBUF(MIb))
2237       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2238 
2239     return !isFLAT(MIb) && !isSMRD(MIb);
2240   }
2241 
2242   if (isSMRD(MIa)) {
2243     if (isSMRD(MIb))
2244       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2245 
2246     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
2247   }
2248 
2249   if (isFLAT(MIa)) {
2250     if (isFLAT(MIb))
2251       return checkInstOffsetsDoNotOverlap(MIa, MIb);
2252 
2253     return false;
2254   }
2255 
2256   return false;
2257 }
2258 
2259 static int64_t getFoldableImm(const MachineOperand* MO) {
2260   if (!MO->isReg())
2261     return false;
2262   const MachineFunction *MF = MO->getParent()->getParent()->getParent();
2263   const MachineRegisterInfo &MRI = MF->getRegInfo();
2264   auto Def = MRI.getUniqueVRegDef(MO->getReg());
2265   if (Def && Def->getOpcode() == AMDGPU::V_MOV_B32_e32 &&
2266       Def->getOperand(1).isImm())
2267     return Def->getOperand(1).getImm();
2268   return AMDGPU::NoRegister;
2269 }
2270 
2271 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
2272                                                  MachineInstr &MI,
2273                                                  LiveVariables *LV) const {
2274   unsigned Opc = MI.getOpcode();
2275   bool IsF16 = false;
2276   bool IsFMA = Opc == AMDGPU::V_FMAC_F32_e32 || Opc == AMDGPU::V_FMAC_F32_e64;
2277 
2278   switch (Opc) {
2279   default:
2280     return nullptr;
2281   case AMDGPU::V_MAC_F16_e64:
2282     IsF16 = true;
2283     LLVM_FALLTHROUGH;
2284   case AMDGPU::V_MAC_F32_e64:
2285   case AMDGPU::V_FMAC_F32_e64:
2286     break;
2287   case AMDGPU::V_MAC_F16_e32:
2288     IsF16 = true;
2289     LLVM_FALLTHROUGH;
2290   case AMDGPU::V_MAC_F32_e32:
2291   case AMDGPU::V_FMAC_F32_e32: {
2292     int Src0Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
2293                                              AMDGPU::OpName::src0);
2294     const MachineOperand *Src0 = &MI.getOperand(Src0Idx);
2295     if (!Src0->isReg() && !Src0->isImm())
2296       return nullptr;
2297 
2298     if (Src0->isImm() && !isInlineConstant(MI, Src0Idx, *Src0))
2299       return nullptr;
2300 
2301     break;
2302   }
2303   }
2304 
2305   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
2306   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
2307   const MachineOperand *Src0Mods =
2308     getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
2309   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2310   const MachineOperand *Src1Mods =
2311     getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
2312   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2313   const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
2314   const MachineOperand *Omod = getNamedOperand(MI, AMDGPU::OpName::omod);
2315 
2316   if (!IsFMA && !Src0Mods && !Src1Mods && !Clamp && !Omod &&
2317       // If we have an SGPR input, we will violate the constant bus restriction.
2318       (!Src0->isReg() || !RI.isSGPRReg(MBB->getParent()->getRegInfo(), Src0->getReg()))) {
2319     if (auto Imm = getFoldableImm(Src2)) {
2320       return BuildMI(*MBB, MI, MI.getDebugLoc(),
2321                      get(IsF16 ? AMDGPU::V_MADAK_F16 : AMDGPU::V_MADAK_F32))
2322                .add(*Dst)
2323                .add(*Src0)
2324                .add(*Src1)
2325                .addImm(Imm);
2326     }
2327     if (auto Imm = getFoldableImm(Src1)) {
2328       return BuildMI(*MBB, MI, MI.getDebugLoc(),
2329                      get(IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32))
2330                .add(*Dst)
2331                .add(*Src0)
2332                .addImm(Imm)
2333                .add(*Src2);
2334     }
2335     if (auto Imm = getFoldableImm(Src0)) {
2336       if (isOperandLegal(MI, AMDGPU::getNamedOperandIdx(AMDGPU::V_MADMK_F32,
2337                            AMDGPU::OpName::src0), Src1))
2338         return BuildMI(*MBB, MI, MI.getDebugLoc(),
2339                        get(IsF16 ? AMDGPU::V_MADMK_F16 : AMDGPU::V_MADMK_F32))
2340                  .add(*Dst)
2341                  .add(*Src1)
2342                  .addImm(Imm)
2343                  .add(*Src2);
2344     }
2345   }
2346 
2347   assert((!IsFMA || !IsF16) && "fmac only expected with f32");
2348   unsigned NewOpc = IsFMA ? AMDGPU::V_FMA_F32 :
2349     (IsF16 ? AMDGPU::V_MAD_F16 : AMDGPU::V_MAD_F32);
2350   return BuildMI(*MBB, MI, MI.getDebugLoc(), get(NewOpc))
2351       .add(*Dst)
2352       .addImm(Src0Mods ? Src0Mods->getImm() : 0)
2353       .add(*Src0)
2354       .addImm(Src1Mods ? Src1Mods->getImm() : 0)
2355       .add(*Src1)
2356       .addImm(0) // Src mods
2357       .add(*Src2)
2358       .addImm(Clamp ? Clamp->getImm() : 0)
2359       .addImm(Omod ? Omod->getImm() : 0);
2360 }
2361 
2362 // It's not generally safe to move VALU instructions across these since it will
2363 // start using the register as a base index rather than directly.
2364 // XXX - Why isn't hasSideEffects sufficient for these?
2365 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
2366   switch (MI.getOpcode()) {
2367   case AMDGPU::S_SET_GPR_IDX_ON:
2368   case AMDGPU::S_SET_GPR_IDX_MODE:
2369   case AMDGPU::S_SET_GPR_IDX_OFF:
2370     return true;
2371   default:
2372     return false;
2373   }
2374 }
2375 
2376 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
2377                                        const MachineBasicBlock *MBB,
2378                                        const MachineFunction &MF) const {
2379   // XXX - Do we want the SP check in the base implementation?
2380 
2381   // Target-independent instructions do not have an implicit-use of EXEC, even
2382   // when they operate on VGPRs. Treating EXEC modifications as scheduling
2383   // boundaries prevents incorrect movements of such instructions.
2384   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
2385          MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
2386          MI.getOpcode() == AMDGPU::S_SETREG_IMM32_B32 ||
2387          MI.getOpcode() == AMDGPU::S_SETREG_B32 ||
2388          changesVGPRIndexingMode(MI);
2389 }
2390 
2391 bool SIInstrInfo::isAlwaysGDS(uint16_t Opcode) const {
2392   return Opcode == AMDGPU::DS_ORDERED_COUNT ||
2393          Opcode == AMDGPU::DS_GWS_INIT ||
2394          Opcode == AMDGPU::DS_GWS_SEMA_V ||
2395          Opcode == AMDGPU::DS_GWS_SEMA_BR ||
2396          Opcode == AMDGPU::DS_GWS_SEMA_P ||
2397          Opcode == AMDGPU::DS_GWS_SEMA_RELEASE_ALL ||
2398          Opcode == AMDGPU::DS_GWS_BARRIER;
2399 }
2400 
2401 bool SIInstrInfo::hasUnwantedEffectsWhenEXECEmpty(const MachineInstr &MI) const {
2402   unsigned Opcode = MI.getOpcode();
2403 
2404   if (MI.mayStore() && isSMRD(MI))
2405     return true; // scalar store or atomic
2406 
2407   // These instructions cause shader I/O that may cause hardware lockups
2408   // when executed with an empty EXEC mask.
2409   //
2410   // Note: exp with VM = DONE = 0 is automatically skipped by hardware when
2411   //       EXEC = 0, but checking for that case here seems not worth it
2412   //       given the typical code patterns.
2413   if (Opcode == AMDGPU::S_SENDMSG || Opcode == AMDGPU::S_SENDMSGHALT ||
2414       Opcode == AMDGPU::EXP || Opcode == AMDGPU::EXP_DONE ||
2415       Opcode == AMDGPU::DS_ORDERED_COUNT)
2416     return true;
2417 
2418   if (MI.isInlineAsm())
2419     return true; // conservative assumption
2420 
2421   // These are like SALU instructions in terms of effects, so it's questionable
2422   // whether we should return true for those.
2423   //
2424   // However, executing them with EXEC = 0 causes them to operate on undefined
2425   // data, which we avoid by returning true here.
2426   if (Opcode == AMDGPU::V_READFIRSTLANE_B32 || Opcode == AMDGPU::V_READLANE_B32)
2427     return true;
2428 
2429   return false;
2430 }
2431 
2432 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
2433   switch (Imm.getBitWidth()) {
2434   case 32:
2435     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
2436                                         ST.hasInv2PiInlineImm());
2437   case 64:
2438     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
2439                                         ST.hasInv2PiInlineImm());
2440   case 16:
2441     return ST.has16BitInsts() &&
2442            AMDGPU::isInlinableLiteral16(Imm.getSExtValue(),
2443                                         ST.hasInv2PiInlineImm());
2444   default:
2445     llvm_unreachable("invalid bitwidth");
2446   }
2447 }
2448 
2449 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
2450                                    uint8_t OperandType) const {
2451   if (!MO.isImm() ||
2452       OperandType < AMDGPU::OPERAND_SRC_FIRST ||
2453       OperandType > AMDGPU::OPERAND_SRC_LAST)
2454     return false;
2455 
2456   // MachineOperand provides no way to tell the true operand size, since it only
2457   // records a 64-bit value. We need to know the size to determine if a 32-bit
2458   // floating point immediate bit pattern is legal for an integer immediate. It
2459   // would be for any 32-bit integer operand, but would not be for a 64-bit one.
2460 
2461   int64_t Imm = MO.getImm();
2462   switch (OperandType) {
2463   case AMDGPU::OPERAND_REG_IMM_INT32:
2464   case AMDGPU::OPERAND_REG_IMM_FP32:
2465   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
2466   case AMDGPU::OPERAND_REG_INLINE_C_FP32: {
2467     int32_t Trunc = static_cast<int32_t>(Imm);
2468     return AMDGPU::isInlinableLiteral32(Trunc, ST.hasInv2PiInlineImm());
2469   }
2470   case AMDGPU::OPERAND_REG_IMM_INT64:
2471   case AMDGPU::OPERAND_REG_IMM_FP64:
2472   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
2473   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
2474     return AMDGPU::isInlinableLiteral64(MO.getImm(),
2475                                         ST.hasInv2PiInlineImm());
2476   case AMDGPU::OPERAND_REG_IMM_INT16:
2477   case AMDGPU::OPERAND_REG_IMM_FP16:
2478   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
2479   case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
2480     if (isInt<16>(Imm) || isUInt<16>(Imm)) {
2481       // A few special case instructions have 16-bit operands on subtargets
2482       // where 16-bit instructions are not legal.
2483       // TODO: Do the 32-bit immediates work? We shouldn't really need to handle
2484       // constants in these cases
2485       int16_t Trunc = static_cast<int16_t>(Imm);
2486       return ST.has16BitInsts() &&
2487              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
2488     }
2489 
2490     return false;
2491   }
2492   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
2493   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
2494     if (isUInt<16>(Imm)) {
2495       int16_t Trunc = static_cast<int16_t>(Imm);
2496       return ST.has16BitInsts() &&
2497              AMDGPU::isInlinableLiteral16(Trunc, ST.hasInv2PiInlineImm());
2498     }
2499     if (!(Imm & 0xffff)) {
2500       return ST.has16BitInsts() &&
2501              AMDGPU::isInlinableLiteral16(Imm >> 16, ST.hasInv2PiInlineImm());
2502     }
2503     uint32_t Trunc = static_cast<uint32_t>(Imm);
2504     return  AMDGPU::isInlinableLiteralV216(Trunc, ST.hasInv2PiInlineImm());
2505   }
2506   default:
2507     llvm_unreachable("invalid bitwidth");
2508   }
2509 }
2510 
2511 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
2512                                         const MCOperandInfo &OpInfo) const {
2513   switch (MO.getType()) {
2514   case MachineOperand::MO_Register:
2515     return false;
2516   case MachineOperand::MO_Immediate:
2517     return !isInlineConstant(MO, OpInfo);
2518   case MachineOperand::MO_FrameIndex:
2519   case MachineOperand::MO_MachineBasicBlock:
2520   case MachineOperand::MO_ExternalSymbol:
2521   case MachineOperand::MO_GlobalAddress:
2522   case MachineOperand::MO_MCSymbol:
2523     return true;
2524   default:
2525     llvm_unreachable("unexpected operand type");
2526   }
2527 }
2528 
2529 static bool compareMachineOp(const MachineOperand &Op0,
2530                              const MachineOperand &Op1) {
2531   if (Op0.getType() != Op1.getType())
2532     return false;
2533 
2534   switch (Op0.getType()) {
2535   case MachineOperand::MO_Register:
2536     return Op0.getReg() == Op1.getReg();
2537   case MachineOperand::MO_Immediate:
2538     return Op0.getImm() == Op1.getImm();
2539   default:
2540     llvm_unreachable("Didn't expect to be comparing these operand types");
2541   }
2542 }
2543 
2544 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
2545                                     const MachineOperand &MO) const {
2546   const MCOperandInfo &OpInfo = get(MI.getOpcode()).OpInfo[OpNo];
2547 
2548   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
2549 
2550   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
2551     return true;
2552 
2553   if (OpInfo.RegClass < 0)
2554     return false;
2555 
2556   if (MO.isImm() && isInlineConstant(MO, OpInfo))
2557     return RI.opCanUseInlineConstant(OpInfo.OperandType);
2558 
2559   return RI.opCanUseLiteralConstant(OpInfo.OperandType);
2560 }
2561 
2562 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
2563   int Op32 = AMDGPU::getVOPe32(Opcode);
2564   if (Op32 == -1)
2565     return false;
2566 
2567   return pseudoToMCOpcode(Op32) != -1;
2568 }
2569 
2570 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
2571   // The src0_modifier operand is present on all instructions
2572   // that have modifiers.
2573 
2574   return AMDGPU::getNamedOperandIdx(Opcode,
2575                                     AMDGPU::OpName::src0_modifiers) != -1;
2576 }
2577 
2578 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
2579                                   unsigned OpName) const {
2580   const MachineOperand *Mods = getNamedOperand(MI, OpName);
2581   return Mods && Mods->getImm();
2582 }
2583 
2584 bool SIInstrInfo::hasAnyModifiersSet(const MachineInstr &MI) const {
2585   return hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
2586          hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
2587          hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers) ||
2588          hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
2589          hasModifiersSet(MI, AMDGPU::OpName::omod);
2590 }
2591 
2592 bool SIInstrInfo::canShrink(const MachineInstr &MI,
2593                             const MachineRegisterInfo &MRI) const {
2594   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2595   // Can't shrink instruction with three operands.
2596   // FIXME: v_cndmask_b32 has 3 operands and is shrinkable, but we need to add
2597   // a special case for it.  It can only be shrunk if the third operand
2598   // is vcc, and src0_modifiers and src1_modifiers are not set.
2599   // We should handle this the same way we handle vopc, by addding
2600   // a register allocation hint pre-regalloc and then do the shrinking
2601   // post-regalloc.
2602   if (Src2) {
2603     switch (MI.getOpcode()) {
2604       default: return false;
2605 
2606       case AMDGPU::V_ADDC_U32_e64:
2607       case AMDGPU::V_SUBB_U32_e64:
2608       case AMDGPU::V_SUBBREV_U32_e64: {
2609         const MachineOperand *Src1
2610           = getNamedOperand(MI, AMDGPU::OpName::src1);
2611         if (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()))
2612           return false;
2613         // Additional verification is needed for sdst/src2.
2614         return true;
2615       }
2616       case AMDGPU::V_MAC_F32_e64:
2617       case AMDGPU::V_MAC_F16_e64:
2618       case AMDGPU::V_FMAC_F32_e64:
2619         if (!Src2->isReg() || !RI.isVGPR(MRI, Src2->getReg()) ||
2620             hasModifiersSet(MI, AMDGPU::OpName::src2_modifiers))
2621           return false;
2622         break;
2623 
2624       case AMDGPU::V_CNDMASK_B32_e64:
2625         break;
2626     }
2627   }
2628 
2629   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2630   if (Src1 && (!Src1->isReg() || !RI.isVGPR(MRI, Src1->getReg()) ||
2631                hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers)))
2632     return false;
2633 
2634   // We don't need to check src0, all input types are legal, so just make sure
2635   // src0 isn't using any modifiers.
2636   if (hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers))
2637     return false;
2638 
2639   // Can it be shrunk to a valid 32 bit opcode?
2640   if (!hasVALU32BitEncoding(MI.getOpcode()))
2641     return false;
2642 
2643   // Check output modifiers
2644   return !hasModifiersSet(MI, AMDGPU::OpName::omod) &&
2645          !hasModifiersSet(MI, AMDGPU::OpName::clamp);
2646 }
2647 
2648 // Set VCC operand with all flags from \p Orig, except for setting it as
2649 // implicit.
2650 static void copyFlagsToImplicitVCC(MachineInstr &MI,
2651                                    const MachineOperand &Orig) {
2652 
2653   for (MachineOperand &Use : MI.implicit_operands()) {
2654     if (Use.isUse() && Use.getReg() == AMDGPU::VCC) {
2655       Use.setIsUndef(Orig.isUndef());
2656       Use.setIsKill(Orig.isKill());
2657       return;
2658     }
2659   }
2660 }
2661 
2662 MachineInstr *SIInstrInfo::buildShrunkInst(MachineInstr &MI,
2663                                            unsigned Op32) const {
2664   MachineBasicBlock *MBB = MI.getParent();;
2665   MachineInstrBuilder Inst32 =
2666     BuildMI(*MBB, MI, MI.getDebugLoc(), get(Op32));
2667 
2668   // Add the dst operand if the 32-bit encoding also has an explicit $vdst.
2669   // For VOPC instructions, this is replaced by an implicit def of vcc.
2670   int Op32DstIdx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::vdst);
2671   if (Op32DstIdx != -1) {
2672     // dst
2673     Inst32.add(MI.getOperand(0));
2674   } else {
2675     assert(MI.getOperand(0).getReg() == AMDGPU::VCC &&
2676            "Unexpected case");
2677   }
2678 
2679   Inst32.add(*getNamedOperand(MI, AMDGPU::OpName::src0));
2680 
2681   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
2682   if (Src1)
2683     Inst32.add(*Src1);
2684 
2685   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
2686 
2687   if (Src2) {
2688     int Op32Src2Idx = AMDGPU::getNamedOperandIdx(Op32, AMDGPU::OpName::src2);
2689     if (Op32Src2Idx != -1) {
2690       Inst32.add(*Src2);
2691     } else {
2692       // In the case of V_CNDMASK_B32_e32, the explicit operand src2 is
2693       // replaced with an implicit read of vcc. This was already added
2694       // during the initial BuildMI, so find it to preserve the flags.
2695       copyFlagsToImplicitVCC(*Inst32, *Src2);
2696     }
2697   }
2698 
2699   return Inst32;
2700 }
2701 
2702 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
2703                                   const MachineOperand &MO,
2704                                   const MCOperandInfo &OpInfo) const {
2705   // Literal constants use the constant bus.
2706   //if (isLiteralConstantLike(MO, OpInfo))
2707   // return true;
2708   if (MO.isImm())
2709     return !isInlineConstant(MO, OpInfo);
2710 
2711   if (!MO.isReg())
2712     return true; // Misc other operands like FrameIndex
2713 
2714   if (!MO.isUse())
2715     return false;
2716 
2717   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2718     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
2719 
2720   // FLAT_SCR is just an SGPR pair.
2721   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
2722     return true;
2723 
2724   // EXEC register uses the constant bus.
2725   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
2726     return true;
2727 
2728   // SGPRs use the constant bus
2729   return (MO.getReg() == AMDGPU::VCC || MO.getReg() == AMDGPU::M0 ||
2730           (!MO.isImplicit() &&
2731            (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
2732             AMDGPU::SGPR_64RegClass.contains(MO.getReg()))));
2733 }
2734 
2735 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
2736   for (const MachineOperand &MO : MI.implicit_operands()) {
2737     // We only care about reads.
2738     if (MO.isDef())
2739       continue;
2740 
2741     switch (MO.getReg()) {
2742     case AMDGPU::VCC:
2743     case AMDGPU::M0:
2744     case AMDGPU::FLAT_SCR:
2745       return MO.getReg();
2746 
2747     default:
2748       break;
2749     }
2750   }
2751 
2752   return AMDGPU::NoRegister;
2753 }
2754 
2755 static bool shouldReadExec(const MachineInstr &MI) {
2756   if (SIInstrInfo::isVALU(MI)) {
2757     switch (MI.getOpcode()) {
2758     case AMDGPU::V_READLANE_B32:
2759     case AMDGPU::V_READLANE_B32_si:
2760     case AMDGPU::V_READLANE_B32_vi:
2761     case AMDGPU::V_WRITELANE_B32:
2762     case AMDGPU::V_WRITELANE_B32_si:
2763     case AMDGPU::V_WRITELANE_B32_vi:
2764       return false;
2765     }
2766 
2767     return true;
2768   }
2769 
2770   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
2771       SIInstrInfo::isSALU(MI) ||
2772       SIInstrInfo::isSMRD(MI))
2773     return false;
2774 
2775   return true;
2776 }
2777 
2778 static bool isSubRegOf(const SIRegisterInfo &TRI,
2779                        const MachineOperand &SuperVec,
2780                        const MachineOperand &SubReg) {
2781   if (TargetRegisterInfo::isPhysicalRegister(SubReg.getReg()))
2782     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
2783 
2784   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
2785          SubReg.getReg() == SuperVec.getReg();
2786 }
2787 
2788 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
2789                                     StringRef &ErrInfo) const {
2790   uint16_t Opcode = MI.getOpcode();
2791   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()))
2792     return true;
2793 
2794   const MachineFunction *MF = MI.getParent()->getParent();
2795   const MachineRegisterInfo &MRI = MF->getRegInfo();
2796 
2797   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
2798   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
2799   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
2800 
2801   // Make sure the number of operands is correct.
2802   const MCInstrDesc &Desc = get(Opcode);
2803   if (!Desc.isVariadic() &&
2804       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
2805     ErrInfo = "Instruction has wrong number of operands.";
2806     return false;
2807   }
2808 
2809   if (MI.isInlineAsm()) {
2810     // Verify register classes for inlineasm constraints.
2811     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
2812          I != E; ++I) {
2813       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
2814       if (!RC)
2815         continue;
2816 
2817       const MachineOperand &Op = MI.getOperand(I);
2818       if (!Op.isReg())
2819         continue;
2820 
2821       unsigned Reg = Op.getReg();
2822       if (!TargetRegisterInfo::isVirtualRegister(Reg) && !RC->contains(Reg)) {
2823         ErrInfo = "inlineasm operand has incorrect register class.";
2824         return false;
2825       }
2826     }
2827 
2828     return true;
2829   }
2830 
2831   // Make sure the register classes are correct.
2832   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
2833     if (MI.getOperand(i).isFPImm()) {
2834       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
2835                 "all fp values to integers.";
2836       return false;
2837     }
2838 
2839     int RegClass = Desc.OpInfo[i].RegClass;
2840 
2841     switch (Desc.OpInfo[i].OperandType) {
2842     case MCOI::OPERAND_REGISTER:
2843       if (MI.getOperand(i).isImm()) {
2844         ErrInfo = "Illegal immediate value for operand.";
2845         return false;
2846       }
2847       break;
2848     case AMDGPU::OPERAND_REG_IMM_INT32:
2849     case AMDGPU::OPERAND_REG_IMM_FP32:
2850       break;
2851     case AMDGPU::OPERAND_REG_INLINE_C_INT32:
2852     case AMDGPU::OPERAND_REG_INLINE_C_FP32:
2853     case AMDGPU::OPERAND_REG_INLINE_C_INT64:
2854     case AMDGPU::OPERAND_REG_INLINE_C_FP64:
2855     case AMDGPU::OPERAND_REG_INLINE_C_INT16:
2856     case AMDGPU::OPERAND_REG_INLINE_C_FP16: {
2857       const MachineOperand &MO = MI.getOperand(i);
2858       if (!MO.isReg() && (!MO.isImm() || !isInlineConstant(MI, i))) {
2859         ErrInfo = "Illegal immediate value for operand.";
2860         return false;
2861       }
2862       break;
2863     }
2864     case MCOI::OPERAND_IMMEDIATE:
2865     case AMDGPU::OPERAND_KIMM32:
2866       // Check if this operand is an immediate.
2867       // FrameIndex operands will be replaced by immediates, so they are
2868       // allowed.
2869       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
2870         ErrInfo = "Expected immediate, but got non-immediate";
2871         return false;
2872       }
2873       LLVM_FALLTHROUGH;
2874     default:
2875       continue;
2876     }
2877 
2878     if (!MI.getOperand(i).isReg())
2879       continue;
2880 
2881     if (RegClass != -1) {
2882       unsigned Reg = MI.getOperand(i).getReg();
2883       if (Reg == AMDGPU::NoRegister ||
2884           TargetRegisterInfo::isVirtualRegister(Reg))
2885         continue;
2886 
2887       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
2888       if (!RC->contains(Reg)) {
2889         ErrInfo = "Operand has incorrect register class.";
2890         return false;
2891       }
2892     }
2893   }
2894 
2895   // Verify SDWA
2896   if (isSDWA(MI)) {
2897     if (!ST.hasSDWA()) {
2898       ErrInfo = "SDWA is not supported on this target";
2899       return false;
2900     }
2901 
2902     int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
2903 
2904     const int OpIndicies[] = { DstIdx, Src0Idx, Src1Idx, Src2Idx };
2905 
2906     for (int OpIdx: OpIndicies) {
2907       if (OpIdx == -1)
2908         continue;
2909       const MachineOperand &MO = MI.getOperand(OpIdx);
2910 
2911       if (!ST.hasSDWAScalar()) {
2912         // Only VGPRS on VI
2913         if (!MO.isReg() || !RI.hasVGPRs(RI.getRegClassForReg(MRI, MO.getReg()))) {
2914           ErrInfo = "Only VGPRs allowed as operands in SDWA instructions on VI";
2915           return false;
2916         }
2917       } else {
2918         // No immediates on GFX9
2919         if (!MO.isReg()) {
2920           ErrInfo = "Only reg allowed as operands in SDWA instructions on GFX9";
2921           return false;
2922         }
2923       }
2924     }
2925 
2926     if (!ST.hasSDWAOmod()) {
2927       // No omod allowed on VI
2928       const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
2929       if (OMod != nullptr &&
2930         (!OMod->isImm() || OMod->getImm() != 0)) {
2931         ErrInfo = "OMod not allowed in SDWA instructions on VI";
2932         return false;
2933       }
2934     }
2935 
2936     uint16_t BasicOpcode = AMDGPU::getBasicFromSDWAOp(Opcode);
2937     if (isVOPC(BasicOpcode)) {
2938       if (!ST.hasSDWASdst() && DstIdx != -1) {
2939         // Only vcc allowed as dst on VI for VOPC
2940         const MachineOperand &Dst = MI.getOperand(DstIdx);
2941         if (!Dst.isReg() || Dst.getReg() != AMDGPU::VCC) {
2942           ErrInfo = "Only VCC allowed as dst in SDWA instructions on VI";
2943           return false;
2944         }
2945       } else if (!ST.hasSDWAOutModsVOPC()) {
2946         // No clamp allowed on GFX9 for VOPC
2947         const MachineOperand *Clamp = getNamedOperand(MI, AMDGPU::OpName::clamp);
2948         if (Clamp && (!Clamp->isImm() || Clamp->getImm() != 0)) {
2949           ErrInfo = "Clamp not allowed in VOPC SDWA instructions on VI";
2950           return false;
2951         }
2952 
2953         // No omod allowed on GFX9 for VOPC
2954         const MachineOperand *OMod = getNamedOperand(MI, AMDGPU::OpName::omod);
2955         if (OMod && (!OMod->isImm() || OMod->getImm() != 0)) {
2956           ErrInfo = "OMod not allowed in VOPC SDWA instructions on VI";
2957           return false;
2958         }
2959       }
2960     }
2961 
2962     const MachineOperand *DstUnused = getNamedOperand(MI, AMDGPU::OpName::dst_unused);
2963     if (DstUnused && DstUnused->isImm() &&
2964         DstUnused->getImm() == AMDGPU::SDWA::UNUSED_PRESERVE) {
2965       const MachineOperand &Dst = MI.getOperand(DstIdx);
2966       if (!Dst.isReg() || !Dst.isTied()) {
2967         ErrInfo = "Dst register should have tied register";
2968         return false;
2969       }
2970 
2971       const MachineOperand &TiedMO =
2972           MI.getOperand(MI.findTiedOperandIdx(DstIdx));
2973       if (!TiedMO.isReg() || !TiedMO.isImplicit() || !TiedMO.isUse()) {
2974         ErrInfo =
2975             "Dst register should be tied to implicit use of preserved register";
2976         return false;
2977       } else if (TargetRegisterInfo::isPhysicalRegister(TiedMO.getReg()) &&
2978                  Dst.getReg() != TiedMO.getReg()) {
2979         ErrInfo = "Dst register should use same physical register as preserved";
2980         return false;
2981       }
2982     }
2983   }
2984 
2985   // Verify MIMG
2986   if (isMIMG(MI.getOpcode()) && !MI.mayStore()) {
2987     // Ensure that the return type used is large enough for all the options
2988     // being used TFE/LWE require an extra result register.
2989     const MachineOperand *DMask = getNamedOperand(MI, AMDGPU::OpName::dmask);
2990     if (DMask) {
2991       uint64_t DMaskImm = DMask->getImm();
2992       uint32_t RegCount =
2993           isGather4(MI.getOpcode()) ? 4 : countPopulation(DMaskImm);
2994       const MachineOperand *TFE = getNamedOperand(MI, AMDGPU::OpName::tfe);
2995       const MachineOperand *LWE = getNamedOperand(MI, AMDGPU::OpName::lwe);
2996       const MachineOperand *D16 = getNamedOperand(MI, AMDGPU::OpName::d16);
2997 
2998       // Adjust for packed 16 bit values
2999       if (D16 && D16->getImm() && !ST.hasUnpackedD16VMem())
3000         RegCount >>= 1;
3001 
3002       // Adjust if using LWE or TFE
3003       if ((LWE && LWE->getImm()) || (TFE && TFE->getImm()))
3004         RegCount += 1;
3005 
3006       const uint32_t DstIdx =
3007           AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
3008       const MachineOperand &Dst = MI.getOperand(DstIdx);
3009       if (Dst.isReg()) {
3010         const TargetRegisterClass *DstRC = getOpRegClass(MI, DstIdx);
3011         uint32_t DstSize = RI.getRegSizeInBits(*DstRC) / 32;
3012         if (RegCount > DstSize) {
3013           ErrInfo = "MIMG instruction returns too many registers for dst "
3014                     "register class";
3015           return false;
3016         }
3017       }
3018     }
3019   }
3020 
3021   // Verify VOP*. Ignore multiple sgpr operands on writelane.
3022   if (Desc.getOpcode() != AMDGPU::V_WRITELANE_B32
3023       && (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI) || isSDWA(MI))) {
3024     // Only look at the true operands. Only a real operand can use the constant
3025     // bus, and we don't want to check pseudo-operands like the source modifier
3026     // flags.
3027     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
3028 
3029     unsigned ConstantBusCount = 0;
3030     unsigned LiteralCount = 0;
3031 
3032     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
3033       ++ConstantBusCount;
3034 
3035     unsigned SGPRUsed = findImplicitSGPRRead(MI);
3036     if (SGPRUsed != AMDGPU::NoRegister)
3037       ++ConstantBusCount;
3038 
3039     for (int OpIdx : OpIndices) {
3040       if (OpIdx == -1)
3041         break;
3042       const MachineOperand &MO = MI.getOperand(OpIdx);
3043       if (usesConstantBus(MRI, MO, MI.getDesc().OpInfo[OpIdx])) {
3044         if (MO.isReg()) {
3045           if (MO.getReg() != SGPRUsed)
3046             ++ConstantBusCount;
3047           SGPRUsed = MO.getReg();
3048         } else {
3049           ++ConstantBusCount;
3050           ++LiteralCount;
3051         }
3052       }
3053     }
3054     if (ConstantBusCount > 1) {
3055       ErrInfo = "VOP* instruction uses the constant bus more than once";
3056       return false;
3057     }
3058 
3059     if (isVOP3(MI) && LiteralCount) {
3060       ErrInfo = "VOP3 instruction uses literal";
3061       return false;
3062     }
3063   }
3064 
3065   // Verify misc. restrictions on specific instructions.
3066   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
3067       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
3068     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
3069     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
3070     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
3071     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
3072       if (!compareMachineOp(Src0, Src1) &&
3073           !compareMachineOp(Src0, Src2)) {
3074         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
3075         return false;
3076       }
3077     }
3078   }
3079 
3080   if (isSOPK(MI)) {
3081     int64_t Imm = getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
3082     if (sopkIsZext(MI)) {
3083       if (!isUInt<16>(Imm)) {
3084         ErrInfo = "invalid immediate for SOPK instruction";
3085         return false;
3086       }
3087     } else {
3088       if (!isInt<16>(Imm)) {
3089         ErrInfo = "invalid immediate for SOPK instruction";
3090         return false;
3091       }
3092     }
3093   }
3094 
3095   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
3096       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
3097       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
3098       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
3099     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
3100                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
3101 
3102     const unsigned StaticNumOps = Desc.getNumOperands() +
3103       Desc.getNumImplicitUses();
3104     const unsigned NumImplicitOps = IsDst ? 2 : 1;
3105 
3106     // Allow additional implicit operands. This allows a fixup done by the post
3107     // RA scheduler where the main implicit operand is killed and implicit-defs
3108     // are added for sub-registers that remain live after this instruction.
3109     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
3110       ErrInfo = "missing implicit register operands";
3111       return false;
3112     }
3113 
3114     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
3115     if (IsDst) {
3116       if (!Dst->isUse()) {
3117         ErrInfo = "v_movreld_b32 vdst should be a use operand";
3118         return false;
3119       }
3120 
3121       unsigned UseOpIdx;
3122       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
3123           UseOpIdx != StaticNumOps + 1) {
3124         ErrInfo = "movrel implicit operands should be tied";
3125         return false;
3126       }
3127     }
3128 
3129     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
3130     const MachineOperand &ImpUse
3131       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
3132     if (!ImpUse.isReg() || !ImpUse.isUse() ||
3133         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
3134       ErrInfo = "src0 should be subreg of implicit vector use";
3135       return false;
3136     }
3137   }
3138 
3139   // Make sure we aren't losing exec uses in the td files. This mostly requires
3140   // being careful when using let Uses to try to add other use registers.
3141   if (shouldReadExec(MI)) {
3142     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
3143       ErrInfo = "VALU instruction does not implicitly read exec mask";
3144       return false;
3145     }
3146   }
3147 
3148   if (isSMRD(MI)) {
3149     if (MI.mayStore()) {
3150       // The register offset form of scalar stores may only use m0 as the
3151       // soffset register.
3152       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
3153       if (Soff && Soff->getReg() != AMDGPU::M0) {
3154         ErrInfo = "scalar stores must use m0 as offset register";
3155         return false;
3156       }
3157     }
3158   }
3159 
3160   if (isFLAT(MI) && !MF->getSubtarget<GCNSubtarget>().hasFlatInstOffsets()) {
3161     const MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
3162     if (Offset->getImm() != 0) {
3163       ErrInfo = "subtarget does not support offsets in flat instructions";
3164       return false;
3165     }
3166   }
3167 
3168   const MachineOperand *DppCt = getNamedOperand(MI, AMDGPU::OpName::dpp_ctrl);
3169   if (DppCt) {
3170     using namespace AMDGPU::DPP;
3171 
3172     unsigned DC = DppCt->getImm();
3173     if (DC == DppCtrl::DPP_UNUSED1 || DC == DppCtrl::DPP_UNUSED2 ||
3174         DC == DppCtrl::DPP_UNUSED3 || DC > DppCtrl::DPP_LAST ||
3175         (DC >= DppCtrl::DPP_UNUSED4_FIRST && DC <= DppCtrl::DPP_UNUSED4_LAST) ||
3176         (DC >= DppCtrl::DPP_UNUSED5_FIRST && DC <= DppCtrl::DPP_UNUSED5_LAST) ||
3177         (DC >= DppCtrl::DPP_UNUSED6_FIRST && DC <= DppCtrl::DPP_UNUSED6_LAST) ||
3178         (DC >= DppCtrl::DPP_UNUSED7_FIRST && DC <= DppCtrl::DPP_UNUSED7_LAST)) {
3179       ErrInfo = "Invalid dpp_ctrl value";
3180       return false;
3181     }
3182   }
3183 
3184   return true;
3185 }
3186 
3187 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) const {
3188   switch (MI.getOpcode()) {
3189   default: return AMDGPU::INSTRUCTION_LIST_END;
3190   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
3191   case AMDGPU::COPY: return AMDGPU::COPY;
3192   case AMDGPU::PHI: return AMDGPU::PHI;
3193   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
3194   case AMDGPU::WQM: return AMDGPU::WQM;
3195   case AMDGPU::WWM: return AMDGPU::WWM;
3196   case AMDGPU::S_MOV_B32:
3197     return MI.getOperand(1).isReg() ?
3198            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
3199   case AMDGPU::S_ADD_I32:
3200     return ST.hasAddNoCarry() ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_I32_e32;
3201   case AMDGPU::S_ADDC_U32:
3202     return AMDGPU::V_ADDC_U32_e32;
3203   case AMDGPU::S_SUB_I32:
3204     return ST.hasAddNoCarry() ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_SUB_I32_e32;
3205     // FIXME: These are not consistently handled, and selected when the carry is
3206     // used.
3207   case AMDGPU::S_ADD_U32:
3208     return AMDGPU::V_ADD_I32_e32;
3209   case AMDGPU::S_SUB_U32:
3210     return AMDGPU::V_SUB_I32_e32;
3211   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
3212   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
3213   case AMDGPU::S_MUL_HI_U32: return AMDGPU::V_MUL_HI_U32;
3214   case AMDGPU::S_MUL_HI_I32: return AMDGPU::V_MUL_HI_I32;
3215   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
3216   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
3217   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
3218   case AMDGPU::S_XNOR_B32:
3219     return ST.hasDLInsts() ? AMDGPU::V_XNOR_B32_e64 : AMDGPU::INSTRUCTION_LIST_END;
3220   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
3221   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
3222   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
3223   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
3224   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
3225   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
3226   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
3227   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
3228   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
3229   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
3230   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
3231   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
3232   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
3233   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
3234   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
3235   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
3236   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
3237   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
3238   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
3239   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
3240   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
3241   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
3242   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
3243   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
3244   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
3245   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
3246   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
3247   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
3248   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
3249   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
3250   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
3251   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
3252   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
3253   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
3254   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
3255   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
3256   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
3257   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
3258   }
3259   llvm_unreachable(
3260       "Unexpected scalar opcode without corresponding vector one!");
3261 }
3262 
3263 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
3264                                                       unsigned OpNo) const {
3265   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3266   const MCInstrDesc &Desc = get(MI.getOpcode());
3267   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
3268       Desc.OpInfo[OpNo].RegClass == -1) {
3269     unsigned Reg = MI.getOperand(OpNo).getReg();
3270 
3271     if (TargetRegisterInfo::isVirtualRegister(Reg))
3272       return MRI.getRegClass(Reg);
3273     return RI.getPhysRegClass(Reg);
3274   }
3275 
3276   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
3277   return RI.getRegClass(RCID);
3278 }
3279 
3280 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
3281   MachineBasicBlock::iterator I = MI;
3282   MachineBasicBlock *MBB = MI.getParent();
3283   MachineOperand &MO = MI.getOperand(OpIdx);
3284   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
3285   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
3286   const TargetRegisterClass *RC = RI.getRegClass(RCID);
3287   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
3288   if (MO.isReg())
3289     Opcode = AMDGPU::COPY;
3290   else if (RI.isSGPRClass(RC))
3291     Opcode = AMDGPU::S_MOV_B32;
3292 
3293   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
3294   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
3295     VRC = &AMDGPU::VReg_64RegClass;
3296   else
3297     VRC = &AMDGPU::VGPR_32RegClass;
3298 
3299   unsigned Reg = MRI.createVirtualRegister(VRC);
3300   DebugLoc DL = MBB->findDebugLoc(I);
3301   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).add(MO);
3302   MO.ChangeToRegister(Reg, false);
3303 }
3304 
3305 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
3306                                          MachineRegisterInfo &MRI,
3307                                          MachineOperand &SuperReg,
3308                                          const TargetRegisterClass *SuperRC,
3309                                          unsigned SubIdx,
3310                                          const TargetRegisterClass *SubRC)
3311                                          const {
3312   MachineBasicBlock *MBB = MI->getParent();
3313   DebugLoc DL = MI->getDebugLoc();
3314   unsigned SubReg = MRI.createVirtualRegister(SubRC);
3315 
3316   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
3317     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
3318       .addReg(SuperReg.getReg(), 0, SubIdx);
3319     return SubReg;
3320   }
3321 
3322   // Just in case the super register is itself a sub-register, copy it to a new
3323   // value so we don't need to worry about merging its subreg index with the
3324   // SubIdx passed to this function. The register coalescer should be able to
3325   // eliminate this extra copy.
3326   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
3327 
3328   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
3329     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
3330 
3331   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
3332     .addReg(NewSuperReg, 0, SubIdx);
3333 
3334   return SubReg;
3335 }
3336 
3337 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
3338   MachineBasicBlock::iterator MII,
3339   MachineRegisterInfo &MRI,
3340   MachineOperand &Op,
3341   const TargetRegisterClass *SuperRC,
3342   unsigned SubIdx,
3343   const TargetRegisterClass *SubRC) const {
3344   if (Op.isImm()) {
3345     if (SubIdx == AMDGPU::sub0)
3346       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
3347     if (SubIdx == AMDGPU::sub1)
3348       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
3349 
3350     llvm_unreachable("Unhandled register index for immediate");
3351   }
3352 
3353   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
3354                                        SubIdx, SubRC);
3355   return MachineOperand::CreateReg(SubReg, false);
3356 }
3357 
3358 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
3359 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
3360   assert(Inst.getNumExplicitOperands() == 3);
3361   MachineOperand Op1 = Inst.getOperand(1);
3362   Inst.RemoveOperand(1);
3363   Inst.addOperand(Op1);
3364 }
3365 
3366 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
3367                                     const MCOperandInfo &OpInfo,
3368                                     const MachineOperand &MO) const {
3369   if (!MO.isReg())
3370     return false;
3371 
3372   unsigned Reg = MO.getReg();
3373   const TargetRegisterClass *RC =
3374     TargetRegisterInfo::isVirtualRegister(Reg) ?
3375     MRI.getRegClass(Reg) :
3376     RI.getPhysRegClass(Reg);
3377 
3378   const SIRegisterInfo *TRI =
3379       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
3380   RC = TRI->getSubRegClass(RC, MO.getSubReg());
3381 
3382   // In order to be legal, the common sub-class must be equal to the
3383   // class of the current operand.  For example:
3384   //
3385   // v_mov_b32 s0 ; Operand defined as vsrc_b32
3386   //              ; RI.getCommonSubClass(s0,vsrc_b32) = sgpr ; LEGAL
3387   //
3388   // s_sendmsg 0, s0 ; Operand defined as m0reg
3389   //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
3390 
3391   return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
3392 }
3393 
3394 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
3395                                      const MCOperandInfo &OpInfo,
3396                                      const MachineOperand &MO) const {
3397   if (MO.isReg())
3398     return isLegalRegOperand(MRI, OpInfo, MO);
3399 
3400   // Handle non-register types that are treated like immediates.
3401   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
3402   return true;
3403 }
3404 
3405 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
3406                                  const MachineOperand *MO) const {
3407   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3408   const MCInstrDesc &InstDesc = MI.getDesc();
3409   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
3410   const TargetRegisterClass *DefinedRC =
3411       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
3412   if (!MO)
3413     MO = &MI.getOperand(OpIdx);
3414 
3415   if (isVALU(MI) && usesConstantBus(MRI, *MO, OpInfo)) {
3416 
3417     RegSubRegPair SGPRUsed;
3418     if (MO->isReg())
3419       SGPRUsed = RegSubRegPair(MO->getReg(), MO->getSubReg());
3420 
3421     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
3422       if (i == OpIdx)
3423         continue;
3424       const MachineOperand &Op = MI.getOperand(i);
3425       if (Op.isReg()) {
3426         if ((Op.getReg() != SGPRUsed.Reg || Op.getSubReg() != SGPRUsed.SubReg) &&
3427             usesConstantBus(MRI, Op, InstDesc.OpInfo[i])) {
3428           return false;
3429         }
3430       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
3431         return false;
3432       }
3433     }
3434   }
3435 
3436   if (MO->isReg()) {
3437     assert(DefinedRC);
3438     return isLegalRegOperand(MRI, OpInfo, *MO);
3439   }
3440 
3441   // Handle non-register types that are treated like immediates.
3442   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
3443 
3444   if (!DefinedRC) {
3445     // This operand expects an immediate.
3446     return true;
3447   }
3448 
3449   return isImmOperandLegal(MI, OpIdx, *MO);
3450 }
3451 
3452 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
3453                                        MachineInstr &MI) const {
3454   unsigned Opc = MI.getOpcode();
3455   const MCInstrDesc &InstrDesc = get(Opc);
3456 
3457   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3458   MachineOperand &Src1 = MI.getOperand(Src1Idx);
3459 
3460   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
3461   // we need to only have one constant bus use.
3462   //
3463   // Note we do not need to worry about literal constants here. They are
3464   // disabled for the operand type for instructions because they will always
3465   // violate the one constant bus use rule.
3466   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
3467   if (HasImplicitSGPR) {
3468     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3469     MachineOperand &Src0 = MI.getOperand(Src0Idx);
3470 
3471     if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg()))
3472       legalizeOpWithMove(MI, Src0Idx);
3473   }
3474 
3475   // Special case: V_WRITELANE_B32 accepts only immediate or SGPR operands for
3476   // both the value to write (src0) and lane select (src1).  Fix up non-SGPR
3477   // src0/src1 with V_READFIRSTLANE.
3478   if (Opc == AMDGPU::V_WRITELANE_B32) {
3479     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3480     MachineOperand &Src0 = MI.getOperand(Src0Idx);
3481     const DebugLoc &DL = MI.getDebugLoc();
3482     if (Src0.isReg() && RI.isVGPR(MRI, Src0.getReg())) {
3483       unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3484       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
3485           .add(Src0);
3486       Src0.ChangeToRegister(Reg, false);
3487     }
3488     if (Src1.isReg() && RI.isVGPR(MRI, Src1.getReg())) {
3489       unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3490       const DebugLoc &DL = MI.getDebugLoc();
3491       BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
3492           .add(Src1);
3493       Src1.ChangeToRegister(Reg, false);
3494     }
3495     return;
3496   }
3497 
3498   // VOP2 src0 instructions support all operand types, so we don't need to check
3499   // their legality. If src1 is already legal, we don't need to do anything.
3500   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
3501     return;
3502 
3503   // Special case: V_READLANE_B32 accepts only immediate or SGPR operands for
3504   // lane select. Fix up using V_READFIRSTLANE, since we assume that the lane
3505   // select is uniform.
3506   if (Opc == AMDGPU::V_READLANE_B32 && Src1.isReg() &&
3507       RI.isVGPR(MRI, Src1.getReg())) {
3508     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3509     const DebugLoc &DL = MI.getDebugLoc();
3510     BuildMI(*MI.getParent(), MI, DL, get(AMDGPU::V_READFIRSTLANE_B32), Reg)
3511         .add(Src1);
3512     Src1.ChangeToRegister(Reg, false);
3513     return;
3514   }
3515 
3516   // We do not use commuteInstruction here because it is too aggressive and will
3517   // commute if it is possible. We only want to commute here if it improves
3518   // legality. This can be called a fairly large number of times so don't waste
3519   // compile time pointlessly swapping and checking legality again.
3520   if (HasImplicitSGPR || !MI.isCommutable()) {
3521     legalizeOpWithMove(MI, Src1Idx);
3522     return;
3523   }
3524 
3525   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3526   MachineOperand &Src0 = MI.getOperand(Src0Idx);
3527 
3528   // If src0 can be used as src1, commuting will make the operands legal.
3529   // Otherwise we have to give up and insert a move.
3530   //
3531   // TODO: Other immediate-like operand kinds could be commuted if there was a
3532   // MachineOperand::ChangeTo* for them.
3533   if ((!Src1.isImm() && !Src1.isReg()) ||
3534       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
3535     legalizeOpWithMove(MI, Src1Idx);
3536     return;
3537   }
3538 
3539   int CommutedOpc = commuteOpcode(MI);
3540   if (CommutedOpc == -1) {
3541     legalizeOpWithMove(MI, Src1Idx);
3542     return;
3543   }
3544 
3545   MI.setDesc(get(CommutedOpc));
3546 
3547   unsigned Src0Reg = Src0.getReg();
3548   unsigned Src0SubReg = Src0.getSubReg();
3549   bool Src0Kill = Src0.isKill();
3550 
3551   if (Src1.isImm())
3552     Src0.ChangeToImmediate(Src1.getImm());
3553   else if (Src1.isReg()) {
3554     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
3555     Src0.setSubReg(Src1.getSubReg());
3556   } else
3557     llvm_unreachable("Should only have register or immediate operands");
3558 
3559   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
3560   Src1.setSubReg(Src0SubReg);
3561 }
3562 
3563 // Legalize VOP3 operands. Because all operand types are supported for any
3564 // operand, and since literal constants are not allowed and should never be
3565 // seen, we only need to worry about inserting copies if we use multiple SGPR
3566 // operands.
3567 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
3568                                        MachineInstr &MI) const {
3569   unsigned Opc = MI.getOpcode();
3570 
3571   int VOP3Idx[3] = {
3572     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
3573     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
3574     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
3575   };
3576 
3577   // Find the one SGPR operand we are allowed to use.
3578   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
3579 
3580   for (unsigned i = 0; i < 3; ++i) {
3581     int Idx = VOP3Idx[i];
3582     if (Idx == -1)
3583       break;
3584     MachineOperand &MO = MI.getOperand(Idx);
3585 
3586     // We should never see a VOP3 instruction with an illegal immediate operand.
3587     if (!MO.isReg())
3588       continue;
3589 
3590     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
3591       continue; // VGPRs are legal
3592 
3593     if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
3594       SGPRReg = MO.getReg();
3595       // We can use one SGPR in each VOP3 instruction.
3596       continue;
3597     }
3598 
3599     // If we make it this far, then the operand is not legal and we must
3600     // legalize it.
3601     legalizeOpWithMove(MI, Idx);
3602   }
3603 }
3604 
3605 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
3606                                          MachineRegisterInfo &MRI) const {
3607   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
3608   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
3609   unsigned DstReg = MRI.createVirtualRegister(SRC);
3610   unsigned SubRegs = RI.getRegSizeInBits(*VRC) / 32;
3611 
3612   if (SubRegs == 1) {
3613     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
3614             get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
3615         .addReg(SrcReg);
3616     return DstReg;
3617   }
3618 
3619   SmallVector<unsigned, 8> SRegs;
3620   for (unsigned i = 0; i < SubRegs; ++i) {
3621     unsigned SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3622     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
3623             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
3624         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
3625     SRegs.push_back(SGPR);
3626   }
3627 
3628   MachineInstrBuilder MIB =
3629       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
3630               get(AMDGPU::REG_SEQUENCE), DstReg);
3631   for (unsigned i = 0; i < SubRegs; ++i) {
3632     MIB.addReg(SRegs[i]);
3633     MIB.addImm(RI.getSubRegFromChannel(i));
3634   }
3635   return DstReg;
3636 }
3637 
3638 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
3639                                        MachineInstr &MI) const {
3640 
3641   // If the pointer is store in VGPRs, then we need to move them to
3642   // SGPRs using v_readfirstlane.  This is safe because we only select
3643   // loads with uniform pointers to SMRD instruction so we know the
3644   // pointer value is uniform.
3645   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
3646   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
3647     unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
3648     SBase->setReg(SGPR);
3649   }
3650   MachineOperand *SOff = getNamedOperand(MI, AMDGPU::OpName::soff);
3651   if (SOff && !RI.isSGPRClass(MRI.getRegClass(SOff->getReg()))) {
3652     unsigned SGPR = readlaneVGPRToSGPR(SOff->getReg(), MI, MRI);
3653     SOff->setReg(SGPR);
3654   }
3655 }
3656 
3657 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
3658                                          MachineBasicBlock::iterator I,
3659                                          const TargetRegisterClass *DstRC,
3660                                          MachineOperand &Op,
3661                                          MachineRegisterInfo &MRI,
3662                                          const DebugLoc &DL) const {
3663   unsigned OpReg = Op.getReg();
3664   unsigned OpSubReg = Op.getSubReg();
3665 
3666   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
3667       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
3668 
3669   // Check if operand is already the correct register class.
3670   if (DstRC == OpRC)
3671     return;
3672 
3673   unsigned DstReg = MRI.createVirtualRegister(DstRC);
3674   MachineInstr *Copy =
3675       BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg).add(Op);
3676 
3677   Op.setReg(DstReg);
3678   Op.setSubReg(0);
3679 
3680   MachineInstr *Def = MRI.getVRegDef(OpReg);
3681   if (!Def)
3682     return;
3683 
3684   // Try to eliminate the copy if it is copying an immediate value.
3685   if (Def->isMoveImmediate())
3686     FoldImmediate(*Copy, *Def, OpReg, &MRI);
3687 }
3688 
3689 // Emit the actual waterfall loop, executing the wrapped instruction for each
3690 // unique value of \p Rsrc across all lanes. In the best case we execute 1
3691 // iteration, in the worst case we execute 64 (once per lane).
3692 static void
3693 emitLoadSRsrcFromVGPRLoop(const SIInstrInfo &TII, MachineRegisterInfo &MRI,
3694                           MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3695                           const DebugLoc &DL, MachineOperand &Rsrc) {
3696   MachineBasicBlock::iterator I = LoopBB.begin();
3697 
3698   unsigned VRsrc = Rsrc.getReg();
3699   unsigned VRsrcUndef = getUndefRegState(Rsrc.isUndef());
3700 
3701   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3702   unsigned CondReg0 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3703   unsigned CondReg1 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3704   unsigned AndCond = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3705   unsigned SRsrcSub0 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3706   unsigned SRsrcSub1 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3707   unsigned SRsrcSub2 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3708   unsigned SRsrcSub3 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3709   unsigned SRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
3710 
3711   // Beginning of the loop, read the next Rsrc variant.
3712   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub0)
3713       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub0);
3714   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub1)
3715       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub1);
3716   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub2)
3717       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub2);
3718   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), SRsrcSub3)
3719       .addReg(VRsrc, VRsrcUndef, AMDGPU::sub3);
3720 
3721   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), SRsrc)
3722       .addReg(SRsrcSub0)
3723       .addImm(AMDGPU::sub0)
3724       .addReg(SRsrcSub1)
3725       .addImm(AMDGPU::sub1)
3726       .addReg(SRsrcSub2)
3727       .addImm(AMDGPU::sub2)
3728       .addReg(SRsrcSub3)
3729       .addImm(AMDGPU::sub3);
3730 
3731   // Update Rsrc operand to use the SGPR Rsrc.
3732   Rsrc.setReg(SRsrc);
3733   Rsrc.setIsKill(true);
3734 
3735   // Identify all lanes with identical Rsrc operands in their VGPRs.
3736   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), CondReg0)
3737       .addReg(SRsrc, 0, AMDGPU::sub0_sub1)
3738       .addReg(VRsrc, 0, AMDGPU::sub0_sub1);
3739   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::V_CMP_EQ_U64_e64), CondReg1)
3740       .addReg(SRsrc, 0, AMDGPU::sub2_sub3)
3741       .addReg(VRsrc, 0, AMDGPU::sub2_sub3);
3742   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_AND_B64), AndCond)
3743       .addReg(CondReg0)
3744       .addReg(CondReg1);
3745 
3746   MRI.setSimpleHint(SaveExec, AndCond);
3747 
3748   // Update EXEC to matching lanes, saving original to SaveExec.
3749   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_AND_SAVEEXEC_B64), SaveExec)
3750       .addReg(AndCond, RegState::Kill);
3751 
3752   // The original instruction is here; we insert the terminators after it.
3753   I = LoopBB.end();
3754 
3755   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3756   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC)
3757       .addReg(AMDGPU::EXEC)
3758       .addReg(SaveExec);
3759   BuildMI(LoopBB, I, DL, TII.get(AMDGPU::S_CBRANCH_EXECNZ)).addMBB(&LoopBB);
3760 }
3761 
3762 // Build a waterfall loop around \p MI, replacing the VGPR \p Rsrc register
3763 // with SGPRs by iterating over all unique values across all lanes.
3764 static void loadSRsrcFromVGPR(const SIInstrInfo &TII, MachineInstr &MI,
3765                               MachineOperand &Rsrc, MachineDominatorTree *MDT) {
3766   MachineBasicBlock &MBB = *MI.getParent();
3767   MachineFunction &MF = *MBB.getParent();
3768   MachineRegisterInfo &MRI = MF.getRegInfo();
3769   MachineBasicBlock::iterator I(&MI);
3770   const DebugLoc &DL = MI.getDebugLoc();
3771 
3772   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3773 
3774   // Save the EXEC mask
3775   BuildMI(MBB, I, DL, TII.get(AMDGPU::S_MOV_B64), SaveExec)
3776       .addReg(AMDGPU::EXEC);
3777 
3778   // Killed uses in the instruction we are waterfalling around will be
3779   // incorrect due to the added control-flow.
3780   for (auto &MO : MI.uses()) {
3781     if (MO.isReg() && MO.isUse()) {
3782       MRI.clearKillFlags(MO.getReg());
3783     }
3784   }
3785 
3786   // To insert the loop we need to split the block. Move everything after this
3787   // point to a new block, and insert a new empty block between the two.
3788   MachineBasicBlock *LoopBB = MF.CreateMachineBasicBlock();
3789   MachineBasicBlock *RemainderBB = MF.CreateMachineBasicBlock();
3790   MachineFunction::iterator MBBI(MBB);
3791   ++MBBI;
3792 
3793   MF.insert(MBBI, LoopBB);
3794   MF.insert(MBBI, RemainderBB);
3795 
3796   LoopBB->addSuccessor(LoopBB);
3797   LoopBB->addSuccessor(RemainderBB);
3798 
3799   // Move MI to the LoopBB, and the remainder of the block to RemainderBB.
3800   MachineBasicBlock::iterator J = I++;
3801   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3802   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3803   LoopBB->splice(LoopBB->begin(), &MBB, J);
3804 
3805   MBB.addSuccessor(LoopBB);
3806 
3807   // Update dominators. We know that MBB immediately dominates LoopBB, that
3808   // LoopBB immediately dominates RemainderBB, and that RemainderBB immediately
3809   // dominates all of the successors transferred to it from MBB that MBB used
3810   // to dominate.
3811   if (MDT) {
3812     MDT->addNewBlock(LoopBB, &MBB);
3813     MDT->addNewBlock(RemainderBB, LoopBB);
3814     for (auto &Succ : RemainderBB->successors()) {
3815       if (MDT->dominates(&MBB, Succ)) {
3816         MDT->changeImmediateDominator(Succ, RemainderBB);
3817       }
3818     }
3819   }
3820 
3821   emitLoadSRsrcFromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, Rsrc);
3822 
3823   // Restore the EXEC mask
3824   MachineBasicBlock::iterator First = RemainderBB->begin();
3825   BuildMI(*RemainderBB, First, DL, TII.get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
3826       .addReg(SaveExec);
3827 }
3828 
3829 // Extract pointer from Rsrc and return a zero-value Rsrc replacement.
3830 static std::tuple<unsigned, unsigned>
3831 extractRsrcPtr(const SIInstrInfo &TII, MachineInstr &MI, MachineOperand &Rsrc) {
3832   MachineBasicBlock &MBB = *MI.getParent();
3833   MachineFunction &MF = *MBB.getParent();
3834   MachineRegisterInfo &MRI = MF.getRegInfo();
3835 
3836   // Extract the ptr from the resource descriptor.
3837   unsigned RsrcPtr =
3838       TII.buildExtractSubReg(MI, MRI, Rsrc, &AMDGPU::VReg_128RegClass,
3839                              AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
3840 
3841   // Create an empty resource descriptor
3842   unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
3843   unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3844   unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3845   unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
3846   uint64_t RsrcDataFormat = TII.getDefaultRsrcDataFormat();
3847 
3848   // Zero64 = 0
3849   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B64), Zero64)
3850       .addImm(0);
3851 
3852   // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
3853   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
3854       .addImm(RsrcDataFormat & 0xFFFFFFFF);
3855 
3856   // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
3857   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
3858       .addImm(RsrcDataFormat >> 32);
3859 
3860   // NewSRsrc = {Zero64, SRsrcFormat}
3861   BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(AMDGPU::REG_SEQUENCE), NewSRsrc)
3862       .addReg(Zero64)
3863       .addImm(AMDGPU::sub0_sub1)
3864       .addReg(SRsrcFormatLo)
3865       .addImm(AMDGPU::sub2)
3866       .addReg(SRsrcFormatHi)
3867       .addImm(AMDGPU::sub3);
3868 
3869   return std::make_tuple(RsrcPtr, NewSRsrc);
3870 }
3871 
3872 void SIInstrInfo::legalizeOperands(MachineInstr &MI,
3873                                    MachineDominatorTree *MDT) const {
3874   MachineFunction &MF = *MI.getParent()->getParent();
3875   MachineRegisterInfo &MRI = MF.getRegInfo();
3876 
3877   // Legalize VOP2
3878   if (isVOP2(MI) || isVOPC(MI)) {
3879     legalizeOperandsVOP2(MRI, MI);
3880     return;
3881   }
3882 
3883   // Legalize VOP3
3884   if (isVOP3(MI)) {
3885     legalizeOperandsVOP3(MRI, MI);
3886     return;
3887   }
3888 
3889   // Legalize SMRD
3890   if (isSMRD(MI)) {
3891     legalizeOperandsSMRD(MRI, MI);
3892     return;
3893   }
3894 
3895   // Legalize REG_SEQUENCE and PHI
3896   // The register class of the operands much be the same type as the register
3897   // class of the output.
3898   if (MI.getOpcode() == AMDGPU::PHI) {
3899     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
3900     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
3901       if (!MI.getOperand(i).isReg() ||
3902           !TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
3903         continue;
3904       const TargetRegisterClass *OpRC =
3905           MRI.getRegClass(MI.getOperand(i).getReg());
3906       if (RI.hasVGPRs(OpRC)) {
3907         VRC = OpRC;
3908       } else {
3909         SRC = OpRC;
3910       }
3911     }
3912 
3913     // If any of the operands are VGPR registers, then they all most be
3914     // otherwise we will create illegal VGPR->SGPR copies when legalizing
3915     // them.
3916     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
3917       if (!VRC) {
3918         assert(SRC);
3919         VRC = RI.getEquivalentVGPRClass(SRC);
3920       }
3921       RC = VRC;
3922     } else {
3923       RC = SRC;
3924     }
3925 
3926     // Update all the operands so they have the same type.
3927     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3928       MachineOperand &Op = MI.getOperand(I);
3929       if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
3930         continue;
3931 
3932       // MI is a PHI instruction.
3933       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
3934       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
3935 
3936       // Avoid creating no-op copies with the same src and dst reg class.  These
3937       // confuse some of the machine passes.
3938       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
3939     }
3940   }
3941 
3942   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
3943   // VGPR dest type and SGPR sources, insert copies so all operands are
3944   // VGPRs. This seems to help operand folding / the register coalescer.
3945   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
3946     MachineBasicBlock *MBB = MI.getParent();
3947     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
3948     if (RI.hasVGPRs(DstRC)) {
3949       // Update all the operands so they are VGPR register classes. These may
3950       // not be the same register class because REG_SEQUENCE supports mixing
3951       // subregister index types e.g. sub0_sub1 + sub2 + sub3
3952       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
3953         MachineOperand &Op = MI.getOperand(I);
3954         if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
3955           continue;
3956 
3957         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
3958         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
3959         if (VRC == OpRC)
3960           continue;
3961 
3962         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
3963         Op.setIsKill();
3964       }
3965     }
3966 
3967     return;
3968   }
3969 
3970   // Legalize INSERT_SUBREG
3971   // src0 must have the same register class as dst
3972   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
3973     unsigned Dst = MI.getOperand(0).getReg();
3974     unsigned Src0 = MI.getOperand(1).getReg();
3975     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
3976     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
3977     if (DstRC != Src0RC) {
3978       MachineBasicBlock *MBB = MI.getParent();
3979       MachineOperand &Op = MI.getOperand(1);
3980       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
3981     }
3982     return;
3983   }
3984 
3985   // Legalize SI_INIT_M0
3986   if (MI.getOpcode() == AMDGPU::SI_INIT_M0) {
3987     MachineOperand &Src = MI.getOperand(0);
3988     if (Src.isReg() && RI.hasVGPRs(MRI.getRegClass(Src.getReg())))
3989       Src.setReg(readlaneVGPRToSGPR(Src.getReg(), MI, MRI));
3990     return;
3991   }
3992 
3993   // Legalize MIMG and MUBUF/MTBUF for shaders.
3994   //
3995   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
3996   // scratch memory access. In both cases, the legalization never involves
3997   // conversion to the addr64 form.
3998   if (isMIMG(MI) ||
3999       (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
4000        (isMUBUF(MI) || isMTBUF(MI)))) {
4001     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
4002     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
4003       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
4004       SRsrc->setReg(SGPR);
4005     }
4006 
4007     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
4008     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
4009       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
4010       SSamp->setReg(SGPR);
4011     }
4012     return;
4013   }
4014 
4015   // Legalize MUBUF* instructions.
4016   int RsrcIdx =
4017       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
4018   if (RsrcIdx != -1) {
4019     // We have an MUBUF instruction
4020     MachineOperand *Rsrc = &MI.getOperand(RsrcIdx);
4021     unsigned RsrcRC = get(MI.getOpcode()).OpInfo[RsrcIdx].RegClass;
4022     if (RI.getCommonSubClass(MRI.getRegClass(Rsrc->getReg()),
4023                              RI.getRegClass(RsrcRC))) {
4024       // The operands are legal.
4025       // FIXME: We may need to legalize operands besided srsrc.
4026       return;
4027     }
4028 
4029     // Legalize a VGPR Rsrc.
4030     //
4031     // If the instruction is _ADDR64, we can avoid a waterfall by extracting
4032     // the base pointer from the VGPR Rsrc, adding it to the VAddr, then using
4033     // a zero-value SRsrc.
4034     //
4035     // If the instruction is _OFFSET (both idxen and offen disabled), and we
4036     // support ADDR64 instructions, we can convert to ADDR64 and do the same as
4037     // above.
4038     //
4039     // Otherwise we are on non-ADDR64 hardware, and/or we have
4040     // idxen/offen/bothen and we fall back to a waterfall loop.
4041 
4042     MachineBasicBlock &MBB = *MI.getParent();
4043 
4044     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
4045     if (VAddr && AMDGPU::getIfAddr64Inst(MI.getOpcode()) != -1) {
4046       // This is already an ADDR64 instruction so we need to add the pointer
4047       // extracted from the resource descriptor to the current value of VAddr.
4048       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4049       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4050       unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4051 
4052       unsigned RsrcPtr, NewSRsrc;
4053       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
4054 
4055       // NewVaddrLo = RsrcPtr:sub0 + VAddr:sub0
4056       DebugLoc DL = MI.getDebugLoc();
4057       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), NewVAddrLo)
4058           .addReg(RsrcPtr, 0, AMDGPU::sub0)
4059           .addReg(VAddr->getReg(), 0, AMDGPU::sub0);
4060 
4061       // NewVaddrHi = RsrcPtr:sub1 + VAddr:sub1
4062       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e32), NewVAddrHi)
4063           .addReg(RsrcPtr, 0, AMDGPU::sub1)
4064           .addReg(VAddr->getReg(), 0, AMDGPU::sub1);
4065 
4066       // NewVaddr = {NewVaddrHi, NewVaddrLo}
4067       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
4068           .addReg(NewVAddrLo)
4069           .addImm(AMDGPU::sub0)
4070           .addReg(NewVAddrHi)
4071           .addImm(AMDGPU::sub1);
4072 
4073       VAddr->setReg(NewVAddr);
4074       Rsrc->setReg(NewSRsrc);
4075     } else if (!VAddr && ST.hasAddr64()) {
4076       // This instructions is the _OFFSET variant, so we need to convert it to
4077       // ADDR64.
4078       assert(MBB.getParent()->getSubtarget<GCNSubtarget>().getGeneration()
4079              < AMDGPUSubtarget::VOLCANIC_ISLANDS &&
4080              "FIXME: Need to emit flat atomics here");
4081 
4082       unsigned RsrcPtr, NewSRsrc;
4083       std::tie(RsrcPtr, NewSRsrc) = extractRsrcPtr(*this, MI, *Rsrc);
4084 
4085       unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4086       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
4087       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
4088       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
4089       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
4090 
4091       // Atomics rith return have have an additional tied operand and are
4092       // missing some of the special bits.
4093       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
4094       MachineInstr *Addr64;
4095 
4096       if (!VDataIn) {
4097         // Regular buffer load / store.
4098         MachineInstrBuilder MIB =
4099             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
4100                 .add(*VData)
4101                 .addReg(NewVAddr)
4102                 .addReg(NewSRsrc)
4103                 .add(*SOffset)
4104                 .add(*Offset);
4105 
4106         // Atomics do not have this operand.
4107         if (const MachineOperand *GLC =
4108                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
4109           MIB.addImm(GLC->getImm());
4110         }
4111 
4112         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
4113 
4114         if (const MachineOperand *TFE =
4115                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
4116           MIB.addImm(TFE->getImm());
4117         }
4118 
4119         MIB.cloneMemRefs(MI);
4120         Addr64 = MIB;
4121       } else {
4122         // Atomics with return.
4123         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
4124                      .add(*VData)
4125                      .add(*VDataIn)
4126                      .addReg(NewVAddr)
4127                      .addReg(NewSRsrc)
4128                      .add(*SOffset)
4129                      .add(*Offset)
4130                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
4131                      .cloneMemRefs(MI);
4132       }
4133 
4134       MI.removeFromParent();
4135 
4136       // NewVaddr = {NewVaddrHi, NewVaddrLo}
4137       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
4138               NewVAddr)
4139           .addReg(RsrcPtr, 0, AMDGPU::sub0)
4140           .addImm(AMDGPU::sub0)
4141           .addReg(RsrcPtr, 0, AMDGPU::sub1)
4142           .addImm(AMDGPU::sub1);
4143     } else {
4144       // This is another variant; legalize Rsrc with waterfall loop from VGPRs
4145       // to SGPRs.
4146       loadSRsrcFromVGPR(*this, MI, *Rsrc, MDT);
4147     }
4148   }
4149 }
4150 
4151 void SIInstrInfo::moveToVALU(MachineInstr &TopInst,
4152                              MachineDominatorTree *MDT) const {
4153   SetVectorType Worklist;
4154   Worklist.insert(&TopInst);
4155 
4156   while (!Worklist.empty()) {
4157     MachineInstr &Inst = *Worklist.pop_back_val();
4158     MachineBasicBlock *MBB = Inst.getParent();
4159     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
4160 
4161     unsigned Opcode = Inst.getOpcode();
4162     unsigned NewOpcode = getVALUOp(Inst);
4163 
4164     // Handle some special cases
4165     switch (Opcode) {
4166     default:
4167       break;
4168     case AMDGPU::S_ADD_U64_PSEUDO:
4169     case AMDGPU::S_SUB_U64_PSEUDO:
4170       splitScalar64BitAddSub(Worklist, Inst, MDT);
4171       Inst.eraseFromParent();
4172       continue;
4173     case AMDGPU::S_ADD_I32:
4174     case AMDGPU::S_SUB_I32:
4175       // FIXME: The u32 versions currently selected use the carry.
4176       if (moveScalarAddSub(Worklist, Inst, MDT))
4177         continue;
4178 
4179       // Default handling
4180       break;
4181     case AMDGPU::S_AND_B64:
4182       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32, MDT);
4183       Inst.eraseFromParent();
4184       continue;
4185 
4186     case AMDGPU::S_OR_B64:
4187       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32, MDT);
4188       Inst.eraseFromParent();
4189       continue;
4190 
4191     case AMDGPU::S_XOR_B64:
4192       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32, MDT);
4193       Inst.eraseFromParent();
4194       continue;
4195 
4196     case AMDGPU::S_NAND_B64:
4197       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NAND_B32, MDT);
4198       Inst.eraseFromParent();
4199       continue;
4200 
4201     case AMDGPU::S_NOR_B64:
4202       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_NOR_B32, MDT);
4203       Inst.eraseFromParent();
4204       continue;
4205 
4206     case AMDGPU::S_XNOR_B64:
4207       if (ST.hasDLInsts())
4208         splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XNOR_B32, MDT);
4209       else
4210         splitScalar64BitXnor(Worklist, Inst, MDT);
4211       Inst.eraseFromParent();
4212       continue;
4213 
4214     case AMDGPU::S_ANDN2_B64:
4215       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ANDN2_B32, MDT);
4216       Inst.eraseFromParent();
4217       continue;
4218 
4219     case AMDGPU::S_ORN2_B64:
4220       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_ORN2_B32, MDT);
4221       Inst.eraseFromParent();
4222       continue;
4223 
4224     case AMDGPU::S_NOT_B64:
4225       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
4226       Inst.eraseFromParent();
4227       continue;
4228 
4229     case AMDGPU::S_BCNT1_I32_B64:
4230       splitScalar64BitBCNT(Worklist, Inst);
4231       Inst.eraseFromParent();
4232       continue;
4233 
4234     case AMDGPU::S_BFE_I64:
4235       splitScalar64BitBFE(Worklist, Inst);
4236       Inst.eraseFromParent();
4237       continue;
4238 
4239     case AMDGPU::S_LSHL_B32:
4240       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4241         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
4242         swapOperands(Inst);
4243       }
4244       break;
4245     case AMDGPU::S_ASHR_I32:
4246       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4247         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
4248         swapOperands(Inst);
4249       }
4250       break;
4251     case AMDGPU::S_LSHR_B32:
4252       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4253         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
4254         swapOperands(Inst);
4255       }
4256       break;
4257     case AMDGPU::S_LSHL_B64:
4258       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4259         NewOpcode = AMDGPU::V_LSHLREV_B64;
4260         swapOperands(Inst);
4261       }
4262       break;
4263     case AMDGPU::S_ASHR_I64:
4264       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4265         NewOpcode = AMDGPU::V_ASHRREV_I64;
4266         swapOperands(Inst);
4267       }
4268       break;
4269     case AMDGPU::S_LSHR_B64:
4270       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
4271         NewOpcode = AMDGPU::V_LSHRREV_B64;
4272         swapOperands(Inst);
4273       }
4274       break;
4275 
4276     case AMDGPU::S_ABS_I32:
4277       lowerScalarAbs(Worklist, Inst);
4278       Inst.eraseFromParent();
4279       continue;
4280 
4281     case AMDGPU::S_CBRANCH_SCC0:
4282     case AMDGPU::S_CBRANCH_SCC1:
4283       // Clear unused bits of vcc
4284       BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
4285               AMDGPU::VCC)
4286           .addReg(AMDGPU::EXEC)
4287           .addReg(AMDGPU::VCC);
4288       break;
4289 
4290     case AMDGPU::S_BFE_U64:
4291     case AMDGPU::S_BFM_B64:
4292       llvm_unreachable("Moving this op to VALU not implemented");
4293 
4294     case AMDGPU::S_PACK_LL_B32_B16:
4295     case AMDGPU::S_PACK_LH_B32_B16:
4296     case AMDGPU::S_PACK_HH_B32_B16:
4297       movePackToVALU(Worklist, MRI, Inst);
4298       Inst.eraseFromParent();
4299       continue;
4300 
4301     case AMDGPU::S_XNOR_B32:
4302       lowerScalarXnor(Worklist, Inst);
4303       Inst.eraseFromParent();
4304       continue;
4305 
4306     case AMDGPU::S_NAND_B32:
4307       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_AND_B32);
4308       Inst.eraseFromParent();
4309       continue;
4310 
4311     case AMDGPU::S_NOR_B32:
4312       splitScalarNotBinop(Worklist, Inst, AMDGPU::S_OR_B32);
4313       Inst.eraseFromParent();
4314       continue;
4315 
4316     case AMDGPU::S_ANDN2_B32:
4317       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_AND_B32);
4318       Inst.eraseFromParent();
4319       continue;
4320 
4321     case AMDGPU::S_ORN2_B32:
4322       splitScalarBinOpN2(Worklist, Inst, AMDGPU::S_OR_B32);
4323       Inst.eraseFromParent();
4324       continue;
4325     }
4326 
4327     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
4328       // We cannot move this instruction to the VALU, so we should try to
4329       // legalize its operands instead.
4330       legalizeOperands(Inst, MDT);
4331       continue;
4332     }
4333 
4334     // Use the new VALU Opcode.
4335     const MCInstrDesc &NewDesc = get(NewOpcode);
4336     Inst.setDesc(NewDesc);
4337 
4338     // Remove any references to SCC. Vector instructions can't read from it, and
4339     // We're just about to add the implicit use / defs of VCC, and we don't want
4340     // both.
4341     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
4342       MachineOperand &Op = Inst.getOperand(i);
4343       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
4344         // Only propagate through live-def of SCC.
4345         if (Op.isDef() && !Op.isDead())
4346           addSCCDefUsersToVALUWorklist(Op, Inst, Worklist);
4347         Inst.RemoveOperand(i);
4348       }
4349     }
4350 
4351     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
4352       // We are converting these to a BFE, so we need to add the missing
4353       // operands for the size and offset.
4354       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
4355       Inst.addOperand(MachineOperand::CreateImm(0));
4356       Inst.addOperand(MachineOperand::CreateImm(Size));
4357 
4358     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
4359       // The VALU version adds the second operand to the result, so insert an
4360       // extra 0 operand.
4361       Inst.addOperand(MachineOperand::CreateImm(0));
4362     }
4363 
4364     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
4365 
4366     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
4367       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
4368       // If we need to move this to VGPRs, we need to unpack the second operand
4369       // back into the 2 separate ones for bit offset and width.
4370       assert(OffsetWidthOp.isImm() &&
4371              "Scalar BFE is only implemented for constant width and offset");
4372       uint32_t Imm = OffsetWidthOp.getImm();
4373 
4374       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
4375       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
4376       Inst.RemoveOperand(2);                     // Remove old immediate.
4377       Inst.addOperand(MachineOperand::CreateImm(Offset));
4378       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
4379     }
4380 
4381     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
4382     unsigned NewDstReg = AMDGPU::NoRegister;
4383     if (HasDst) {
4384       unsigned DstReg = Inst.getOperand(0).getReg();
4385       if (TargetRegisterInfo::isPhysicalRegister(DstReg))
4386         continue;
4387 
4388       // Update the destination register class.
4389       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
4390       if (!NewDstRC)
4391         continue;
4392 
4393       if (Inst.isCopy() &&
4394           TargetRegisterInfo::isVirtualRegister(Inst.getOperand(1).getReg()) &&
4395           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
4396         // Instead of creating a copy where src and dst are the same register
4397         // class, we just replace all uses of dst with src.  These kinds of
4398         // copies interfere with the heuristics MachineSink uses to decide
4399         // whether or not to split a critical edge.  Since the pass assumes
4400         // that copies will end up as machine instructions and not be
4401         // eliminated.
4402         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
4403         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
4404         MRI.clearKillFlags(Inst.getOperand(1).getReg());
4405         Inst.getOperand(0).setReg(DstReg);
4406 
4407         // Make sure we don't leave around a dead VGPR->SGPR copy. Normally
4408         // these are deleted later, but at -O0 it would leave a suspicious
4409         // looking illegal copy of an undef register.
4410         for (unsigned I = Inst.getNumOperands() - 1; I != 0; --I)
4411           Inst.RemoveOperand(I);
4412         Inst.setDesc(get(AMDGPU::IMPLICIT_DEF));
4413         continue;
4414       }
4415 
4416       NewDstReg = MRI.createVirtualRegister(NewDstRC);
4417       MRI.replaceRegWith(DstReg, NewDstReg);
4418     }
4419 
4420     // Legalize the operands
4421     legalizeOperands(Inst, MDT);
4422 
4423     if (HasDst)
4424      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
4425   }
4426 }
4427 
4428 // Add/sub require special handling to deal with carry outs.
4429 bool SIInstrInfo::moveScalarAddSub(SetVectorType &Worklist, MachineInstr &Inst,
4430                                    MachineDominatorTree *MDT) const {
4431   if (ST.hasAddNoCarry()) {
4432     // Assume there is no user of scc since we don't select this in that case.
4433     // Since scc isn't used, it doesn't really matter if the i32 or u32 variant
4434     // is used.
4435 
4436     MachineBasicBlock &MBB = *Inst.getParent();
4437     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4438 
4439     unsigned OldDstReg = Inst.getOperand(0).getReg();
4440     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4441 
4442     unsigned Opc = Inst.getOpcode();
4443     assert(Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_SUB_I32);
4444 
4445     unsigned NewOpc = Opc == AMDGPU::S_ADD_I32 ?
4446       AMDGPU::V_ADD_U32_e64 : AMDGPU::V_SUB_U32_e64;
4447 
4448     assert(Inst.getOperand(3).getReg() == AMDGPU::SCC);
4449     Inst.RemoveOperand(3);
4450 
4451     Inst.setDesc(get(NewOpc));
4452     Inst.addOperand(MachineOperand::CreateImm(0)); // clamp bit
4453     Inst.addImplicitDefUseOperands(*MBB.getParent());
4454     MRI.replaceRegWith(OldDstReg, ResultReg);
4455     legalizeOperands(Inst, MDT);
4456 
4457     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4458     return true;
4459   }
4460 
4461   return false;
4462 }
4463 
4464 void SIInstrInfo::lowerScalarAbs(SetVectorType &Worklist,
4465                                  MachineInstr &Inst) const {
4466   MachineBasicBlock &MBB = *Inst.getParent();
4467   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4468   MachineBasicBlock::iterator MII = Inst;
4469   DebugLoc DL = Inst.getDebugLoc();
4470 
4471   MachineOperand &Dest = Inst.getOperand(0);
4472   MachineOperand &Src = Inst.getOperand(1);
4473   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4474   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4475 
4476   unsigned SubOp = ST.hasAddNoCarry() ?
4477     AMDGPU::V_SUB_U32_e32 : AMDGPU::V_SUB_I32_e32;
4478 
4479   BuildMI(MBB, MII, DL, get(SubOp), TmpReg)
4480     .addImm(0)
4481     .addReg(Src.getReg());
4482 
4483   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
4484     .addReg(Src.getReg())
4485     .addReg(TmpReg);
4486 
4487   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4488   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4489 }
4490 
4491 void SIInstrInfo::lowerScalarXnor(SetVectorType &Worklist,
4492                                   MachineInstr &Inst) const {
4493   MachineBasicBlock &MBB = *Inst.getParent();
4494   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4495   MachineBasicBlock::iterator MII = Inst;
4496   const DebugLoc &DL = Inst.getDebugLoc();
4497 
4498   MachineOperand &Dest = Inst.getOperand(0);
4499   MachineOperand &Src0 = Inst.getOperand(1);
4500   MachineOperand &Src1 = Inst.getOperand(2);
4501 
4502   if (ST.hasDLInsts()) {
4503     unsigned NewDest = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4504     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src0, MRI, DL);
4505     legalizeGenericOperand(MBB, MII, &AMDGPU::VGPR_32RegClass, Src1, MRI, DL);
4506 
4507     BuildMI(MBB, MII, DL, get(AMDGPU::V_XNOR_B32_e64), NewDest)
4508       .add(Src0)
4509       .add(Src1);
4510 
4511     MRI.replaceRegWith(Dest.getReg(), NewDest);
4512     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
4513   } else {
4514     // Using the identity !(x ^ y) == (!x ^ y) == (x ^ !y), we can
4515     // invert either source and then perform the XOR. If either source is a
4516     // scalar register, then we can leave the inversion on the scalar unit to
4517     // acheive a better distrubution of scalar and vector instructions.
4518     bool Src0IsSGPR = Src0.isReg() &&
4519                       RI.isSGPRClass(MRI.getRegClass(Src0.getReg()));
4520     bool Src1IsSGPR = Src1.isReg() &&
4521                       RI.isSGPRClass(MRI.getRegClass(Src1.getReg()));
4522     MachineInstr *Not = nullptr;
4523     MachineInstr *Xor = nullptr;
4524     unsigned Temp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4525     unsigned NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4526 
4527     // Build a pair of scalar instructions and add them to the work list.
4528     // The next iteration over the work list will lower these to the vector
4529     // unit as necessary.
4530     if (Src0IsSGPR) {
4531       Not = BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp)
4532         .add(Src0);
4533       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
4534       .addReg(Temp)
4535       .add(Src1);
4536     } else if (Src1IsSGPR) {
4537       Not = BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Temp)
4538         .add(Src1);
4539       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), NewDest)
4540       .add(Src0)
4541       .addReg(Temp);
4542     } else {
4543       Xor = BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B32), Temp)
4544         .add(Src0)
4545         .add(Src1);
4546       Not = BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
4547         .addReg(Temp);
4548       Worklist.insert(Not);
4549     }
4550 
4551     MRI.replaceRegWith(Dest.getReg(), NewDest);
4552 
4553     Worklist.insert(Xor);
4554 
4555     addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
4556   }
4557 }
4558 
4559 void SIInstrInfo::splitScalarNotBinop(SetVectorType &Worklist,
4560                                       MachineInstr &Inst,
4561                                       unsigned Opcode) const {
4562   MachineBasicBlock &MBB = *Inst.getParent();
4563   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4564   MachineBasicBlock::iterator MII = Inst;
4565   const DebugLoc &DL = Inst.getDebugLoc();
4566 
4567   MachineOperand &Dest = Inst.getOperand(0);
4568   MachineOperand &Src0 = Inst.getOperand(1);
4569   MachineOperand &Src1 = Inst.getOperand(2);
4570 
4571   unsigned NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4572   unsigned Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4573 
4574   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), Interm)
4575     .add(Src0)
4576     .add(Src1);
4577 
4578   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), NewDest)
4579     .addReg(Interm);
4580 
4581   Worklist.insert(&Op);
4582   Worklist.insert(&Not);
4583 
4584   MRI.replaceRegWith(Dest.getReg(), NewDest);
4585   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
4586 }
4587 
4588 void SIInstrInfo::splitScalarBinOpN2(SetVectorType& Worklist,
4589                                      MachineInstr &Inst,
4590                                      unsigned Opcode) const {
4591   MachineBasicBlock &MBB = *Inst.getParent();
4592   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4593   MachineBasicBlock::iterator MII = Inst;
4594   const DebugLoc &DL = Inst.getDebugLoc();
4595 
4596   MachineOperand &Dest = Inst.getOperand(0);
4597   MachineOperand &Src0 = Inst.getOperand(1);
4598   MachineOperand &Src1 = Inst.getOperand(2);
4599 
4600   unsigned NewDest = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4601   unsigned Interm = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4602 
4603   MachineInstr &Not = *BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B32), Interm)
4604     .add(Src1);
4605 
4606   MachineInstr &Op = *BuildMI(MBB, MII, DL, get(Opcode), NewDest)
4607     .add(Src0)
4608     .addReg(Interm);
4609 
4610   Worklist.insert(&Not);
4611   Worklist.insert(&Op);
4612 
4613   MRI.replaceRegWith(Dest.getReg(), NewDest);
4614   addUsersToMoveToVALUWorklist(NewDest, MRI, Worklist);
4615 }
4616 
4617 void SIInstrInfo::splitScalar64BitUnaryOp(
4618     SetVectorType &Worklist, MachineInstr &Inst,
4619     unsigned Opcode) const {
4620   MachineBasicBlock &MBB = *Inst.getParent();
4621   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4622 
4623   MachineOperand &Dest = Inst.getOperand(0);
4624   MachineOperand &Src0 = Inst.getOperand(1);
4625   DebugLoc DL = Inst.getDebugLoc();
4626 
4627   MachineBasicBlock::iterator MII = Inst;
4628 
4629   const MCInstrDesc &InstDesc = get(Opcode);
4630   const TargetRegisterClass *Src0RC = Src0.isReg() ?
4631     MRI.getRegClass(Src0.getReg()) :
4632     &AMDGPU::SGPR_32RegClass;
4633 
4634   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
4635 
4636   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4637                                                        AMDGPU::sub0, Src0SubRC);
4638 
4639   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
4640   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
4641   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
4642 
4643   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
4644   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0).add(SrcReg0Sub0);
4645 
4646   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4647                                                        AMDGPU::sub1, Src0SubRC);
4648 
4649   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
4650   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1).add(SrcReg0Sub1);
4651 
4652   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
4653   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
4654     .addReg(DestSub0)
4655     .addImm(AMDGPU::sub0)
4656     .addReg(DestSub1)
4657     .addImm(AMDGPU::sub1);
4658 
4659   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4660 
4661   Worklist.insert(&LoHalf);
4662   Worklist.insert(&HiHalf);
4663 
4664   // We don't need to legalizeOperands here because for a single operand, src0
4665   // will support any kind of input.
4666 
4667   // Move all users of this moved value.
4668   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4669 }
4670 
4671 void SIInstrInfo::splitScalar64BitAddSub(SetVectorType &Worklist,
4672                                          MachineInstr &Inst,
4673                                          MachineDominatorTree *MDT) const {
4674   bool IsAdd = (Inst.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4675 
4676   MachineBasicBlock &MBB = *Inst.getParent();
4677   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4678 
4679   unsigned FullDestReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4680   unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4681   unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4682 
4683   unsigned CarryReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
4684   unsigned DeadCarryReg = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
4685 
4686   MachineOperand &Dest = Inst.getOperand(0);
4687   MachineOperand &Src0 = Inst.getOperand(1);
4688   MachineOperand &Src1 = Inst.getOperand(2);
4689   const DebugLoc &DL = Inst.getDebugLoc();
4690   MachineBasicBlock::iterator MII = Inst;
4691 
4692   const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0.getReg());
4693   const TargetRegisterClass *Src1RC = MRI.getRegClass(Src1.getReg());
4694   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
4695   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
4696 
4697   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4698                                                        AMDGPU::sub0, Src0SubRC);
4699   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4700                                                        AMDGPU::sub0, Src1SubRC);
4701 
4702 
4703   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4704                                                        AMDGPU::sub1, Src0SubRC);
4705   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4706                                                        AMDGPU::sub1, Src1SubRC);
4707 
4708   unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
4709   MachineInstr *LoHalf =
4710     BuildMI(MBB, MII, DL, get(LoOpc), DestSub0)
4711     .addReg(CarryReg, RegState::Define)
4712     .add(SrcReg0Sub0)
4713     .add(SrcReg1Sub0)
4714     .addImm(0); // clamp bit
4715 
4716   unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4717   MachineInstr *HiHalf =
4718     BuildMI(MBB, MII, DL, get(HiOpc), DestSub1)
4719     .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4720     .add(SrcReg0Sub1)
4721     .add(SrcReg1Sub1)
4722     .addReg(CarryReg, RegState::Kill)
4723     .addImm(0); // clamp bit
4724 
4725   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
4726     .addReg(DestSub0)
4727     .addImm(AMDGPU::sub0)
4728     .addReg(DestSub1)
4729     .addImm(AMDGPU::sub1);
4730 
4731   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4732 
4733   // Try to legalize the operands in case we need to swap the order to keep it
4734   // valid.
4735   legalizeOperands(*LoHalf, MDT);
4736   legalizeOperands(*HiHalf, MDT);
4737 
4738   // Move all users of this moved vlaue.
4739   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4740 }
4741 
4742 void SIInstrInfo::splitScalar64BitBinaryOp(SetVectorType &Worklist,
4743                                            MachineInstr &Inst, unsigned Opcode,
4744                                            MachineDominatorTree *MDT) const {
4745   MachineBasicBlock &MBB = *Inst.getParent();
4746   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4747 
4748   MachineOperand &Dest = Inst.getOperand(0);
4749   MachineOperand &Src0 = Inst.getOperand(1);
4750   MachineOperand &Src1 = Inst.getOperand(2);
4751   DebugLoc DL = Inst.getDebugLoc();
4752 
4753   MachineBasicBlock::iterator MII = Inst;
4754 
4755   const MCInstrDesc &InstDesc = get(Opcode);
4756   const TargetRegisterClass *Src0RC = Src0.isReg() ?
4757     MRI.getRegClass(Src0.getReg()) :
4758     &AMDGPU::SGPR_32RegClass;
4759 
4760   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
4761   const TargetRegisterClass *Src1RC = Src1.isReg() ?
4762     MRI.getRegClass(Src1.getReg()) :
4763     &AMDGPU::SGPR_32RegClass;
4764 
4765   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
4766 
4767   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4768                                                        AMDGPU::sub0, Src0SubRC);
4769   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4770                                                        AMDGPU::sub0, Src1SubRC);
4771   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
4772                                                        AMDGPU::sub1, Src0SubRC);
4773   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
4774                                                        AMDGPU::sub1, Src1SubRC);
4775 
4776   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
4777   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
4778   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
4779 
4780   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
4781   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
4782                               .add(SrcReg0Sub0)
4783                               .add(SrcReg1Sub0);
4784 
4785   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
4786   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
4787                               .add(SrcReg0Sub1)
4788                               .add(SrcReg1Sub1);
4789 
4790   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
4791   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
4792     .addReg(DestSub0)
4793     .addImm(AMDGPU::sub0)
4794     .addReg(DestSub1)
4795     .addImm(AMDGPU::sub1);
4796 
4797   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
4798 
4799   Worklist.insert(&LoHalf);
4800   Worklist.insert(&HiHalf);
4801 
4802   // Move all users of this moved vlaue.
4803   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
4804 }
4805 
4806 void SIInstrInfo::splitScalar64BitXnor(SetVectorType &Worklist,
4807                                        MachineInstr &Inst,
4808                                        MachineDominatorTree *MDT) const {
4809   MachineBasicBlock &MBB = *Inst.getParent();
4810   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4811 
4812   MachineOperand &Dest = Inst.getOperand(0);
4813   MachineOperand &Src0 = Inst.getOperand(1);
4814   MachineOperand &Src1 = Inst.getOperand(2);
4815   const DebugLoc &DL = Inst.getDebugLoc();
4816 
4817   MachineBasicBlock::iterator MII = Inst;
4818 
4819   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
4820 
4821   unsigned Interm = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
4822 
4823   MachineOperand* Op0;
4824   MachineOperand* Op1;
4825 
4826   if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg())) {
4827     Op0 = &Src0;
4828     Op1 = &Src1;
4829   } else {
4830     Op0 = &Src1;
4831     Op1 = &Src0;
4832   }
4833 
4834   BuildMI(MBB, MII, DL, get(AMDGPU::S_NOT_B64), Interm)
4835     .add(*Op0);
4836 
4837   unsigned NewDest = MRI.createVirtualRegister(DestRC);
4838 
4839   MachineInstr &Xor = *BuildMI(MBB, MII, DL, get(AMDGPU::S_XOR_B64), NewDest)
4840     .addReg(Interm)
4841     .add(*Op1);
4842 
4843   MRI.replaceRegWith(Dest.getReg(), NewDest);
4844 
4845   Worklist.insert(&Xor);
4846 }
4847 
4848 void SIInstrInfo::splitScalar64BitBCNT(
4849     SetVectorType &Worklist, MachineInstr &Inst) const {
4850   MachineBasicBlock &MBB = *Inst.getParent();
4851   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4852 
4853   MachineBasicBlock::iterator MII = Inst;
4854   const DebugLoc &DL = Inst.getDebugLoc();
4855 
4856   MachineOperand &Dest = Inst.getOperand(0);
4857   MachineOperand &Src = Inst.getOperand(1);
4858 
4859   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
4860   const TargetRegisterClass *SrcRC = Src.isReg() ?
4861     MRI.getRegClass(Src.getReg()) :
4862     &AMDGPU::SGPR_32RegClass;
4863 
4864   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4865   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4866 
4867   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
4868 
4869   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
4870                                                       AMDGPU::sub0, SrcSubRC);
4871   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
4872                                                       AMDGPU::sub1, SrcSubRC);
4873 
4874   BuildMI(MBB, MII, DL, InstDesc, MidReg).add(SrcRegSub0).addImm(0);
4875 
4876   BuildMI(MBB, MII, DL, InstDesc, ResultReg).add(SrcRegSub1).addReg(MidReg);
4877 
4878   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4879 
4880   // We don't need to legalize operands here. src0 for etiher instruction can be
4881   // an SGPR, and the second input is unused or determined here.
4882   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4883 }
4884 
4885 void SIInstrInfo::splitScalar64BitBFE(SetVectorType &Worklist,
4886                                       MachineInstr &Inst) const {
4887   MachineBasicBlock &MBB = *Inst.getParent();
4888   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4889   MachineBasicBlock::iterator MII = Inst;
4890   const DebugLoc &DL = Inst.getDebugLoc();
4891 
4892   MachineOperand &Dest = Inst.getOperand(0);
4893   uint32_t Imm = Inst.getOperand(2).getImm();
4894   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
4895   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
4896 
4897   (void) Offset;
4898 
4899   // Only sext_inreg cases handled.
4900   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
4901          Offset == 0 && "Not implemented");
4902 
4903   if (BitWidth < 32) {
4904     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4905     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4906     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4907 
4908     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
4909         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
4910         .addImm(0)
4911         .addImm(BitWidth);
4912 
4913     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
4914       .addImm(31)
4915       .addReg(MidRegLo);
4916 
4917     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
4918       .addReg(MidRegLo)
4919       .addImm(AMDGPU::sub0)
4920       .addReg(MidRegHi)
4921       .addImm(AMDGPU::sub1);
4922 
4923     MRI.replaceRegWith(Dest.getReg(), ResultReg);
4924     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4925     return;
4926   }
4927 
4928   MachineOperand &Src = Inst.getOperand(1);
4929   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4930   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
4931 
4932   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
4933     .addImm(31)
4934     .addReg(Src.getReg(), 0, AMDGPU::sub0);
4935 
4936   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
4937     .addReg(Src.getReg(), 0, AMDGPU::sub0)
4938     .addImm(AMDGPU::sub0)
4939     .addReg(TmpReg)
4940     .addImm(AMDGPU::sub1);
4941 
4942   MRI.replaceRegWith(Dest.getReg(), ResultReg);
4943   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
4944 }
4945 
4946 void SIInstrInfo::addUsersToMoveToVALUWorklist(
4947   unsigned DstReg,
4948   MachineRegisterInfo &MRI,
4949   SetVectorType &Worklist) const {
4950   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
4951          E = MRI.use_end(); I != E;) {
4952     MachineInstr &UseMI = *I->getParent();
4953 
4954     unsigned OpNo = 0;
4955 
4956     switch (UseMI.getOpcode()) {
4957     case AMDGPU::COPY:
4958     case AMDGPU::WQM:
4959     case AMDGPU::WWM:
4960     case AMDGPU::REG_SEQUENCE:
4961     case AMDGPU::PHI:
4962     case AMDGPU::INSERT_SUBREG:
4963       break;
4964     default:
4965       OpNo = I.getOperandNo();
4966       break;
4967     }
4968 
4969     if (!RI.hasVGPRs(getOpRegClass(UseMI, OpNo))) {
4970       Worklist.insert(&UseMI);
4971 
4972       do {
4973         ++I;
4974       } while (I != E && I->getParent() == &UseMI);
4975     } else {
4976       ++I;
4977     }
4978   }
4979 }
4980 
4981 void SIInstrInfo::movePackToVALU(SetVectorType &Worklist,
4982                                  MachineRegisterInfo &MRI,
4983                                  MachineInstr &Inst) const {
4984   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4985   MachineBasicBlock *MBB = Inst.getParent();
4986   MachineOperand &Src0 = Inst.getOperand(1);
4987   MachineOperand &Src1 = Inst.getOperand(2);
4988   const DebugLoc &DL = Inst.getDebugLoc();
4989 
4990   switch (Inst.getOpcode()) {
4991   case AMDGPU::S_PACK_LL_B32_B16: {
4992     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4993     unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4994 
4995     // FIXME: Can do a lot better if we know the high bits of src0 or src1 are
4996     // 0.
4997     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
4998       .addImm(0xffff);
4999 
5000     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_B32_e64), TmpReg)
5001       .addReg(ImmReg, RegState::Kill)
5002       .add(Src0);
5003 
5004     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHL_OR_B32), ResultReg)
5005       .add(Src1)
5006       .addImm(16)
5007       .addReg(TmpReg, RegState::Kill);
5008     break;
5009   }
5010   case AMDGPU::S_PACK_LH_B32_B16: {
5011     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5012     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
5013       .addImm(0xffff);
5014     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_BFI_B32), ResultReg)
5015       .addReg(ImmReg, RegState::Kill)
5016       .add(Src0)
5017       .add(Src1);
5018     break;
5019   }
5020   case AMDGPU::S_PACK_HH_B32_B16: {
5021     unsigned ImmReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5022     unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5023     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_LSHRREV_B32_e64), TmpReg)
5024       .addImm(16)
5025       .add(Src0);
5026     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_MOV_B32_e32), ImmReg)
5027       .addImm(0xffff0000);
5028     BuildMI(*MBB, Inst, DL, get(AMDGPU::V_AND_OR_B32), ResultReg)
5029       .add(Src1)
5030       .addReg(ImmReg, RegState::Kill)
5031       .addReg(TmpReg, RegState::Kill);
5032     break;
5033   }
5034   default:
5035     llvm_unreachable("unhandled s_pack_* instruction");
5036   }
5037 
5038   MachineOperand &Dest = Inst.getOperand(0);
5039   MRI.replaceRegWith(Dest.getReg(), ResultReg);
5040   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
5041 }
5042 
5043 void SIInstrInfo::addSCCDefUsersToVALUWorklist(MachineOperand &Op,
5044                                                MachineInstr &SCCDefInst,
5045                                                SetVectorType &Worklist) const {
5046   // Ensure that def inst defines SCC, which is still live.
5047   assert(Op.isReg() && Op.getReg() == AMDGPU::SCC && Op.isDef() &&
5048          !Op.isDead() && Op.getParent() == &SCCDefInst);
5049   // This assumes that all the users of SCC are in the same block
5050   // as the SCC def.
5051   for (MachineInstr &MI : // Skip the def inst itself.
5052        make_range(std::next(MachineBasicBlock::iterator(SCCDefInst)),
5053                   SCCDefInst.getParent()->end())) {
5054     // Check if SCC is used first.
5055     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC, false, &RI) != -1)
5056       Worklist.insert(&MI);
5057     // Exit if we find another SCC def.
5058     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC, false, false, &RI) != -1)
5059       return;
5060   }
5061 }
5062 
5063 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
5064   const MachineInstr &Inst) const {
5065   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
5066 
5067   switch (Inst.getOpcode()) {
5068   // For target instructions, getOpRegClass just returns the virtual register
5069   // class associated with the operand, so we need to find an equivalent VGPR
5070   // register class in order to move the instruction to the VALU.
5071   case AMDGPU::COPY:
5072   case AMDGPU::PHI:
5073   case AMDGPU::REG_SEQUENCE:
5074   case AMDGPU::INSERT_SUBREG:
5075   case AMDGPU::WQM:
5076   case AMDGPU::WWM:
5077     if (RI.hasVGPRs(NewDstRC))
5078       return nullptr;
5079 
5080     NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
5081     if (!NewDstRC)
5082       return nullptr;
5083     return NewDstRC;
5084   default:
5085     return NewDstRC;
5086   }
5087 }
5088 
5089 // Find the one SGPR operand we are allowed to use.
5090 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
5091                                    int OpIndices[3]) const {
5092   const MCInstrDesc &Desc = MI.getDesc();
5093 
5094   // Find the one SGPR operand we are allowed to use.
5095   //
5096   // First we need to consider the instruction's operand requirements before
5097   // legalizing. Some operands are required to be SGPRs, such as implicit uses
5098   // of VCC, but we are still bound by the constant bus requirement to only use
5099   // one.
5100   //
5101   // If the operand's class is an SGPR, we can never move it.
5102 
5103   unsigned SGPRReg = findImplicitSGPRRead(MI);
5104   if (SGPRReg != AMDGPU::NoRegister)
5105     return SGPRReg;
5106 
5107   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
5108   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5109 
5110   for (unsigned i = 0; i < 3; ++i) {
5111     int Idx = OpIndices[i];
5112     if (Idx == -1)
5113       break;
5114 
5115     const MachineOperand &MO = MI.getOperand(Idx);
5116     if (!MO.isReg())
5117       continue;
5118 
5119     // Is this operand statically required to be an SGPR based on the operand
5120     // constraints?
5121     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
5122     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
5123     if (IsRequiredSGPR)
5124       return MO.getReg();
5125 
5126     // If this could be a VGPR or an SGPR, Check the dynamic register class.
5127     unsigned Reg = MO.getReg();
5128     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
5129     if (RI.isSGPRClass(RegRC))
5130       UsedSGPRs[i] = Reg;
5131   }
5132 
5133   // We don't have a required SGPR operand, so we have a bit more freedom in
5134   // selecting operands to move.
5135 
5136   // Try to select the most used SGPR. If an SGPR is equal to one of the
5137   // others, we choose that.
5138   //
5139   // e.g.
5140   // V_FMA_F32 v0, s0, s0, s0 -> No moves
5141   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
5142 
5143   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
5144   // prefer those.
5145 
5146   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
5147     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
5148       SGPRReg = UsedSGPRs[0];
5149   }
5150 
5151   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
5152     if (UsedSGPRs[1] == UsedSGPRs[2])
5153       SGPRReg = UsedSGPRs[1];
5154   }
5155 
5156   return SGPRReg;
5157 }
5158 
5159 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
5160                                              unsigned OperandName) const {
5161   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
5162   if (Idx == -1)
5163     return nullptr;
5164 
5165   return &MI.getOperand(Idx);
5166 }
5167 
5168 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
5169   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
5170   if (ST.isAmdHsaOS()) {
5171     // Set ATC = 1. GFX9 doesn't have this bit.
5172     if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5173       RsrcDataFormat |= (1ULL << 56);
5174 
5175     // Set MTYPE = 2 (MTYPE_UC = uncached). GFX9 doesn't have this.
5176     // BTW, it disables TC L2 and therefore decreases performance.
5177     if (ST.getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS)
5178       RsrcDataFormat |= (2ULL << 59);
5179   }
5180 
5181   return RsrcDataFormat;
5182 }
5183 
5184 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
5185   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
5186                     AMDGPU::RSRC_TID_ENABLE |
5187                     0xffffffff; // Size;
5188 
5189   // GFX9 doesn't have ELEMENT_SIZE.
5190   if (ST.getGeneration() <= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
5191     uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
5192     Rsrc23 |= EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT;
5193   }
5194 
5195   // IndexStride = 64.
5196   Rsrc23 |= UINT64_C(3) << AMDGPU::RSRC_INDEX_STRIDE_SHIFT;
5197 
5198   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
5199   // Clear them unless we want a huge stride.
5200   if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5201     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
5202 
5203   return Rsrc23;
5204 }
5205 
5206 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
5207   unsigned Opc = MI.getOpcode();
5208 
5209   return isSMRD(Opc);
5210 }
5211 
5212 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
5213   unsigned Opc = MI.getOpcode();
5214 
5215   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
5216 }
5217 
5218 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
5219                                     int &FrameIndex) const {
5220   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
5221   if (!Addr || !Addr->isFI())
5222     return AMDGPU::NoRegister;
5223 
5224   assert(!MI.memoperands_empty() &&
5225          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
5226 
5227   FrameIndex = Addr->getIndex();
5228   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
5229 }
5230 
5231 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
5232                                         int &FrameIndex) const {
5233   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
5234   assert(Addr && Addr->isFI());
5235   FrameIndex = Addr->getIndex();
5236   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
5237 }
5238 
5239 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
5240                                           int &FrameIndex) const {
5241   if (!MI.mayLoad())
5242     return AMDGPU::NoRegister;
5243 
5244   if (isMUBUF(MI) || isVGPRSpill(MI))
5245     return isStackAccess(MI, FrameIndex);
5246 
5247   if (isSGPRSpill(MI))
5248     return isSGPRStackAccess(MI, FrameIndex);
5249 
5250   return AMDGPU::NoRegister;
5251 }
5252 
5253 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
5254                                          int &FrameIndex) const {
5255   if (!MI.mayStore())
5256     return AMDGPU::NoRegister;
5257 
5258   if (isMUBUF(MI) || isVGPRSpill(MI))
5259     return isStackAccess(MI, FrameIndex);
5260 
5261   if (isSGPRSpill(MI))
5262     return isSGPRStackAccess(MI, FrameIndex);
5263 
5264   return AMDGPU::NoRegister;
5265 }
5266 
5267 unsigned SIInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
5268   unsigned Size = 0;
5269   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
5270   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
5271   while (++I != E && I->isInsideBundle()) {
5272     assert(!I->isBundle() && "No nested bundle!");
5273     Size += getInstSizeInBytes(*I);
5274   }
5275 
5276   return Size;
5277 }
5278 
5279 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
5280   unsigned Opc = MI.getOpcode();
5281   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
5282   unsigned DescSize = Desc.getSize();
5283 
5284   // If we have a definitive size, we can use it. Otherwise we need to inspect
5285   // the operands to know the size.
5286   if (isFixedSize(MI))
5287     return DescSize;
5288 
5289   // 4-byte instructions may have a 32-bit literal encoded after them. Check
5290   // operands that coud ever be literals.
5291   if (isVALU(MI) || isSALU(MI)) {
5292     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
5293     if (Src0Idx == -1)
5294       return DescSize; // No operands.
5295 
5296     if (isLiteralConstantLike(MI.getOperand(Src0Idx), Desc.OpInfo[Src0Idx]))
5297       return DescSize + 4;
5298 
5299     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
5300     if (Src1Idx == -1)
5301       return DescSize;
5302 
5303     if (isLiteralConstantLike(MI.getOperand(Src1Idx), Desc.OpInfo[Src1Idx]))
5304       return DescSize + 4;
5305 
5306     int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
5307     if (Src2Idx == -1)
5308       return DescSize;
5309 
5310     if (isLiteralConstantLike(MI.getOperand(Src2Idx), Desc.OpInfo[Src2Idx]))
5311       return DescSize + 4;
5312 
5313     return DescSize;
5314   }
5315 
5316   switch (Opc) {
5317   case TargetOpcode::IMPLICIT_DEF:
5318   case TargetOpcode::KILL:
5319   case TargetOpcode::DBG_VALUE:
5320   case TargetOpcode::EH_LABEL:
5321     return 0;
5322   case TargetOpcode::BUNDLE:
5323     return getInstBundleSize(MI);
5324   case TargetOpcode::INLINEASM:
5325   case TargetOpcode::INLINEASM_BR: {
5326     const MachineFunction *MF = MI.getParent()->getParent();
5327     const char *AsmStr = MI.getOperand(0).getSymbolName();
5328     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
5329   }
5330   default:
5331     return DescSize;
5332   }
5333 }
5334 
5335 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
5336   if (!isFLAT(MI))
5337     return false;
5338 
5339   if (MI.memoperands_empty())
5340     return true;
5341 
5342   for (const MachineMemOperand *MMO : MI.memoperands()) {
5343     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
5344       return true;
5345   }
5346   return false;
5347 }
5348 
5349 bool SIInstrInfo::isNonUniformBranchInstr(MachineInstr &Branch) const {
5350   return Branch.getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO;
5351 }
5352 
5353 void SIInstrInfo::convertNonUniformIfRegion(MachineBasicBlock *IfEntry,
5354                                             MachineBasicBlock *IfEnd) const {
5355   MachineBasicBlock::iterator TI = IfEntry->getFirstTerminator();
5356   assert(TI != IfEntry->end());
5357 
5358   MachineInstr *Branch = &(*TI);
5359   MachineFunction *MF = IfEntry->getParent();
5360   MachineRegisterInfo &MRI = IfEntry->getParent()->getRegInfo();
5361 
5362   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
5363     unsigned DstReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5364     MachineInstr *SIIF =
5365         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_IF), DstReg)
5366             .add(Branch->getOperand(0))
5367             .add(Branch->getOperand(1));
5368     MachineInstr *SIEND =
5369         BuildMI(*MF, Branch->getDebugLoc(), get(AMDGPU::SI_END_CF))
5370             .addReg(DstReg);
5371 
5372     IfEntry->erase(TI);
5373     IfEntry->insert(IfEntry->end(), SIIF);
5374     IfEnd->insert(IfEnd->getFirstNonPHI(), SIEND);
5375   }
5376 }
5377 
5378 void SIInstrInfo::convertNonUniformLoopRegion(
5379     MachineBasicBlock *LoopEntry, MachineBasicBlock *LoopEnd) const {
5380   MachineBasicBlock::iterator TI = LoopEnd->getFirstTerminator();
5381   // We expect 2 terminators, one conditional and one unconditional.
5382   assert(TI != LoopEnd->end());
5383 
5384   MachineInstr *Branch = &(*TI);
5385   MachineFunction *MF = LoopEnd->getParent();
5386   MachineRegisterInfo &MRI = LoopEnd->getParent()->getRegInfo();
5387 
5388   if (Branch->getOpcode() == AMDGPU::SI_NON_UNIFORM_BRCOND_PSEUDO) {
5389 
5390     unsigned DstReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5391     unsigned BackEdgeReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5392     MachineInstrBuilder HeaderPHIBuilder =
5393         BuildMI(*(MF), Branch->getDebugLoc(), get(TargetOpcode::PHI), DstReg);
5394     for (MachineBasicBlock::pred_iterator PI = LoopEntry->pred_begin(),
5395                                           E = LoopEntry->pred_end();
5396          PI != E; ++PI) {
5397       if (*PI == LoopEnd) {
5398         HeaderPHIBuilder.addReg(BackEdgeReg);
5399       } else {
5400         MachineBasicBlock *PMBB = *PI;
5401         unsigned ZeroReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5402         materializeImmediate(*PMBB, PMBB->getFirstTerminator(), DebugLoc(),
5403                              ZeroReg, 0);
5404         HeaderPHIBuilder.addReg(ZeroReg);
5405       }
5406       HeaderPHIBuilder.addMBB(*PI);
5407     }
5408     MachineInstr *HeaderPhi = HeaderPHIBuilder;
5409     MachineInstr *SIIFBREAK = BuildMI(*(MF), Branch->getDebugLoc(),
5410                                       get(AMDGPU::SI_IF_BREAK), BackEdgeReg)
5411                                   .addReg(DstReg)
5412                                   .add(Branch->getOperand(0));
5413     MachineInstr *SILOOP =
5414         BuildMI(*(MF), Branch->getDebugLoc(), get(AMDGPU::SI_LOOP))
5415             .addReg(BackEdgeReg)
5416             .addMBB(LoopEntry);
5417 
5418     LoopEntry->insert(LoopEntry->begin(), HeaderPhi);
5419     LoopEnd->erase(TI);
5420     LoopEnd->insert(LoopEnd->end(), SIIFBREAK);
5421     LoopEnd->insert(LoopEnd->end(), SILOOP);
5422   }
5423 }
5424 
5425 ArrayRef<std::pair<int, const char *>>
5426 SIInstrInfo::getSerializableTargetIndices() const {
5427   static const std::pair<int, const char *> TargetIndices[] = {
5428       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
5429       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
5430       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
5431       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
5432       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
5433   return makeArrayRef(TargetIndices);
5434 }
5435 
5436 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
5437 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
5438 ScheduleHazardRecognizer *
5439 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
5440                                             const ScheduleDAG *DAG) const {
5441   return new GCNHazardRecognizer(DAG->MF);
5442 }
5443 
5444 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
5445 /// pass.
5446 ScheduleHazardRecognizer *
5447 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
5448   return new GCNHazardRecognizer(MF);
5449 }
5450 
5451 std::pair<unsigned, unsigned>
5452 SIInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
5453   return std::make_pair(TF & MO_MASK, TF & ~MO_MASK);
5454 }
5455 
5456 ArrayRef<std::pair<unsigned, const char *>>
5457 SIInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
5458   static const std::pair<unsigned, const char *> TargetFlags[] = {
5459     { MO_GOTPCREL, "amdgpu-gotprel" },
5460     { MO_GOTPCREL32_LO, "amdgpu-gotprel32-lo" },
5461     { MO_GOTPCREL32_HI, "amdgpu-gotprel32-hi" },
5462     { MO_REL32_LO, "amdgpu-rel32-lo" },
5463     { MO_REL32_HI, "amdgpu-rel32-hi" }
5464   };
5465 
5466   return makeArrayRef(TargetFlags);
5467 }
5468 
5469 bool SIInstrInfo::isBasicBlockPrologue(const MachineInstr &MI) const {
5470   return !MI.isTerminator() && MI.getOpcode() != AMDGPU::COPY &&
5471          MI.modifiesRegister(AMDGPU::EXEC, &RI);
5472 }
5473 
5474 MachineInstrBuilder
5475 SIInstrInfo::getAddNoCarry(MachineBasicBlock &MBB,
5476                            MachineBasicBlock::iterator I,
5477                            const DebugLoc &DL,
5478                            unsigned DestReg) const {
5479   if (ST.hasAddNoCarry())
5480     return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_U32_e64), DestReg);
5481 
5482   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5483   unsigned UnusedCarry = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
5484   MRI.setRegAllocationHint(UnusedCarry, 0, AMDGPU::VCC);
5485 
5486   return BuildMI(MBB, I, DL, get(AMDGPU::V_ADD_I32_e64), DestReg)
5487            .addReg(UnusedCarry, RegState::Define | RegState::Dead);
5488 }
5489 
5490 bool SIInstrInfo::isKillTerminator(unsigned Opcode) {
5491   switch (Opcode) {
5492   case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR:
5493   case AMDGPU::SI_KILL_I1_TERMINATOR:
5494     return true;
5495   default:
5496     return false;
5497   }
5498 }
5499 
5500 const MCInstrDesc &SIInstrInfo::getKillTerminatorFromPseudo(unsigned Opcode) const {
5501   switch (Opcode) {
5502   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
5503     return get(AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR);
5504   case AMDGPU::SI_KILL_I1_PSEUDO:
5505     return get(AMDGPU::SI_KILL_I1_TERMINATOR);
5506   default:
5507     llvm_unreachable("invalid opcode, expected SI_KILL_*_PSEUDO");
5508   }
5509 }
5510 
5511 bool SIInstrInfo::isBufferSMRD(const MachineInstr &MI) const {
5512   if (!isSMRD(MI))
5513     return false;
5514 
5515   // Check that it is using a buffer resource.
5516   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::sbase);
5517   if (Idx == -1) // e.g. s_memtime
5518     return false;
5519 
5520   const auto RCID = MI.getDesc().OpInfo[Idx].RegClass;
5521   return RCID == AMDGPU::SReg_128RegClassID;
5522 }
5523 
5524 // This must be kept in sync with the SIEncodingFamily class in SIInstrInfo.td
5525 enum SIEncodingFamily {
5526   SI = 0,
5527   VI = 1,
5528   SDWA = 2,
5529   SDWA9 = 3,
5530   GFX80 = 4,
5531   GFX9 = 5
5532 };
5533 
5534 static SIEncodingFamily subtargetEncodingFamily(const GCNSubtarget &ST) {
5535   switch (ST.getGeneration()) {
5536   default:
5537     break;
5538   case AMDGPUSubtarget::SOUTHERN_ISLANDS:
5539   case AMDGPUSubtarget::SEA_ISLANDS:
5540     return SIEncodingFamily::SI;
5541   case AMDGPUSubtarget::VOLCANIC_ISLANDS:
5542   case AMDGPUSubtarget::GFX9:
5543     return SIEncodingFamily::VI;
5544   }
5545   llvm_unreachable("Unknown subtarget generation!");
5546 }
5547 
5548 int SIInstrInfo::pseudoToMCOpcode(int Opcode) const {
5549   SIEncodingFamily Gen = subtargetEncodingFamily(ST);
5550 
5551   if ((get(Opcode).TSFlags & SIInstrFlags::renamedInGFX9) != 0 &&
5552     ST.getGeneration() >= AMDGPUSubtarget::GFX9)
5553     Gen = SIEncodingFamily::GFX9;
5554 
5555   if (get(Opcode).TSFlags & SIInstrFlags::SDWA)
5556     Gen = ST.getGeneration() == AMDGPUSubtarget::GFX9 ? SIEncodingFamily::SDWA9
5557                                                       : SIEncodingFamily::SDWA;
5558   // Adjust the encoding family to GFX80 for D16 buffer instructions when the
5559   // subtarget has UnpackedD16VMem feature.
5560   // TODO: remove this when we discard GFX80 encoding.
5561   if (ST.hasUnpackedD16VMem() && (get(Opcode).TSFlags & SIInstrFlags::D16Buf))
5562     Gen = SIEncodingFamily::GFX80;
5563 
5564   int MCOp = AMDGPU::getMCOpcode(Opcode, Gen);
5565 
5566   // -1 means that Opcode is already a native instruction.
5567   if (MCOp == -1)
5568     return Opcode;
5569 
5570   // (uint16_t)-1 means that Opcode is a pseudo instruction that has
5571   // no encoding in the given subtarget generation.
5572   if (MCOp == (uint16_t)-1)
5573     return -1;
5574 
5575   return MCOp;
5576 }
5577 
5578 static
5579 TargetInstrInfo::RegSubRegPair getRegOrUndef(const MachineOperand &RegOpnd) {
5580   assert(RegOpnd.isReg());
5581   return RegOpnd.isUndef() ? TargetInstrInfo::RegSubRegPair() :
5582                              getRegSubRegPair(RegOpnd);
5583 }
5584 
5585 TargetInstrInfo::RegSubRegPair
5586 llvm::getRegSequenceSubReg(MachineInstr &MI, unsigned SubReg) {
5587   assert(MI.isRegSequence());
5588   for (unsigned I = 0, E = (MI.getNumOperands() - 1)/ 2; I < E; ++I)
5589     if (MI.getOperand(1 + 2 * I + 1).getImm() == SubReg) {
5590       auto &RegOp = MI.getOperand(1 + 2 * I);
5591       return getRegOrUndef(RegOp);
5592     }
5593   return TargetInstrInfo::RegSubRegPair();
5594 }
5595 
5596 // Try to find the definition of reg:subreg in subreg-manipulation pseudos
5597 // Following a subreg of reg:subreg isn't supported
5598 static bool followSubRegDef(MachineInstr &MI,
5599                             TargetInstrInfo::RegSubRegPair &RSR) {
5600   if (!RSR.SubReg)
5601     return false;
5602   switch (MI.getOpcode()) {
5603   default: break;
5604   case AMDGPU::REG_SEQUENCE:
5605     RSR = getRegSequenceSubReg(MI, RSR.SubReg);
5606     return true;
5607   // EXTRACT_SUBREG ins't supported as this would follow a subreg of subreg
5608   case AMDGPU::INSERT_SUBREG:
5609     if (RSR.SubReg == (unsigned)MI.getOperand(3).getImm())
5610       // inserted the subreg we're looking for
5611       RSR = getRegOrUndef(MI.getOperand(2));
5612     else { // the subreg in the rest of the reg
5613       auto R1 = getRegOrUndef(MI.getOperand(1));
5614       if (R1.SubReg) // subreg of subreg isn't supported
5615         return false;
5616       RSR.Reg = R1.Reg;
5617     }
5618     return true;
5619   }
5620   return false;
5621 }
5622 
5623 MachineInstr *llvm::getVRegSubRegDef(const TargetInstrInfo::RegSubRegPair &P,
5624                                      MachineRegisterInfo &MRI) {
5625   assert(MRI.isSSA());
5626   if (!TargetRegisterInfo::isVirtualRegister(P.Reg))
5627     return nullptr;
5628 
5629   auto RSR = P;
5630   auto *DefInst = MRI.getVRegDef(RSR.Reg);
5631   while (auto *MI = DefInst) {
5632     DefInst = nullptr;
5633     switch (MI->getOpcode()) {
5634     case AMDGPU::COPY:
5635     case AMDGPU::V_MOV_B32_e32: {
5636       auto &Op1 = MI->getOperand(1);
5637       if (Op1.isReg() &&
5638         TargetRegisterInfo::isVirtualRegister(Op1.getReg())) {
5639         if (Op1.isUndef())
5640           return nullptr;
5641         RSR = getRegSubRegPair(Op1);
5642         DefInst = MRI.getVRegDef(RSR.Reg);
5643       }
5644       break;
5645     }
5646     default:
5647       if (followSubRegDef(*MI, RSR)) {
5648         if (!RSR.Reg)
5649           return nullptr;
5650         DefInst = MRI.getVRegDef(RSR.Reg);
5651       }
5652     }
5653     if (!DefInst)
5654       return MI;
5655   }
5656   return nullptr;
5657 }
5658 
5659 bool llvm::isEXECMaskConstantBetweenDefAndUses(unsigned VReg,
5660                                                MachineRegisterInfo &MRI) {
5661   assert(MRI.isSSA() && "Must be run on SSA");
5662   auto *TRI = MRI.getTargetRegisterInfo();
5663 
5664   auto *DefI = MRI.getVRegDef(VReg);
5665   auto *BB = DefI->getParent();
5666 
5667   DenseSet<MachineInstr*> Uses;
5668   for (auto &Use : MRI.use_nodbg_operands(VReg)) {
5669     auto *I = Use.getParent();
5670     if (I->getParent() != BB)
5671       return false;
5672     Uses.insert(I);
5673   }
5674 
5675   auto E = BB->end();
5676   for (auto I = std::next(DefI->getIterator()); I != E; ++I) {
5677     Uses.erase(&*I);
5678     // don't check the last use
5679     if (Uses.empty() || I->modifiesRegister(AMDGPU::EXEC, TRI))
5680       break;
5681   }
5682   return Uses.empty();
5683 }
5684