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