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