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