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