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