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