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