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