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