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