1 //===-- SIInstrInfo.cpp - SI Instruction Information  ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief SI Implementation of TargetInstrInfo.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "SIInstrInfo.h"
16 #include "AMDGPUTargetMachine.h"
17 #include "GCNHazardRecognizer.h"
18 #include "SIDefines.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/ScheduleDAG.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/CodeGen/RegisterScavenging.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/Support/Debug.h"
28 
29 using namespace llvm;
30 
31 // Must be at least 4 to be able to branch over minimum unconditional branch
32 // code. This is only for making it possible to write reasonably small tests for
33 // long branches.
34 static cl::opt<unsigned>
35 BranchOffsetBits("amdgpu-s-branch-bits", cl::ReallyHidden, cl::init(16),
36                  cl::desc("Restrict range of branch instructions (DEBUG)"));
37 
38 SIInstrInfo::SIInstrInfo(const SISubtarget &ST)
39   : AMDGPUInstrInfo(ST), RI(), ST(ST) {}
40 
41 //===----------------------------------------------------------------------===//
42 // TargetInstrInfo callbacks
43 //===----------------------------------------------------------------------===//
44 
45 static unsigned getNumOperandsNoGlue(SDNode *Node) {
46   unsigned N = Node->getNumOperands();
47   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
48     --N;
49   return N;
50 }
51 
52 static SDValue findChainOperand(SDNode *Load) {
53   SDValue LastOp = Load->getOperand(getNumOperandsNoGlue(Load) - 1);
54   assert(LastOp.getValueType() == MVT::Other && "Chain missing from load node");
55   return LastOp;
56 }
57 
58 /// \brief Returns true if both nodes have the same value for the given
59 ///        operand \p Op, or if both nodes do not have this operand.
60 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
61   unsigned Opc0 = N0->getMachineOpcode();
62   unsigned Opc1 = N1->getMachineOpcode();
63 
64   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
65   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
66 
67   if (Op0Idx == -1 && Op1Idx == -1)
68     return true;
69 
70 
71   if ((Op0Idx == -1 && Op1Idx != -1) ||
72       (Op1Idx == -1 && Op0Idx != -1))
73     return false;
74 
75   // getNamedOperandIdx returns the index for the MachineInstr's operands,
76   // which includes the result as the first operand. We are indexing into the
77   // MachineSDNode's operands, so we need to skip the result operand to get
78   // the real index.
79   --Op0Idx;
80   --Op1Idx;
81 
82   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
83 }
84 
85 bool SIInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI,
86                                                     AliasAnalysis *AA) const {
87   // TODO: The generic check fails for VALU instructions that should be
88   // rematerializable due to implicit reads of exec. We really want all of the
89   // generic logic for this except for this.
90   switch (MI.getOpcode()) {
91   case AMDGPU::V_MOV_B32_e32:
92   case AMDGPU::V_MOV_B32_e64:
93   case AMDGPU::V_MOV_B64_PSEUDO:
94     return true;
95   default:
96     return false;
97   }
98 }
99 
100 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
101                                           int64_t &Offset0,
102                                           int64_t &Offset1) const {
103   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
104     return false;
105 
106   unsigned Opc0 = Load0->getMachineOpcode();
107   unsigned Opc1 = Load1->getMachineOpcode();
108 
109   // Make sure both are actually loads.
110   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
111     return false;
112 
113   if (isDS(Opc0) && isDS(Opc1)) {
114 
115     // FIXME: Handle this case:
116     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
117       return false;
118 
119     // Check base reg.
120     if (Load0->getOperand(1) != Load1->getOperand(1))
121       return false;
122 
123     // Check chain.
124     if (findChainOperand(Load0) != findChainOperand(Load1))
125       return false;
126 
127     // Skip read2 / write2 variants for simplicity.
128     // TODO: We should report true if the used offsets are adjacent (excluded
129     // st64 versions).
130     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
131         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
132       return false;
133 
134     Offset0 = cast<ConstantSDNode>(Load0->getOperand(2))->getZExtValue();
135     Offset1 = cast<ConstantSDNode>(Load1->getOperand(2))->getZExtValue();
136     return true;
137   }
138 
139   if (isSMRD(Opc0) && isSMRD(Opc1)) {
140     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
141 
142     // Check base reg.
143     if (Load0->getOperand(0) != Load1->getOperand(0))
144       return false;
145 
146     const ConstantSDNode *Load0Offset =
147         dyn_cast<ConstantSDNode>(Load0->getOperand(1));
148     const ConstantSDNode *Load1Offset =
149         dyn_cast<ConstantSDNode>(Load1->getOperand(1));
150 
151     if (!Load0Offset || !Load1Offset)
152       return false;
153 
154     // Check chain.
155     if (findChainOperand(Load0) != findChainOperand(Load1))
156       return false;
157 
158     Offset0 = Load0Offset->getZExtValue();
159     Offset1 = Load1Offset->getZExtValue();
160     return true;
161   }
162 
163   // MUBUF and MTBUF can access the same addresses.
164   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
165 
166     // MUBUF and MTBUF have vaddr at different indices.
167     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
168         findChainOperand(Load0) != findChainOperand(Load1) ||
169         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
170         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
171       return false;
172 
173     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
174     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
175 
176     if (OffIdx0 == -1 || OffIdx1 == -1)
177       return false;
178 
179     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
180     // inlcude the output in the operand list, but SDNodes don't, we need to
181     // subtract the index by one.
182     --OffIdx0;
183     --OffIdx1;
184 
185     SDValue Off0 = Load0->getOperand(OffIdx0);
186     SDValue Off1 = Load1->getOperand(OffIdx1);
187 
188     // The offset might be a FrameIndexSDNode.
189     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
190       return false;
191 
192     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
193     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
194     return true;
195   }
196 
197   return false;
198 }
199 
200 static bool isStride64(unsigned Opc) {
201   switch (Opc) {
202   case AMDGPU::DS_READ2ST64_B32:
203   case AMDGPU::DS_READ2ST64_B64:
204   case AMDGPU::DS_WRITE2ST64_B32:
205   case AMDGPU::DS_WRITE2ST64_B64:
206     return true;
207   default:
208     return false;
209   }
210 }
211 
212 bool SIInstrInfo::getMemOpBaseRegImmOfs(MachineInstr &LdSt, unsigned &BaseReg,
213                                         int64_t &Offset,
214                                         const TargetRegisterInfo *TRI) const {
215   unsigned Opc = LdSt.getOpcode();
216 
217   if (isDS(LdSt)) {
218     const MachineOperand *OffsetImm =
219         getNamedOperand(LdSt, AMDGPU::OpName::offset);
220     if (OffsetImm) {
221       // Normal, single offset LDS instruction.
222       const MachineOperand *AddrReg =
223           getNamedOperand(LdSt, AMDGPU::OpName::addr);
224 
225       BaseReg = AddrReg->getReg();
226       Offset = OffsetImm->getImm();
227       return true;
228     }
229 
230     // The 2 offset instructions use offset0 and offset1 instead. We can treat
231     // these as a load with a single offset if the 2 offsets are consecutive. We
232     // will use this for some partially aligned loads.
233     const MachineOperand *Offset0Imm =
234         getNamedOperand(LdSt, AMDGPU::OpName::offset0);
235     const MachineOperand *Offset1Imm =
236         getNamedOperand(LdSt, AMDGPU::OpName::offset1);
237 
238     uint8_t Offset0 = Offset0Imm->getImm();
239     uint8_t Offset1 = Offset1Imm->getImm();
240 
241     if (Offset1 > Offset0 && Offset1 - Offset0 == 1) {
242       // Each of these offsets is in element sized units, so we need to convert
243       // to bytes of the individual reads.
244 
245       unsigned EltSize;
246       if (LdSt.mayLoad())
247         EltSize = getOpRegClass(LdSt, 0)->getSize() / 2;
248       else {
249         assert(LdSt.mayStore());
250         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
251         EltSize = getOpRegClass(LdSt, Data0Idx)->getSize();
252       }
253 
254       if (isStride64(Opc))
255         EltSize *= 64;
256 
257       const MachineOperand *AddrReg =
258           getNamedOperand(LdSt, AMDGPU::OpName::addr);
259       BaseReg = AddrReg->getReg();
260       Offset = EltSize * Offset0;
261       return true;
262     }
263 
264     return false;
265   }
266 
267   if (isMUBUF(LdSt) || isMTBUF(LdSt)) {
268     const MachineOperand *SOffset = getNamedOperand(LdSt, AMDGPU::OpName::soffset);
269     if (SOffset && SOffset->isReg())
270       return false;
271 
272     const MachineOperand *AddrReg =
273         getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
274     if (!AddrReg)
275       return false;
276 
277     const MachineOperand *OffsetImm =
278         getNamedOperand(LdSt, AMDGPU::OpName::offset);
279     BaseReg = AddrReg->getReg();
280     Offset = OffsetImm->getImm();
281 
282     if (SOffset) // soffset can be an inline immediate.
283       Offset += SOffset->getImm();
284 
285     return true;
286   }
287 
288   if (isSMRD(LdSt)) {
289     const MachineOperand *OffsetImm =
290         getNamedOperand(LdSt, AMDGPU::OpName::offset);
291     if (!OffsetImm)
292       return false;
293 
294     const MachineOperand *SBaseReg =
295         getNamedOperand(LdSt, AMDGPU::OpName::sbase);
296     BaseReg = SBaseReg->getReg();
297     Offset = OffsetImm->getImm();
298     return true;
299   }
300 
301   if (isFLAT(LdSt)) {
302     const MachineOperand *AddrReg = getNamedOperand(LdSt, AMDGPU::OpName::vaddr);
303     BaseReg = AddrReg->getReg();
304     Offset = 0;
305     return true;
306   }
307 
308   return false;
309 }
310 
311 bool SIInstrInfo::shouldClusterMemOps(MachineInstr &FirstLdSt,
312                                       MachineInstr &SecondLdSt,
313                                       unsigned NumLoads) const {
314   const MachineOperand *FirstDst = nullptr;
315   const MachineOperand *SecondDst = nullptr;
316 
317   if ((isMUBUF(FirstLdSt) && isMUBUF(SecondLdSt)) ||
318       (isMTBUF(FirstLdSt) && isMTBUF(SecondLdSt))) {
319     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdata);
320     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdata);
321   } else if (isSMRD(FirstLdSt) && isSMRD(SecondLdSt)) {
322     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::sdst);
323     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::sdst);
324   } else if (isDS(FirstLdSt) && isDS(SecondLdSt)) {
325     FirstDst = getNamedOperand(FirstLdSt, AMDGPU::OpName::vdst);
326     SecondDst = getNamedOperand(SecondLdSt, AMDGPU::OpName::vdst);
327   }
328 
329   if (!FirstDst || !SecondDst)
330     return false;
331 
332   // Try to limit clustering based on the total number of bytes loaded
333   // rather than the number of instructions.  This is done to help reduce
334   // register pressure.  The method used is somewhat inexact, though,
335   // because it assumes that all loads in the cluster will load the
336   // same number of bytes as FirstLdSt.
337 
338   // The unit of this value is bytes.
339   // FIXME: This needs finer tuning.
340   unsigned LoadClusterThreshold = 16;
341 
342   const MachineRegisterInfo &MRI =
343       FirstLdSt.getParent()->getParent()->getRegInfo();
344   const TargetRegisterClass *DstRC = MRI.getRegClass(FirstDst->getReg());
345 
346   return (NumLoads * DstRC->getSize()) <= LoadClusterThreshold;
347 }
348 
349 void SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
350                               MachineBasicBlock::iterator MI,
351                               const DebugLoc &DL, unsigned DestReg,
352                               unsigned SrcReg, bool KillSrc) const {
353   const TargetRegisterClass *RC = RI.getPhysRegClass(DestReg);
354 
355   if (RC == &AMDGPU::VGPR_32RegClass) {
356     assert(AMDGPU::VGPR_32RegClass.contains(SrcReg) ||
357            AMDGPU::SReg_32RegClass.contains(SrcReg));
358     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
359       .addReg(SrcReg, getKillRegState(KillSrc));
360     return;
361   }
362 
363   if (RC == &AMDGPU::SReg_32_XM0RegClass ||
364       RC == &AMDGPU::SReg_32RegClass) {
365     if (SrcReg == AMDGPU::SCC) {
366       BuildMI(MBB, MI, DL, get(AMDGPU::S_CSELECT_B32), DestReg)
367           .addImm(-1)
368           .addImm(0);
369       return;
370     }
371 
372     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
373     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
374             .addReg(SrcReg, getKillRegState(KillSrc));
375     return;
376   }
377 
378   if (RC == &AMDGPU::SReg_64RegClass) {
379     if (DestReg == AMDGPU::VCC) {
380       if (AMDGPU::SReg_64RegClass.contains(SrcReg)) {
381         BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), AMDGPU::VCC)
382           .addReg(SrcReg, getKillRegState(KillSrc));
383       } else {
384         // FIXME: Hack until VReg_1 removed.
385         assert(AMDGPU::VGPR_32RegClass.contains(SrcReg));
386         BuildMI(MBB, MI, DL, get(AMDGPU::V_CMP_NE_U32_e32))
387           .addImm(0)
388           .addReg(SrcReg, getKillRegState(KillSrc));
389       }
390 
391       return;
392     }
393 
394     assert(AMDGPU::SReg_64RegClass.contains(SrcReg));
395     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
396             .addReg(SrcReg, getKillRegState(KillSrc));
397     return;
398   }
399 
400   if (DestReg == AMDGPU::SCC) {
401     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
402     BuildMI(MBB, MI, DL, get(AMDGPU::S_CMP_LG_U32))
403       .addReg(SrcReg, getKillRegState(KillSrc))
404       .addImm(0);
405     return;
406   }
407 
408   unsigned EltSize = 4;
409   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
410   if (RI.isSGPRClass(RC)) {
411     if (RC->getSize() > 4) {
412       Opcode =  AMDGPU::S_MOV_B64;
413       EltSize = 8;
414     } else {
415       Opcode = AMDGPU::S_MOV_B32;
416       EltSize = 4;
417     }
418   }
419 
420   ArrayRef<int16_t> SubIndices = RI.getRegSplitParts(RC, EltSize);
421   bool Forward = RI.getHWRegIndex(DestReg) <= RI.getHWRegIndex(SrcReg);
422 
423   for (unsigned Idx = 0; Idx < SubIndices.size(); ++Idx) {
424     unsigned SubIdx;
425     if (Forward)
426       SubIdx = SubIndices[Idx];
427     else
428       SubIdx = SubIndices[SubIndices.size() - Idx - 1];
429 
430     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
431       get(Opcode), RI.getSubReg(DestReg, SubIdx));
432 
433     Builder.addReg(RI.getSubReg(SrcReg, SubIdx));
434 
435     if (Idx == SubIndices.size() - 1)
436       Builder.addReg(SrcReg, getKillRegState(KillSrc) | RegState::Implicit);
437 
438     if (Idx == 0)
439       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
440 
441     Builder.addReg(SrcReg, RegState::Implicit);
442   }
443 }
444 
445 int SIInstrInfo::commuteOpcode(unsigned Opcode) const {
446   int NewOpc;
447 
448   // Try to map original to commuted opcode
449   NewOpc = AMDGPU::getCommuteRev(Opcode);
450   if (NewOpc != -1)
451     // Check if the commuted (REV) opcode exists on the target.
452     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
453 
454   // Try to map commuted to original opcode
455   NewOpc = AMDGPU::getCommuteOrig(Opcode);
456   if (NewOpc != -1)
457     // Check if the original (non-REV) opcode exists on the target.
458     return pseudoToMCOpcode(NewOpc) != -1 ? NewOpc : -1;
459 
460   return Opcode;
461 }
462 
463 unsigned SIInstrInfo::getMovOpcode(const TargetRegisterClass *DstRC) const {
464 
465   if (DstRC->getSize() == 4) {
466     return RI.isSGPRClass(DstRC) ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
467   } else if (DstRC->getSize() == 8 && RI.isSGPRClass(DstRC)) {
468     return AMDGPU::S_MOV_B64;
469   } else if (DstRC->getSize() == 8 && !RI.isSGPRClass(DstRC)) {
470     return  AMDGPU::V_MOV_B64_PSEUDO;
471   }
472   return AMDGPU::COPY;
473 }
474 
475 static unsigned getSGPRSpillSaveOpcode(unsigned Size) {
476   switch (Size) {
477   case 4:
478     return AMDGPU::SI_SPILL_S32_SAVE;
479   case 8:
480     return AMDGPU::SI_SPILL_S64_SAVE;
481   case 16:
482     return AMDGPU::SI_SPILL_S128_SAVE;
483   case 32:
484     return AMDGPU::SI_SPILL_S256_SAVE;
485   case 64:
486     return AMDGPU::SI_SPILL_S512_SAVE;
487   default:
488     llvm_unreachable("unknown register size");
489   }
490 }
491 
492 static unsigned getVGPRSpillSaveOpcode(unsigned Size) {
493   switch (Size) {
494   case 4:
495     return AMDGPU::SI_SPILL_V32_SAVE;
496   case 8:
497     return AMDGPU::SI_SPILL_V64_SAVE;
498   case 12:
499     return AMDGPU::SI_SPILL_V96_SAVE;
500   case 16:
501     return AMDGPU::SI_SPILL_V128_SAVE;
502   case 32:
503     return AMDGPU::SI_SPILL_V256_SAVE;
504   case 64:
505     return AMDGPU::SI_SPILL_V512_SAVE;
506   default:
507     llvm_unreachable("unknown register size");
508   }
509 }
510 
511 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
512                                       MachineBasicBlock::iterator MI,
513                                       unsigned SrcReg, bool isKill,
514                                       int FrameIndex,
515                                       const TargetRegisterClass *RC,
516                                       const TargetRegisterInfo *TRI) const {
517   MachineFunction *MF = MBB.getParent();
518   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
519   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
520   DebugLoc DL = MBB.findDebugLoc(MI);
521 
522   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
523   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
524   MachinePointerInfo PtrInfo
525     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
526   MachineMemOperand *MMO
527     = MF->getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
528                                Size, Align);
529 
530   if (RI.isSGPRClass(RC)) {
531     MFI->setHasSpilledSGPRs();
532 
533     // We are only allowed to create one new instruction when spilling
534     // registers, so we need to use pseudo instruction for spilling SGPRs.
535     const MCInstrDesc &OpDesc = get(getSGPRSpillSaveOpcode(RC->getSize()));
536 
537     // The SGPR spill/restore instructions only work on number sgprs, so we need
538     // to make sure we are using the correct register class.
539     if (TargetRegisterInfo::isVirtualRegister(SrcReg) && RC->getSize() == 4) {
540       MachineRegisterInfo &MRI = MF->getRegInfo();
541       MRI.constrainRegClass(SrcReg, &AMDGPU::SReg_32_XM0RegClass);
542     }
543 
544     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc)
545       .addReg(SrcReg, getKillRegState(isKill)) // data
546       .addFrameIndex(FrameIndex)               // addr
547       .addMemOperand(MMO)
548       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
549       .addReg(MFI->getScratchWaveOffsetReg(), RegState::Implicit);
550     // Add the scratch resource registers as implicit uses because we may end up
551     // needing them, and need to ensure that the reserved registers are
552     // correctly handled.
553 
554     if (ST.hasScalarStores()) {
555       // m0 is used for offset to scalar stores if used to spill.
556       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine);
557     }
558 
559     return;
560   }
561 
562   if (!ST.isVGPRSpillingEnabled(*MF->getFunction())) {
563     LLVMContext &Ctx = MF->getFunction()->getContext();
564     Ctx.emitError("SIInstrInfo::storeRegToStackSlot - Do not know how to"
565                   " spill register");
566     BuildMI(MBB, MI, DL, get(AMDGPU::KILL))
567       .addReg(SrcReg);
568 
569     return;
570   }
571 
572   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
573 
574   unsigned Opcode = getVGPRSpillSaveOpcode(RC->getSize());
575   MFI->setHasSpilledVGPRs();
576   BuildMI(MBB, MI, DL, get(Opcode))
577     .addReg(SrcReg, getKillRegState(isKill)) // data
578     .addFrameIndex(FrameIndex)               // addr
579     .addReg(MFI->getScratchRSrcReg())        // scratch_rsrc
580     .addReg(MFI->getScratchWaveOffsetReg())  // scratch_offset
581     .addImm(0)                               // offset
582     .addMemOperand(MMO);
583 }
584 
585 static unsigned getSGPRSpillRestoreOpcode(unsigned Size) {
586   switch (Size) {
587   case 4:
588     return AMDGPU::SI_SPILL_S32_RESTORE;
589   case 8:
590     return AMDGPU::SI_SPILL_S64_RESTORE;
591   case 16:
592     return AMDGPU::SI_SPILL_S128_RESTORE;
593   case 32:
594     return AMDGPU::SI_SPILL_S256_RESTORE;
595   case 64:
596     return AMDGPU::SI_SPILL_S512_RESTORE;
597   default:
598     llvm_unreachable("unknown register size");
599   }
600 }
601 
602 static unsigned getVGPRSpillRestoreOpcode(unsigned Size) {
603   switch (Size) {
604   case 4:
605     return AMDGPU::SI_SPILL_V32_RESTORE;
606   case 8:
607     return AMDGPU::SI_SPILL_V64_RESTORE;
608   case 12:
609     return AMDGPU::SI_SPILL_V96_RESTORE;
610   case 16:
611     return AMDGPU::SI_SPILL_V128_RESTORE;
612   case 32:
613     return AMDGPU::SI_SPILL_V256_RESTORE;
614   case 64:
615     return AMDGPU::SI_SPILL_V512_RESTORE;
616   default:
617     llvm_unreachable("unknown register size");
618   }
619 }
620 
621 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
622                                        MachineBasicBlock::iterator MI,
623                                        unsigned DestReg, int FrameIndex,
624                                        const TargetRegisterClass *RC,
625                                        const TargetRegisterInfo *TRI) const {
626   MachineFunction *MF = MBB.getParent();
627   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
628   MachineFrameInfo &FrameInfo = MF->getFrameInfo();
629   DebugLoc DL = MBB.findDebugLoc(MI);
630   unsigned Align = FrameInfo.getObjectAlignment(FrameIndex);
631   unsigned Size = FrameInfo.getObjectSize(FrameIndex);
632 
633   MachinePointerInfo PtrInfo
634     = MachinePointerInfo::getFixedStack(*MF, FrameIndex);
635 
636   MachineMemOperand *MMO = MF->getMachineMemOperand(
637     PtrInfo, MachineMemOperand::MOLoad, Size, Align);
638 
639   if (RI.isSGPRClass(RC)) {
640     // FIXME: Maybe this should not include a memoperand because it will be
641     // lowered to non-memory instructions.
642     const MCInstrDesc &OpDesc = get(getSGPRSpillRestoreOpcode(RC->getSize()));
643     if (TargetRegisterInfo::isVirtualRegister(DestReg) && RC->getSize() == 4) {
644       MachineRegisterInfo &MRI = MF->getRegInfo();
645       MRI.constrainRegClass(DestReg, &AMDGPU::SReg_32_XM0RegClass);
646     }
647 
648     MachineInstrBuilder Spill = BuildMI(MBB, MI, DL, OpDesc, DestReg)
649       .addFrameIndex(FrameIndex) // addr
650       .addMemOperand(MMO)
651       .addReg(MFI->getScratchRSrcReg(), RegState::Implicit)
652       .addReg(MFI->getScratchWaveOffsetReg(), RegState::Implicit);
653 
654     if (ST.hasScalarStores()) {
655       // m0 is used for offset to scalar stores if used to spill.
656       Spill.addReg(AMDGPU::M0, RegState::ImplicitDefine);
657     }
658 
659     return;
660   }
661 
662   if (!ST.isVGPRSpillingEnabled(*MF->getFunction())) {
663     LLVMContext &Ctx = MF->getFunction()->getContext();
664     Ctx.emitError("SIInstrInfo::loadRegFromStackSlot - Do not know how to"
665                   " restore register");
666     BuildMI(MBB, MI, DL, get(AMDGPU::IMPLICIT_DEF), DestReg);
667 
668     return;
669   }
670 
671   assert(RI.hasVGPRs(RC) && "Only VGPR spilling expected");
672 
673   unsigned Opcode = getVGPRSpillRestoreOpcode(RC->getSize());
674   BuildMI(MBB, MI, DL, get(Opcode), DestReg)
675     .addFrameIndex(FrameIndex)              // vaddr
676     .addReg(MFI->getScratchRSrcReg())       // scratch_rsrc
677     .addReg(MFI->getScratchWaveOffsetReg()) // scratch_offset
678     .addImm(0)                              // offset
679     .addMemOperand(MMO);
680 }
681 
682 /// \param @Offset Offset in bytes of the FrameIndex being spilled
683 unsigned SIInstrInfo::calculateLDSSpillAddress(
684     MachineBasicBlock &MBB, MachineInstr &MI, RegScavenger *RS, unsigned TmpReg,
685     unsigned FrameOffset, unsigned Size) const {
686   MachineFunction *MF = MBB.getParent();
687   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
688   const SISubtarget &ST = MF->getSubtarget<SISubtarget>();
689   const SIRegisterInfo *TRI = ST.getRegisterInfo();
690   DebugLoc DL = MBB.findDebugLoc(MI);
691   unsigned WorkGroupSize = MFI->getMaxFlatWorkGroupSize();
692   unsigned WavefrontSize = ST.getWavefrontSize();
693 
694   unsigned TIDReg = MFI->getTIDReg();
695   if (!MFI->hasCalculatedTID()) {
696     MachineBasicBlock &Entry = MBB.getParent()->front();
697     MachineBasicBlock::iterator Insert = Entry.front();
698     DebugLoc DL = Insert->getDebugLoc();
699 
700     TIDReg = RI.findUnusedRegister(MF->getRegInfo(), &AMDGPU::VGPR_32RegClass,
701                                    *MF);
702     if (TIDReg == AMDGPU::NoRegister)
703       return TIDReg;
704 
705     if (!AMDGPU::isShader(MF->getFunction()->getCallingConv()) &&
706         WorkGroupSize > WavefrontSize) {
707 
708       unsigned TIDIGXReg
709         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_X);
710       unsigned TIDIGYReg
711         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Y);
712       unsigned TIDIGZReg
713         = TRI->getPreloadedValue(*MF, SIRegisterInfo::WORKGROUP_ID_Z);
714       unsigned InputPtrReg =
715           TRI->getPreloadedValue(*MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
716       for (unsigned Reg : {TIDIGXReg, TIDIGYReg, TIDIGZReg}) {
717         if (!Entry.isLiveIn(Reg))
718           Entry.addLiveIn(Reg);
719       }
720 
721       RS->enterBasicBlock(Entry);
722       // FIXME: Can we scavenge an SReg_64 and access the subregs?
723       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
724       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
725       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
726               .addReg(InputPtrReg)
727               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
728       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
729               .addReg(InputPtrReg)
730               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
731 
732       // NGROUPS.X * NGROUPS.Y
733       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
734               .addReg(STmp1)
735               .addReg(STmp0);
736       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
737       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
738               .addReg(STmp1)
739               .addReg(TIDIGXReg);
740       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
741       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
742               .addReg(STmp0)
743               .addReg(TIDIGYReg)
744               .addReg(TIDReg);
745       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
746       BuildMI(Entry, Insert, DL, get(AMDGPU::V_ADD_I32_e32), TIDReg)
747               .addReg(TIDReg)
748               .addReg(TIDIGZReg);
749     } else {
750       // Get the wave id
751       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
752               TIDReg)
753               .addImm(-1)
754               .addImm(0);
755 
756       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e64),
757               TIDReg)
758               .addImm(-1)
759               .addReg(TIDReg);
760     }
761 
762     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
763             TIDReg)
764             .addImm(2)
765             .addReg(TIDReg);
766     MFI->setTIDReg(TIDReg);
767   }
768 
769   // Add FrameIndex to LDS offset
770   unsigned LDSOffset = MFI->getLDSSize() + (FrameOffset * WorkGroupSize);
771   BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), TmpReg)
772           .addImm(LDSOffset)
773           .addReg(TIDReg);
774 
775   return TmpReg;
776 }
777 
778 void SIInstrInfo::insertWaitStates(MachineBasicBlock &MBB,
779                                    MachineBasicBlock::iterator MI,
780                                    int Count) const {
781   DebugLoc DL = MBB.findDebugLoc(MI);
782   while (Count > 0) {
783     int Arg;
784     if (Count >= 8)
785       Arg = 7;
786     else
787       Arg = Count - 1;
788     Count -= 8;
789     BuildMI(MBB, MI, DL, get(AMDGPU::S_NOP))
790             .addImm(Arg);
791   }
792 }
793 
794 void SIInstrInfo::insertNoop(MachineBasicBlock &MBB,
795                              MachineBasicBlock::iterator MI) const {
796   insertWaitStates(MBB, MI, 1);
797 }
798 
799 unsigned SIInstrInfo::getNumWaitStates(const MachineInstr &MI) const {
800   switch (MI.getOpcode()) {
801   default: return 1; // FIXME: Do wait states equal cycles?
802 
803   case AMDGPU::S_NOP:
804     return MI.getOperand(0).getImm() + 1;
805   }
806 }
807 
808 bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
809   MachineBasicBlock &MBB = *MI.getParent();
810   DebugLoc DL = MBB.findDebugLoc(MI);
811   switch (MI.getOpcode()) {
812   default: return AMDGPUInstrInfo::expandPostRAPseudo(MI);
813   case AMDGPU::S_MOV_B64_term: {
814     // This is only a terminator to get the correct spill code placement during
815     // register allocation.
816     MI.setDesc(get(AMDGPU::S_MOV_B64));
817     break;
818   }
819   case AMDGPU::S_XOR_B64_term: {
820     // This is only a terminator to get the correct spill code placement during
821     // register allocation.
822     MI.setDesc(get(AMDGPU::S_XOR_B64));
823     break;
824   }
825   case AMDGPU::S_ANDN2_B64_term: {
826     // This is only a terminator to get the correct spill code placement during
827     // register allocation.
828     MI.setDesc(get(AMDGPU::S_ANDN2_B64));
829     break;
830   }
831   case AMDGPU::V_MOV_B64_PSEUDO: {
832     unsigned Dst = MI.getOperand(0).getReg();
833     unsigned DstLo = RI.getSubReg(Dst, AMDGPU::sub0);
834     unsigned DstHi = RI.getSubReg(Dst, AMDGPU::sub1);
835 
836     const MachineOperand &SrcOp = MI.getOperand(1);
837     // FIXME: Will this work for 64-bit floating point immediates?
838     assert(!SrcOp.isFPImm());
839     if (SrcOp.isImm()) {
840       APInt Imm(64, SrcOp.getImm());
841       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
842         .addImm(Imm.getLoBits(32).getZExtValue())
843         .addReg(Dst, RegState::Implicit | RegState::Define);
844       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
845         .addImm(Imm.getHiBits(32).getZExtValue())
846         .addReg(Dst, RegState::Implicit | RegState::Define);
847     } else {
848       assert(SrcOp.isReg());
849       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstLo)
850         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub0))
851         .addReg(Dst, RegState::Implicit | RegState::Define);
852       BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DstHi)
853         .addReg(RI.getSubReg(SrcOp.getReg(), AMDGPU::sub1))
854         .addReg(Dst, RegState::Implicit | RegState::Define);
855     }
856     MI.eraseFromParent();
857     break;
858   }
859   case AMDGPU::V_MOVRELD_B32_V1:
860   case AMDGPU::V_MOVRELD_B32_V2:
861   case AMDGPU::V_MOVRELD_B32_V4:
862   case AMDGPU::V_MOVRELD_B32_V8:
863   case AMDGPU::V_MOVRELD_B32_V16: {
864     const MCInstrDesc &MovRelDesc = get(AMDGPU::V_MOVRELD_B32_e32);
865     unsigned VecReg = MI.getOperand(0).getReg();
866     bool IsUndef = MI.getOperand(1).isUndef();
867     unsigned SubReg = AMDGPU::sub0 + MI.getOperand(3).getImm();
868     assert(VecReg == MI.getOperand(1).getReg());
869 
870     MachineInstr *MovRel =
871         BuildMI(MBB, MI, DL, MovRelDesc)
872             .addReg(RI.getSubReg(VecReg, SubReg), RegState::Undef)
873             .addOperand(MI.getOperand(2))
874             .addReg(VecReg, RegState::ImplicitDefine)
875             .addReg(VecReg, RegState::Implicit | (IsUndef ? RegState::Undef : 0));
876 
877     const int ImpDefIdx =
878         MovRelDesc.getNumOperands() + MovRelDesc.getNumImplicitUses();
879     const int ImpUseIdx = ImpDefIdx + 1;
880     MovRel->tieOperands(ImpDefIdx, ImpUseIdx);
881 
882     MI.eraseFromParent();
883     break;
884   }
885   case AMDGPU::SI_PC_ADD_REL_OFFSET: {
886     MachineFunction &MF = *MBB.getParent();
887     unsigned Reg = MI.getOperand(0).getReg();
888     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
889     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
890 
891     // Create a bundle so these instructions won't be re-ordered by the
892     // post-RA scheduler.
893     MIBundleBuilder Bundler(MBB, MI);
894     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_GETPC_B64), Reg));
895 
896     // Add 32-bit offset from this instruction to the start of the
897     // constant data.
898     Bundler.append(BuildMI(MF, DL, get(AMDGPU::S_ADD_U32), RegLo)
899                        .addReg(RegLo)
900                        .addOperand(MI.getOperand(1)));
901 
902     MachineInstrBuilder MIB = BuildMI(MF, DL, get(AMDGPU::S_ADDC_U32), RegHi)
903                                   .addReg(RegHi);
904     if (MI.getOperand(2).getTargetFlags() == SIInstrInfo::MO_NONE)
905       MIB.addImm(0);
906     else
907       MIB.addOperand(MI.getOperand(2));
908 
909     Bundler.append(MIB);
910     llvm::finalizeBundle(MBB, Bundler.begin());
911 
912     MI.eraseFromParent();
913     break;
914   }
915   }
916   return true;
917 }
918 
919 bool SIInstrInfo::swapSourceModifiers(MachineInstr &MI,
920                                       MachineOperand &Src0,
921                                       unsigned Src0OpName,
922                                       MachineOperand &Src1,
923                                       unsigned Src1OpName) const {
924   MachineOperand *Src0Mods = getNamedOperand(MI, Src0OpName);
925   if (!Src0Mods)
926     return false;
927 
928   MachineOperand *Src1Mods = getNamedOperand(MI, Src1OpName);
929   assert(Src1Mods &&
930          "All commutable instructions have both src0 and src1 modifiers");
931 
932   int Src0ModsVal = Src0Mods->getImm();
933   int Src1ModsVal = Src1Mods->getImm();
934 
935   Src1Mods->setImm(Src0ModsVal);
936   Src0Mods->setImm(Src1ModsVal);
937   return true;
938 }
939 
940 static MachineInstr *swapRegAndNonRegOperand(MachineInstr &MI,
941                                              MachineOperand &RegOp,
942                                              MachineOperand &NonRegOp) {
943   unsigned Reg = RegOp.getReg();
944   unsigned SubReg = RegOp.getSubReg();
945   bool IsKill = RegOp.isKill();
946   bool IsDead = RegOp.isDead();
947   bool IsUndef = RegOp.isUndef();
948   bool IsDebug = RegOp.isDebug();
949 
950   if (NonRegOp.isImm())
951     RegOp.ChangeToImmediate(NonRegOp.getImm());
952   else if (NonRegOp.isFI())
953     RegOp.ChangeToFrameIndex(NonRegOp.getIndex());
954   else
955     return nullptr;
956 
957   NonRegOp.ChangeToRegister(Reg, false, false, IsKill, IsDead, IsUndef, IsDebug);
958   NonRegOp.setSubReg(SubReg);
959 
960   return &MI;
961 }
962 
963 MachineInstr *SIInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI,
964                                                   unsigned Src0Idx,
965                                                   unsigned Src1Idx) const {
966   assert(!NewMI && "this should never be used");
967 
968   unsigned Opc = MI.getOpcode();
969   int CommutedOpcode = commuteOpcode(Opc);
970   if (CommutedOpcode == -1)
971     return nullptr;
972 
973   assert(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0) ==
974            static_cast<int>(Src0Idx) &&
975          AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) ==
976            static_cast<int>(Src1Idx) &&
977          "inconsistency with findCommutedOpIndices");
978 
979   MachineOperand &Src0 = MI.getOperand(Src0Idx);
980   MachineOperand &Src1 = MI.getOperand(Src1Idx);
981 
982   MachineInstr *CommutedMI = nullptr;
983   if (Src0.isReg() && Src1.isReg()) {
984     if (isOperandLegal(MI, Src1Idx, &Src0)) {
985       // Be sure to copy the source modifiers to the right place.
986       CommutedMI
987         = TargetInstrInfo::commuteInstructionImpl(MI, NewMI, Src0Idx, Src1Idx);
988     }
989 
990   } else if (Src0.isReg() && !Src1.isReg()) {
991     // src0 should always be able to support any operand type, so no need to
992     // check operand legality.
993     CommutedMI = swapRegAndNonRegOperand(MI, Src0, Src1);
994   } else if (!Src0.isReg() && Src1.isReg()) {
995     if (isOperandLegal(MI, Src1Idx, &Src0))
996       CommutedMI = swapRegAndNonRegOperand(MI, Src1, Src0);
997   } else {
998     // FIXME: Found two non registers to commute. This does happen.
999     return nullptr;
1000   }
1001 
1002 
1003   if (CommutedMI) {
1004     swapSourceModifiers(MI, Src0, AMDGPU::OpName::src0_modifiers,
1005                         Src1, AMDGPU::OpName::src1_modifiers);
1006 
1007     CommutedMI->setDesc(get(CommutedOpcode));
1008   }
1009 
1010   return CommutedMI;
1011 }
1012 
1013 // This needs to be implemented because the source modifiers may be inserted
1014 // between the true commutable operands, and the base
1015 // TargetInstrInfo::commuteInstruction uses it.
1016 bool SIInstrInfo::findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx0,
1017                                         unsigned &SrcOpIdx1) const {
1018   if (!MI.isCommutable())
1019     return false;
1020 
1021   unsigned Opc = MI.getOpcode();
1022   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1023   if (Src0Idx == -1)
1024     return false;
1025 
1026   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1027   if (Src1Idx == -1)
1028     return false;
1029 
1030   return fixCommutedOpIndices(SrcOpIdx0, SrcOpIdx1, Src0Idx, Src1Idx);
1031 }
1032 
1033 bool SIInstrInfo::isBranchOffsetInRange(unsigned BranchOp,
1034                                         int64_t BrOffset) const {
1035   // BranchRelaxation should never have to check s_setpc_b64 because its dest
1036   // block is unanalyzable.
1037   assert(BranchOp != AMDGPU::S_SETPC_B64);
1038 
1039   // Convert to dwords.
1040   BrOffset /= 4;
1041 
1042   // The branch instructions do PC += signext(SIMM16 * 4) + 4, so the offset is
1043   // from the next instruction.
1044   BrOffset -= 1;
1045 
1046   return isIntN(BranchOffsetBits, BrOffset);
1047 }
1048 
1049 MachineBasicBlock *SIInstrInfo::getBranchDestBlock(
1050   const MachineInstr &MI) const {
1051   if (MI.getOpcode() == AMDGPU::S_SETPC_B64) {
1052     // This would be a difficult analysis to perform, but can always be legal so
1053     // there's no need to analyze it.
1054     return nullptr;
1055   }
1056 
1057   return MI.getOperand(0).getMBB();
1058 }
1059 
1060 unsigned SIInstrInfo::insertIndirectBranch(MachineBasicBlock &MBB,
1061                                            MachineBasicBlock &DestBB,
1062                                            const DebugLoc &DL,
1063                                            int64_t BrOffset,
1064                                            RegScavenger *RS) const {
1065   assert(RS && "RegScavenger required for long branching");
1066   assert(MBB.empty() &&
1067          "new block should be inserted for expanding unconditional branch");
1068   assert(MBB.pred_size() == 1);
1069 
1070   MachineFunction *MF = MBB.getParent();
1071   MachineRegisterInfo &MRI = MF->getRegInfo();
1072 
1073   // FIXME: Virtual register workaround for RegScavenger not working with empty
1074   // blocks.
1075   unsigned PCReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1076 
1077   auto I = MBB.end();
1078 
1079   // We need to compute the offset relative to the instruction immediately after
1080   // s_getpc_b64. Insert pc arithmetic code before last terminator.
1081   MachineInstr *GetPC = BuildMI(MBB, I, DL, get(AMDGPU::S_GETPC_B64), PCReg);
1082 
1083   // TODO: Handle > 32-bit block address.
1084   if (BrOffset >= 0) {
1085     BuildMI(MBB, I, DL, get(AMDGPU::S_ADD_U32))
1086       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1087       .addReg(PCReg, 0, AMDGPU::sub0)
1088       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_FORWARD);
1089     BuildMI(MBB, I, DL, get(AMDGPU::S_ADDC_U32))
1090       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1091       .addReg(PCReg, 0, AMDGPU::sub1)
1092       .addImm(0);
1093   } else {
1094     // Backwards branch.
1095     BuildMI(MBB, I, DL, get(AMDGPU::S_SUB_U32))
1096       .addReg(PCReg, RegState::Define, AMDGPU::sub0)
1097       .addReg(PCReg, 0, AMDGPU::sub0)
1098       .addMBB(&DestBB, AMDGPU::TF_LONG_BRANCH_BACKWARD);
1099     BuildMI(MBB, I, DL, get(AMDGPU::S_SUBB_U32))
1100       .addReg(PCReg, RegState::Define, AMDGPU::sub1)
1101       .addReg(PCReg, 0, AMDGPU::sub1)
1102       .addImm(0);
1103   }
1104 
1105   // Insert the indirect branch after the other terminator.
1106   BuildMI(&MBB, DL, get(AMDGPU::S_SETPC_B64))
1107     .addReg(PCReg);
1108 
1109   // FIXME: If spilling is necessary, this will fail because this scavenger has
1110   // no emergency stack slots. It is non-trivial to spill in this situation,
1111   // because the restore code needs to be specially placed after the
1112   // jump. BranchRelaxation then needs to be made aware of the newly inserted
1113   // block.
1114   //
1115   // If a spill is needed for the pc register pair, we need to insert a spill
1116   // restore block right before the destination block, and insert a short branch
1117   // into the old destination block's fallthrough predecessor.
1118   // e.g.:
1119   //
1120   // s_cbranch_scc0 skip_long_branch:
1121   //
1122   // long_branch_bb:
1123   //   spill s[8:9]
1124   //   s_getpc_b64 s[8:9]
1125   //   s_add_u32 s8, s8, restore_bb
1126   //   s_addc_u32 s9, s9, 0
1127   //   s_setpc_b64 s[8:9]
1128   //
1129   // skip_long_branch:
1130   //   foo;
1131   //
1132   // .....
1133   //
1134   // dest_bb_fallthrough_predecessor:
1135   // bar;
1136   // s_branch dest_bb
1137   //
1138   // restore_bb:
1139   //  restore s[8:9]
1140   //  fallthrough dest_bb
1141   ///
1142   // dest_bb:
1143   //   buzz;
1144 
1145   RS->enterBasicBlockEnd(MBB);
1146   unsigned Scav = RS->scavengeRegister(&AMDGPU::SReg_64RegClass,
1147                                        MachineBasicBlock::iterator(GetPC), 0);
1148   MRI.replaceRegWith(PCReg, Scav);
1149   MRI.clearVirtRegs();
1150   RS->setRegUsed(Scav);
1151 
1152   return 4 + 8 + 4 + 4;
1153 }
1154 
1155 unsigned SIInstrInfo::getBranchOpcode(SIInstrInfo::BranchPredicate Cond) {
1156   switch (Cond) {
1157   case SIInstrInfo::SCC_TRUE:
1158     return AMDGPU::S_CBRANCH_SCC1;
1159   case SIInstrInfo::SCC_FALSE:
1160     return AMDGPU::S_CBRANCH_SCC0;
1161   case SIInstrInfo::VCCNZ:
1162     return AMDGPU::S_CBRANCH_VCCNZ;
1163   case SIInstrInfo::VCCZ:
1164     return AMDGPU::S_CBRANCH_VCCZ;
1165   case SIInstrInfo::EXECNZ:
1166     return AMDGPU::S_CBRANCH_EXECNZ;
1167   case SIInstrInfo::EXECZ:
1168     return AMDGPU::S_CBRANCH_EXECZ;
1169   default:
1170     llvm_unreachable("invalid branch predicate");
1171   }
1172 }
1173 
1174 SIInstrInfo::BranchPredicate SIInstrInfo::getBranchPredicate(unsigned Opcode) {
1175   switch (Opcode) {
1176   case AMDGPU::S_CBRANCH_SCC0:
1177     return SCC_FALSE;
1178   case AMDGPU::S_CBRANCH_SCC1:
1179     return SCC_TRUE;
1180   case AMDGPU::S_CBRANCH_VCCNZ:
1181     return VCCNZ;
1182   case AMDGPU::S_CBRANCH_VCCZ:
1183     return VCCZ;
1184   case AMDGPU::S_CBRANCH_EXECNZ:
1185     return EXECNZ;
1186   case AMDGPU::S_CBRANCH_EXECZ:
1187     return EXECZ;
1188   default:
1189     return INVALID_BR;
1190   }
1191 }
1192 
1193 bool SIInstrInfo::analyzeBranchImpl(MachineBasicBlock &MBB,
1194                                     MachineBasicBlock::iterator I,
1195                                     MachineBasicBlock *&TBB,
1196                                     MachineBasicBlock *&FBB,
1197                                     SmallVectorImpl<MachineOperand> &Cond,
1198                                     bool AllowModify) const {
1199   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1200     // Unconditional Branch
1201     TBB = I->getOperand(0).getMBB();
1202     return false;
1203   }
1204 
1205   BranchPredicate Pred = getBranchPredicate(I->getOpcode());
1206   if (Pred == INVALID_BR)
1207     return true;
1208 
1209   MachineBasicBlock *CondBB = I->getOperand(0).getMBB();
1210   Cond.push_back(MachineOperand::CreateImm(Pred));
1211   Cond.push_back(I->getOperand(1)); // Save the branch register.
1212 
1213   ++I;
1214 
1215   if (I == MBB.end()) {
1216     // Conditional branch followed by fall-through.
1217     TBB = CondBB;
1218     return false;
1219   }
1220 
1221   if (I->getOpcode() == AMDGPU::S_BRANCH) {
1222     TBB = CondBB;
1223     FBB = I->getOperand(0).getMBB();
1224     return false;
1225   }
1226 
1227   return true;
1228 }
1229 
1230 bool SIInstrInfo::analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
1231                                 MachineBasicBlock *&FBB,
1232                                 SmallVectorImpl<MachineOperand> &Cond,
1233                                 bool AllowModify) const {
1234   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1235   if (I == MBB.end())
1236     return false;
1237 
1238   if (I->getOpcode() != AMDGPU::SI_MASK_BRANCH)
1239     return analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify);
1240 
1241   ++I;
1242 
1243   // TODO: Should be able to treat as fallthrough?
1244   if (I == MBB.end())
1245     return true;
1246 
1247   if (analyzeBranchImpl(MBB, I, TBB, FBB, Cond, AllowModify))
1248     return true;
1249 
1250   MachineBasicBlock *MaskBrDest = I->getOperand(0).getMBB();
1251 
1252   // Specifically handle the case where the conditional branch is to the same
1253   // destination as the mask branch. e.g.
1254   //
1255   // si_mask_branch BB8
1256   // s_cbranch_execz BB8
1257   // s_cbranch BB9
1258   //
1259   // This is required to understand divergent loops which may need the branches
1260   // to be relaxed.
1261   if (TBB != MaskBrDest || Cond.empty())
1262     return true;
1263 
1264   auto Pred = Cond[0].getImm();
1265   return (Pred != EXECZ && Pred != EXECNZ);
1266 }
1267 
1268 unsigned SIInstrInfo::removeBranch(MachineBasicBlock &MBB,
1269                                    int *BytesRemoved) const {
1270   MachineBasicBlock::iterator I = MBB.getFirstTerminator();
1271 
1272   unsigned Count = 0;
1273   unsigned RemovedSize = 0;
1274   while (I != MBB.end()) {
1275     MachineBasicBlock::iterator Next = std::next(I);
1276     if (I->getOpcode() == AMDGPU::SI_MASK_BRANCH) {
1277       I = Next;
1278       continue;
1279     }
1280 
1281     RemovedSize += getInstSizeInBytes(*I);
1282     I->eraseFromParent();
1283     ++Count;
1284     I = Next;
1285   }
1286 
1287   if (BytesRemoved)
1288     *BytesRemoved = RemovedSize;
1289 
1290   return Count;
1291 }
1292 
1293 unsigned SIInstrInfo::insertBranch(MachineBasicBlock &MBB,
1294                                    MachineBasicBlock *TBB,
1295                                    MachineBasicBlock *FBB,
1296                                    ArrayRef<MachineOperand> Cond,
1297                                    const DebugLoc &DL,
1298                                    int *BytesAdded) const {
1299 
1300   if (!FBB && Cond.empty()) {
1301     BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1302       .addMBB(TBB);
1303     if (BytesAdded)
1304       *BytesAdded = 4;
1305     return 1;
1306   }
1307 
1308   assert(TBB && Cond[0].isImm());
1309 
1310   unsigned Opcode
1311     = getBranchOpcode(static_cast<BranchPredicate>(Cond[0].getImm()));
1312 
1313   if (!FBB) {
1314     Cond[1].isUndef();
1315     MachineInstr *CondBr =
1316       BuildMI(&MBB, DL, get(Opcode))
1317       .addMBB(TBB);
1318 
1319     // Copy the flags onto the implicit condition register operand.
1320     MachineOperand &CondReg = CondBr->getOperand(1);
1321     CondReg.setIsUndef(Cond[1].isUndef());
1322     CondReg.setIsKill(Cond[1].isKill());
1323 
1324     if (BytesAdded)
1325       *BytesAdded = 4;
1326     return 1;
1327   }
1328 
1329   assert(TBB && FBB);
1330 
1331   MachineInstr *CondBr =
1332     BuildMI(&MBB, DL, get(Opcode))
1333     .addMBB(TBB);
1334   BuildMI(&MBB, DL, get(AMDGPU::S_BRANCH))
1335     .addMBB(FBB);
1336 
1337   MachineOperand &CondReg = CondBr->getOperand(1);
1338   CondReg.setIsUndef(Cond[1].isUndef());
1339   CondReg.setIsKill(Cond[1].isKill());
1340 
1341   if (BytesAdded)
1342       *BytesAdded = 8;
1343 
1344   return 2;
1345 }
1346 
1347 bool SIInstrInfo::reverseBranchCondition(
1348   SmallVectorImpl<MachineOperand> &Cond) const {
1349   assert(Cond.size() == 2);
1350   Cond[0].setImm(-Cond[0].getImm());
1351   return false;
1352 }
1353 
1354 static void removeModOperands(MachineInstr &MI) {
1355   unsigned Opc = MI.getOpcode();
1356   int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1357                                               AMDGPU::OpName::src0_modifiers);
1358   int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1359                                               AMDGPU::OpName::src1_modifiers);
1360   int Src2ModIdx = AMDGPU::getNamedOperandIdx(Opc,
1361                                               AMDGPU::OpName::src2_modifiers);
1362 
1363   MI.RemoveOperand(Src2ModIdx);
1364   MI.RemoveOperand(Src1ModIdx);
1365   MI.RemoveOperand(Src0ModIdx);
1366 }
1367 
1368 bool SIInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI,
1369                                 unsigned Reg, MachineRegisterInfo *MRI) const {
1370   if (!MRI->hasOneNonDBGUse(Reg))
1371     return false;
1372 
1373   unsigned Opc = UseMI.getOpcode();
1374   if (Opc == AMDGPU::COPY) {
1375     bool isVGPRCopy = RI.isVGPR(*MRI, UseMI.getOperand(0).getReg());
1376     switch (DefMI.getOpcode()) {
1377     default:
1378       return false;
1379     case AMDGPU::S_MOV_B64:
1380       // TODO: We could fold 64-bit immediates, but this get compilicated
1381       // when there are sub-registers.
1382       return false;
1383 
1384     case AMDGPU::V_MOV_B32_e32:
1385     case AMDGPU::S_MOV_B32:
1386       break;
1387     }
1388     unsigned NewOpc = isVGPRCopy ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
1389     const MachineOperand *ImmOp = getNamedOperand(DefMI, AMDGPU::OpName::src0);
1390     assert(ImmOp);
1391     // FIXME: We could handle FrameIndex values here.
1392     if (!ImmOp->isImm()) {
1393       return false;
1394     }
1395     UseMI.setDesc(get(NewOpc));
1396     UseMI.getOperand(1).ChangeToImmediate(ImmOp->getImm());
1397     UseMI.addImplicitDefUseOperands(*UseMI.getParent()->getParent());
1398     return true;
1399   }
1400 
1401   if (Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64 ||
1402       Opc == AMDGPU::V_MAD_F16 || Opc == AMDGPU::V_MAC_F16_e64) {
1403     bool IsF32 = Opc == AMDGPU::V_MAD_F32 || Opc == AMDGPU::V_MAC_F32_e64;
1404 
1405     // Don't fold if we are using source modifiers. The new VOP2 instructions
1406     // don't have them.
1407     if (hasModifiersSet(UseMI, AMDGPU::OpName::src0_modifiers) ||
1408         hasModifiersSet(UseMI, AMDGPU::OpName::src1_modifiers) ||
1409         hasModifiersSet(UseMI, AMDGPU::OpName::src2_modifiers)) {
1410       return false;
1411     }
1412 
1413     const MachineOperand &ImmOp = DefMI.getOperand(1);
1414 
1415     // If this is a free constant, there's no reason to do this.
1416     // TODO: We could fold this here instead of letting SIFoldOperands do it
1417     // later.
1418     if (isInlineConstant(ImmOp, 4))
1419       return false;
1420 
1421     MachineOperand *Src0 = getNamedOperand(UseMI, AMDGPU::OpName::src0);
1422     MachineOperand *Src1 = getNamedOperand(UseMI, AMDGPU::OpName::src1);
1423     MachineOperand *Src2 = getNamedOperand(UseMI, AMDGPU::OpName::src2);
1424 
1425     // Multiplied part is the constant: Use v_madmk_{f16, f32}.
1426     // We should only expect these to be on src0 due to canonicalizations.
1427     if (Src0->isReg() && Src0->getReg() == Reg) {
1428       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1429         return false;
1430 
1431       if (!Src2->isReg() || RI.isSGPRClass(MRI->getRegClass(Src2->getReg())))
1432         return false;
1433 
1434       // We need to swap operands 0 and 1 since madmk constant is at operand 1.
1435 
1436       const int64_t Imm = DefMI.getOperand(1).getImm();
1437 
1438       // FIXME: This would be a lot easier if we could return a new instruction
1439       // instead of having to modify in place.
1440 
1441       // Remove these first since they are at the end.
1442       UseMI.RemoveOperand(
1443           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1444       UseMI.RemoveOperand(
1445           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1446 
1447       unsigned Src1Reg = Src1->getReg();
1448       unsigned Src1SubReg = Src1->getSubReg();
1449       Src0->setReg(Src1Reg);
1450       Src0->setSubReg(Src1SubReg);
1451       Src0->setIsKill(Src1->isKill());
1452 
1453       if (Opc == AMDGPU::V_MAC_F32_e64 ||
1454           Opc == AMDGPU::V_MAC_F16_e64)
1455         UseMI.untieRegOperand(
1456             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1457 
1458       Src1->ChangeToImmediate(Imm);
1459 
1460       removeModOperands(UseMI);
1461       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADMK_F32 : AMDGPU::V_MADMK_F16));
1462 
1463       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1464       if (DeleteDef)
1465         DefMI.eraseFromParent();
1466 
1467       return true;
1468     }
1469 
1470     // Added part is the constant: Use v_madak_{f16, f32}.
1471     if (Src2->isReg() && Src2->getReg() == Reg) {
1472       // Not allowed to use constant bus for another operand.
1473       // We can however allow an inline immediate as src0.
1474       if (!Src0->isImm() &&
1475           (Src0->isReg() && RI.isSGPRClass(MRI->getRegClass(Src0->getReg()))))
1476         return false;
1477 
1478       if (!Src1->isReg() || RI.isSGPRClass(MRI->getRegClass(Src1->getReg())))
1479         return false;
1480 
1481       const int64_t Imm = DefMI.getOperand(1).getImm();
1482 
1483       // FIXME: This would be a lot easier if we could return a new instruction
1484       // instead of having to modify in place.
1485 
1486       // Remove these first since they are at the end.
1487       UseMI.RemoveOperand(
1488           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod));
1489       UseMI.RemoveOperand(
1490           AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp));
1491 
1492       if (Opc == AMDGPU::V_MAC_F32_e64 ||
1493           Opc == AMDGPU::V_MAC_F16_e64)
1494         UseMI.untieRegOperand(
1495             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2));
1496 
1497       // ChangingToImmediate adds Src2 back to the instruction.
1498       Src2->ChangeToImmediate(Imm);
1499 
1500       // These come before src2.
1501       removeModOperands(UseMI);
1502       UseMI.setDesc(get(IsF32 ? AMDGPU::V_MADAK_F32 : AMDGPU::V_MADAK_F16));
1503 
1504       bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1505       if (DeleteDef)
1506         DefMI.eraseFromParent();
1507 
1508       return true;
1509     }
1510   }
1511 
1512   return false;
1513 }
1514 
1515 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
1516                                 int WidthB, int OffsetB) {
1517   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1518   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1519   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1520   return LowOffset + LowWidth <= HighOffset;
1521 }
1522 
1523 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr &MIa,
1524                                                MachineInstr &MIb) const {
1525   unsigned BaseReg0, BaseReg1;
1526   int64_t Offset0, Offset1;
1527 
1528   if (getMemOpBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
1529       getMemOpBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
1530 
1531     if (!MIa.hasOneMemOperand() || !MIb.hasOneMemOperand()) {
1532       // FIXME: Handle ds_read2 / ds_write2.
1533       return false;
1534     }
1535     unsigned Width0 = (*MIa.memoperands_begin())->getSize();
1536     unsigned Width1 = (*MIb.memoperands_begin())->getSize();
1537     if (BaseReg0 == BaseReg1 &&
1538         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
1539       return true;
1540     }
1541   }
1542 
1543   return false;
1544 }
1545 
1546 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr &MIa,
1547                                                   MachineInstr &MIb,
1548                                                   AliasAnalysis *AA) const {
1549   assert((MIa.mayLoad() || MIa.mayStore()) &&
1550          "MIa must load from or modify a memory location");
1551   assert((MIb.mayLoad() || MIb.mayStore()) &&
1552          "MIb must load from or modify a memory location");
1553 
1554   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects())
1555     return false;
1556 
1557   // XXX - Can we relax this between address spaces?
1558   if (MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1559     return false;
1560 
1561   if (AA && MIa.hasOneMemOperand() && MIb.hasOneMemOperand()) {
1562     const MachineMemOperand *MMOa = *MIa.memoperands_begin();
1563     const MachineMemOperand *MMOb = *MIb.memoperands_begin();
1564     if (MMOa->getValue() && MMOb->getValue()) {
1565       MemoryLocation LocA(MMOa->getValue(), MMOa->getSize(), MMOa->getAAInfo());
1566       MemoryLocation LocB(MMOb->getValue(), MMOb->getSize(), MMOb->getAAInfo());
1567       if (!AA->alias(LocA, LocB))
1568         return true;
1569     }
1570   }
1571 
1572   // TODO: Should we check the address space from the MachineMemOperand? That
1573   // would allow us to distinguish objects we know don't alias based on the
1574   // underlying address space, even if it was lowered to a different one,
1575   // e.g. private accesses lowered to use MUBUF instructions on a scratch
1576   // buffer.
1577   if (isDS(MIa)) {
1578     if (isDS(MIb))
1579       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1580 
1581     return !isFLAT(MIb);
1582   }
1583 
1584   if (isMUBUF(MIa) || isMTBUF(MIa)) {
1585     if (isMUBUF(MIb) || isMTBUF(MIb))
1586       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1587 
1588     return !isFLAT(MIb) && !isSMRD(MIb);
1589   }
1590 
1591   if (isSMRD(MIa)) {
1592     if (isSMRD(MIb))
1593       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1594 
1595     return !isFLAT(MIb) && !isMUBUF(MIa) && !isMTBUF(MIa);
1596   }
1597 
1598   if (isFLAT(MIa)) {
1599     if (isFLAT(MIb))
1600       return checkInstOffsetsDoNotOverlap(MIa, MIb);
1601 
1602     return false;
1603   }
1604 
1605   return false;
1606 }
1607 
1608 MachineInstr *SIInstrInfo::convertToThreeAddress(MachineFunction::iterator &MBB,
1609                                                  MachineInstr &MI,
1610                                                  LiveVariables *LV) const {
1611   bool IsF16 = false;
1612 
1613   switch (MI.getOpcode()) {
1614   default:
1615     return nullptr;
1616   case AMDGPU::V_MAC_F16_e64:
1617     IsF16 = true;
1618   case AMDGPU::V_MAC_F32_e64:
1619     break;
1620   case AMDGPU::V_MAC_F16_e32:
1621     IsF16 = true;
1622   case AMDGPU::V_MAC_F32_e32: {
1623     const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1624     if (Src0->isImm() && !isInlineConstant(*Src0, 4))
1625       return nullptr;
1626     break;
1627   }
1628   }
1629 
1630   const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
1631   const MachineOperand *Src0 = getNamedOperand(MI, AMDGPU::OpName::src0);
1632   const MachineOperand *Src1 = getNamedOperand(MI, AMDGPU::OpName::src1);
1633   const MachineOperand *Src2 = getNamedOperand(MI, AMDGPU::OpName::src2);
1634 
1635   return BuildMI(*MBB, MI, MI.getDebugLoc(),
1636                  get(IsF16 ? AMDGPU::V_MAD_F16 : AMDGPU::V_MAD_F32))
1637       .addOperand(*Dst)
1638       .addImm(0) // Src0 mods
1639       .addOperand(*Src0)
1640       .addImm(0) // Src1 mods
1641       .addOperand(*Src1)
1642       .addImm(0) // Src mods
1643       .addOperand(*Src2)
1644       .addImm(0)  // clamp
1645       .addImm(0); // omod
1646 }
1647 
1648 // It's not generally safe to move VALU instructions across these since it will
1649 // start using the register as a base index rather than directly.
1650 // XXX - Why isn't hasSideEffects sufficient for these?
1651 static bool changesVGPRIndexingMode(const MachineInstr &MI) {
1652   switch (MI.getOpcode()) {
1653   case AMDGPU::S_SET_GPR_IDX_ON:
1654   case AMDGPU::S_SET_GPR_IDX_MODE:
1655   case AMDGPU::S_SET_GPR_IDX_OFF:
1656     return true;
1657   default:
1658     return false;
1659   }
1660 }
1661 
1662 bool SIInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1663                                        const MachineBasicBlock *MBB,
1664                                        const MachineFunction &MF) const {
1665   // XXX - Do we want the SP check in the base implementation?
1666 
1667   // Target-independent instructions do not have an implicit-use of EXEC, even
1668   // when they operate on VGPRs. Treating EXEC modifications as scheduling
1669   // boundaries prevents incorrect movements of such instructions.
1670   return TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF) ||
1671          MI.modifiesRegister(AMDGPU::EXEC, &RI) ||
1672          changesVGPRIndexingMode(MI);
1673 }
1674 
1675 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
1676   switch (Imm.getBitWidth()) {
1677   case 32:
1678     return AMDGPU::isInlinableLiteral32(Imm.getSExtValue(),
1679                                         ST.hasInv2PiInlineImm());
1680   case 64:
1681     return AMDGPU::isInlinableLiteral64(Imm.getSExtValue(),
1682                                         ST.hasInv2PiInlineImm());
1683   default:
1684     llvm_unreachable("invalid bitwidth");
1685   }
1686 }
1687 
1688 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO,
1689                                    unsigned OpSize) const {
1690   if (MO.isImm()) {
1691     // MachineOperand provides no way to tell the true operand size, since it
1692     // only records a 64-bit value. We need to know the size to determine if a
1693     // 32-bit floating point immediate bit pattern is legal for an integer
1694     // immediate. It would be for any 32-bit integer operand, but would not be
1695     // for a 64-bit one.
1696     switch (OpSize) {
1697     case 4:
1698       return AMDGPU::isInlinableLiteral32(static_cast<int32_t>(MO.getImm()),
1699                                           ST.hasInv2PiInlineImm());
1700     case 8:
1701       return AMDGPU::isInlinableLiteral64(MO.getImm(),
1702                                           ST.hasInv2PiInlineImm());
1703     default:
1704       llvm_unreachable("invalid bitwidth");
1705     }
1706   }
1707 
1708   return false;
1709 }
1710 
1711 bool SIInstrInfo::isLiteralConstant(const MachineOperand &MO,
1712                                     unsigned OpSize) const {
1713   return MO.isImm() && !isInlineConstant(MO, OpSize);
1714 }
1715 
1716 bool SIInstrInfo::isLiteralConstantLike(const MachineOperand &MO,
1717                                         unsigned OpSize) const {
1718   switch (MO.getType()) {
1719   case MachineOperand::MO_Register:
1720     return false;
1721   case MachineOperand::MO_Immediate:
1722     return !isInlineConstant(MO, OpSize);
1723   case MachineOperand::MO_FrameIndex:
1724   case MachineOperand::MO_MachineBasicBlock:
1725   case MachineOperand::MO_ExternalSymbol:
1726   case MachineOperand::MO_GlobalAddress:
1727   case MachineOperand::MO_MCSymbol:
1728     return true;
1729   default:
1730     llvm_unreachable("unexpected operand type");
1731   }
1732 }
1733 
1734 static bool compareMachineOp(const MachineOperand &Op0,
1735                              const MachineOperand &Op1) {
1736   if (Op0.getType() != Op1.getType())
1737     return false;
1738 
1739   switch (Op0.getType()) {
1740   case MachineOperand::MO_Register:
1741     return Op0.getReg() == Op1.getReg();
1742   case MachineOperand::MO_Immediate:
1743     return Op0.getImm() == Op1.getImm();
1744   default:
1745     llvm_unreachable("Didn't expect to be comparing these operand types");
1746   }
1747 }
1748 
1749 bool SIInstrInfo::isImmOperandLegal(const MachineInstr &MI, unsigned OpNo,
1750                                     const MachineOperand &MO) const {
1751   const MCOperandInfo &OpInfo = get(MI.getOpcode()).OpInfo[OpNo];
1752 
1753   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
1754 
1755   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
1756     return true;
1757 
1758   if (OpInfo.RegClass < 0)
1759     return false;
1760 
1761   unsigned OpSize = RI.getRegClass(OpInfo.RegClass)->getSize();
1762   if (isLiteralConstant(MO, OpSize))
1763     return RI.opCanUseLiteralConstant(OpInfo.OperandType);
1764 
1765   return RI.opCanUseInlineConstant(OpInfo.OperandType);
1766 }
1767 
1768 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
1769   int Op32 = AMDGPU::getVOPe32(Opcode);
1770   if (Op32 == -1)
1771     return false;
1772 
1773   return pseudoToMCOpcode(Op32) != -1;
1774 }
1775 
1776 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1777   // The src0_modifier operand is present on all instructions
1778   // that have modifiers.
1779 
1780   return AMDGPU::getNamedOperandIdx(Opcode,
1781                                     AMDGPU::OpName::src0_modifiers) != -1;
1782 }
1783 
1784 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1785                                   unsigned OpName) const {
1786   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1787   return Mods && Mods->getImm();
1788 }
1789 
1790 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1791                                   const MachineOperand &MO,
1792                                   unsigned OpSize) const {
1793   // Literal constants use the constant bus.
1794   if (isLiteralConstant(MO, OpSize))
1795     return true;
1796 
1797   if (!MO.isReg() || !MO.isUse())
1798     return false;
1799 
1800   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1801     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
1802 
1803   // FLAT_SCR is just an SGPR pair.
1804   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
1805     return true;
1806 
1807   // EXEC register uses the constant bus.
1808   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
1809     return true;
1810 
1811   // SGPRs use the constant bus
1812   return (MO.getReg() == AMDGPU::VCC || MO.getReg() == AMDGPU::M0 ||
1813           (!MO.isImplicit() &&
1814            (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
1815             AMDGPU::SGPR_64RegClass.contains(MO.getReg()))));
1816 }
1817 
1818 static unsigned findImplicitSGPRRead(const MachineInstr &MI) {
1819   for (const MachineOperand &MO : MI.implicit_operands()) {
1820     // We only care about reads.
1821     if (MO.isDef())
1822       continue;
1823 
1824     switch (MO.getReg()) {
1825     case AMDGPU::VCC:
1826     case AMDGPU::M0:
1827     case AMDGPU::FLAT_SCR:
1828       return MO.getReg();
1829 
1830     default:
1831       break;
1832     }
1833   }
1834 
1835   return AMDGPU::NoRegister;
1836 }
1837 
1838 static bool shouldReadExec(const MachineInstr &MI) {
1839   if (SIInstrInfo::isVALU(MI)) {
1840     switch (MI.getOpcode()) {
1841     case AMDGPU::V_READLANE_B32:
1842     case AMDGPU::V_READLANE_B32_si:
1843     case AMDGPU::V_READLANE_B32_vi:
1844     case AMDGPU::V_WRITELANE_B32:
1845     case AMDGPU::V_WRITELANE_B32_si:
1846     case AMDGPU::V_WRITELANE_B32_vi:
1847       return false;
1848     }
1849 
1850     return true;
1851   }
1852 
1853   if (SIInstrInfo::isGenericOpcode(MI.getOpcode()) ||
1854       SIInstrInfo::isSALU(MI) ||
1855       SIInstrInfo::isSMRD(MI))
1856     return false;
1857 
1858   return true;
1859 }
1860 
1861 static bool isSubRegOf(const SIRegisterInfo &TRI,
1862                        const MachineOperand &SuperVec,
1863                        const MachineOperand &SubReg) {
1864   if (TargetRegisterInfo::isPhysicalRegister(SubReg.getReg()))
1865     return TRI.isSubRegister(SuperVec.getReg(), SubReg.getReg());
1866 
1867   return SubReg.getSubReg() != AMDGPU::NoSubRegister &&
1868          SubReg.getReg() == SuperVec.getReg();
1869 }
1870 
1871 bool SIInstrInfo::verifyInstruction(const MachineInstr &MI,
1872                                     StringRef &ErrInfo) const {
1873   uint16_t Opcode = MI.getOpcode();
1874   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1875   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
1876   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
1877   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
1878 
1879   // Make sure the number of operands is correct.
1880   const MCInstrDesc &Desc = get(Opcode);
1881   if (!Desc.isVariadic() &&
1882       Desc.getNumOperands() != MI.getNumExplicitOperands()) {
1883     ErrInfo = "Instruction has wrong number of operands.";
1884     return false;
1885   }
1886 
1887   if (MI.isInlineAsm()) {
1888     // Verify register classes for inlineasm constraints.
1889     for (unsigned I = InlineAsm::MIOp_FirstOperand, E = MI.getNumOperands();
1890          I != E; ++I) {
1891       const TargetRegisterClass *RC = MI.getRegClassConstraint(I, this, &RI);
1892       if (!RC)
1893         continue;
1894 
1895       const MachineOperand &Op = MI.getOperand(I);
1896       if (!Op.isReg())
1897         continue;
1898 
1899       unsigned Reg = Op.getReg();
1900       if (!TargetRegisterInfo::isVirtualRegister(Reg) && !RC->contains(Reg)) {
1901         ErrInfo = "inlineasm operand has incorrect register class.";
1902         return false;
1903       }
1904     }
1905 
1906     return true;
1907   }
1908 
1909   // Make sure the register classes are correct.
1910   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
1911     if (MI.getOperand(i).isFPImm()) {
1912       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
1913                 "all fp values to integers.";
1914       return false;
1915     }
1916 
1917     int RegClass = Desc.OpInfo[i].RegClass;
1918 
1919     switch (Desc.OpInfo[i].OperandType) {
1920     case MCOI::OPERAND_REGISTER:
1921       if (MI.getOperand(i).isImm()) {
1922         ErrInfo = "Illegal immediate value for operand.";
1923         return false;
1924       }
1925       break;
1926     case AMDGPU::OPERAND_REG_IMM32_INT:
1927     case AMDGPU::OPERAND_REG_IMM32_FP:
1928       break;
1929     case AMDGPU::OPERAND_REG_INLINE_C_INT:
1930     case AMDGPU::OPERAND_REG_INLINE_C_FP:
1931       if (isLiteralConstant(MI.getOperand(i),
1932                             RI.getRegClass(RegClass)->getSize())) {
1933         ErrInfo = "Illegal immediate value for operand.";
1934         return false;
1935       }
1936       break;
1937     case MCOI::OPERAND_IMMEDIATE:
1938     case AMDGPU::OPERAND_KIMM32:
1939       // Check if this operand is an immediate.
1940       // FrameIndex operands will be replaced by immediates, so they are
1941       // allowed.
1942       if (!MI.getOperand(i).isImm() && !MI.getOperand(i).isFI()) {
1943         ErrInfo = "Expected immediate, but got non-immediate";
1944         return false;
1945       }
1946       LLVM_FALLTHROUGH;
1947     default:
1948       continue;
1949     }
1950 
1951     if (!MI.getOperand(i).isReg())
1952       continue;
1953 
1954     if (RegClass != -1) {
1955       unsigned Reg = MI.getOperand(i).getReg();
1956       if (Reg == AMDGPU::NoRegister ||
1957           TargetRegisterInfo::isVirtualRegister(Reg))
1958         continue;
1959 
1960       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
1961       if (!RC->contains(Reg)) {
1962         ErrInfo = "Operand has incorrect register class.";
1963         return false;
1964       }
1965     }
1966   }
1967 
1968   // Verify VOP*
1969   if (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isVOPC(MI)) {
1970     // Only look at the true operands. Only a real operand can use the constant
1971     // bus, and we don't want to check pseudo-operands like the source modifier
1972     // flags.
1973     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
1974 
1975     unsigned ConstantBusCount = 0;
1976 
1977     if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1)
1978       ++ConstantBusCount;
1979 
1980     unsigned SGPRUsed = findImplicitSGPRRead(MI);
1981     if (SGPRUsed != AMDGPU::NoRegister)
1982       ++ConstantBusCount;
1983 
1984     for (int OpIdx : OpIndices) {
1985       if (OpIdx == -1)
1986         break;
1987       const MachineOperand &MO = MI.getOperand(OpIdx);
1988       if (usesConstantBus(MRI, MO, getOpSize(Opcode, OpIdx))) {
1989         if (MO.isReg()) {
1990           if (MO.getReg() != SGPRUsed)
1991             ++ConstantBusCount;
1992           SGPRUsed = MO.getReg();
1993         } else {
1994           ++ConstantBusCount;
1995         }
1996       }
1997     }
1998     if (ConstantBusCount > 1) {
1999       ErrInfo = "VOP* instruction uses the constant bus more than once";
2000       return false;
2001     }
2002   }
2003 
2004   // Verify misc. restrictions on specific instructions.
2005   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
2006       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
2007     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
2008     const MachineOperand &Src1 = MI.getOperand(Src1Idx);
2009     const MachineOperand &Src2 = MI.getOperand(Src2Idx);
2010     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
2011       if (!compareMachineOp(Src0, Src1) &&
2012           !compareMachineOp(Src0, Src2)) {
2013         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
2014         return false;
2015       }
2016     }
2017   }
2018 
2019   if (isSOPK(MI)) {
2020     int64_t Imm = getNamedOperand(MI, AMDGPU::OpName::simm16)->getImm();
2021     if (sopkIsZext(MI)) {
2022       if (!isUInt<16>(Imm)) {
2023         ErrInfo = "invalid immediate for SOPK instruction";
2024         return false;
2025       }
2026     } else {
2027       if (!isInt<16>(Imm)) {
2028         ErrInfo = "invalid immediate for SOPK instruction";
2029         return false;
2030       }
2031     }
2032   }
2033 
2034   if (Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e32 ||
2035       Desc.getOpcode() == AMDGPU::V_MOVRELS_B32_e64 ||
2036       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
2037       Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64) {
2038     const bool IsDst = Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e32 ||
2039                        Desc.getOpcode() == AMDGPU::V_MOVRELD_B32_e64;
2040 
2041     const unsigned StaticNumOps = Desc.getNumOperands() +
2042       Desc.getNumImplicitUses();
2043     const unsigned NumImplicitOps = IsDst ? 2 : 1;
2044 
2045     // Allow additional implicit operands. This allows a fixup done by the post
2046     // RA scheduler where the main implicit operand is killed and implicit-defs
2047     // are added for sub-registers that remain live after this instruction.
2048     if (MI.getNumOperands() < StaticNumOps + NumImplicitOps) {
2049       ErrInfo = "missing implicit register operands";
2050       return false;
2051     }
2052 
2053     const MachineOperand *Dst = getNamedOperand(MI, AMDGPU::OpName::vdst);
2054     if (IsDst) {
2055       if (!Dst->isUse()) {
2056         ErrInfo = "v_movreld_b32 vdst should be a use operand";
2057         return false;
2058       }
2059 
2060       unsigned UseOpIdx;
2061       if (!MI.isRegTiedToUseOperand(StaticNumOps, &UseOpIdx) ||
2062           UseOpIdx != StaticNumOps + 1) {
2063         ErrInfo = "movrel implicit operands should be tied";
2064         return false;
2065       }
2066     }
2067 
2068     const MachineOperand &Src0 = MI.getOperand(Src0Idx);
2069     const MachineOperand &ImpUse
2070       = MI.getOperand(StaticNumOps + NumImplicitOps - 1);
2071     if (!ImpUse.isReg() || !ImpUse.isUse() ||
2072         !isSubRegOf(RI, ImpUse, IsDst ? *Dst : Src0)) {
2073       ErrInfo = "src0 should be subreg of implicit vector use";
2074       return false;
2075     }
2076   }
2077 
2078   // Make sure we aren't losing exec uses in the td files. This mostly requires
2079   // being careful when using let Uses to try to add other use registers.
2080   if (shouldReadExec(MI)) {
2081     if (!MI.hasRegisterImplicitUseOperand(AMDGPU::EXEC)) {
2082       ErrInfo = "VALU instruction does not implicitly read exec mask";
2083       return false;
2084     }
2085   }
2086 
2087   if (isSMRD(MI)) {
2088     if (MI.mayStore()) {
2089       // The register offset form of scalar stores may only use m0 as the
2090       // soffset register.
2091       const MachineOperand *Soff = getNamedOperand(MI, AMDGPU::OpName::soff);
2092       if (Soff && Soff->getReg() != AMDGPU::M0) {
2093         ErrInfo = "scalar stores must use m0 as offset register";
2094         return false;
2095       }
2096     }
2097   }
2098 
2099   return true;
2100 }
2101 
2102 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
2103   switch (MI.getOpcode()) {
2104   default: return AMDGPU::INSTRUCTION_LIST_END;
2105   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
2106   case AMDGPU::COPY: return AMDGPU::COPY;
2107   case AMDGPU::PHI: return AMDGPU::PHI;
2108   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
2109   case AMDGPU::S_MOV_B32:
2110     return MI.getOperand(1).isReg() ?
2111            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
2112   case AMDGPU::S_ADD_I32:
2113   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
2114   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
2115   case AMDGPU::S_SUB_I32:
2116   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
2117   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
2118   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
2119   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e64;
2120   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e64;
2121   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e64;
2122   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e64;
2123   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e64;
2124   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e64;
2125   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e64;
2126   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
2127   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
2128   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
2129   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
2130   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
2131   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
2132   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
2133   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
2134   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
2135   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
2136   case AMDGPU::S_BFM_B32: return AMDGPU::V_BFM_B32_e64;
2137   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
2138   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
2139   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
2140   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
2141   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
2142   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
2143   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
2144   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
2145   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
2146   case AMDGPU::S_CMP_EQ_U32: return AMDGPU::V_CMP_EQ_U32_e32;
2147   case AMDGPU::S_CMP_LG_U32: return AMDGPU::V_CMP_NE_U32_e32;
2148   case AMDGPU::S_CMP_GT_U32: return AMDGPU::V_CMP_GT_U32_e32;
2149   case AMDGPU::S_CMP_GE_U32: return AMDGPU::V_CMP_GE_U32_e32;
2150   case AMDGPU::S_CMP_LT_U32: return AMDGPU::V_CMP_LT_U32_e32;
2151   case AMDGPU::S_CMP_LE_U32: return AMDGPU::V_CMP_LE_U32_e32;
2152   case AMDGPU::S_CMP_EQ_U64: return AMDGPU::V_CMP_EQ_U64_e32;
2153   case AMDGPU::S_CMP_LG_U64: return AMDGPU::V_CMP_NE_U64_e32;
2154   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e64;
2155   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
2156   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
2157   case AMDGPU::S_FLBIT_I32: return AMDGPU::V_FFBH_I32_e64;
2158   case AMDGPU::S_CBRANCH_SCC0: return AMDGPU::S_CBRANCH_VCCZ;
2159   case AMDGPU::S_CBRANCH_SCC1: return AMDGPU::S_CBRANCH_VCCNZ;
2160   }
2161 }
2162 
2163 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
2164   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
2165 }
2166 
2167 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
2168                                                       unsigned OpNo) const {
2169   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2170   const MCInstrDesc &Desc = get(MI.getOpcode());
2171   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
2172       Desc.OpInfo[OpNo].RegClass == -1) {
2173     unsigned Reg = MI.getOperand(OpNo).getReg();
2174 
2175     if (TargetRegisterInfo::isVirtualRegister(Reg))
2176       return MRI.getRegClass(Reg);
2177     return RI.getPhysRegClass(Reg);
2178   }
2179 
2180   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
2181   return RI.getRegClass(RCID);
2182 }
2183 
2184 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
2185   switch (MI.getOpcode()) {
2186   case AMDGPU::COPY:
2187   case AMDGPU::REG_SEQUENCE:
2188   case AMDGPU::PHI:
2189   case AMDGPU::INSERT_SUBREG:
2190     return RI.hasVGPRs(getOpRegClass(MI, 0));
2191   default:
2192     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
2193   }
2194 }
2195 
2196 void SIInstrInfo::legalizeOpWithMove(MachineInstr &MI, unsigned OpIdx) const {
2197   MachineBasicBlock::iterator I = MI;
2198   MachineBasicBlock *MBB = MI.getParent();
2199   MachineOperand &MO = MI.getOperand(OpIdx);
2200   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
2201   unsigned RCID = get(MI.getOpcode()).OpInfo[OpIdx].RegClass;
2202   const TargetRegisterClass *RC = RI.getRegClass(RCID);
2203   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
2204   if (MO.isReg())
2205     Opcode = AMDGPU::COPY;
2206   else if (RI.isSGPRClass(RC))
2207     Opcode = AMDGPU::S_MOV_B32;
2208 
2209   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
2210   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
2211     VRC = &AMDGPU::VReg_64RegClass;
2212   else
2213     VRC = &AMDGPU::VGPR_32RegClass;
2214 
2215   unsigned Reg = MRI.createVirtualRegister(VRC);
2216   DebugLoc DL = MBB->findDebugLoc(I);
2217   BuildMI(*MI.getParent(), I, DL, get(Opcode), Reg).addOperand(MO);
2218   MO.ChangeToRegister(Reg, false);
2219 }
2220 
2221 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
2222                                          MachineRegisterInfo &MRI,
2223                                          MachineOperand &SuperReg,
2224                                          const TargetRegisterClass *SuperRC,
2225                                          unsigned SubIdx,
2226                                          const TargetRegisterClass *SubRC)
2227                                          const {
2228   MachineBasicBlock *MBB = MI->getParent();
2229   DebugLoc DL = MI->getDebugLoc();
2230   unsigned SubReg = MRI.createVirtualRegister(SubRC);
2231 
2232   if (SuperReg.getSubReg() == AMDGPU::NoSubRegister) {
2233     BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
2234       .addReg(SuperReg.getReg(), 0, SubIdx);
2235     return SubReg;
2236   }
2237 
2238   // Just in case the super register is itself a sub-register, copy it to a new
2239   // value so we don't need to worry about merging its subreg index with the
2240   // SubIdx passed to this function. The register coalescer should be able to
2241   // eliminate this extra copy.
2242   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
2243 
2244   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
2245     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
2246 
2247   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
2248     .addReg(NewSuperReg, 0, SubIdx);
2249 
2250   return SubReg;
2251 }
2252 
2253 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
2254   MachineBasicBlock::iterator MII,
2255   MachineRegisterInfo &MRI,
2256   MachineOperand &Op,
2257   const TargetRegisterClass *SuperRC,
2258   unsigned SubIdx,
2259   const TargetRegisterClass *SubRC) const {
2260   if (Op.isImm()) {
2261     if (SubIdx == AMDGPU::sub0)
2262       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm()));
2263     if (SubIdx == AMDGPU::sub1)
2264       return MachineOperand::CreateImm(static_cast<int32_t>(Op.getImm() >> 32));
2265 
2266     llvm_unreachable("Unhandled register index for immediate");
2267   }
2268 
2269   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
2270                                        SubIdx, SubRC);
2271   return MachineOperand::CreateReg(SubReg, false);
2272 }
2273 
2274 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
2275 void SIInstrInfo::swapOperands(MachineInstr &Inst) const {
2276   assert(Inst.getNumExplicitOperands() == 3);
2277   MachineOperand Op1 = Inst.getOperand(1);
2278   Inst.RemoveOperand(1);
2279   Inst.addOperand(Op1);
2280 }
2281 
2282 bool SIInstrInfo::isLegalRegOperand(const MachineRegisterInfo &MRI,
2283                                     const MCOperandInfo &OpInfo,
2284                                     const MachineOperand &MO) const {
2285   if (!MO.isReg())
2286     return false;
2287 
2288   unsigned Reg = MO.getReg();
2289   const TargetRegisterClass *RC =
2290     TargetRegisterInfo::isVirtualRegister(Reg) ?
2291     MRI.getRegClass(Reg) :
2292     RI.getPhysRegClass(Reg);
2293 
2294   const SIRegisterInfo *TRI =
2295       static_cast<const SIRegisterInfo*>(MRI.getTargetRegisterInfo());
2296   RC = TRI->getSubRegClass(RC, MO.getSubReg());
2297 
2298   // In order to be legal, the common sub-class must be equal to the
2299   // class of the current operand.  For example:
2300   //
2301   // v_mov_b32 s0 ; Operand defined as vsrc_b32
2302   //              ; RI.getCommonSubClass(s0,vsrc_b32) = sgpr ; LEGAL
2303   //
2304   // s_sendmsg 0, s0 ; Operand defined as m0reg
2305   //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
2306 
2307   return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
2308 }
2309 
2310 bool SIInstrInfo::isLegalVSrcOperand(const MachineRegisterInfo &MRI,
2311                                      const MCOperandInfo &OpInfo,
2312                                      const MachineOperand &MO) const {
2313   if (MO.isReg())
2314     return isLegalRegOperand(MRI, OpInfo, MO);
2315 
2316   // Handle non-register types that are treated like immediates.
2317   assert(MO.isImm() || MO.isTargetIndex() || MO.isFI());
2318   return true;
2319 }
2320 
2321 bool SIInstrInfo::isOperandLegal(const MachineInstr &MI, unsigned OpIdx,
2322                                  const MachineOperand *MO) const {
2323   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
2324   const MCInstrDesc &InstDesc = MI.getDesc();
2325   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
2326   const TargetRegisterClass *DefinedRC =
2327       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
2328   if (!MO)
2329     MO = &MI.getOperand(OpIdx);
2330 
2331   if (isVALU(MI) && usesConstantBus(MRI, *MO, DefinedRC->getSize())) {
2332 
2333     RegSubRegPair SGPRUsed;
2334     if (MO->isReg())
2335       SGPRUsed = RegSubRegPair(MO->getReg(), MO->getSubReg());
2336 
2337     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2338       if (i == OpIdx)
2339         continue;
2340       const MachineOperand &Op = MI.getOperand(i);
2341       if (Op.isReg()) {
2342         if ((Op.getReg() != SGPRUsed.Reg || Op.getSubReg() != SGPRUsed.SubReg) &&
2343             usesConstantBus(MRI, Op, getOpSize(MI, i))) {
2344           return false;
2345         }
2346       } else if (InstDesc.OpInfo[i].OperandType == AMDGPU::OPERAND_KIMM32) {
2347         return false;
2348       }
2349     }
2350   }
2351 
2352   if (MO->isReg()) {
2353     assert(DefinedRC);
2354     return isLegalRegOperand(MRI, OpInfo, *MO);
2355   }
2356 
2357   // Handle non-register types that are treated like immediates.
2358   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
2359 
2360   if (!DefinedRC) {
2361     // This operand expects an immediate.
2362     return true;
2363   }
2364 
2365   return isImmOperandLegal(MI, OpIdx, *MO);
2366 }
2367 
2368 void SIInstrInfo::legalizeOperandsVOP2(MachineRegisterInfo &MRI,
2369                                        MachineInstr &MI) const {
2370   unsigned Opc = MI.getOpcode();
2371   const MCInstrDesc &InstrDesc = get(Opc);
2372 
2373   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
2374   MachineOperand &Src1 = MI.getOperand(Src1Idx);
2375 
2376   // If there is an implicit SGPR use such as VCC use for v_addc_u32/v_subb_u32
2377   // we need to only have one constant bus use.
2378   //
2379   // Note we do not need to worry about literal constants here. They are
2380   // disabled for the operand type for instructions because they will always
2381   // violate the one constant bus use rule.
2382   bool HasImplicitSGPR = findImplicitSGPRRead(MI) != AMDGPU::NoRegister;
2383   if (HasImplicitSGPR) {
2384     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2385     MachineOperand &Src0 = MI.getOperand(Src0Idx);
2386 
2387     if (Src0.isReg() && RI.isSGPRReg(MRI, Src0.getReg()))
2388       legalizeOpWithMove(MI, Src0Idx);
2389   }
2390 
2391   // VOP2 src0 instructions support all operand types, so we don't need to check
2392   // their legality. If src1 is already legal, we don't need to do anything.
2393   if (isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src1))
2394     return;
2395 
2396   // We do not use commuteInstruction here because it is too aggressive and will
2397   // commute if it is possible. We only want to commute here if it improves
2398   // legality. This can be called a fairly large number of times so don't waste
2399   // compile time pointlessly swapping and checking legality again.
2400   if (HasImplicitSGPR || !MI.isCommutable()) {
2401     legalizeOpWithMove(MI, Src1Idx);
2402     return;
2403   }
2404 
2405   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
2406   MachineOperand &Src0 = MI.getOperand(Src0Idx);
2407 
2408   // If src0 can be used as src1, commuting will make the operands legal.
2409   // Otherwise we have to give up and insert a move.
2410   //
2411   // TODO: Other immediate-like operand kinds could be commuted if there was a
2412   // MachineOperand::ChangeTo* for them.
2413   if ((!Src1.isImm() && !Src1.isReg()) ||
2414       !isLegalRegOperand(MRI, InstrDesc.OpInfo[Src1Idx], Src0)) {
2415     legalizeOpWithMove(MI, Src1Idx);
2416     return;
2417   }
2418 
2419   int CommutedOpc = commuteOpcode(MI);
2420   if (CommutedOpc == -1) {
2421     legalizeOpWithMove(MI, Src1Idx);
2422     return;
2423   }
2424 
2425   MI.setDesc(get(CommutedOpc));
2426 
2427   unsigned Src0Reg = Src0.getReg();
2428   unsigned Src0SubReg = Src0.getSubReg();
2429   bool Src0Kill = Src0.isKill();
2430 
2431   if (Src1.isImm())
2432     Src0.ChangeToImmediate(Src1.getImm());
2433   else if (Src1.isReg()) {
2434     Src0.ChangeToRegister(Src1.getReg(), false, false, Src1.isKill());
2435     Src0.setSubReg(Src1.getSubReg());
2436   } else
2437     llvm_unreachable("Should only have register or immediate operands");
2438 
2439   Src1.ChangeToRegister(Src0Reg, false, false, Src0Kill);
2440   Src1.setSubReg(Src0SubReg);
2441 }
2442 
2443 // Legalize VOP3 operands. Because all operand types are supported for any
2444 // operand, and since literal constants are not allowed and should never be
2445 // seen, we only need to worry about inserting copies if we use multiple SGPR
2446 // operands.
2447 void SIInstrInfo::legalizeOperandsVOP3(MachineRegisterInfo &MRI,
2448                                        MachineInstr &MI) const {
2449   unsigned Opc = MI.getOpcode();
2450 
2451   int VOP3Idx[3] = {
2452     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
2453     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1),
2454     AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2)
2455   };
2456 
2457   // Find the one SGPR operand we are allowed to use.
2458   unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
2459 
2460   for (unsigned i = 0; i < 3; ++i) {
2461     int Idx = VOP3Idx[i];
2462     if (Idx == -1)
2463       break;
2464     MachineOperand &MO = MI.getOperand(Idx);
2465 
2466     // We should never see a VOP3 instruction with an illegal immediate operand.
2467     if (!MO.isReg())
2468       continue;
2469 
2470     if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2471       continue; // VGPRs are legal
2472 
2473     if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
2474       SGPRReg = MO.getReg();
2475       // We can use one SGPR in each VOP3 instruction.
2476       continue;
2477     }
2478 
2479     // If we make it this far, then the operand is not legal and we must
2480     // legalize it.
2481     legalizeOpWithMove(MI, Idx);
2482   }
2483 }
2484 
2485 unsigned SIInstrInfo::readlaneVGPRToSGPR(unsigned SrcReg, MachineInstr &UseMI,
2486                                          MachineRegisterInfo &MRI) const {
2487   const TargetRegisterClass *VRC = MRI.getRegClass(SrcReg);
2488   const TargetRegisterClass *SRC = RI.getEquivalentSGPRClass(VRC);
2489   unsigned DstReg = MRI.createVirtualRegister(SRC);
2490   unsigned SubRegs = VRC->getSize() / 4;
2491 
2492   SmallVector<unsigned, 8> SRegs;
2493   for (unsigned i = 0; i < SubRegs; ++i) {
2494     unsigned SGPR = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2495     BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2496             get(AMDGPU::V_READFIRSTLANE_B32), SGPR)
2497         .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
2498     SRegs.push_back(SGPR);
2499   }
2500 
2501   MachineInstrBuilder MIB =
2502       BuildMI(*UseMI.getParent(), UseMI, UseMI.getDebugLoc(),
2503               get(AMDGPU::REG_SEQUENCE), DstReg);
2504   for (unsigned i = 0; i < SubRegs; ++i) {
2505     MIB.addReg(SRegs[i]);
2506     MIB.addImm(RI.getSubRegFromChannel(i));
2507   }
2508   return DstReg;
2509 }
2510 
2511 void SIInstrInfo::legalizeOperandsSMRD(MachineRegisterInfo &MRI,
2512                                        MachineInstr &MI) const {
2513 
2514   // If the pointer is store in VGPRs, then we need to move them to
2515   // SGPRs using v_readfirstlane.  This is safe because we only select
2516   // loads with uniform pointers to SMRD instruction so we know the
2517   // pointer value is uniform.
2518   MachineOperand *SBase = getNamedOperand(MI, AMDGPU::OpName::sbase);
2519   if (SBase && !RI.isSGPRClass(MRI.getRegClass(SBase->getReg()))) {
2520       unsigned SGPR = readlaneVGPRToSGPR(SBase->getReg(), MI, MRI);
2521       SBase->setReg(SGPR);
2522   }
2523 }
2524 
2525 void SIInstrInfo::legalizeGenericOperand(MachineBasicBlock &InsertMBB,
2526                                          MachineBasicBlock::iterator I,
2527                                          const TargetRegisterClass *DstRC,
2528                                          MachineOperand &Op,
2529                                          MachineRegisterInfo &MRI,
2530                                          const DebugLoc &DL) const {
2531 
2532   unsigned OpReg = Op.getReg();
2533   unsigned OpSubReg = Op.getSubReg();
2534 
2535   const TargetRegisterClass *OpRC = RI.getSubClassWithSubReg(
2536       RI.getRegClassForReg(MRI, OpReg), OpSubReg);
2537 
2538   // Check if operand is already the correct register class.
2539   if (DstRC == OpRC)
2540     return;
2541 
2542   unsigned DstReg = MRI.createVirtualRegister(DstRC);
2543   MachineInstr *Copy = BuildMI(InsertMBB, I, DL, get(AMDGPU::COPY), DstReg)
2544                                .addOperand(Op);
2545 
2546   Op.setReg(DstReg);
2547   Op.setSubReg(0);
2548 
2549   MachineInstr *Def = MRI.getVRegDef(OpReg);
2550   if (!Def)
2551     return;
2552 
2553   // Try to eliminate the copy if it is copying an immediate value.
2554   if (Def->isMoveImmediate())
2555     FoldImmediate(*Copy, *Def, OpReg, &MRI);
2556 }
2557 
2558 void SIInstrInfo::legalizeOperands(MachineInstr &MI) const {
2559   MachineFunction &MF = *MI.getParent()->getParent();
2560   MachineRegisterInfo &MRI = MF.getRegInfo();
2561 
2562   // Legalize VOP2
2563   if (isVOP2(MI) || isVOPC(MI)) {
2564     legalizeOperandsVOP2(MRI, MI);
2565     return;
2566   }
2567 
2568   // Legalize VOP3
2569   if (isVOP3(MI)) {
2570     legalizeOperandsVOP3(MRI, MI);
2571     return;
2572   }
2573 
2574   // Legalize SMRD
2575   if (isSMRD(MI)) {
2576     legalizeOperandsSMRD(MRI, MI);
2577     return;
2578   }
2579 
2580   // Legalize REG_SEQUENCE and PHI
2581   // The register class of the operands much be the same type as the register
2582   // class of the output.
2583   if (MI.getOpcode() == AMDGPU::PHI) {
2584     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
2585     for (unsigned i = 1, e = MI.getNumOperands(); i != e; i += 2) {
2586       if (!MI.getOperand(i).isReg() ||
2587           !TargetRegisterInfo::isVirtualRegister(MI.getOperand(i).getReg()))
2588         continue;
2589       const TargetRegisterClass *OpRC =
2590           MRI.getRegClass(MI.getOperand(i).getReg());
2591       if (RI.hasVGPRs(OpRC)) {
2592         VRC = OpRC;
2593       } else {
2594         SRC = OpRC;
2595       }
2596     }
2597 
2598     // If any of the operands are VGPR registers, then they all most be
2599     // otherwise we will create illegal VGPR->SGPR copies when legalizing
2600     // them.
2601     if (VRC || !RI.isSGPRClass(getOpRegClass(MI, 0))) {
2602       if (!VRC) {
2603         assert(SRC);
2604         VRC = RI.getEquivalentVGPRClass(SRC);
2605       }
2606       RC = VRC;
2607     } else {
2608       RC = SRC;
2609     }
2610 
2611     // Update all the operands so they have the same type.
2612     for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2613       MachineOperand &Op = MI.getOperand(I);
2614       if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2615         continue;
2616 
2617       // MI is a PHI instruction.
2618       MachineBasicBlock *InsertBB = MI.getOperand(I + 1).getMBB();
2619       MachineBasicBlock::iterator Insert = InsertBB->getFirstTerminator();
2620 
2621       // Avoid creating no-op copies with the same src and dst reg class.  These
2622       // confuse some of the machine passes.
2623       legalizeGenericOperand(*InsertBB, Insert, RC, Op, MRI, MI.getDebugLoc());
2624     }
2625   }
2626 
2627   // REG_SEQUENCE doesn't really require operand legalization, but if one has a
2628   // VGPR dest type and SGPR sources, insert copies so all operands are
2629   // VGPRs. This seems to help operand folding / the register coalescer.
2630   if (MI.getOpcode() == AMDGPU::REG_SEQUENCE) {
2631     MachineBasicBlock *MBB = MI.getParent();
2632     const TargetRegisterClass *DstRC = getOpRegClass(MI, 0);
2633     if (RI.hasVGPRs(DstRC)) {
2634       // Update all the operands so they are VGPR register classes. These may
2635       // not be the same register class because REG_SEQUENCE supports mixing
2636       // subregister index types e.g. sub0_sub1 + sub2 + sub3
2637       for (unsigned I = 1, E = MI.getNumOperands(); I != E; I += 2) {
2638         MachineOperand &Op = MI.getOperand(I);
2639         if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg()))
2640           continue;
2641 
2642         const TargetRegisterClass *OpRC = MRI.getRegClass(Op.getReg());
2643         const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(OpRC);
2644         if (VRC == OpRC)
2645           continue;
2646 
2647         legalizeGenericOperand(*MBB, MI, VRC, Op, MRI, MI.getDebugLoc());
2648         Op.setIsKill();
2649       }
2650     }
2651 
2652     return;
2653   }
2654 
2655   // Legalize INSERT_SUBREG
2656   // src0 must have the same register class as dst
2657   if (MI.getOpcode() == AMDGPU::INSERT_SUBREG) {
2658     unsigned Dst = MI.getOperand(0).getReg();
2659     unsigned Src0 = MI.getOperand(1).getReg();
2660     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
2661     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
2662     if (DstRC != Src0RC) {
2663       MachineBasicBlock *MBB = MI.getParent();
2664       MachineOperand &Op = MI.getOperand(1);
2665       legalizeGenericOperand(*MBB, MI, DstRC, Op, MRI, MI.getDebugLoc());
2666     }
2667     return;
2668   }
2669 
2670   // Legalize MIMG and MUBUF/MTBUF for shaders.
2671   //
2672   // Shaders only generate MUBUF/MTBUF instructions via intrinsics or via
2673   // scratch memory access. In both cases, the legalization never involves
2674   // conversion to the addr64 form.
2675   if (isMIMG(MI) ||
2676       (AMDGPU::isShader(MF.getFunction()->getCallingConv()) &&
2677        (isMUBUF(MI) || isMTBUF(MI)))) {
2678     MachineOperand *SRsrc = getNamedOperand(MI, AMDGPU::OpName::srsrc);
2679     if (SRsrc && !RI.isSGPRClass(MRI.getRegClass(SRsrc->getReg()))) {
2680       unsigned SGPR = readlaneVGPRToSGPR(SRsrc->getReg(), MI, MRI);
2681       SRsrc->setReg(SGPR);
2682     }
2683 
2684     MachineOperand *SSamp = getNamedOperand(MI, AMDGPU::OpName::ssamp);
2685     if (SSamp && !RI.isSGPRClass(MRI.getRegClass(SSamp->getReg()))) {
2686       unsigned SGPR = readlaneVGPRToSGPR(SSamp->getReg(), MI, MRI);
2687       SSamp->setReg(SGPR);
2688     }
2689     return;
2690   }
2691 
2692   // Legalize MUBUF* instructions by converting to addr64 form.
2693   // FIXME: If we start using the non-addr64 instructions for compute, we
2694   // may need to legalize them as above. This especially applies to the
2695   // buffer_load_format_* variants and variants with idxen (or bothen).
2696   int SRsrcIdx =
2697       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::srsrc);
2698   if (SRsrcIdx != -1) {
2699     // We have an MUBUF instruction
2700     MachineOperand *SRsrc = &MI.getOperand(SRsrcIdx);
2701     unsigned SRsrcRC = get(MI.getOpcode()).OpInfo[SRsrcIdx].RegClass;
2702     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
2703                                              RI.getRegClass(SRsrcRC))) {
2704       // The operands are legal.
2705       // FIXME: We may need to legalize operands besided srsrc.
2706       return;
2707     }
2708 
2709     MachineBasicBlock &MBB = *MI.getParent();
2710 
2711     // Extract the ptr from the resource descriptor.
2712     unsigned SRsrcPtr = buildExtractSubReg(MI, MRI, *SRsrc,
2713       &AMDGPU::VReg_128RegClass, AMDGPU::sub0_sub1, &AMDGPU::VReg_64RegClass);
2714 
2715     // Create an empty resource descriptor
2716     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2717     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2718     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2719     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
2720     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
2721 
2722     // Zero64 = 0
2723     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B64), Zero64)
2724         .addImm(0);
2725 
2726     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
2727     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatLo)
2728         .addImm(RsrcDataFormat & 0xFFFFFFFF);
2729 
2730     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
2731     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::S_MOV_B32), SRsrcFormatHi)
2732         .addImm(RsrcDataFormat >> 32);
2733 
2734     // NewSRsrc = {Zero64, SRsrcFormat}
2735     BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewSRsrc)
2736         .addReg(Zero64)
2737         .addImm(AMDGPU::sub0_sub1)
2738         .addReg(SRsrcFormatLo)
2739         .addImm(AMDGPU::sub2)
2740         .addReg(SRsrcFormatHi)
2741         .addImm(AMDGPU::sub3);
2742 
2743     MachineOperand *VAddr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
2744     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2745     if (VAddr) {
2746       // This is already an ADDR64 instruction so we need to add the pointer
2747       // extracted from the resource descriptor to the current value of VAddr.
2748       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2749       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2750 
2751       // NewVaddrLo = SRsrcPtr:sub0 + VAddr:sub0
2752       DebugLoc DL = MI.getDebugLoc();
2753       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), NewVAddrLo)
2754         .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2755         .addReg(VAddr->getReg(), 0, AMDGPU::sub0);
2756 
2757       // NewVaddrHi = SRsrcPtr:sub1 + VAddr:sub1
2758       BuildMI(MBB, MI, DL, get(AMDGPU::V_ADDC_U32_e32), NewVAddrHi)
2759         .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2760         .addReg(VAddr->getReg(), 0, AMDGPU::sub1);
2761 
2762       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2763       BuildMI(MBB, MI, MI.getDebugLoc(), get(AMDGPU::REG_SEQUENCE), NewVAddr)
2764           .addReg(NewVAddrLo)
2765           .addImm(AMDGPU::sub0)
2766           .addReg(NewVAddrHi)
2767           .addImm(AMDGPU::sub1);
2768     } else {
2769       // This instructions is the _OFFSET variant, so we need to convert it to
2770       // ADDR64.
2771       assert(MBB.getParent()->getSubtarget<SISubtarget>().getGeneration()
2772              < SISubtarget::VOLCANIC_ISLANDS &&
2773              "FIXME: Need to emit flat atomics here");
2774 
2775       MachineOperand *VData = getNamedOperand(MI, AMDGPU::OpName::vdata);
2776       MachineOperand *Offset = getNamedOperand(MI, AMDGPU::OpName::offset);
2777       MachineOperand *SOffset = getNamedOperand(MI, AMDGPU::OpName::soffset);
2778       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI.getOpcode());
2779 
2780       // Atomics rith return have have an additional tied operand and are
2781       // missing some of the special bits.
2782       MachineOperand *VDataIn = getNamedOperand(MI, AMDGPU::OpName::vdata_in);
2783       MachineInstr *Addr64;
2784 
2785       if (!VDataIn) {
2786         // Regular buffer load / store.
2787         MachineInstrBuilder MIB =
2788             BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
2789                 .addOperand(*VData)
2790                 .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
2791                 // This will be replaced later
2792                 // with the new value of vaddr.
2793                 .addOperand(*SRsrc)
2794                 .addOperand(*SOffset)
2795                 .addOperand(*Offset);
2796 
2797         // Atomics do not have this operand.
2798         if (const MachineOperand *GLC =
2799                 getNamedOperand(MI, AMDGPU::OpName::glc)) {
2800           MIB.addImm(GLC->getImm());
2801         }
2802 
2803         MIB.addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc));
2804 
2805         if (const MachineOperand *TFE =
2806                 getNamedOperand(MI, AMDGPU::OpName::tfe)) {
2807           MIB.addImm(TFE->getImm());
2808         }
2809 
2810         MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
2811         Addr64 = MIB;
2812       } else {
2813         // Atomics with return.
2814         Addr64 = BuildMI(MBB, MI, MI.getDebugLoc(), get(Addr64Opcode))
2815                      .addOperand(*VData)
2816                      .addOperand(*VDataIn)
2817                      .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
2818                      // This will be replaced later
2819                      // with the new value of vaddr.
2820                      .addOperand(*SRsrc)
2821                      .addOperand(*SOffset)
2822                      .addOperand(*Offset)
2823                      .addImm(getNamedImmOperand(MI, AMDGPU::OpName::slc))
2824                      .setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
2825       }
2826 
2827       MI.removeFromParent();
2828 
2829       // NewVaddr = {NewVaddrHi, NewVaddrLo}
2830       BuildMI(MBB, Addr64, Addr64->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
2831               NewVAddr)
2832           .addReg(SRsrcPtr, 0, AMDGPU::sub0)
2833           .addImm(AMDGPU::sub0)
2834           .addReg(SRsrcPtr, 0, AMDGPU::sub1)
2835           .addImm(AMDGPU::sub1);
2836 
2837       VAddr = getNamedOperand(*Addr64, AMDGPU::OpName::vaddr);
2838       SRsrc = getNamedOperand(*Addr64, AMDGPU::OpName::srsrc);
2839     }
2840 
2841     // Update the instruction to use NewVaddr
2842     VAddr->setReg(NewVAddr);
2843     // Update the instruction to use NewSRsrc
2844     SRsrc->setReg(NewSRsrc);
2845   }
2846 }
2847 
2848 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
2849   SmallVector<MachineInstr *, 128> Worklist;
2850   Worklist.push_back(&TopInst);
2851 
2852   while (!Worklist.empty()) {
2853     MachineInstr &Inst = *Worklist.pop_back_val();
2854     MachineBasicBlock *MBB = Inst.getParent();
2855     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
2856 
2857     unsigned Opcode = Inst.getOpcode();
2858     unsigned NewOpcode = getVALUOp(Inst);
2859 
2860     // Handle some special cases
2861     switch (Opcode) {
2862     default:
2863       break;
2864     case AMDGPU::S_AND_B64:
2865       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_AND_B32_e64);
2866       Inst.eraseFromParent();
2867       continue;
2868 
2869     case AMDGPU::S_OR_B64:
2870       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_OR_B32_e64);
2871       Inst.eraseFromParent();
2872       continue;
2873 
2874     case AMDGPU::S_XOR_B64:
2875       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::V_XOR_B32_e64);
2876       Inst.eraseFromParent();
2877       continue;
2878 
2879     case AMDGPU::S_NOT_B64:
2880       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::V_NOT_B32_e32);
2881       Inst.eraseFromParent();
2882       continue;
2883 
2884     case AMDGPU::S_BCNT1_I32_B64:
2885       splitScalar64BitBCNT(Worklist, Inst);
2886       Inst.eraseFromParent();
2887       continue;
2888 
2889     case AMDGPU::S_BFE_I64: {
2890       splitScalar64BitBFE(Worklist, Inst);
2891       Inst.eraseFromParent();
2892       continue;
2893     }
2894 
2895     case AMDGPU::S_LSHL_B32:
2896       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2897         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
2898         swapOperands(Inst);
2899       }
2900       break;
2901     case AMDGPU::S_ASHR_I32:
2902       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2903         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
2904         swapOperands(Inst);
2905       }
2906       break;
2907     case AMDGPU::S_LSHR_B32:
2908       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2909         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
2910         swapOperands(Inst);
2911       }
2912       break;
2913     case AMDGPU::S_LSHL_B64:
2914       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2915         NewOpcode = AMDGPU::V_LSHLREV_B64;
2916         swapOperands(Inst);
2917       }
2918       break;
2919     case AMDGPU::S_ASHR_I64:
2920       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2921         NewOpcode = AMDGPU::V_ASHRREV_I64;
2922         swapOperands(Inst);
2923       }
2924       break;
2925     case AMDGPU::S_LSHR_B64:
2926       if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
2927         NewOpcode = AMDGPU::V_LSHRREV_B64;
2928         swapOperands(Inst);
2929       }
2930       break;
2931 
2932     case AMDGPU::S_ABS_I32:
2933       lowerScalarAbs(Worklist, Inst);
2934       Inst.eraseFromParent();
2935       continue;
2936 
2937     case AMDGPU::S_CBRANCH_SCC0:
2938     case AMDGPU::S_CBRANCH_SCC1:
2939       // Clear unused bits of vcc
2940       BuildMI(*MBB, Inst, Inst.getDebugLoc(), get(AMDGPU::S_AND_B64),
2941               AMDGPU::VCC)
2942           .addReg(AMDGPU::EXEC)
2943           .addReg(AMDGPU::VCC);
2944       break;
2945 
2946     case AMDGPU::S_BFE_U64:
2947     case AMDGPU::S_BFM_B64:
2948       llvm_unreachable("Moving this op to VALU not implemented");
2949     }
2950 
2951     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
2952       // We cannot move this instruction to the VALU, so we should try to
2953       // legalize its operands instead.
2954       legalizeOperands(Inst);
2955       continue;
2956     }
2957 
2958     // Use the new VALU Opcode.
2959     const MCInstrDesc &NewDesc = get(NewOpcode);
2960     Inst.setDesc(NewDesc);
2961 
2962     // Remove any references to SCC. Vector instructions can't read from it, and
2963     // We're just about to add the implicit use / defs of VCC, and we don't want
2964     // both.
2965     for (unsigned i = Inst.getNumOperands() - 1; i > 0; --i) {
2966       MachineOperand &Op = Inst.getOperand(i);
2967       if (Op.isReg() && Op.getReg() == AMDGPU::SCC) {
2968         Inst.RemoveOperand(i);
2969         addSCCDefUsersToVALUWorklist(Inst, Worklist);
2970       }
2971     }
2972 
2973     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
2974       // We are converting these to a BFE, so we need to add the missing
2975       // operands for the size and offset.
2976       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
2977       Inst.addOperand(MachineOperand::CreateImm(0));
2978       Inst.addOperand(MachineOperand::CreateImm(Size));
2979 
2980     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
2981       // The VALU version adds the second operand to the result, so insert an
2982       // extra 0 operand.
2983       Inst.addOperand(MachineOperand::CreateImm(0));
2984     }
2985 
2986     Inst.addImplicitDefUseOperands(*Inst.getParent()->getParent());
2987 
2988     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
2989       const MachineOperand &OffsetWidthOp = Inst.getOperand(2);
2990       // If we need to move this to VGPRs, we need to unpack the second operand
2991       // back into the 2 separate ones for bit offset and width.
2992       assert(OffsetWidthOp.isImm() &&
2993              "Scalar BFE is only implemented for constant width and offset");
2994       uint32_t Imm = OffsetWidthOp.getImm();
2995 
2996       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2997       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2998       Inst.RemoveOperand(2);                     // Remove old immediate.
2999       Inst.addOperand(MachineOperand::CreateImm(Offset));
3000       Inst.addOperand(MachineOperand::CreateImm(BitWidth));
3001     }
3002 
3003     bool HasDst = Inst.getOperand(0).isReg() && Inst.getOperand(0).isDef();
3004     unsigned NewDstReg = AMDGPU::NoRegister;
3005     if (HasDst) {
3006       // Update the destination register class.
3007       const TargetRegisterClass *NewDstRC = getDestEquivalentVGPRClass(Inst);
3008       if (!NewDstRC)
3009         continue;
3010 
3011       unsigned DstReg = Inst.getOperand(0).getReg();
3012       if (Inst.isCopy() &&
3013           TargetRegisterInfo::isVirtualRegister(Inst.getOperand(1).getReg()) &&
3014           NewDstRC == RI.getRegClassForReg(MRI, Inst.getOperand(1).getReg())) {
3015         // Instead of creating a copy where src and dst are the same register
3016         // class, we just replace all uses of dst with src.  These kinds of
3017         // copies interfere with the heuristics MachineSink uses to decide
3018         // whether or not to split a critical edge.  Since the pass assumes
3019         // that copies will end up as machine instructions and not be
3020         // eliminated.
3021         addUsersToMoveToVALUWorklist(DstReg, MRI, Worklist);
3022         MRI.replaceRegWith(DstReg, Inst.getOperand(1).getReg());
3023         MRI.clearKillFlags(Inst.getOperand(1).getReg());
3024         Inst.getOperand(0).setReg(DstReg);
3025         continue;
3026       }
3027 
3028       NewDstReg = MRI.createVirtualRegister(NewDstRC);
3029       MRI.replaceRegWith(DstReg, NewDstReg);
3030     }
3031 
3032     // Legalize the operands
3033     legalizeOperands(Inst);
3034 
3035     if (HasDst)
3036      addUsersToMoveToVALUWorklist(NewDstReg, MRI, Worklist);
3037   }
3038 }
3039 
3040 void SIInstrInfo::lowerScalarAbs(SmallVectorImpl<MachineInstr *> &Worklist,
3041                                  MachineInstr &Inst) const {
3042   MachineBasicBlock &MBB = *Inst.getParent();
3043   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3044   MachineBasicBlock::iterator MII = Inst;
3045   DebugLoc DL = Inst.getDebugLoc();
3046 
3047   MachineOperand &Dest = Inst.getOperand(0);
3048   MachineOperand &Src = Inst.getOperand(1);
3049   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3050   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3051 
3052   BuildMI(MBB, MII, DL, get(AMDGPU::V_SUB_I32_e32), TmpReg)
3053     .addImm(0)
3054     .addReg(Src.getReg());
3055 
3056   BuildMI(MBB, MII, DL, get(AMDGPU::V_MAX_I32_e64), ResultReg)
3057     .addReg(Src.getReg())
3058     .addReg(TmpReg);
3059 
3060   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3061   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3062 }
3063 
3064 void SIInstrInfo::splitScalar64BitUnaryOp(
3065     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
3066     unsigned Opcode) const {
3067   MachineBasicBlock &MBB = *Inst.getParent();
3068   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3069 
3070   MachineOperand &Dest = Inst.getOperand(0);
3071   MachineOperand &Src0 = Inst.getOperand(1);
3072   DebugLoc DL = Inst.getDebugLoc();
3073 
3074   MachineBasicBlock::iterator MII = Inst;
3075 
3076   const MCInstrDesc &InstDesc = get(Opcode);
3077   const TargetRegisterClass *Src0RC = Src0.isReg() ?
3078     MRI.getRegClass(Src0.getReg()) :
3079     &AMDGPU::SGPR_32RegClass;
3080 
3081   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
3082 
3083   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3084                                                        AMDGPU::sub0, Src0SubRC);
3085 
3086   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
3087   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
3088   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
3089 
3090   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
3091   BuildMI(MBB, MII, DL, InstDesc, DestSub0)
3092     .addOperand(SrcReg0Sub0);
3093 
3094   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3095                                                        AMDGPU::sub1, Src0SubRC);
3096 
3097   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
3098   BuildMI(MBB, MII, DL, InstDesc, DestSub1)
3099     .addOperand(SrcReg0Sub1);
3100 
3101   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
3102   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
3103     .addReg(DestSub0)
3104     .addImm(AMDGPU::sub0)
3105     .addReg(DestSub1)
3106     .addImm(AMDGPU::sub1);
3107 
3108   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
3109 
3110   // We don't need to legalizeOperands here because for a single operand, src0
3111   // will support any kind of input.
3112 
3113   // Move all users of this moved value.
3114   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
3115 }
3116 
3117 void SIInstrInfo::splitScalar64BitBinaryOp(
3118     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst,
3119     unsigned Opcode) const {
3120   MachineBasicBlock &MBB = *Inst.getParent();
3121   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3122 
3123   MachineOperand &Dest = Inst.getOperand(0);
3124   MachineOperand &Src0 = Inst.getOperand(1);
3125   MachineOperand &Src1 = Inst.getOperand(2);
3126   DebugLoc DL = Inst.getDebugLoc();
3127 
3128   MachineBasicBlock::iterator MII = Inst;
3129 
3130   const MCInstrDesc &InstDesc = get(Opcode);
3131   const TargetRegisterClass *Src0RC = Src0.isReg() ?
3132     MRI.getRegClass(Src0.getReg()) :
3133     &AMDGPU::SGPR_32RegClass;
3134 
3135   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
3136   const TargetRegisterClass *Src1RC = Src1.isReg() ?
3137     MRI.getRegClass(Src1.getReg()) :
3138     &AMDGPU::SGPR_32RegClass;
3139 
3140   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
3141 
3142   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3143                                                        AMDGPU::sub0, Src0SubRC);
3144   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
3145                                                        AMDGPU::sub0, Src1SubRC);
3146 
3147   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
3148   const TargetRegisterClass *NewDestRC = RI.getEquivalentVGPRClass(DestRC);
3149   const TargetRegisterClass *NewDestSubRC = RI.getSubRegClass(NewDestRC, AMDGPU::sub0);
3150 
3151   unsigned DestSub0 = MRI.createVirtualRegister(NewDestSubRC);
3152   MachineInstr &LoHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub0)
3153                               .addOperand(SrcReg0Sub0)
3154                               .addOperand(SrcReg1Sub0);
3155 
3156   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
3157                                                        AMDGPU::sub1, Src0SubRC);
3158   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
3159                                                        AMDGPU::sub1, Src1SubRC);
3160 
3161   unsigned DestSub1 = MRI.createVirtualRegister(NewDestSubRC);
3162   MachineInstr &HiHalf = *BuildMI(MBB, MII, DL, InstDesc, DestSub1)
3163                               .addOperand(SrcReg0Sub1)
3164                               .addOperand(SrcReg1Sub1);
3165 
3166   unsigned FullDestReg = MRI.createVirtualRegister(NewDestRC);
3167   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
3168     .addReg(DestSub0)
3169     .addImm(AMDGPU::sub0)
3170     .addReg(DestSub1)
3171     .addImm(AMDGPU::sub1);
3172 
3173   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
3174 
3175   // Try to legalize the operands in case we need to swap the order to keep it
3176   // valid.
3177   legalizeOperands(LoHalf);
3178   legalizeOperands(HiHalf);
3179 
3180   // Move all users of this moved vlaue.
3181   addUsersToMoveToVALUWorklist(FullDestReg, MRI, Worklist);
3182 }
3183 
3184 void SIInstrInfo::splitScalar64BitBCNT(
3185     SmallVectorImpl<MachineInstr *> &Worklist, MachineInstr &Inst) const {
3186   MachineBasicBlock &MBB = *Inst.getParent();
3187   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3188 
3189   MachineBasicBlock::iterator MII = Inst;
3190   DebugLoc DL = Inst.getDebugLoc();
3191 
3192   MachineOperand &Dest = Inst.getOperand(0);
3193   MachineOperand &Src = Inst.getOperand(1);
3194 
3195   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e64);
3196   const TargetRegisterClass *SrcRC = Src.isReg() ?
3197     MRI.getRegClass(Src.getReg()) :
3198     &AMDGPU::SGPR_32RegClass;
3199 
3200   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3201   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3202 
3203   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
3204 
3205   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
3206                                                       AMDGPU::sub0, SrcSubRC);
3207   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
3208                                                       AMDGPU::sub1, SrcSubRC);
3209 
3210   BuildMI(MBB, MII, DL, InstDesc, MidReg)
3211     .addOperand(SrcRegSub0)
3212     .addImm(0);
3213 
3214   BuildMI(MBB, MII, DL, InstDesc, ResultReg)
3215     .addOperand(SrcRegSub1)
3216     .addReg(MidReg);
3217 
3218   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3219 
3220   // We don't need to legalize operands here. src0 for etiher instruction can be
3221   // an SGPR, and the second input is unused or determined here.
3222   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3223 }
3224 
3225 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
3226                                       MachineInstr &Inst) const {
3227   MachineBasicBlock &MBB = *Inst.getParent();
3228   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3229   MachineBasicBlock::iterator MII = Inst;
3230   DebugLoc DL = Inst.getDebugLoc();
3231 
3232   MachineOperand &Dest = Inst.getOperand(0);
3233   uint32_t Imm = Inst.getOperand(2).getImm();
3234   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
3235   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
3236 
3237   (void) Offset;
3238 
3239   // Only sext_inreg cases handled.
3240   assert(Inst.getOpcode() == AMDGPU::S_BFE_I64 && BitWidth <= 32 &&
3241          Offset == 0 && "Not implemented");
3242 
3243   if (BitWidth < 32) {
3244     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3245     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3246     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
3247 
3248     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
3249         .addReg(Inst.getOperand(1).getReg(), 0, AMDGPU::sub0)
3250         .addImm(0)
3251         .addImm(BitWidth);
3252 
3253     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
3254       .addImm(31)
3255       .addReg(MidRegLo);
3256 
3257     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
3258       .addReg(MidRegLo)
3259       .addImm(AMDGPU::sub0)
3260       .addReg(MidRegHi)
3261       .addImm(AMDGPU::sub1);
3262 
3263     MRI.replaceRegWith(Dest.getReg(), ResultReg);
3264     addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3265     return;
3266   }
3267 
3268   MachineOperand &Src = Inst.getOperand(1);
3269   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3270   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
3271 
3272   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
3273     .addImm(31)
3274     .addReg(Src.getReg(), 0, AMDGPU::sub0);
3275 
3276   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
3277     .addReg(Src.getReg(), 0, AMDGPU::sub0)
3278     .addImm(AMDGPU::sub0)
3279     .addReg(TmpReg)
3280     .addImm(AMDGPU::sub1);
3281 
3282   MRI.replaceRegWith(Dest.getReg(), ResultReg);
3283   addUsersToMoveToVALUWorklist(ResultReg, MRI, Worklist);
3284 }
3285 
3286 void SIInstrInfo::addUsersToMoveToVALUWorklist(
3287   unsigned DstReg,
3288   MachineRegisterInfo &MRI,
3289   SmallVectorImpl<MachineInstr *> &Worklist) const {
3290   for (MachineRegisterInfo::use_iterator I = MRI.use_begin(DstReg),
3291          E = MRI.use_end(); I != E; ++I) {
3292     MachineInstr &UseMI = *I->getParent();
3293     if (!canReadVGPR(UseMI, I.getOperandNo())) {
3294       Worklist.push_back(&UseMI);
3295     }
3296   }
3297 }
3298 
3299 void SIInstrInfo::addSCCDefUsersToVALUWorklist(
3300     MachineInstr &SCCDefInst, SmallVectorImpl<MachineInstr *> &Worklist) const {
3301   // This assumes that all the users of SCC are in the same block
3302   // as the SCC def.
3303   for (MachineInstr &MI :
3304        llvm::make_range(MachineBasicBlock::iterator(SCCDefInst),
3305                         SCCDefInst.getParent()->end())) {
3306     // Exit if we find another SCC def.
3307     if (MI.findRegisterDefOperandIdx(AMDGPU::SCC) != -1)
3308       return;
3309 
3310     if (MI.findRegisterUseOperandIdx(AMDGPU::SCC) != -1)
3311       Worklist.push_back(&MI);
3312   }
3313 }
3314 
3315 const TargetRegisterClass *SIInstrInfo::getDestEquivalentVGPRClass(
3316   const MachineInstr &Inst) const {
3317   const TargetRegisterClass *NewDstRC = getOpRegClass(Inst, 0);
3318 
3319   switch (Inst.getOpcode()) {
3320   // For target instructions, getOpRegClass just returns the virtual register
3321   // class associated with the operand, so we need to find an equivalent VGPR
3322   // register class in order to move the instruction to the VALU.
3323   case AMDGPU::COPY:
3324   case AMDGPU::PHI:
3325   case AMDGPU::REG_SEQUENCE:
3326   case AMDGPU::INSERT_SUBREG:
3327     if (RI.hasVGPRs(NewDstRC))
3328       return nullptr;
3329 
3330     NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
3331     if (!NewDstRC)
3332       return nullptr;
3333     return NewDstRC;
3334   default:
3335     return NewDstRC;
3336   }
3337 }
3338 
3339 // Find the one SGPR operand we are allowed to use.
3340 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr &MI,
3341                                    int OpIndices[3]) const {
3342   const MCInstrDesc &Desc = MI.getDesc();
3343 
3344   // Find the one SGPR operand we are allowed to use.
3345   //
3346   // First we need to consider the instruction's operand requirements before
3347   // legalizing. Some operands are required to be SGPRs, such as implicit uses
3348   // of VCC, but we are still bound by the constant bus requirement to only use
3349   // one.
3350   //
3351   // If the operand's class is an SGPR, we can never move it.
3352 
3353   unsigned SGPRReg = findImplicitSGPRRead(MI);
3354   if (SGPRReg != AMDGPU::NoRegister)
3355     return SGPRReg;
3356 
3357   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
3358   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
3359 
3360   for (unsigned i = 0; i < 3; ++i) {
3361     int Idx = OpIndices[i];
3362     if (Idx == -1)
3363       break;
3364 
3365     const MachineOperand &MO = MI.getOperand(Idx);
3366     if (!MO.isReg())
3367       continue;
3368 
3369     // Is this operand statically required to be an SGPR based on the operand
3370     // constraints?
3371     const TargetRegisterClass *OpRC = RI.getRegClass(Desc.OpInfo[Idx].RegClass);
3372     bool IsRequiredSGPR = RI.isSGPRClass(OpRC);
3373     if (IsRequiredSGPR)
3374       return MO.getReg();
3375 
3376     // If this could be a VGPR or an SGPR, Check the dynamic register class.
3377     unsigned Reg = MO.getReg();
3378     const TargetRegisterClass *RegRC = MRI.getRegClass(Reg);
3379     if (RI.isSGPRClass(RegRC))
3380       UsedSGPRs[i] = Reg;
3381   }
3382 
3383   // We don't have a required SGPR operand, so we have a bit more freedom in
3384   // selecting operands to move.
3385 
3386   // Try to select the most used SGPR. If an SGPR is equal to one of the
3387   // others, we choose that.
3388   //
3389   // e.g.
3390   // V_FMA_F32 v0, s0, s0, s0 -> No moves
3391   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
3392 
3393   // TODO: If some of the operands are 64-bit SGPRs and some 32, we should
3394   // prefer those.
3395 
3396   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
3397     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
3398       SGPRReg = UsedSGPRs[0];
3399   }
3400 
3401   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
3402     if (UsedSGPRs[1] == UsedSGPRs[2])
3403       SGPRReg = UsedSGPRs[1];
3404   }
3405 
3406   return SGPRReg;
3407 }
3408 
3409 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
3410                                              unsigned OperandName) const {
3411   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
3412   if (Idx == -1)
3413     return nullptr;
3414 
3415   return &MI.getOperand(Idx);
3416 }
3417 
3418 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
3419   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
3420   if (ST.isAmdHsaOS()) {
3421     RsrcDataFormat |= (1ULL << 56);
3422 
3423     if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3424       // Set MTYPE = 2
3425       RsrcDataFormat |= (2ULL << 59);
3426   }
3427 
3428   return RsrcDataFormat;
3429 }
3430 
3431 uint64_t SIInstrInfo::getScratchRsrcWords23() const {
3432   uint64_t Rsrc23 = getDefaultRsrcDataFormat() |
3433                     AMDGPU::RSRC_TID_ENABLE |
3434                     0xffffffff; // Size;
3435 
3436   uint64_t EltSizeValue = Log2_32(ST.getMaxPrivateElementSize()) - 1;
3437 
3438   Rsrc23 |= (EltSizeValue << AMDGPU::RSRC_ELEMENT_SIZE_SHIFT) |
3439             // IndexStride = 64
3440             (UINT64_C(3) << AMDGPU::RSRC_INDEX_STRIDE_SHIFT);
3441 
3442   // If TID_ENABLE is set, DATA_FORMAT specifies stride bits [14:17].
3443   // Clear them unless we want a huge stride.
3444   if (ST.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3445     Rsrc23 &= ~AMDGPU::RSRC_DATA_FORMAT;
3446 
3447   return Rsrc23;
3448 }
3449 
3450 bool SIInstrInfo::isLowLatencyInstruction(const MachineInstr &MI) const {
3451   unsigned Opc = MI.getOpcode();
3452 
3453   return isSMRD(Opc);
3454 }
3455 
3456 bool SIInstrInfo::isHighLatencyInstruction(const MachineInstr &MI) const {
3457   unsigned Opc = MI.getOpcode();
3458 
3459   return isMUBUF(Opc) || isMTBUF(Opc) || isMIMG(Opc);
3460 }
3461 
3462 unsigned SIInstrInfo::isStackAccess(const MachineInstr &MI,
3463                                     int &FrameIndex) const {
3464   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::vaddr);
3465   if (!Addr || !Addr->isFI())
3466     return AMDGPU::NoRegister;
3467 
3468   assert(!MI.memoperands_empty() &&
3469          (*MI.memoperands_begin())->getAddrSpace() == AMDGPUAS::PRIVATE_ADDRESS);
3470 
3471   FrameIndex = Addr->getIndex();
3472   return getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
3473 }
3474 
3475 unsigned SIInstrInfo::isSGPRStackAccess(const MachineInstr &MI,
3476                                         int &FrameIndex) const {
3477   const MachineOperand *Addr = getNamedOperand(MI, AMDGPU::OpName::addr);
3478   assert(Addr && Addr->isFI());
3479   FrameIndex = Addr->getIndex();
3480   return getNamedOperand(MI, AMDGPU::OpName::data)->getReg();
3481 }
3482 
3483 unsigned SIInstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
3484                                           int &FrameIndex) const {
3485 
3486   if (!MI.mayLoad())
3487     return AMDGPU::NoRegister;
3488 
3489   if (isMUBUF(MI) || isVGPRSpill(MI))
3490     return isStackAccess(MI, FrameIndex);
3491 
3492   if (isSGPRSpill(MI))
3493     return isSGPRStackAccess(MI, FrameIndex);
3494 
3495   return AMDGPU::NoRegister;
3496 }
3497 
3498 unsigned SIInstrInfo::isStoreToStackSlot(const MachineInstr &MI,
3499                                          int &FrameIndex) const {
3500   if (!MI.mayStore())
3501     return AMDGPU::NoRegister;
3502 
3503   if (isMUBUF(MI) || isVGPRSpill(MI))
3504     return isStackAccess(MI, FrameIndex);
3505 
3506   if (isSGPRSpill(MI))
3507     return isSGPRStackAccess(MI, FrameIndex);
3508 
3509   return AMDGPU::NoRegister;
3510 }
3511 
3512 unsigned SIInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
3513   unsigned Opc = MI.getOpcode();
3514   const MCInstrDesc &Desc = getMCOpcodeFromPseudo(Opc);
3515   unsigned DescSize = Desc.getSize();
3516 
3517   // If we have a definitive size, we can use it. Otherwise we need to inspect
3518   // the operands to know the size.
3519   //
3520   // FIXME: Instructions that have a base 32-bit encoding report their size as
3521   // 4, even though they are really 8 bytes if they have a literal operand.
3522   if (DescSize != 0 && DescSize != 4)
3523     return DescSize;
3524 
3525   if (Opc == AMDGPU::WAVE_BARRIER)
3526     return 0;
3527 
3528   // 4-byte instructions may have a 32-bit literal encoded after them. Check
3529   // operands that coud ever be literals.
3530   if (isVALU(MI) || isSALU(MI)) {
3531     if (isFixedSize(MI)) {
3532       assert(DescSize == 4);
3533       return DescSize;
3534     }
3535 
3536     int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
3537     if (Src0Idx == -1)
3538       return 4; // No operands.
3539 
3540     if (isLiteralConstantLike(MI.getOperand(Src0Idx), getOpSize(MI, Src0Idx)))
3541       return 8;
3542 
3543     int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
3544     if (Src1Idx == -1)
3545       return 4;
3546 
3547     if (isLiteralConstantLike(MI.getOperand(Src1Idx), getOpSize(MI, Src1Idx)))
3548       return 8;
3549 
3550     return 4;
3551   }
3552 
3553   if (DescSize == 4)
3554     return 4;
3555 
3556   switch (Opc) {
3557   case AMDGPU::SI_MASK_BRANCH:
3558   case TargetOpcode::IMPLICIT_DEF:
3559   case TargetOpcode::KILL:
3560   case TargetOpcode::DBG_VALUE:
3561   case TargetOpcode::BUNDLE:
3562   case TargetOpcode::EH_LABEL:
3563     return 0;
3564   case TargetOpcode::INLINEASM: {
3565     const MachineFunction *MF = MI.getParent()->getParent();
3566     const char *AsmStr = MI.getOperand(0).getSymbolName();
3567     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
3568   }
3569   default:
3570     llvm_unreachable("unable to find instruction size");
3571   }
3572 }
3573 
3574 bool SIInstrInfo::mayAccessFlatAddressSpace(const MachineInstr &MI) const {
3575   if (!isFLAT(MI))
3576     return false;
3577 
3578   if (MI.memoperands_empty())
3579     return true;
3580 
3581   for (const MachineMemOperand *MMO : MI.memoperands()) {
3582     if (MMO->getAddrSpace() == AMDGPUAS::FLAT_ADDRESS)
3583       return true;
3584   }
3585   return false;
3586 }
3587 
3588 ArrayRef<std::pair<int, const char *>>
3589 SIInstrInfo::getSerializableTargetIndices() const {
3590   static const std::pair<int, const char *> TargetIndices[] = {
3591       {AMDGPU::TI_CONSTDATA_START, "amdgpu-constdata-start"},
3592       {AMDGPU::TI_SCRATCH_RSRC_DWORD0, "amdgpu-scratch-rsrc-dword0"},
3593       {AMDGPU::TI_SCRATCH_RSRC_DWORD1, "amdgpu-scratch-rsrc-dword1"},
3594       {AMDGPU::TI_SCRATCH_RSRC_DWORD2, "amdgpu-scratch-rsrc-dword2"},
3595       {AMDGPU::TI_SCRATCH_RSRC_DWORD3, "amdgpu-scratch-rsrc-dword3"}};
3596   return makeArrayRef(TargetIndices);
3597 }
3598 
3599 /// This is used by the post-RA scheduler (SchedulePostRAList.cpp).  The
3600 /// post-RA version of misched uses CreateTargetMIHazardRecognizer.
3601 ScheduleHazardRecognizer *
3602 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
3603                                             const ScheduleDAG *DAG) const {
3604   return new GCNHazardRecognizer(DAG->MF);
3605 }
3606 
3607 /// This is the hazard recognizer used at -O0 by the PostRAHazardRecognizer
3608 /// pass.
3609 ScheduleHazardRecognizer *
3610 SIInstrInfo::CreateTargetPostRAHazardRecognizer(const MachineFunction &MF) const {
3611   return new GCNHazardRecognizer(MF);
3612 }
3613