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