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