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