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