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