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