R600/SI: isLegalOperand() shouldn't check constant bus for SALU instructions
[oota-llvm.git] / lib / Target / R600 / SIInstrInfo.cpp
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
16 #include "SIInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIDefines.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/CodeGen/RegisterScavenging.h"
25 #include "llvm/MC/MCInstrDesc.h"
26 #include "llvm/Support/Debug.h"
27
28 using namespace llvm;
29
30 SIInstrInfo::SIInstrInfo(const AMDGPUSubtarget &st)
31   : AMDGPUInstrInfo(st),
32     RI(st) { }
33
34 //===----------------------------------------------------------------------===//
35 // TargetInstrInfo callbacks
36 //===----------------------------------------------------------------------===//
37
38 static unsigned getNumOperandsNoGlue(SDNode *Node) {
39   unsigned N = Node->getNumOperands();
40   while (N && Node->getOperand(N - 1).getValueType() == MVT::Glue)
41     --N;
42   return N;
43 }
44
45 static SDValue findChainOperand(SDNode *Load) {
46   SDValue LastOp = Load->getOperand(getNumOperandsNoGlue(Load) - 1);
47   assert(LastOp.getValueType() == MVT::Other && "Chain missing from load node");
48   return LastOp;
49 }
50
51 /// \brief Returns true if both nodes have the same value for the given
52 ///        operand \p Op, or if both nodes do not have this operand.
53 static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* N1, unsigned OpName) {
54   unsigned Opc0 = N0->getMachineOpcode();
55   unsigned Opc1 = N1->getMachineOpcode();
56
57   int Op0Idx = AMDGPU::getNamedOperandIdx(Opc0, OpName);
58   int Op1Idx = AMDGPU::getNamedOperandIdx(Opc1, OpName);
59
60   if (Op0Idx == -1 && Op1Idx == -1)
61     return true;
62
63
64   if ((Op0Idx == -1 && Op1Idx != -1) ||
65       (Op1Idx == -1 && Op0Idx != -1))
66     return false;
67
68   // getNamedOperandIdx returns the index for the MachineInstr's operands,
69   // which includes the result as the first operand. We are indexing into the
70   // MachineSDNode's operands, so we need to skip the result operand to get
71   // the real index.
72   --Op0Idx;
73   --Op1Idx;
74
75   return N0->getOperand(Op0Idx) == N1->getOperand(Op1Idx);
76 }
77
78 bool SIInstrInfo::areLoadsFromSameBasePtr(SDNode *Load0, SDNode *Load1,
79                                           int64_t &Offset0,
80                                           int64_t &Offset1) const {
81   if (!Load0->isMachineOpcode() || !Load1->isMachineOpcode())
82     return false;
83
84   unsigned Opc0 = Load0->getMachineOpcode();
85   unsigned Opc1 = Load1->getMachineOpcode();
86
87   // Make sure both are actually loads.
88   if (!get(Opc0).mayLoad() || !get(Opc1).mayLoad())
89     return false;
90
91   if (isDS(Opc0) && isDS(Opc1)) {
92
93     // FIXME: Handle this case:
94     if (getNumOperandsNoGlue(Load0) != getNumOperandsNoGlue(Load1))
95       return false;
96
97     // Check base reg.
98     if (Load0->getOperand(1) != Load1->getOperand(1))
99       return false;
100
101     // Check chain.
102     if (findChainOperand(Load0) != findChainOperand(Load1))
103       return false;
104
105     // Skip read2 / write2 variants for simplicity.
106     // TODO: We should report true if the used offsets are adjacent (excluded
107     // st64 versions).
108     if (AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::data1) != -1 ||
109         AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::data1) != -1)
110       return false;
111
112     Offset0 = cast<ConstantSDNode>(Load0->getOperand(2))->getZExtValue();
113     Offset1 = cast<ConstantSDNode>(Load1->getOperand(2))->getZExtValue();
114     return true;
115   }
116
117   if (isSMRD(Opc0) && isSMRD(Opc1)) {
118     assert(getNumOperandsNoGlue(Load0) == getNumOperandsNoGlue(Load1));
119
120     // Check base reg.
121     if (Load0->getOperand(0) != Load1->getOperand(0))
122       return false;
123
124     // Check chain.
125     if (findChainOperand(Load0) != findChainOperand(Load1))
126       return false;
127
128     Offset0 = cast<ConstantSDNode>(Load0->getOperand(1))->getZExtValue();
129     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getZExtValue();
130     return true;
131   }
132
133   // MUBUF and MTBUF can access the same addresses.
134   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1))) {
135
136     // MUBUF and MTBUF have vaddr at different indices.
137     if (!nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::soffset) ||
138         findChainOperand(Load0) != findChainOperand(Load1) ||
139         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::vaddr) ||
140         !nodesHaveSameOperandValue(Load0, Load1, AMDGPU::OpName::srsrc))
141       return false;
142
143     int OffIdx0 = AMDGPU::getNamedOperandIdx(Opc0, AMDGPU::OpName::offset);
144     int OffIdx1 = AMDGPU::getNamedOperandIdx(Opc1, AMDGPU::OpName::offset);
145
146     if (OffIdx0 == -1 || OffIdx1 == -1)
147       return false;
148
149     // getNamedOperandIdx returns the index for MachineInstrs.  Since they
150     // inlcude the output in the operand list, but SDNodes don't, we need to
151     // subtract the index by one.
152     --OffIdx0;
153     --OffIdx1;
154
155     SDValue Off0 = Load0->getOperand(OffIdx0);
156     SDValue Off1 = Load1->getOperand(OffIdx1);
157
158     // The offset might be a FrameIndexSDNode.
159     if (!isa<ConstantSDNode>(Off0) || !isa<ConstantSDNode>(Off1))
160       return false;
161
162     Offset0 = cast<ConstantSDNode>(Off0)->getZExtValue();
163     Offset1 = cast<ConstantSDNode>(Off1)->getZExtValue();
164     return true;
165   }
166
167   return false;
168 }
169
170 static bool isStride64(unsigned Opc) {
171   switch (Opc) {
172   case AMDGPU::DS_READ2ST64_B32:
173   case AMDGPU::DS_READ2ST64_B64:
174   case AMDGPU::DS_WRITE2ST64_B32:
175   case AMDGPU::DS_WRITE2ST64_B64:
176     return true;
177   default:
178     return false;
179   }
180 }
181
182 bool SIInstrInfo::getLdStBaseRegImmOfs(MachineInstr *LdSt,
183                                        unsigned &BaseReg, unsigned &Offset,
184                                        const TargetRegisterInfo *TRI) const {
185   unsigned Opc = LdSt->getOpcode();
186   if (isDS(Opc)) {
187     const MachineOperand *OffsetImm = getNamedOperand(*LdSt,
188                                                       AMDGPU::OpName::offset);
189     if (OffsetImm) {
190       // Normal, single offset LDS instruction.
191       const MachineOperand *AddrReg = getNamedOperand(*LdSt,
192                                                       AMDGPU::OpName::addr);
193
194       BaseReg = AddrReg->getReg();
195       Offset = OffsetImm->getImm();
196       return true;
197     }
198
199     // The 2 offset instructions use offset0 and offset1 instead. We can treat
200     // these as a load with a single offset if the 2 offsets are consecutive. We
201     // will use this for some partially aligned loads.
202     const MachineOperand *Offset0Imm = getNamedOperand(*LdSt,
203                                                        AMDGPU::OpName::offset0);
204     const MachineOperand *Offset1Imm = getNamedOperand(*LdSt,
205                                                        AMDGPU::OpName::offset1);
206
207     uint8_t Offset0 = Offset0Imm->getImm();
208     uint8_t Offset1 = Offset1Imm->getImm();
209     assert(Offset1 > Offset0);
210
211     if (Offset1 - Offset0 == 1) {
212       // Each of these offsets is in element sized units, so we need to convert
213       // to bytes of the individual reads.
214
215       unsigned EltSize;
216       if (LdSt->mayLoad())
217         EltSize = getOpRegClass(*LdSt, 0)->getSize() / 2;
218       else {
219         assert(LdSt->mayStore());
220         int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
221         EltSize = getOpRegClass(*LdSt, Data0Idx)->getSize();
222       }
223
224       if (isStride64(Opc))
225         EltSize *= 64;
226
227       const MachineOperand *AddrReg = getNamedOperand(*LdSt,
228                                                       AMDGPU::OpName::addr);
229       BaseReg = AddrReg->getReg();
230       Offset = EltSize * Offset0;
231       return true;
232     }
233
234     return false;
235   }
236
237   if (isMUBUF(Opc) || isMTBUF(Opc)) {
238     if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::soffset) != -1)
239       return false;
240
241     const MachineOperand *AddrReg = getNamedOperand(*LdSt,
242                                                     AMDGPU::OpName::vaddr);
243     if (!AddrReg)
244       return false;
245
246     const MachineOperand *OffsetImm = getNamedOperand(*LdSt,
247                                                       AMDGPU::OpName::offset);
248     BaseReg = AddrReg->getReg();
249     Offset = OffsetImm->getImm();
250     return true;
251   }
252
253   if (isSMRD(Opc)) {
254     const MachineOperand *OffsetImm = getNamedOperand(*LdSt,
255                                                       AMDGPU::OpName::offset);
256     if (!OffsetImm)
257       return false;
258
259     const MachineOperand *SBaseReg = getNamedOperand(*LdSt,
260                                                      AMDGPU::OpName::sbase);
261     BaseReg = SBaseReg->getReg();
262     Offset = OffsetImm->getImm();
263     return true;
264   }
265
266   return false;
267 }
268
269 bool SIInstrInfo::shouldClusterLoads(MachineInstr *FirstLdSt,
270                                      MachineInstr *SecondLdSt,
271                                      unsigned NumLoads) const {
272   unsigned Opc0 = FirstLdSt->getOpcode();
273   unsigned Opc1 = SecondLdSt->getOpcode();
274
275   // TODO: This needs finer tuning
276   if (NumLoads > 4)
277     return false;
278
279   if (isDS(Opc0) && isDS(Opc1))
280     return true;
281
282   if (isSMRD(Opc0) && isSMRD(Opc1))
283     return true;
284
285   if ((isMUBUF(Opc0) || isMTBUF(Opc0)) && (isMUBUF(Opc1) || isMTBUF(Opc1)))
286     return true;
287
288   return false;
289 }
290
291 void
292 SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
293                          MachineBasicBlock::iterator MI, DebugLoc DL,
294                          unsigned DestReg, unsigned SrcReg,
295                          bool KillSrc) const {
296
297   // If we are trying to copy to or from SCC, there is a bug somewhere else in
298   // the backend.  While it may be theoretically possible to do this, it should
299   // never be necessary.
300   assert(DestReg != AMDGPU::SCC && SrcReg != AMDGPU::SCC);
301
302   static const int16_t Sub0_15[] = {
303     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
304     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
305     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
306     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15, 0
307   };
308
309   static const int16_t Sub0_7[] = {
310     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
311     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7, 0
312   };
313
314   static const int16_t Sub0_3[] = {
315     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3, 0
316   };
317
318   static const int16_t Sub0_2[] = {
319     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, 0
320   };
321
322   static const int16_t Sub0_1[] = {
323     AMDGPU::sub0, AMDGPU::sub1, 0
324   };
325
326   unsigned Opcode;
327   const int16_t *SubIndices;
328
329   if (AMDGPU::SReg_32RegClass.contains(DestReg)) {
330     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
331     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
332             .addReg(SrcReg, getKillRegState(KillSrc));
333     return;
334
335   } else if (AMDGPU::SReg_64RegClass.contains(DestReg)) {
336     assert(AMDGPU::SReg_64RegClass.contains(SrcReg));
337     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
338             .addReg(SrcReg, getKillRegState(KillSrc));
339     return;
340
341   } else if (AMDGPU::SReg_128RegClass.contains(DestReg)) {
342     assert(AMDGPU::SReg_128RegClass.contains(SrcReg));
343     Opcode = AMDGPU::S_MOV_B32;
344     SubIndices = Sub0_3;
345
346   } else if (AMDGPU::SReg_256RegClass.contains(DestReg)) {
347     assert(AMDGPU::SReg_256RegClass.contains(SrcReg));
348     Opcode = AMDGPU::S_MOV_B32;
349     SubIndices = Sub0_7;
350
351   } else if (AMDGPU::SReg_512RegClass.contains(DestReg)) {
352     assert(AMDGPU::SReg_512RegClass.contains(SrcReg));
353     Opcode = AMDGPU::S_MOV_B32;
354     SubIndices = Sub0_15;
355
356   } else if (AMDGPU::VReg_32RegClass.contains(DestReg)) {
357     assert(AMDGPU::VReg_32RegClass.contains(SrcReg) ||
358            AMDGPU::SReg_32RegClass.contains(SrcReg));
359     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
360             .addReg(SrcReg, getKillRegState(KillSrc));
361     return;
362
363   } else if (AMDGPU::VReg_64RegClass.contains(DestReg)) {
364     assert(AMDGPU::VReg_64RegClass.contains(SrcReg) ||
365            AMDGPU::SReg_64RegClass.contains(SrcReg));
366     Opcode = AMDGPU::V_MOV_B32_e32;
367     SubIndices = Sub0_1;
368
369   } else if (AMDGPU::VReg_96RegClass.contains(DestReg)) {
370     assert(AMDGPU::VReg_96RegClass.contains(SrcReg));
371     Opcode = AMDGPU::V_MOV_B32_e32;
372     SubIndices = Sub0_2;
373
374   } else if (AMDGPU::VReg_128RegClass.contains(DestReg)) {
375     assert(AMDGPU::VReg_128RegClass.contains(SrcReg) ||
376            AMDGPU::SReg_128RegClass.contains(SrcReg));
377     Opcode = AMDGPU::V_MOV_B32_e32;
378     SubIndices = Sub0_3;
379
380   } else if (AMDGPU::VReg_256RegClass.contains(DestReg)) {
381     assert(AMDGPU::VReg_256RegClass.contains(SrcReg) ||
382            AMDGPU::SReg_256RegClass.contains(SrcReg));
383     Opcode = AMDGPU::V_MOV_B32_e32;
384     SubIndices = Sub0_7;
385
386   } else if (AMDGPU::VReg_512RegClass.contains(DestReg)) {
387     assert(AMDGPU::VReg_512RegClass.contains(SrcReg) ||
388            AMDGPU::SReg_512RegClass.contains(SrcReg));
389     Opcode = AMDGPU::V_MOV_B32_e32;
390     SubIndices = Sub0_15;
391
392   } else {
393     llvm_unreachable("Can't copy register!");
394   }
395
396   while (unsigned SubIdx = *SubIndices++) {
397     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
398       get(Opcode), RI.getSubReg(DestReg, SubIdx));
399
400     Builder.addReg(RI.getSubReg(SrcReg, SubIdx), getKillRegState(KillSrc));
401
402     if (*SubIndices)
403       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
404   }
405 }
406
407 unsigned SIInstrInfo::commuteOpcode(unsigned Opcode) const {
408   int NewOpc;
409
410   // Try to map original to commuted opcode
411   if ((NewOpc = AMDGPU::getCommuteRev(Opcode)) != -1)
412     return NewOpc;
413
414   // Try to map commuted to original opcode
415   if ((NewOpc = AMDGPU::getCommuteOrig(Opcode)) != -1)
416     return NewOpc;
417
418   return Opcode;
419 }
420
421 static bool shouldTryToSpillVGPRs(MachineFunction *MF) {
422
423   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
424   const TargetMachine &TM = MF->getTarget();
425
426   // FIXME: Even though it can cause problems, we need to enable
427   // spilling at -O0, since the fast register allocator always
428   // spills registers that are live at the end of blocks.
429   return MFI->getShaderType() == ShaderType::COMPUTE &&
430          TM.getOptLevel() == CodeGenOpt::None;
431
432 }
433
434 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
435                                       MachineBasicBlock::iterator MI,
436                                       unsigned SrcReg, bool isKill,
437                                       int FrameIndex,
438                                       const TargetRegisterClass *RC,
439                                       const TargetRegisterInfo *TRI) const {
440   MachineFunction *MF = MBB.getParent();
441   MachineFrameInfo *FrameInfo = MF->getFrameInfo();
442   DebugLoc DL = MBB.findDebugLoc(MI);
443   int Opcode = -1;
444
445   if (RI.isSGPRClass(RC)) {
446     // We are only allowed to create one new instruction when spilling
447     // registers, so we need to use pseudo instruction for spilling
448     // SGPRs.
449     switch (RC->getSize() * 8) {
450       case 32:  Opcode = AMDGPU::SI_SPILL_S32_SAVE;  break;
451       case 64:  Opcode = AMDGPU::SI_SPILL_S64_SAVE;  break;
452       case 128: Opcode = AMDGPU::SI_SPILL_S128_SAVE; break;
453       case 256: Opcode = AMDGPU::SI_SPILL_S256_SAVE; break;
454       case 512: Opcode = AMDGPU::SI_SPILL_S512_SAVE; break;
455     }
456   } else if(shouldTryToSpillVGPRs(MF) && RI.hasVGPRs(RC)) {
457     switch(RC->getSize() * 8) {
458       case 32: Opcode = AMDGPU::SI_SPILL_V32_SAVE; break;
459       case 64: Opcode = AMDGPU::SI_SPILL_V64_SAVE; break;
460       case 96: Opcode = AMDGPU::SI_SPILL_V96_SAVE; break;
461       case 128: Opcode = AMDGPU::SI_SPILL_V128_SAVE; break;
462       case 256: Opcode = AMDGPU::SI_SPILL_V256_SAVE; break;
463       case 512: Opcode = AMDGPU::SI_SPILL_V512_SAVE; break;
464     }
465   }
466
467   if (Opcode != -1) {
468     FrameInfo->setObjectAlignment(FrameIndex, 4);
469     BuildMI(MBB, MI, DL, get(Opcode))
470             .addReg(SrcReg)
471             .addFrameIndex(FrameIndex);
472   } else {
473     LLVMContext &Ctx = MF->getFunction()->getContext();
474     Ctx.emitError("SIInstrInfo::storeRegToStackSlot - Do not know how to"
475                   " spill register");
476     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), AMDGPU::VGPR0)
477             .addReg(SrcReg);
478   }
479 }
480
481 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
482                                        MachineBasicBlock::iterator MI,
483                                        unsigned DestReg, int FrameIndex,
484                                        const TargetRegisterClass *RC,
485                                        const TargetRegisterInfo *TRI) const {
486   MachineFunction *MF = MBB.getParent();
487   MachineFrameInfo *FrameInfo = MF->getFrameInfo();
488   DebugLoc DL = MBB.findDebugLoc(MI);
489   int Opcode = -1;
490
491   if (RI.isSGPRClass(RC)){
492     switch(RC->getSize() * 8) {
493       case 32:  Opcode = AMDGPU::SI_SPILL_S32_RESTORE; break;
494       case 64:  Opcode = AMDGPU::SI_SPILL_S64_RESTORE;  break;
495       case 128: Opcode = AMDGPU::SI_SPILL_S128_RESTORE; break;
496       case 256: Opcode = AMDGPU::SI_SPILL_S256_RESTORE; break;
497       case 512: Opcode = AMDGPU::SI_SPILL_S512_RESTORE; break;
498     }
499   } else if(shouldTryToSpillVGPRs(MF) && RI.hasVGPRs(RC)) {
500     switch(RC->getSize() * 8) {
501       case 32: Opcode = AMDGPU::SI_SPILL_V32_RESTORE; break;
502       case 64: Opcode = AMDGPU::SI_SPILL_V64_RESTORE; break;
503       case 96: Opcode = AMDGPU::SI_SPILL_V96_RESTORE; break;
504       case 128: Opcode = AMDGPU::SI_SPILL_V128_RESTORE; break;
505       case 256: Opcode = AMDGPU::SI_SPILL_V256_RESTORE; break;
506       case 512: Opcode = AMDGPU::SI_SPILL_V512_RESTORE; break;
507     }
508   }
509
510   if (Opcode != -1) {
511     FrameInfo->setObjectAlignment(FrameIndex, 4);
512     BuildMI(MBB, MI, DL, get(Opcode), DestReg)
513             .addFrameIndex(FrameIndex);
514   } else {
515     LLVMContext &Ctx = MF->getFunction()->getContext();
516     Ctx.emitError("SIInstrInfo::loadRegFromStackSlot - Do not know how to"
517                   " restore register");
518     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
519             .addReg(AMDGPU::VGPR0);
520   }
521 }
522
523 /// \param @Offset Offset in bytes of the FrameIndex being spilled
524 unsigned SIInstrInfo::calculateLDSSpillAddress(MachineBasicBlock &MBB,
525                                                MachineBasicBlock::iterator MI,
526                                                RegScavenger *RS, unsigned TmpReg,
527                                                unsigned FrameOffset,
528                                                unsigned Size) const {
529   MachineFunction *MF = MBB.getParent();
530   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
531   const AMDGPUSubtarget &ST = MF->getTarget().getSubtarget<AMDGPUSubtarget>();
532   const SIRegisterInfo *TRI =
533       static_cast<const SIRegisterInfo*>(ST.getRegisterInfo());
534   DebugLoc DL = MBB.findDebugLoc(MI);
535   unsigned WorkGroupSize = MFI->getMaximumWorkGroupSize(*MF);
536   unsigned WavefrontSize = ST.getWavefrontSize();
537
538   unsigned TIDReg = MFI->getTIDReg();
539   if (!MFI->hasCalculatedTID()) {
540     MachineBasicBlock &Entry = MBB.getParent()->front();
541     MachineBasicBlock::iterator Insert = Entry.front();
542     DebugLoc DL = Insert->getDebugLoc();
543
544     TIDReg = RI.findUnusedVGPR(MF->getRegInfo());
545     if (TIDReg == AMDGPU::NoRegister)
546       return TIDReg;
547
548
549     if (MFI->getShaderType() == ShaderType::COMPUTE &&
550         WorkGroupSize > WavefrontSize) {
551
552       unsigned TIDIGXReg = TRI->getPreloadedValue(*MF, SIRegisterInfo::TIDIG_X);
553       unsigned TIDIGYReg = TRI->getPreloadedValue(*MF, SIRegisterInfo::TIDIG_Y);
554       unsigned TIDIGZReg = TRI->getPreloadedValue(*MF, SIRegisterInfo::TIDIG_Z);
555       unsigned InputPtrReg =
556           TRI->getPreloadedValue(*MF, SIRegisterInfo::INPUT_PTR);
557       static const unsigned TIDIGRegs[3] = {
558         TIDIGXReg, TIDIGYReg, TIDIGZReg
559       };
560       for (unsigned Reg : TIDIGRegs) {
561         if (!Entry.isLiveIn(Reg))
562           Entry.addLiveIn(Reg);
563       }
564
565       RS->enterBasicBlock(&Entry);
566       unsigned STmp0 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
567       unsigned STmp1 = RS->scavengeRegister(&AMDGPU::SGPR_32RegClass, 0);
568       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp0)
569               .addReg(InputPtrReg)
570               .addImm(SI::KernelInputOffsets::NGROUPS_Z);
571       BuildMI(Entry, Insert, DL, get(AMDGPU::S_LOAD_DWORD_IMM), STmp1)
572               .addReg(InputPtrReg)
573               .addImm(SI::KernelInputOffsets::NGROUPS_Y);
574
575       // NGROUPS.X * NGROUPS.Y
576       BuildMI(Entry, Insert, DL, get(AMDGPU::S_MUL_I32), STmp1)
577               .addReg(STmp1)
578               .addReg(STmp0);
579       // (NGROUPS.X * NGROUPS.Y) * TIDIG.X
580       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MUL_U32_U24_e32), TIDReg)
581               .addReg(STmp1)
582               .addReg(TIDIGXReg);
583       // NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)
584       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MAD_U32_U24), TIDReg)
585               .addReg(STmp0)
586               .addReg(TIDIGYReg)
587               .addReg(TIDReg);
588       // (NGROUPS.Z * TIDIG.Y + (NGROUPS.X * NGROPUS.Y * TIDIG.X)) + TIDIG.Z
589       BuildMI(Entry, Insert, DL, get(AMDGPU::V_ADD_I32_e32), TIDReg)
590               .addReg(TIDReg)
591               .addReg(TIDIGZReg);
592     } else {
593       // Get the wave id
594       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_LO_U32_B32_e64),
595               TIDReg)
596               .addImm(-1)
597               .addImm(0);
598
599       BuildMI(Entry, Insert, DL, get(AMDGPU::V_MBCNT_HI_U32_B32_e32),
600               TIDReg)
601               .addImm(-1)
602               .addReg(TIDReg);
603     }
604
605     BuildMI(Entry, Insert, DL, get(AMDGPU::V_LSHLREV_B32_e32),
606             TIDReg)
607             .addImm(2)
608             .addReg(TIDReg);
609     MFI->setTIDReg(TIDReg);
610   }
611
612   // Add FrameIndex to LDS offset
613   unsigned LDSOffset = MFI->LDSSize + (FrameOffset * WorkGroupSize);
614   BuildMI(MBB, MI, DL, get(AMDGPU::V_ADD_I32_e32), TmpReg)
615           .addImm(LDSOffset)
616           .addReg(TIDReg);
617
618   return TmpReg;
619 }
620
621 void SIInstrInfo::insertNOPs(MachineBasicBlock::iterator MI,
622                              int Count) const {
623   while (Count > 0) {
624     int Arg;
625     if (Count >= 8)
626       Arg = 7;
627     else
628       Arg = Count - 1;
629     Count -= 8;
630     BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(AMDGPU::S_NOP))
631             .addImm(Arg);
632   }
633 }
634
635 bool SIInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
636   MachineBasicBlock &MBB = *MI->getParent();
637   DebugLoc DL = MBB.findDebugLoc(MI);
638   switch (MI->getOpcode()) {
639   default: return AMDGPUInstrInfo::expandPostRAPseudo(MI);
640
641   case AMDGPU::SI_CONSTDATA_PTR: {
642     unsigned Reg = MI->getOperand(0).getReg();
643     unsigned RegLo = RI.getSubReg(Reg, AMDGPU::sub0);
644     unsigned RegHi = RI.getSubReg(Reg, AMDGPU::sub1);
645
646     BuildMI(MBB, MI, DL, get(AMDGPU::S_GETPC_B64), Reg);
647
648     // Add 32-bit offset from this instruction to the start of the constant data.
649     BuildMI(MBB, MI, DL, get(AMDGPU::S_ADD_U32), RegLo)
650             .addReg(RegLo)
651             .addTargetIndex(AMDGPU::TI_CONSTDATA_START)
652             .addReg(AMDGPU::SCC, RegState::Define | RegState::Implicit);
653     BuildMI(MBB, MI, DL, get(AMDGPU::S_ADDC_U32), RegHi)
654             .addReg(RegHi)
655             .addImm(0)
656             .addReg(AMDGPU::SCC, RegState::Define | RegState::Implicit)
657             .addReg(AMDGPU::SCC, RegState::Implicit);
658     MI->eraseFromParent();
659     break;
660   }
661   case AMDGPU::SGPR_USE:
662     // This is just a placeholder for register allocation.
663     MI->eraseFromParent();
664     break;
665   }
666   return true;
667 }
668
669 MachineInstr *SIInstrInfo::commuteInstruction(MachineInstr *MI,
670                                               bool NewMI) const {
671   if (MI->getNumOperands() < 3)
672     return nullptr;
673
674   int Src0Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
675                                            AMDGPU::OpName::src0);
676   assert(Src0Idx != -1 && "Should always have src0 operand");
677
678   MachineOperand &Src0 = MI->getOperand(Src0Idx);
679   if (!Src0.isReg())
680     return nullptr;
681
682   int Src1Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
683                                            AMDGPU::OpName::src1);
684   if (Src1Idx == -1)
685     return nullptr;
686
687   MachineOperand &Src1 = MI->getOperand(Src1Idx);
688
689   // Make sure it's legal to commute operands for VOP2.
690   if (isVOP2(MI->getOpcode()) &&
691       (!isOperandLegal(MI, Src0Idx, &Src1) ||
692        !isOperandLegal(MI, Src1Idx, &Src0)))
693     return nullptr;
694
695   if (!Src1.isReg()) {
696     // Allow commuting instructions with Imm or FPImm operands.
697     if (NewMI || (!Src1.isImm() && !Src1.isFPImm()) ||
698        (!isVOP2(MI->getOpcode()) && !isVOP3(MI->getOpcode()))) {
699       return nullptr;
700     }
701
702     // Be sure to copy the source modifiers to the right place.
703     if (MachineOperand *Src0Mods
704           = getNamedOperand(*MI, AMDGPU::OpName::src0_modifiers)) {
705       MachineOperand *Src1Mods
706         = getNamedOperand(*MI, AMDGPU::OpName::src1_modifiers);
707
708       int Src0ModsVal = Src0Mods->getImm();
709       if (!Src1Mods && Src0ModsVal != 0)
710         return nullptr;
711
712       // XXX - This assert might be a lie. It might be useful to have a neg
713       // modifier with 0.0.
714       int Src1ModsVal = Src1Mods->getImm();
715       assert((Src1ModsVal == 0) && "Not expecting modifiers with immediates");
716
717       Src1Mods->setImm(Src0ModsVal);
718       Src0Mods->setImm(Src1ModsVal);
719     }
720
721     unsigned Reg = Src0.getReg();
722     unsigned SubReg = Src0.getSubReg();
723     if (Src1.isImm())
724       Src0.ChangeToImmediate(Src1.getImm());
725     else if (Src1.isFPImm())
726       Src0.ChangeToFPImmediate(Src1.getFPImm());
727     else
728       llvm_unreachable("Should only have immediates");
729
730     Src1.ChangeToRegister(Reg, false);
731     Src1.setSubReg(SubReg);
732   } else {
733     MI = TargetInstrInfo::commuteInstruction(MI, NewMI);
734   }
735
736   if (MI)
737     MI->setDesc(get(commuteOpcode(MI->getOpcode())));
738
739   return MI;
740 }
741
742 // This needs to be implemented because the source modifiers may be inserted
743 // between the true commutable operands, and the base
744 // TargetInstrInfo::commuteInstruction uses it.
745 bool SIInstrInfo::findCommutedOpIndices(MachineInstr *MI,
746                                         unsigned &SrcOpIdx1,
747                                         unsigned &SrcOpIdx2) const {
748   const MCInstrDesc &MCID = MI->getDesc();
749   if (!MCID.isCommutable())
750     return false;
751
752   unsigned Opc = MI->getOpcode();
753   int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
754   if (Src0Idx == -1)
755     return false;
756
757   // FIXME: Workaround TargetInstrInfo::commuteInstruction asserting on
758   // immediate.
759   if (!MI->getOperand(Src0Idx).isReg())
760     return false;
761
762   int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
763   if (Src1Idx == -1)
764     return false;
765
766   if (!MI->getOperand(Src1Idx).isReg())
767     return false;
768
769   // If any source modifiers are set, the generic instruction commuting won't
770   // understand how to copy the source modifiers.
771   if (hasModifiersSet(*MI, AMDGPU::OpName::src0_modifiers) ||
772       hasModifiersSet(*MI, AMDGPU::OpName::src1_modifiers))
773     return false;
774
775   SrcOpIdx1 = Src0Idx;
776   SrcOpIdx2 = Src1Idx;
777   return true;
778 }
779
780 MachineInstr *SIInstrInfo::buildMovInstr(MachineBasicBlock *MBB,
781                                          MachineBasicBlock::iterator I,
782                                          unsigned DstReg,
783                                          unsigned SrcReg) const {
784   return BuildMI(*MBB, I, MBB->findDebugLoc(I), get(AMDGPU::V_MOV_B32_e32),
785                  DstReg) .addReg(SrcReg);
786 }
787
788 bool SIInstrInfo::isMov(unsigned Opcode) const {
789   switch(Opcode) {
790   default: return false;
791   case AMDGPU::S_MOV_B32:
792   case AMDGPU::S_MOV_B64:
793   case AMDGPU::V_MOV_B32_e32:
794   case AMDGPU::V_MOV_B32_e64:
795     return true;
796   }
797 }
798
799 bool
800 SIInstrInfo::isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
801   return RC != &AMDGPU::EXECRegRegClass;
802 }
803
804 bool
805 SIInstrInfo::isTriviallyReMaterializable(const MachineInstr *MI,
806                                          AliasAnalysis *AA) const {
807   switch(MI->getOpcode()) {
808   default: return AMDGPUInstrInfo::isTriviallyReMaterializable(MI, AA);
809   case AMDGPU::S_MOV_B32:
810   case AMDGPU::S_MOV_B64:
811   case AMDGPU::V_MOV_B32_e32:
812     return MI->getOperand(1).isImm();
813   }
814 }
815
816 static bool offsetsDoNotOverlap(int WidthA, int OffsetA,
817                                 int WidthB, int OffsetB) {
818   int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
819   int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
820   int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
821   return LowOffset + LowWidth <= HighOffset;
822 }
823
824 bool SIInstrInfo::checkInstOffsetsDoNotOverlap(MachineInstr *MIa,
825                                                MachineInstr *MIb) const {
826   unsigned BaseReg0, Offset0;
827   unsigned BaseReg1, Offset1;
828
829   if (getLdStBaseRegImmOfs(MIa, BaseReg0, Offset0, &RI) &&
830       getLdStBaseRegImmOfs(MIb, BaseReg1, Offset1, &RI)) {
831     assert(MIa->hasOneMemOperand() && MIb->hasOneMemOperand() &&
832            "read2 / write2 not expected here yet");
833     unsigned Width0 = (*MIa->memoperands_begin())->getSize();
834     unsigned Width1 = (*MIb->memoperands_begin())->getSize();
835     if (BaseReg0 == BaseReg1 &&
836         offsetsDoNotOverlap(Width0, Offset0, Width1, Offset1)) {
837       return true;
838     }
839   }
840
841   return false;
842 }
843
844 bool SIInstrInfo::areMemAccessesTriviallyDisjoint(MachineInstr *MIa,
845                                                   MachineInstr *MIb,
846                                                   AliasAnalysis *AA) const {
847   unsigned Opc0 = MIa->getOpcode();
848   unsigned Opc1 = MIb->getOpcode();
849
850   assert(MIa && (MIa->mayLoad() || MIa->mayStore()) &&
851          "MIa must load from or modify a memory location");
852   assert(MIb && (MIb->mayLoad() || MIb->mayStore()) &&
853          "MIb must load from or modify a memory location");
854
855   if (MIa->hasUnmodeledSideEffects() || MIb->hasUnmodeledSideEffects())
856     return false;
857
858   // XXX - Can we relax this between address spaces?
859   if (MIa->hasOrderedMemoryRef() || MIb->hasOrderedMemoryRef())
860     return false;
861
862   // TODO: Should we check the address space from the MachineMemOperand? That
863   // would allow us to distinguish objects we know don't alias based on the
864   // underlying addres space, even if it was lowered to a different one,
865   // e.g. private accesses lowered to use MUBUF instructions on a scratch
866   // buffer.
867   if (isDS(Opc0)) {
868     if (isDS(Opc1))
869       return checkInstOffsetsDoNotOverlap(MIa, MIb);
870
871     return !isFLAT(Opc1);
872   }
873
874   if (isMUBUF(Opc0) || isMTBUF(Opc0)) {
875     if (isMUBUF(Opc1) || isMTBUF(Opc1))
876       return checkInstOffsetsDoNotOverlap(MIa, MIb);
877
878     return !isFLAT(Opc1) && !isSMRD(Opc1);
879   }
880
881   if (isSMRD(Opc0)) {
882     if (isSMRD(Opc1))
883       return checkInstOffsetsDoNotOverlap(MIa, MIb);
884
885     return !isFLAT(Opc1) && !isMUBUF(Opc0) && !isMTBUF(Opc0);
886   }
887
888   if (isFLAT(Opc0)) {
889     if (isFLAT(Opc1))
890       return checkInstOffsetsDoNotOverlap(MIa, MIb);
891
892     return false;
893   }
894
895   return false;
896 }
897
898 bool SIInstrInfo::isInlineConstant(const APInt &Imm) const {
899   int64_t SVal = Imm.getSExtValue();
900   if (SVal >= -16 && SVal <= 64)
901     return true;
902
903   if (Imm.getBitWidth() == 64) {
904     uint64_t Val = Imm.getZExtValue();
905     return (DoubleToBits(0.0) == Val) ||
906            (DoubleToBits(1.0) == Val) ||
907            (DoubleToBits(-1.0) == Val) ||
908            (DoubleToBits(0.5) == Val) ||
909            (DoubleToBits(-0.5) == Val) ||
910            (DoubleToBits(2.0) == Val) ||
911            (DoubleToBits(-2.0) == Val) ||
912            (DoubleToBits(4.0) == Val) ||
913            (DoubleToBits(-4.0) == Val);
914   }
915
916   // The actual type of the operand does not seem to matter as long
917   // as the bits match one of the inline immediate values.  For example:
918   //
919   // -nan has the hexadecimal encoding of 0xfffffffe which is -2 in decimal,
920   // so it is a legal inline immediate.
921   //
922   // 1065353216 has the hexadecimal encoding 0x3f800000 which is 1.0f in
923   // floating-point, so it is a legal inline immediate.
924   uint32_t Val = Imm.getZExtValue();
925
926   return (FloatToBits(0.0f) == Val) ||
927          (FloatToBits(1.0f) == Val) ||
928          (FloatToBits(-1.0f) == Val) ||
929          (FloatToBits(0.5f) == Val) ||
930          (FloatToBits(-0.5f) == Val) ||
931          (FloatToBits(2.0f) == Val) ||
932          (FloatToBits(-2.0f) == Val) ||
933          (FloatToBits(4.0f) == Val) ||
934          (FloatToBits(-4.0f) == Val);
935 }
936
937 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO) const {
938   if (MO.isImm())
939     return isInlineConstant(APInt(32, MO.getImm(), true));
940
941   if (MO.isFPImm()) {
942     APFloat FpImm = MO.getFPImm()->getValueAPF();
943     return isInlineConstant(FpImm.bitcastToAPInt());
944   }
945
946   return false;
947 }
948
949 bool SIInstrInfo::isLiteralConstant(const MachineOperand &MO) const {
950   return (MO.isImm() || MO.isFPImm()) && !isInlineConstant(MO);
951 }
952
953 static bool compareMachineOp(const MachineOperand &Op0,
954                              const MachineOperand &Op1) {
955   if (Op0.getType() != Op1.getType())
956     return false;
957
958   switch (Op0.getType()) {
959   case MachineOperand::MO_Register:
960     return Op0.getReg() == Op1.getReg();
961   case MachineOperand::MO_Immediate:
962     return Op0.getImm() == Op1.getImm();
963   case MachineOperand::MO_FPImmediate:
964     return Op0.getFPImm() == Op1.getFPImm();
965   default:
966     llvm_unreachable("Didn't expect to be comparing these operand types");
967   }
968 }
969
970 bool SIInstrInfo::isImmOperandLegal(const MachineInstr *MI, unsigned OpNo,
971                                  const MachineOperand &MO) const {
972   const MCOperandInfo &OpInfo = get(MI->getOpcode()).OpInfo[OpNo];
973
974   assert(MO.isImm() || MO.isFPImm() || MO.isTargetIndex() || MO.isFI());
975
976   if (OpInfo.OperandType == MCOI::OPERAND_IMMEDIATE)
977     return true;
978
979   if (OpInfo.RegClass < 0)
980     return false;
981
982   if (isLiteralConstant(MO))
983     return RI.regClassCanUseLiteralConstant(OpInfo.RegClass);
984
985   return RI.regClassCanUseInlineConstant(OpInfo.RegClass);
986 }
987
988 bool SIInstrInfo::canFoldOffset(unsigned OffsetSize, unsigned AS) const {
989   switch (AS) {
990   case AMDGPUAS::GLOBAL_ADDRESS: {
991     // MUBUF instructions a 12-bit offset in bytes.
992     return isUInt<12>(OffsetSize);
993   }
994   case AMDGPUAS::CONSTANT_ADDRESS: {
995     // SMRD instructions have an 8-bit offset in dwords on SI and
996     // a 20-bit offset in bytes on VI.
997     if (RI.ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
998       return isUInt<20>(OffsetSize);
999     else
1000       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1001   }
1002   case AMDGPUAS::LOCAL_ADDRESS:
1003   case AMDGPUAS::REGION_ADDRESS: {
1004     // The single offset versions have a 16-bit offset in bytes.
1005     return isUInt<16>(OffsetSize);
1006   }
1007   case AMDGPUAS::PRIVATE_ADDRESS:
1008     // Indirect register addressing does not use any offsets.
1009   default:
1010     return 0;
1011   }
1012 }
1013
1014 bool SIInstrInfo::hasVALU32BitEncoding(unsigned Opcode) const {
1015   return AMDGPU::getVOPe32(Opcode) != -1;
1016 }
1017
1018 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1019   // The src0_modifier operand is present on all instructions
1020   // that have modifiers.
1021
1022   return AMDGPU::getNamedOperandIdx(Opcode,
1023                                     AMDGPU::OpName::src0_modifiers) != -1;
1024 }
1025
1026 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1027                                   unsigned OpName) const {
1028   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1029   return Mods && Mods->getImm();
1030 }
1031
1032 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1033                                   const MachineOperand &MO) const {
1034   // Literal constants use the constant bus.
1035   if (isLiteralConstant(MO))
1036     return true;
1037
1038   if (!MO.isReg() || !MO.isUse())
1039     return false;
1040
1041   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1042     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
1043
1044   // FLAT_SCR is just an SGPR pair.
1045   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
1046     return true;
1047
1048   // EXEC register uses the constant bus.
1049   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
1050     return true;
1051
1052   // SGPRs use the constant bus
1053   if (MO.getReg() == AMDGPU::M0 || MO.getReg() == AMDGPU::VCC ||
1054       (!MO.isImplicit() &&
1055       (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
1056        AMDGPU::SGPR_64RegClass.contains(MO.getReg())))) {
1057     return true;
1058   }
1059
1060   return false;
1061 }
1062
1063 bool SIInstrInfo::verifyInstruction(const MachineInstr *MI,
1064                                     StringRef &ErrInfo) const {
1065   uint16_t Opcode = MI->getOpcode();
1066   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1067   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
1068   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
1069   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
1070
1071   // Make sure the number of operands is correct.
1072   const MCInstrDesc &Desc = get(Opcode);
1073   if (!Desc.isVariadic() &&
1074       Desc.getNumOperands() != MI->getNumExplicitOperands()) {
1075      ErrInfo = "Instruction has wrong number of operands.";
1076      return false;
1077   }
1078
1079   // Make sure the register classes are correct
1080   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
1081     switch (Desc.OpInfo[i].OperandType) {
1082     case MCOI::OPERAND_REGISTER: {
1083       if ((MI->getOperand(i).isImm() || MI->getOperand(i).isFPImm()) &&
1084           !isImmOperandLegal(MI, i, MI->getOperand(i))) {
1085           ErrInfo = "Illegal immediate value for operand.";
1086           return false;
1087         }
1088       }
1089       break;
1090     case MCOI::OPERAND_IMMEDIATE:
1091       // Check if this operand is an immediate.
1092       // FrameIndex operands will be replaced by immediates, so they are
1093       // allowed.
1094       if (!MI->getOperand(i).isImm() && !MI->getOperand(i).isFPImm() &&
1095           !MI->getOperand(i).isFI()) {
1096         ErrInfo = "Expected immediate, but got non-immediate";
1097         return false;
1098       }
1099       // Fall-through
1100     default:
1101       continue;
1102     }
1103
1104     if (!MI->getOperand(i).isReg())
1105       continue;
1106
1107     int RegClass = Desc.OpInfo[i].RegClass;
1108     if (RegClass != -1) {
1109       unsigned Reg = MI->getOperand(i).getReg();
1110       if (TargetRegisterInfo::isVirtualRegister(Reg))
1111         continue;
1112
1113       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
1114       if (!RC->contains(Reg)) {
1115         ErrInfo = "Operand has incorrect register class.";
1116         return false;
1117       }
1118     }
1119   }
1120
1121
1122   // Verify VOP*
1123   if (isVOP1(Opcode) || isVOP2(Opcode) || isVOP3(Opcode) || isVOPC(Opcode)) {
1124     // Only look at the true operands. Only a real operand can use the constant
1125     // bus, and we don't want to check pseudo-operands like the source modifier
1126     // flags.
1127     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
1128
1129     unsigned ConstantBusCount = 0;
1130     unsigned SGPRUsed = AMDGPU::NoRegister;
1131     for (int OpIdx : OpIndices) {
1132       if (OpIdx == -1)
1133         break;
1134
1135       const MachineOperand &MO = MI->getOperand(OpIdx);
1136       if (usesConstantBus(MRI, MO)) {
1137         if (MO.isReg()) {
1138           if (MO.getReg() != SGPRUsed)
1139             ++ConstantBusCount;
1140           SGPRUsed = MO.getReg();
1141         } else {
1142           ++ConstantBusCount;
1143         }
1144       }
1145     }
1146     if (ConstantBusCount > 1) {
1147       ErrInfo = "VOP* instruction uses the constant bus more than once";
1148       return false;
1149     }
1150   }
1151
1152   // Verify SRC1 for VOP2 and VOPC
1153   if (Src1Idx != -1 && (isVOP2(Opcode) || isVOPC(Opcode))) {
1154     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
1155     if (Src1.isImm() || Src1.isFPImm()) {
1156       ErrInfo = "VOP[2C] src1 cannot be an immediate.";
1157       return false;
1158     }
1159   }
1160
1161   // Verify VOP3
1162   if (isVOP3(Opcode)) {
1163     if (Src0Idx != -1 && isLiteralConstant(MI->getOperand(Src0Idx))) {
1164       ErrInfo = "VOP3 src0 cannot be a literal constant.";
1165       return false;
1166     }
1167     if (Src1Idx != -1 && isLiteralConstant(MI->getOperand(Src1Idx))) {
1168       ErrInfo = "VOP3 src1 cannot be a literal constant.";
1169       return false;
1170     }
1171     if (Src2Idx != -1 && isLiteralConstant(MI->getOperand(Src2Idx))) {
1172       ErrInfo = "VOP3 src2 cannot be a literal constant.";
1173       return false;
1174     }
1175   }
1176
1177   // Verify misc. restrictions on specific instructions.
1178   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
1179       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
1180     const MachineOperand &Src0 = MI->getOperand(Src0Idx);
1181     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
1182     const MachineOperand &Src2 = MI->getOperand(Src2Idx);
1183     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
1184       if (!compareMachineOp(Src0, Src1) &&
1185           !compareMachineOp(Src0, Src2)) {
1186         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
1187         return false;
1188       }
1189     }
1190   }
1191
1192   return true;
1193 }
1194
1195 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
1196   switch (MI.getOpcode()) {
1197   default: return AMDGPU::INSTRUCTION_LIST_END;
1198   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
1199   case AMDGPU::COPY: return AMDGPU::COPY;
1200   case AMDGPU::PHI: return AMDGPU::PHI;
1201   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
1202   case AMDGPU::S_MOV_B32:
1203     return MI.getOperand(1).isReg() ?
1204            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
1205   case AMDGPU::S_ADD_I32:
1206   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
1207   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
1208   case AMDGPU::S_SUB_I32:
1209   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
1210   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
1211   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
1212   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e32;
1213   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e32;
1214   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e32;
1215   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e32;
1216   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e32;
1217   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e32;
1218   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e32;
1219   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
1220   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
1221   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
1222   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
1223   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
1224   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
1225   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
1226   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
1227   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
1228   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
1229   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
1230   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
1231   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
1232   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
1233   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
1234   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
1235   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
1236   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
1237   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
1238   case AMDGPU::S_LOAD_DWORD_IMM:
1239   case AMDGPU::S_LOAD_DWORD_SGPR: return AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1240   case AMDGPU::S_LOAD_DWORDX2_IMM:
1241   case AMDGPU::S_LOAD_DWORDX2_SGPR: return AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1242   case AMDGPU::S_LOAD_DWORDX4_IMM:
1243   case AMDGPU::S_LOAD_DWORDX4_SGPR: return AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1244   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e32;
1245   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
1246   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
1247   }
1248 }
1249
1250 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
1251   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
1252 }
1253
1254 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
1255                                                       unsigned OpNo) const {
1256   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1257   const MCInstrDesc &Desc = get(MI.getOpcode());
1258   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
1259       Desc.OpInfo[OpNo].RegClass == -1) {
1260     unsigned Reg = MI.getOperand(OpNo).getReg();
1261
1262     if (TargetRegisterInfo::isVirtualRegister(Reg))
1263       return MRI.getRegClass(Reg);
1264     return RI.getRegClass(Reg);
1265   }
1266
1267   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
1268   return RI.getRegClass(RCID);
1269 }
1270
1271 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
1272   switch (MI.getOpcode()) {
1273   case AMDGPU::COPY:
1274   case AMDGPU::REG_SEQUENCE:
1275   case AMDGPU::PHI:
1276   case AMDGPU::INSERT_SUBREG:
1277     return RI.hasVGPRs(getOpRegClass(MI, 0));
1278   default:
1279     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
1280   }
1281 }
1282
1283 void SIInstrInfo::legalizeOpWithMove(MachineInstr *MI, unsigned OpIdx) const {
1284   MachineBasicBlock::iterator I = MI;
1285   MachineBasicBlock *MBB = MI->getParent();
1286   MachineOperand &MO = MI->getOperand(OpIdx);
1287   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1288   unsigned RCID = get(MI->getOpcode()).OpInfo[OpIdx].RegClass;
1289   const TargetRegisterClass *RC = RI.getRegClass(RCID);
1290   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1291   if (MO.isReg())
1292     Opcode = AMDGPU::COPY;
1293   else if (RI.isSGPRClass(RC))
1294     Opcode = AMDGPU::S_MOV_B32;
1295
1296
1297   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
1298   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
1299     VRC = &AMDGPU::VReg_64RegClass;
1300   else
1301     VRC = &AMDGPU::VReg_32RegClass;
1302
1303   unsigned Reg = MRI.createVirtualRegister(VRC);
1304   DebugLoc DL = MBB->findDebugLoc(I);
1305   BuildMI(*MI->getParent(), I, DL, get(Opcode), Reg)
1306     .addOperand(MO);
1307   MO.ChangeToRegister(Reg, false);
1308 }
1309
1310 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
1311                                          MachineRegisterInfo &MRI,
1312                                          MachineOperand &SuperReg,
1313                                          const TargetRegisterClass *SuperRC,
1314                                          unsigned SubIdx,
1315                                          const TargetRegisterClass *SubRC)
1316                                          const {
1317   assert(SuperReg.isReg());
1318
1319   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
1320   unsigned SubReg = MRI.createVirtualRegister(SubRC);
1321
1322   // Just in case the super register is itself a sub-register, copy it to a new
1323   // value so we don't need to worry about merging its subreg index with the
1324   // SubIdx passed to this function. The register coalescer should be able to
1325   // eliminate this extra copy.
1326   MachineBasicBlock *MBB = MI->getParent();
1327   DebugLoc DL = MI->getDebugLoc();
1328
1329   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
1330     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
1331
1332   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1333     .addReg(NewSuperReg, 0, SubIdx);
1334
1335   return SubReg;
1336 }
1337
1338 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
1339   MachineBasicBlock::iterator MII,
1340   MachineRegisterInfo &MRI,
1341   MachineOperand &Op,
1342   const TargetRegisterClass *SuperRC,
1343   unsigned SubIdx,
1344   const TargetRegisterClass *SubRC) const {
1345   if (Op.isImm()) {
1346     // XXX - Is there a better way to do this?
1347     if (SubIdx == AMDGPU::sub0)
1348       return MachineOperand::CreateImm(Op.getImm() & 0xFFFFFFFF);
1349     if (SubIdx == AMDGPU::sub1)
1350       return MachineOperand::CreateImm(Op.getImm() >> 32);
1351
1352     llvm_unreachable("Unhandled register index for immediate");
1353   }
1354
1355   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
1356                                        SubIdx, SubRC);
1357   return MachineOperand::CreateReg(SubReg, false);
1358 }
1359
1360 unsigned SIInstrInfo::split64BitImm(SmallVectorImpl<MachineInstr *> &Worklist,
1361                                     MachineBasicBlock::iterator MI,
1362                                     MachineRegisterInfo &MRI,
1363                                     const TargetRegisterClass *RC,
1364                                     const MachineOperand &Op) const {
1365   MachineBasicBlock *MBB = MI->getParent();
1366   DebugLoc DL = MI->getDebugLoc();
1367   unsigned LoDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1368   unsigned HiDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1369   unsigned Dst = MRI.createVirtualRegister(RC);
1370
1371   MachineInstr *Lo = BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32),
1372                              LoDst)
1373     .addImm(Op.getImm() & 0xFFFFFFFF);
1374   MachineInstr *Hi = BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32),
1375                              HiDst)
1376     .addImm(Op.getImm() >> 32);
1377
1378   BuildMI(*MBB, MI, DL, get(TargetOpcode::REG_SEQUENCE), Dst)
1379     .addReg(LoDst)
1380     .addImm(AMDGPU::sub0)
1381     .addReg(HiDst)
1382     .addImm(AMDGPU::sub1);
1383
1384   Worklist.push_back(Lo);
1385   Worklist.push_back(Hi);
1386
1387   return Dst;
1388 }
1389
1390 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
1391 void SIInstrInfo::swapOperands(MachineBasicBlock::iterator Inst) const {
1392   assert(Inst->getNumExplicitOperands() == 3);
1393   MachineOperand Op1 = Inst->getOperand(1);
1394   Inst->RemoveOperand(1);
1395   Inst->addOperand(Op1);
1396 }
1397
1398 bool SIInstrInfo::isOperandLegal(const MachineInstr *MI, unsigned OpIdx,
1399                                  const MachineOperand *MO) const {
1400   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1401   const MCInstrDesc &InstDesc = get(MI->getOpcode());
1402   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
1403   const TargetRegisterClass *DefinedRC =
1404       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
1405   if (!MO)
1406     MO = &MI->getOperand(OpIdx);
1407
1408   if (isVALU(InstDesc.Opcode) && usesConstantBus(MRI, *MO)) {
1409     unsigned SGPRUsed =
1410         MO->isReg() ? MO->getReg() : (unsigned)AMDGPU::NoRegister;
1411     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1412       if (i == OpIdx)
1413         continue;
1414       if (usesConstantBus(MRI, MI->getOperand(i)) &&
1415           MI->getOperand(i).isReg() && MI->getOperand(i).getReg() != SGPRUsed) {
1416         return false;
1417       }
1418     }
1419   }
1420
1421   if (MO->isReg()) {
1422     assert(DefinedRC);
1423     const TargetRegisterClass *RC = MRI.getRegClass(MO->getReg());
1424
1425     // In order to be legal, the common sub-class must be equal to the
1426     // class of the current operand.  For example:
1427     //
1428     // v_mov_b32 s0 ; Operand defined as vsrc_32
1429     //              ; RI.getCommonSubClass(s0,vsrc_32) = sgpr ; LEGAL
1430     //
1431     // s_sendmsg 0, s0 ; Operand defined as m0reg
1432     //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
1433     return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
1434   }
1435
1436
1437   // Handle non-register types that are treated like immediates.
1438   assert(MO->isImm() || MO->isFPImm() || MO->isTargetIndex() || MO->isFI());
1439
1440   if (!DefinedRC) {
1441     // This operand expects an immediate.
1442     return true;
1443   }
1444
1445   return isImmOperandLegal(MI, OpIdx, *MO);
1446 }
1447
1448 void SIInstrInfo::legalizeOperands(MachineInstr *MI) const {
1449   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1450
1451   int Src0Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1452                                            AMDGPU::OpName::src0);
1453   int Src1Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1454                                            AMDGPU::OpName::src1);
1455   int Src2Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1456                                            AMDGPU::OpName::src2);
1457
1458   // Legalize VOP2
1459   if (isVOP2(MI->getOpcode()) && Src1Idx != -1) {
1460     // Legalize src0
1461     if (!isOperandLegal(MI, Src0Idx))
1462       legalizeOpWithMove(MI, Src0Idx);
1463
1464     // Legalize src1
1465     if (isOperandLegal(MI, Src1Idx))
1466       return;
1467
1468     // Usually src0 of VOP2 instructions allow more types of inputs
1469     // than src1, so try to commute the instruction to decrease our
1470     // chances of having to insert a MOV instruction to legalize src1.
1471     if (MI->isCommutable()) {
1472       if (commuteInstruction(MI))
1473         // If we are successful in commuting, then we know MI is legal, so
1474         // we are done.
1475         return;
1476     }
1477
1478     legalizeOpWithMove(MI, Src1Idx);
1479     return;
1480   }
1481
1482   // XXX - Do any VOP3 instructions read VCC?
1483   // Legalize VOP3
1484   if (isVOP3(MI->getOpcode())) {
1485     int VOP3Idx[3] = { Src0Idx, Src1Idx, Src2Idx };
1486
1487     // Find the one SGPR operand we are allowed to use.
1488     unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
1489
1490     for (unsigned i = 0; i < 3; ++i) {
1491       int Idx = VOP3Idx[i];
1492       if (Idx == -1)
1493         break;
1494       MachineOperand &MO = MI->getOperand(Idx);
1495
1496       if (MO.isReg()) {
1497         if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
1498           continue; // VGPRs are legal
1499
1500         assert(MO.getReg() != AMDGPU::SCC && "SCC operand to VOP3 instruction");
1501
1502         if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
1503           SGPRReg = MO.getReg();
1504           // We can use one SGPR in each VOP3 instruction.
1505           continue;
1506         }
1507       } else if (!isLiteralConstant(MO)) {
1508         // If it is not a register and not a literal constant, then it must be
1509         // an inline constant which is always legal.
1510         continue;
1511       }
1512       // If we make it this far, then the operand is not legal and we must
1513       // legalize it.
1514       legalizeOpWithMove(MI, Idx);
1515     }
1516   }
1517
1518   // Legalize REG_SEQUENCE and PHI
1519   // The register class of the operands much be the same type as the register
1520   // class of the output.
1521   if (MI->getOpcode() == AMDGPU::REG_SEQUENCE ||
1522       MI->getOpcode() == AMDGPU::PHI) {
1523     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
1524     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
1525       if (!MI->getOperand(i).isReg() ||
1526           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
1527         continue;
1528       const TargetRegisterClass *OpRC =
1529               MRI.getRegClass(MI->getOperand(i).getReg());
1530       if (RI.hasVGPRs(OpRC)) {
1531         VRC = OpRC;
1532       } else {
1533         SRC = OpRC;
1534       }
1535     }
1536
1537     // If any of the operands are VGPR registers, then they all most be
1538     // otherwise we will create illegal VGPR->SGPR copies when legalizing
1539     // them.
1540     if (VRC || !RI.isSGPRClass(getOpRegClass(*MI, 0))) {
1541       if (!VRC) {
1542         assert(SRC);
1543         VRC = RI.getEquivalentVGPRClass(SRC);
1544       }
1545       RC = VRC;
1546     } else {
1547       RC = SRC;
1548     }
1549
1550     // Update all the operands so they have the same type.
1551     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
1552       if (!MI->getOperand(i).isReg() ||
1553           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
1554         continue;
1555       unsigned DstReg = MRI.createVirtualRegister(RC);
1556       MachineBasicBlock *InsertBB;
1557       MachineBasicBlock::iterator Insert;
1558       if (MI->getOpcode() == AMDGPU::REG_SEQUENCE) {
1559         InsertBB = MI->getParent();
1560         Insert = MI;
1561       } else {
1562         // MI is a PHI instruction.
1563         InsertBB = MI->getOperand(i + 1).getMBB();
1564         Insert = InsertBB->getFirstTerminator();
1565       }
1566       BuildMI(*InsertBB, Insert, MI->getDebugLoc(),
1567               get(AMDGPU::COPY), DstReg)
1568               .addOperand(MI->getOperand(i));
1569       MI->getOperand(i).setReg(DstReg);
1570     }
1571   }
1572
1573   // Legalize INSERT_SUBREG
1574   // src0 must have the same register class as dst
1575   if (MI->getOpcode() == AMDGPU::INSERT_SUBREG) {
1576     unsigned Dst = MI->getOperand(0).getReg();
1577     unsigned Src0 = MI->getOperand(1).getReg();
1578     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
1579     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
1580     if (DstRC != Src0RC) {
1581       MachineBasicBlock &MBB = *MI->getParent();
1582       unsigned NewSrc0 = MRI.createVirtualRegister(DstRC);
1583       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::COPY), NewSrc0)
1584               .addReg(Src0);
1585       MI->getOperand(1).setReg(NewSrc0);
1586     }
1587     return;
1588   }
1589
1590   // Legalize MUBUF* instructions
1591   // FIXME: If we start using the non-addr64 instructions for compute, we
1592   // may need to legalize them here.
1593   int SRsrcIdx =
1594       AMDGPU::getNamedOperandIdx(MI->getOpcode(), AMDGPU::OpName::srsrc);
1595   if (SRsrcIdx != -1) {
1596     // We have an MUBUF instruction
1597     MachineOperand *SRsrc = &MI->getOperand(SRsrcIdx);
1598     unsigned SRsrcRC = get(MI->getOpcode()).OpInfo[SRsrcIdx].RegClass;
1599     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
1600                                              RI.getRegClass(SRsrcRC))) {
1601       // The operands are legal.
1602       // FIXME: We may need to legalize operands besided srsrc.
1603       return;
1604     }
1605
1606     MachineBasicBlock &MBB = *MI->getParent();
1607     // Extract the the ptr from the resource descriptor.
1608
1609     // SRsrcPtrLo = srsrc:sub0
1610     unsigned SRsrcPtrLo = buildExtractSubReg(MI, MRI, *SRsrc,
1611         &AMDGPU::VReg_128RegClass, AMDGPU::sub0, &AMDGPU::VReg_32RegClass);
1612
1613     // SRsrcPtrHi = srsrc:sub1
1614     unsigned SRsrcPtrHi = buildExtractSubReg(MI, MRI, *SRsrc,
1615         &AMDGPU::VReg_128RegClass, AMDGPU::sub1, &AMDGPU::VReg_32RegClass);
1616
1617     // Create an empty resource descriptor
1618     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1619     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1620     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1621     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
1622     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
1623
1624     // Zero64 = 0
1625     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B64),
1626             Zero64)
1627             .addImm(0);
1628
1629     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
1630     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1631             SRsrcFormatLo)
1632             .addImm(RsrcDataFormat & 0xFFFFFFFF);
1633
1634     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
1635     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1636             SRsrcFormatHi)
1637             .addImm(RsrcDataFormat >> 32);
1638
1639     // NewSRsrc = {Zero64, SRsrcFormat}
1640     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
1641             NewSRsrc)
1642             .addReg(Zero64)
1643             .addImm(AMDGPU::sub0_sub1)
1644             .addReg(SRsrcFormatLo)
1645             .addImm(AMDGPU::sub2)
1646             .addReg(SRsrcFormatHi)
1647             .addImm(AMDGPU::sub3);
1648
1649     MachineOperand *VAddr = getNamedOperand(*MI, AMDGPU::OpName::vaddr);
1650     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
1651     unsigned NewVAddrLo;
1652     unsigned NewVAddrHi;
1653     if (VAddr) {
1654       // This is already an ADDR64 instruction so we need to add the pointer
1655       // extracted from the resource descriptor to the current value of VAddr.
1656       NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
1657       NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
1658
1659       // NewVaddrLo = SRsrcPtrLo + VAddr:sub0
1660       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADD_I32_e32),
1661               NewVAddrLo)
1662               .addReg(SRsrcPtrLo)
1663               .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
1664               .addReg(AMDGPU::VCC, RegState::ImplicitDefine);
1665
1666       // NewVaddrHi = SRsrcPtrHi + VAddr:sub1
1667       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADDC_U32_e32),
1668               NewVAddrHi)
1669               .addReg(SRsrcPtrHi)
1670               .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
1671               .addReg(AMDGPU::VCC, RegState::ImplicitDefine)
1672               .addReg(AMDGPU::VCC, RegState::Implicit);
1673
1674     } else {
1675       // This instructions is the _OFFSET variant, so we need to convert it to
1676       // ADDR64.
1677       MachineOperand *VData = getNamedOperand(*MI, AMDGPU::OpName::vdata);
1678       MachineOperand *Offset = getNamedOperand(*MI, AMDGPU::OpName::offset);
1679       MachineOperand *SOffset = getNamedOperand(*MI, AMDGPU::OpName::soffset);
1680       assert(SOffset->isImm() && SOffset->getImm() == 0 && "Legalizing MUBUF "
1681              "with non-zero soffset is not implemented");
1682       (void)SOffset;
1683
1684       // Create the new instruction.
1685       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI->getOpcode());
1686       MachineInstr *Addr64 =
1687           BuildMI(MBB, MI, MI->getDebugLoc(), get(Addr64Opcode))
1688                   .addOperand(*VData)
1689                   .addOperand(*SRsrc)
1690                   .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
1691                                               // This will be replaced later
1692                                               // with the new value of vaddr.
1693                   .addOperand(*Offset);
1694
1695       MI->removeFromParent();
1696       MI = Addr64;
1697
1698       NewVAddrLo = SRsrcPtrLo;
1699       NewVAddrHi = SRsrcPtrHi;
1700       VAddr = getNamedOperand(*MI, AMDGPU::OpName::vaddr);
1701       SRsrc = getNamedOperand(*MI, AMDGPU::OpName::srsrc);
1702     }
1703
1704     // NewVaddr = {NewVaddrHi, NewVaddrLo}
1705     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
1706             NewVAddr)
1707             .addReg(NewVAddrLo)
1708             .addImm(AMDGPU::sub0)
1709             .addReg(NewVAddrHi)
1710             .addImm(AMDGPU::sub1);
1711
1712
1713     // Update the instruction to use NewVaddr
1714     VAddr->setReg(NewVAddr);
1715     // Update the instruction to use NewSRsrc
1716     SRsrc->setReg(NewSRsrc);
1717   }
1718 }
1719
1720 void SIInstrInfo::splitSMRD(MachineInstr *MI,
1721                             const TargetRegisterClass *HalfRC,
1722                             unsigned HalfImmOp, unsigned HalfSGPROp,
1723                             MachineInstr *&Lo, MachineInstr *&Hi) const {
1724
1725   DebugLoc DL = MI->getDebugLoc();
1726   MachineBasicBlock *MBB = MI->getParent();
1727   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1728   unsigned RegLo = MRI.createVirtualRegister(HalfRC);
1729   unsigned RegHi = MRI.createVirtualRegister(HalfRC);
1730   unsigned HalfSize = HalfRC->getSize();
1731   const MachineOperand *OffOp =
1732       getNamedOperand(*MI, AMDGPU::OpName::offset);
1733   const MachineOperand *SBase = getNamedOperand(*MI, AMDGPU::OpName::sbase);
1734
1735   // The SMRD has an 8-bit offset in dwords on SI and a 20-bit offset in bytes
1736   // on VI.
1737   if (OffOp) {
1738     bool isVI = RI.ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS;
1739     unsigned OffScale = isVI ? 1 : 4;
1740     // Handle the _IMM variant
1741     unsigned LoOffset = OffOp->getImm() * OffScale;
1742     unsigned HiOffset = LoOffset + HalfSize;
1743     Lo = BuildMI(*MBB, MI, DL, get(HalfImmOp), RegLo)
1744                   .addOperand(*SBase)
1745                   .addImm(LoOffset / OffScale);
1746
1747     if (!isUInt<20>(HiOffset) || (!isVI && !isUInt<8>(HiOffset / OffScale))) {
1748       unsigned OffsetSGPR =
1749           MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
1750       BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32), OffsetSGPR)
1751               .addImm(HiOffset); // The offset in register is in bytes.
1752       Hi = BuildMI(*MBB, MI, DL, get(HalfSGPROp), RegHi)
1753                     .addOperand(*SBase)
1754                     .addReg(OffsetSGPR);
1755     } else {
1756       Hi = BuildMI(*MBB, MI, DL, get(HalfImmOp), RegHi)
1757                      .addOperand(*SBase)
1758                      .addImm(HiOffset / OffScale);
1759     }
1760   } else {
1761     // Handle the _SGPR variant
1762     MachineOperand *SOff = getNamedOperand(*MI, AMDGPU::OpName::soff);
1763     Lo = BuildMI(*MBB, MI, DL, get(HalfSGPROp), RegLo)
1764                   .addOperand(*SBase)
1765                   .addOperand(*SOff);
1766     unsigned OffsetSGPR = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
1767     BuildMI(*MBB, MI, DL, get(AMDGPU::S_ADD_I32), OffsetSGPR)
1768             .addOperand(*SOff)
1769             .addImm(HalfSize);
1770     Hi = BuildMI(*MBB, MI, DL, get(HalfSGPROp))
1771                   .addOperand(*SBase)
1772                   .addReg(OffsetSGPR);
1773   }
1774
1775   unsigned SubLo, SubHi;
1776   switch (HalfSize) {
1777     case 4:
1778       SubLo = AMDGPU::sub0;
1779       SubHi = AMDGPU::sub1;
1780       break;
1781     case 8:
1782       SubLo = AMDGPU::sub0_sub1;
1783       SubHi = AMDGPU::sub2_sub3;
1784       break;
1785     case 16:
1786       SubLo = AMDGPU::sub0_sub1_sub2_sub3;
1787       SubHi = AMDGPU::sub4_sub5_sub6_sub7;
1788       break;
1789     case 32:
1790       SubLo = AMDGPU::sub0_sub1_sub2_sub3_sub4_sub5_sub6_sub7;
1791       SubHi = AMDGPU::sub8_sub9_sub10_sub11_sub12_sub13_sub14_sub15;
1792       break;
1793     default:
1794       llvm_unreachable("Unhandled HalfSize");
1795   }
1796
1797   BuildMI(*MBB, MI, DL, get(AMDGPU::REG_SEQUENCE))
1798           .addOperand(MI->getOperand(0))
1799           .addReg(RegLo)
1800           .addImm(SubLo)
1801           .addReg(RegHi)
1802           .addImm(SubHi);
1803 }
1804
1805 void SIInstrInfo::moveSMRDToVALU(MachineInstr *MI, MachineRegisterInfo &MRI) const {
1806   MachineBasicBlock *MBB = MI->getParent();
1807   switch (MI->getOpcode()) {
1808     case AMDGPU::S_LOAD_DWORD_IMM:
1809     case AMDGPU::S_LOAD_DWORD_SGPR:
1810     case AMDGPU::S_LOAD_DWORDX2_IMM:
1811     case AMDGPU::S_LOAD_DWORDX2_SGPR:
1812     case AMDGPU::S_LOAD_DWORDX4_IMM:
1813     case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1814       unsigned NewOpcode = getVALUOp(*MI);
1815       unsigned RegOffset;
1816       unsigned ImmOffset;
1817
1818       if (MI->getOperand(2).isReg()) {
1819         RegOffset = MI->getOperand(2).getReg();
1820         ImmOffset = 0;
1821       } else {
1822         assert(MI->getOperand(2).isImm());
1823         // SMRD instructions take a dword offsets on SI and byte offset on VI
1824         // and MUBUF instructions always take a byte offset.
1825         ImmOffset = MI->getOperand(2).getImm();
1826         if (RI.ST.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
1827           ImmOffset <<= 2;
1828         RegOffset = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1829
1830         if (isUInt<12>(ImmOffset)) {
1831           BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1832                   RegOffset)
1833                   .addImm(0);
1834         } else {
1835           BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1836                   RegOffset)
1837                   .addImm(ImmOffset);
1838           ImmOffset = 0;
1839         }
1840       }
1841
1842       unsigned SRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
1843       unsigned DWord0 = RegOffset;
1844       unsigned DWord1 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1845       unsigned DWord2 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1846       unsigned DWord3 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1847       uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
1848
1849       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord1)
1850               .addImm(0);
1851       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord2)
1852               .addImm(RsrcDataFormat & 0xFFFFFFFF);
1853       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord3)
1854               .addImm(RsrcDataFormat >> 32);
1855       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE), SRsrc)
1856               .addReg(DWord0)
1857               .addImm(AMDGPU::sub0)
1858               .addReg(DWord1)
1859               .addImm(AMDGPU::sub1)
1860               .addReg(DWord2)
1861               .addImm(AMDGPU::sub2)
1862               .addReg(DWord3)
1863               .addImm(AMDGPU::sub3);
1864       MI->setDesc(get(NewOpcode));
1865       if (MI->getOperand(2).isReg()) {
1866         MI->getOperand(2).setReg(MI->getOperand(1).getReg());
1867       } else {
1868         MI->getOperand(2).ChangeToRegister(MI->getOperand(1).getReg(), false);
1869       }
1870       MI->getOperand(1).setReg(SRsrc);
1871       MI->addOperand(*MBB->getParent(), MachineOperand::CreateImm(ImmOffset));
1872
1873       const TargetRegisterClass *NewDstRC =
1874           RI.getRegClass(get(NewOpcode).OpInfo[0].RegClass);
1875
1876       unsigned DstReg = MI->getOperand(0).getReg();
1877       unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
1878       MRI.replaceRegWith(DstReg, NewDstReg);
1879       break;
1880     }
1881     case AMDGPU::S_LOAD_DWORDX8_IMM:
1882     case AMDGPU::S_LOAD_DWORDX8_SGPR: {
1883       MachineInstr *Lo, *Hi;
1884       splitSMRD(MI, &AMDGPU::SReg_128RegClass, AMDGPU::S_LOAD_DWORDX4_IMM,
1885                 AMDGPU::S_LOAD_DWORDX4_SGPR, Lo, Hi);
1886       MI->eraseFromParent();
1887       moveSMRDToVALU(Lo, MRI);
1888       moveSMRDToVALU(Hi, MRI);
1889       break;
1890     }
1891
1892     case AMDGPU::S_LOAD_DWORDX16_IMM:
1893     case AMDGPU::S_LOAD_DWORDX16_SGPR: {
1894       MachineInstr *Lo, *Hi;
1895       splitSMRD(MI, &AMDGPU::SReg_256RegClass, AMDGPU::S_LOAD_DWORDX8_IMM,
1896                 AMDGPU::S_LOAD_DWORDX8_SGPR, Lo, Hi);
1897       MI->eraseFromParent();
1898       moveSMRDToVALU(Lo, MRI);
1899       moveSMRDToVALU(Hi, MRI);
1900       break;
1901     }
1902   }
1903 }
1904
1905 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
1906   SmallVector<MachineInstr *, 128> Worklist;
1907   Worklist.push_back(&TopInst);
1908
1909   while (!Worklist.empty()) {
1910     MachineInstr *Inst = Worklist.pop_back_val();
1911     MachineBasicBlock *MBB = Inst->getParent();
1912     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1913
1914     unsigned Opcode = Inst->getOpcode();
1915     unsigned NewOpcode = getVALUOp(*Inst);
1916
1917     // Handle some special cases
1918     switch (Opcode) {
1919     default:
1920       if (isSMRD(Inst->getOpcode())) {
1921         moveSMRDToVALU(Inst, MRI);
1922       }
1923       break;
1924     case AMDGPU::S_MOV_B64: {
1925       DebugLoc DL = Inst->getDebugLoc();
1926
1927       // If the source operand is a register we can replace this with a
1928       // copy.
1929       if (Inst->getOperand(1).isReg()) {
1930         MachineInstr *Copy = BuildMI(*MBB, Inst, DL, get(TargetOpcode::COPY))
1931           .addOperand(Inst->getOperand(0))
1932           .addOperand(Inst->getOperand(1));
1933         Worklist.push_back(Copy);
1934       } else {
1935         // Otherwise, we need to split this into two movs, because there is
1936         // no 64-bit VALU move instruction.
1937         unsigned Reg = Inst->getOperand(0).getReg();
1938         unsigned Dst = split64BitImm(Worklist,
1939                                      Inst,
1940                                      MRI,
1941                                      MRI.getRegClass(Reg),
1942                                      Inst->getOperand(1));
1943         MRI.replaceRegWith(Reg, Dst);
1944       }
1945       Inst->eraseFromParent();
1946       continue;
1947     }
1948     case AMDGPU::S_AND_B64:
1949       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32);
1950       Inst->eraseFromParent();
1951       continue;
1952
1953     case AMDGPU::S_OR_B64:
1954       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32);
1955       Inst->eraseFromParent();
1956       continue;
1957
1958     case AMDGPU::S_XOR_B64:
1959       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32);
1960       Inst->eraseFromParent();
1961       continue;
1962
1963     case AMDGPU::S_NOT_B64:
1964       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
1965       Inst->eraseFromParent();
1966       continue;
1967
1968     case AMDGPU::S_BCNT1_I32_B64:
1969       splitScalar64BitBCNT(Worklist, Inst);
1970       Inst->eraseFromParent();
1971       continue;
1972
1973     case AMDGPU::S_BFE_I64: {
1974       splitScalar64BitBFE(Worklist, Inst);
1975       Inst->eraseFromParent();
1976       continue;
1977     }
1978
1979     case AMDGPU::S_LSHL_B32:
1980       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1981         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
1982         swapOperands(Inst);
1983       }
1984       break;
1985     case AMDGPU::S_ASHR_I32:
1986       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1987         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
1988         swapOperands(Inst);
1989       }
1990       break;
1991     case AMDGPU::S_LSHR_B32:
1992       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1993         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
1994         swapOperands(Inst);
1995       }
1996       break;
1997
1998     case AMDGPU::S_BFE_U64:
1999     case AMDGPU::S_BFM_B64:
2000       llvm_unreachable("Moving this op to VALU not implemented");
2001     }
2002
2003     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
2004       // We cannot move this instruction to the VALU, so we should try to
2005       // legalize its operands instead.
2006       legalizeOperands(Inst);
2007       continue;
2008     }
2009
2010     // Use the new VALU Opcode.
2011     const MCInstrDesc &NewDesc = get(NewOpcode);
2012     Inst->setDesc(NewDesc);
2013
2014     // Remove any references to SCC. Vector instructions can't read from it, and
2015     // We're just about to add the implicit use / defs of VCC, and we don't want
2016     // both.
2017     for (unsigned i = Inst->getNumOperands() - 1; i > 0; --i) {
2018       MachineOperand &Op = Inst->getOperand(i);
2019       if (Op.isReg() && Op.getReg() == AMDGPU::SCC)
2020         Inst->RemoveOperand(i);
2021     }
2022
2023     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
2024       // We are converting these to a BFE, so we need to add the missing
2025       // operands for the size and offset.
2026       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
2027       Inst->addOperand(MachineOperand::CreateImm(0));
2028       Inst->addOperand(MachineOperand::CreateImm(Size));
2029
2030     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
2031       // The VALU version adds the second operand to the result, so insert an
2032       // extra 0 operand.
2033       Inst->addOperand(MachineOperand::CreateImm(0));
2034     }
2035
2036     addDescImplicitUseDef(NewDesc, Inst);
2037
2038     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
2039       const MachineOperand &OffsetWidthOp = Inst->getOperand(2);
2040       // If we need to move this to VGPRs, we need to unpack the second operand
2041       // back into the 2 separate ones for bit offset and width.
2042       assert(OffsetWidthOp.isImm() &&
2043              "Scalar BFE is only implemented for constant width and offset");
2044       uint32_t Imm = OffsetWidthOp.getImm();
2045
2046       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2047       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2048       Inst->RemoveOperand(2); // Remove old immediate.
2049       Inst->addOperand(MachineOperand::CreateImm(Offset));
2050       Inst->addOperand(MachineOperand::CreateImm(BitWidth));
2051     }
2052
2053     // Update the destination register class.
2054
2055     const TargetRegisterClass *NewDstRC = getOpRegClass(*Inst, 0);
2056
2057     switch (Opcode) {
2058       // For target instructions, getOpRegClass just returns the virtual
2059       // register class associated with the operand, so we need to find an
2060       // equivalent VGPR register class in order to move the instruction to the
2061       // VALU.
2062     case AMDGPU::COPY:
2063     case AMDGPU::PHI:
2064     case AMDGPU::REG_SEQUENCE:
2065     case AMDGPU::INSERT_SUBREG:
2066       if (RI.hasVGPRs(NewDstRC))
2067         continue;
2068       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
2069       if (!NewDstRC)
2070         continue;
2071       break;
2072     default:
2073       break;
2074     }
2075
2076     unsigned DstReg = Inst->getOperand(0).getReg();
2077     unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
2078     MRI.replaceRegWith(DstReg, NewDstReg);
2079
2080     // Legalize the operands
2081     legalizeOperands(Inst);
2082
2083     for (MachineRegisterInfo::use_iterator I = MRI.use_begin(NewDstReg),
2084            E = MRI.use_end(); I != E; ++I) {
2085       MachineInstr &UseMI = *I->getParent();
2086       if (!canReadVGPR(UseMI, I.getOperandNo())) {
2087         Worklist.push_back(&UseMI);
2088       }
2089     }
2090   }
2091 }
2092
2093 //===----------------------------------------------------------------------===//
2094 // Indirect addressing callbacks
2095 //===----------------------------------------------------------------------===//
2096
2097 unsigned SIInstrInfo::calculateIndirectAddress(unsigned RegIndex,
2098                                                  unsigned Channel) const {
2099   assert(Channel == 0);
2100   return RegIndex;
2101 }
2102
2103 const TargetRegisterClass *SIInstrInfo::getIndirectAddrRegClass() const {
2104   return &AMDGPU::VReg_32RegClass;
2105 }
2106
2107 void SIInstrInfo::splitScalar64BitUnaryOp(
2108   SmallVectorImpl<MachineInstr *> &Worklist,
2109   MachineInstr *Inst,
2110   unsigned Opcode) const {
2111   MachineBasicBlock &MBB = *Inst->getParent();
2112   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2113
2114   MachineOperand &Dest = Inst->getOperand(0);
2115   MachineOperand &Src0 = Inst->getOperand(1);
2116   DebugLoc DL = Inst->getDebugLoc();
2117
2118   MachineBasicBlock::iterator MII = Inst;
2119
2120   const MCInstrDesc &InstDesc = get(Opcode);
2121   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2122     MRI.getRegClass(Src0.getReg()) :
2123     &AMDGPU::SGPR_32RegClass;
2124
2125   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2126
2127   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2128                                                        AMDGPU::sub0, Src0SubRC);
2129
2130   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2131   const TargetRegisterClass *DestSubRC = RI.getSubRegClass(DestRC, AMDGPU::sub0);
2132
2133   unsigned DestSub0 = MRI.createVirtualRegister(DestRC);
2134   MachineInstr *LoHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2135     .addOperand(SrcReg0Sub0);
2136
2137   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2138                                                        AMDGPU::sub1, Src0SubRC);
2139
2140   unsigned DestSub1 = MRI.createVirtualRegister(DestSubRC);
2141   MachineInstr *HiHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2142     .addOperand(SrcReg0Sub1);
2143
2144   unsigned FullDestReg = MRI.createVirtualRegister(DestRC);
2145   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2146     .addReg(DestSub0)
2147     .addImm(AMDGPU::sub0)
2148     .addReg(DestSub1)
2149     .addImm(AMDGPU::sub1);
2150
2151   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2152
2153   // Try to legalize the operands in case we need to swap the order to keep it
2154   // valid.
2155   Worklist.push_back(LoHalf);
2156   Worklist.push_back(HiHalf);
2157 }
2158
2159 void SIInstrInfo::splitScalar64BitBinaryOp(
2160   SmallVectorImpl<MachineInstr *> &Worklist,
2161   MachineInstr *Inst,
2162   unsigned Opcode) const {
2163   MachineBasicBlock &MBB = *Inst->getParent();
2164   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2165
2166   MachineOperand &Dest = Inst->getOperand(0);
2167   MachineOperand &Src0 = Inst->getOperand(1);
2168   MachineOperand &Src1 = Inst->getOperand(2);
2169   DebugLoc DL = Inst->getDebugLoc();
2170
2171   MachineBasicBlock::iterator MII = Inst;
2172
2173   const MCInstrDesc &InstDesc = get(Opcode);
2174   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2175     MRI.getRegClass(Src0.getReg()) :
2176     &AMDGPU::SGPR_32RegClass;
2177
2178   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2179   const TargetRegisterClass *Src1RC = Src1.isReg() ?
2180     MRI.getRegClass(Src1.getReg()) :
2181     &AMDGPU::SGPR_32RegClass;
2182
2183   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
2184
2185   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2186                                                        AMDGPU::sub0, Src0SubRC);
2187   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2188                                                        AMDGPU::sub0, Src1SubRC);
2189
2190   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2191   const TargetRegisterClass *DestSubRC = RI.getSubRegClass(DestRC, AMDGPU::sub0);
2192
2193   unsigned DestSub0 = MRI.createVirtualRegister(DestRC);
2194   MachineInstr *LoHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2195     .addOperand(SrcReg0Sub0)
2196     .addOperand(SrcReg1Sub0);
2197
2198   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2199                                                        AMDGPU::sub1, Src0SubRC);
2200   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2201                                                        AMDGPU::sub1, Src1SubRC);
2202
2203   unsigned DestSub1 = MRI.createVirtualRegister(DestSubRC);
2204   MachineInstr *HiHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2205     .addOperand(SrcReg0Sub1)
2206     .addOperand(SrcReg1Sub1);
2207
2208   unsigned FullDestReg = MRI.createVirtualRegister(DestRC);
2209   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2210     .addReg(DestSub0)
2211     .addImm(AMDGPU::sub0)
2212     .addReg(DestSub1)
2213     .addImm(AMDGPU::sub1);
2214
2215   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2216
2217   // Try to legalize the operands in case we need to swap the order to keep it
2218   // valid.
2219   Worklist.push_back(LoHalf);
2220   Worklist.push_back(HiHalf);
2221 }
2222
2223 void SIInstrInfo::splitScalar64BitBCNT(SmallVectorImpl<MachineInstr *> &Worklist,
2224                                        MachineInstr *Inst) const {
2225   MachineBasicBlock &MBB = *Inst->getParent();
2226   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2227
2228   MachineBasicBlock::iterator MII = Inst;
2229   DebugLoc DL = Inst->getDebugLoc();
2230
2231   MachineOperand &Dest = Inst->getOperand(0);
2232   MachineOperand &Src = Inst->getOperand(1);
2233
2234   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e32);
2235   const TargetRegisterClass *SrcRC = Src.isReg() ?
2236     MRI.getRegClass(Src.getReg()) :
2237     &AMDGPU::SGPR_32RegClass;
2238
2239   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2240   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2241
2242   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
2243
2244   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2245                                                       AMDGPU::sub0, SrcSubRC);
2246   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2247                                                       AMDGPU::sub1, SrcSubRC);
2248
2249   MachineInstr *First = BuildMI(MBB, MII, DL, InstDesc, MidReg)
2250     .addOperand(SrcRegSub0)
2251     .addImm(0);
2252
2253   MachineInstr *Second = BuildMI(MBB, MII, DL, InstDesc, ResultReg)
2254     .addOperand(SrcRegSub1)
2255     .addReg(MidReg);
2256
2257   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2258
2259   Worklist.push_back(First);
2260   Worklist.push_back(Second);
2261 }
2262
2263 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
2264                                       MachineInstr *Inst) const {
2265   MachineBasicBlock &MBB = *Inst->getParent();
2266   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2267   MachineBasicBlock::iterator MII = Inst;
2268   DebugLoc DL = Inst->getDebugLoc();
2269
2270   MachineOperand &Dest = Inst->getOperand(0);
2271   uint32_t Imm = Inst->getOperand(2).getImm();
2272   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2273   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2274
2275   (void) Offset;
2276
2277   // Only sext_inreg cases handled.
2278   assert(Inst->getOpcode() == AMDGPU::S_BFE_I64 &&
2279          BitWidth <= 32 &&
2280          Offset == 0 &&
2281          "Not implemented");
2282
2283   if (BitWidth < 32) {
2284     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2285     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2286     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2287
2288     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
2289       .addReg(Inst->getOperand(1).getReg(), 0, AMDGPU::sub0)
2290       .addImm(0)
2291       .addImm(BitWidth);
2292
2293     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
2294       .addImm(31)
2295       .addReg(MidRegLo);
2296
2297     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2298       .addReg(MidRegLo)
2299       .addImm(AMDGPU::sub0)
2300       .addReg(MidRegHi)
2301       .addImm(AMDGPU::sub1);
2302
2303     MRI.replaceRegWith(Dest.getReg(), ResultReg);
2304     return;
2305   }
2306
2307   MachineOperand &Src = Inst->getOperand(1);
2308   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2309   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2310
2311   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
2312     .addImm(31)
2313     .addReg(Src.getReg(), 0, AMDGPU::sub0);
2314
2315   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2316     .addReg(Src.getReg(), 0, AMDGPU::sub0)
2317     .addImm(AMDGPU::sub0)
2318     .addReg(TmpReg)
2319     .addImm(AMDGPU::sub1);
2320
2321   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2322 }
2323
2324 void SIInstrInfo::addDescImplicitUseDef(const MCInstrDesc &NewDesc,
2325                                         MachineInstr *Inst) const {
2326   // Add the implict and explicit register definitions.
2327   if (NewDesc.ImplicitUses) {
2328     for (unsigned i = 0; NewDesc.ImplicitUses[i]; ++i) {
2329       unsigned Reg = NewDesc.ImplicitUses[i];
2330       Inst->addOperand(MachineOperand::CreateReg(Reg, false, true));
2331     }
2332   }
2333
2334   if (NewDesc.ImplicitDefs) {
2335     for (unsigned i = 0; NewDesc.ImplicitDefs[i]; ++i) {
2336       unsigned Reg = NewDesc.ImplicitDefs[i];
2337       Inst->addOperand(MachineOperand::CreateReg(Reg, true, true));
2338     }
2339   }
2340 }
2341
2342 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr *MI,
2343                                    int OpIndices[3]) const {
2344   const MCInstrDesc &Desc = get(MI->getOpcode());
2345
2346   // Find the one SGPR operand we are allowed to use.
2347   unsigned SGPRReg = AMDGPU::NoRegister;
2348
2349   // First we need to consider the instruction's operand requirements before
2350   // legalizing. Some operands are required to be SGPRs, such as implicit uses
2351   // of VCC, but we are still bound by the constant bus requirement to only use
2352   // one.
2353   //
2354   // If the operand's class is an SGPR, we can never move it.
2355
2356   for (const MachineOperand &MO : MI->implicit_operands()) {
2357     // We only care about reads.
2358     if (MO.isDef())
2359       continue;
2360
2361     if (MO.getReg() == AMDGPU::VCC)
2362       return AMDGPU::VCC;
2363
2364     if (MO.getReg() == AMDGPU::FLAT_SCR)
2365       return AMDGPU::FLAT_SCR;
2366   }
2367
2368   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
2369   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2370
2371   for (unsigned i = 0; i < 3; ++i) {
2372     int Idx = OpIndices[i];
2373     if (Idx == -1)
2374       break;
2375
2376     const MachineOperand &MO = MI->getOperand(Idx);
2377     if (RI.isSGPRClassID(Desc.OpInfo[Idx].RegClass))
2378       SGPRReg = MO.getReg();
2379
2380     if (MO.isReg() && RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2381       UsedSGPRs[i] = MO.getReg();
2382   }
2383
2384   if (SGPRReg != AMDGPU::NoRegister)
2385     return SGPRReg;
2386
2387   // We don't have a required SGPR operand, so we have a bit more freedom in
2388   // selecting operands to move.
2389
2390   // Try to select the most used SGPR. If an SGPR is equal to one of the
2391   // others, we choose that.
2392   //
2393   // e.g.
2394   // V_FMA_F32 v0, s0, s0, s0 -> No moves
2395   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
2396
2397   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
2398     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
2399       SGPRReg = UsedSGPRs[0];
2400   }
2401
2402   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
2403     if (UsedSGPRs[1] == UsedSGPRs[2])
2404       SGPRReg = UsedSGPRs[1];
2405   }
2406
2407   return SGPRReg;
2408 }
2409
2410 MachineInstrBuilder SIInstrInfo::buildIndirectWrite(
2411                                    MachineBasicBlock *MBB,
2412                                    MachineBasicBlock::iterator I,
2413                                    unsigned ValueReg,
2414                                    unsigned Address, unsigned OffsetReg) const {
2415   const DebugLoc &DL = MBB->findDebugLoc(I);
2416   unsigned IndirectBaseReg = AMDGPU::VReg_32RegClass.getRegister(
2417                                       getIndirectIndexBegin(*MBB->getParent()));
2418
2419   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_DST_V1))
2420           .addReg(IndirectBaseReg, RegState::Define)
2421           .addOperand(I->getOperand(0))
2422           .addReg(IndirectBaseReg)
2423           .addReg(OffsetReg)
2424           .addImm(0)
2425           .addReg(ValueReg);
2426 }
2427
2428 MachineInstrBuilder SIInstrInfo::buildIndirectRead(
2429                                    MachineBasicBlock *MBB,
2430                                    MachineBasicBlock::iterator I,
2431                                    unsigned ValueReg,
2432                                    unsigned Address, unsigned OffsetReg) const {
2433   const DebugLoc &DL = MBB->findDebugLoc(I);
2434   unsigned IndirectBaseReg = AMDGPU::VReg_32RegClass.getRegister(
2435                                       getIndirectIndexBegin(*MBB->getParent()));
2436
2437   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_SRC))
2438           .addOperand(I->getOperand(0))
2439           .addOperand(I->getOperand(1))
2440           .addReg(IndirectBaseReg)
2441           .addReg(OffsetReg)
2442           .addImm(0);
2443
2444 }
2445
2446 void SIInstrInfo::reserveIndirectRegisters(BitVector &Reserved,
2447                                             const MachineFunction &MF) const {
2448   int End = getIndirectIndexEnd(MF);
2449   int Begin = getIndirectIndexBegin(MF);
2450
2451   if (End == -1)
2452     return;
2453
2454
2455   for (int Index = Begin; Index <= End; ++Index)
2456     Reserved.set(AMDGPU::VReg_32RegClass.getRegister(Index));
2457
2458   for (int Index = std::max(0, Begin - 1); Index <= End; ++Index)
2459     Reserved.set(AMDGPU::VReg_64RegClass.getRegister(Index));
2460
2461   for (int Index = std::max(0, Begin - 2); Index <= End; ++Index)
2462     Reserved.set(AMDGPU::VReg_96RegClass.getRegister(Index));
2463
2464   for (int Index = std::max(0, Begin - 3); Index <= End; ++Index)
2465     Reserved.set(AMDGPU::VReg_128RegClass.getRegister(Index));
2466
2467   for (int Index = std::max(0, Begin - 7); Index <= End; ++Index)
2468     Reserved.set(AMDGPU::VReg_256RegClass.getRegister(Index));
2469
2470   for (int Index = std::max(0, Begin - 15); Index <= End; ++Index)
2471     Reserved.set(AMDGPU::VReg_512RegClass.getRegister(Index));
2472 }
2473
2474 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
2475                                              unsigned OperandName) const {
2476   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
2477   if (Idx == -1)
2478     return nullptr;
2479
2480   return &MI.getOperand(Idx);
2481 }
2482
2483 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
2484   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
2485   if (ST.isAmdHsaOS())
2486     RsrcDataFormat |= (1ULL << 56);
2487
2488   return RsrcDataFormat;
2489 }