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