R600/SI: Don't shrink instructions whose e32 encoding doesn't exist
[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   int Op32 = AMDGPU::getVOPe32(Opcode);
1057   if (Op32 == -1)
1058     return false;
1059
1060   return pseudoToMCOpcode(Op32) != -1;
1061 }
1062
1063 bool SIInstrInfo::hasModifiers(unsigned Opcode) const {
1064   // The src0_modifier operand is present on all instructions
1065   // that have modifiers.
1066
1067   return AMDGPU::getNamedOperandIdx(Opcode,
1068                                     AMDGPU::OpName::src0_modifiers) != -1;
1069 }
1070
1071 bool SIInstrInfo::hasModifiersSet(const MachineInstr &MI,
1072                                   unsigned OpName) const {
1073   const MachineOperand *Mods = getNamedOperand(MI, OpName);
1074   return Mods && Mods->getImm();
1075 }
1076
1077 bool SIInstrInfo::usesConstantBus(const MachineRegisterInfo &MRI,
1078                                   const MachineOperand &MO) const {
1079   // Literal constants use the constant bus.
1080   if (isLiteralConstant(MO))
1081     return true;
1082
1083   if (!MO.isReg() || !MO.isUse())
1084     return false;
1085
1086   if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1087     return RI.isSGPRClass(MRI.getRegClass(MO.getReg()));
1088
1089   // FLAT_SCR is just an SGPR pair.
1090   if (!MO.isImplicit() && (MO.getReg() == AMDGPU::FLAT_SCR))
1091     return true;
1092
1093   // EXEC register uses the constant bus.
1094   if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
1095     return true;
1096
1097   // SGPRs use the constant bus
1098   if (MO.getReg() == AMDGPU::M0 || MO.getReg() == AMDGPU::VCC ||
1099       (!MO.isImplicit() &&
1100       (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
1101        AMDGPU::SGPR_64RegClass.contains(MO.getReg())))) {
1102     return true;
1103   }
1104
1105   return false;
1106 }
1107
1108 bool SIInstrInfo::verifyInstruction(const MachineInstr *MI,
1109                                     StringRef &ErrInfo) const {
1110   uint16_t Opcode = MI->getOpcode();
1111   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1112   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
1113   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
1114   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
1115
1116   // Make sure the number of operands is correct.
1117   const MCInstrDesc &Desc = get(Opcode);
1118   if (!Desc.isVariadic() &&
1119       Desc.getNumOperands() != MI->getNumExplicitOperands()) {
1120      ErrInfo = "Instruction has wrong number of operands.";
1121      return false;
1122   }
1123
1124   // Make sure the register classes are correct
1125   for (int i = 0, e = Desc.getNumOperands(); i != e; ++i) {
1126     if (MI->getOperand(i).isFPImm()) {
1127       ErrInfo = "FPImm Machine Operands are not supported. ISel should bitcast "
1128                 "all fp values to integers.";
1129       return false;
1130     }
1131
1132     switch (Desc.OpInfo[i].OperandType) {
1133     case MCOI::OPERAND_REGISTER: {
1134       if (MI->getOperand(i).isImm() &&
1135           !isImmOperandLegal(MI, i, MI->getOperand(i))) {
1136           ErrInfo = "Illegal immediate value for operand.";
1137           return false;
1138         }
1139       }
1140       break;
1141     case MCOI::OPERAND_IMMEDIATE:
1142       // Check if this operand is an immediate.
1143       // FrameIndex operands will be replaced by immediates, so they are
1144       // allowed.
1145       if (!MI->getOperand(i).isImm() && !MI->getOperand(i).isFI()) {
1146         ErrInfo = "Expected immediate, but got non-immediate";
1147         return false;
1148       }
1149       // Fall-through
1150     default:
1151       continue;
1152     }
1153
1154     if (!MI->getOperand(i).isReg())
1155       continue;
1156
1157     int RegClass = Desc.OpInfo[i].RegClass;
1158     if (RegClass != -1) {
1159       unsigned Reg = MI->getOperand(i).getReg();
1160       if (TargetRegisterInfo::isVirtualRegister(Reg))
1161         continue;
1162
1163       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
1164       if (!RC->contains(Reg)) {
1165         ErrInfo = "Operand has incorrect register class.";
1166         return false;
1167       }
1168     }
1169   }
1170
1171
1172   // Verify VOP*
1173   if (isVOP1(Opcode) || isVOP2(Opcode) || isVOP3(Opcode) || isVOPC(Opcode)) {
1174     // Only look at the true operands. Only a real operand can use the constant
1175     // bus, and we don't want to check pseudo-operands like the source modifier
1176     // flags.
1177     const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
1178
1179     unsigned ConstantBusCount = 0;
1180     unsigned SGPRUsed = AMDGPU::NoRegister;
1181     for (int OpIdx : OpIndices) {
1182       if (OpIdx == -1)
1183         break;
1184
1185       const MachineOperand &MO = MI->getOperand(OpIdx);
1186       if (usesConstantBus(MRI, MO)) {
1187         if (MO.isReg()) {
1188           if (MO.getReg() != SGPRUsed)
1189             ++ConstantBusCount;
1190           SGPRUsed = MO.getReg();
1191         } else {
1192           ++ConstantBusCount;
1193         }
1194       }
1195     }
1196     if (ConstantBusCount > 1) {
1197       ErrInfo = "VOP* instruction uses the constant bus more than once";
1198       return false;
1199     }
1200   }
1201
1202   // Verify SRC1 for VOP2 and VOPC
1203   if (Src1Idx != -1 && (isVOP2(Opcode) || isVOPC(Opcode))) {
1204     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
1205     if (Src1.isImm()) {
1206       ErrInfo = "VOP[2C] src1 cannot be an immediate.";
1207       return false;
1208     }
1209   }
1210
1211   // Verify VOP3
1212   if (isVOP3(Opcode)) {
1213     if (Src0Idx != -1 && isLiteralConstant(MI->getOperand(Src0Idx))) {
1214       ErrInfo = "VOP3 src0 cannot be a literal constant.";
1215       return false;
1216     }
1217     if (Src1Idx != -1 && isLiteralConstant(MI->getOperand(Src1Idx))) {
1218       ErrInfo = "VOP3 src1 cannot be a literal constant.";
1219       return false;
1220     }
1221     if (Src2Idx != -1 && isLiteralConstant(MI->getOperand(Src2Idx))) {
1222       ErrInfo = "VOP3 src2 cannot be a literal constant.";
1223       return false;
1224     }
1225   }
1226
1227   // Verify misc. restrictions on specific instructions.
1228   if (Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F32 ||
1229       Desc.getOpcode() == AMDGPU::V_DIV_SCALE_F64) {
1230     const MachineOperand &Src0 = MI->getOperand(Src0Idx);
1231     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
1232     const MachineOperand &Src2 = MI->getOperand(Src2Idx);
1233     if (Src0.isReg() && Src1.isReg() && Src2.isReg()) {
1234       if (!compareMachineOp(Src0, Src1) &&
1235           !compareMachineOp(Src0, Src2)) {
1236         ErrInfo = "v_div_scale_{f32|f64} require src0 = src1 or src2";
1237         return false;
1238       }
1239     }
1240   }
1241
1242   return true;
1243 }
1244
1245 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
1246   switch (MI.getOpcode()) {
1247   default: return AMDGPU::INSTRUCTION_LIST_END;
1248   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
1249   case AMDGPU::COPY: return AMDGPU::COPY;
1250   case AMDGPU::PHI: return AMDGPU::PHI;
1251   case AMDGPU::INSERT_SUBREG: return AMDGPU::INSERT_SUBREG;
1252   case AMDGPU::S_MOV_B32:
1253     return MI.getOperand(1).isReg() ?
1254            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
1255   case AMDGPU::S_ADD_I32:
1256   case AMDGPU::S_ADD_U32: return AMDGPU::V_ADD_I32_e32;
1257   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
1258   case AMDGPU::S_SUB_I32:
1259   case AMDGPU::S_SUB_U32: return AMDGPU::V_SUB_I32_e32;
1260   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
1261   case AMDGPU::S_MUL_I32: return AMDGPU::V_MUL_LO_I32;
1262   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e32;
1263   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e32;
1264   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e32;
1265   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e32;
1266   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e32;
1267   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e32;
1268   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e32;
1269   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
1270   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
1271   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
1272   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
1273   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
1274   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
1275   case AMDGPU::S_SEXT_I32_I8: return AMDGPU::V_BFE_I32;
1276   case AMDGPU::S_SEXT_I32_I16: return AMDGPU::V_BFE_I32;
1277   case AMDGPU::S_BFE_U32: return AMDGPU::V_BFE_U32;
1278   case AMDGPU::S_BFE_I32: return AMDGPU::V_BFE_I32;
1279   case AMDGPU::S_BREV_B32: return AMDGPU::V_BFREV_B32_e32;
1280   case AMDGPU::S_NOT_B32: return AMDGPU::V_NOT_B32_e32;
1281   case AMDGPU::S_NOT_B64: return AMDGPU::V_NOT_B32_e32;
1282   case AMDGPU::S_CMP_EQ_I32: return AMDGPU::V_CMP_EQ_I32_e32;
1283   case AMDGPU::S_CMP_LG_I32: return AMDGPU::V_CMP_NE_I32_e32;
1284   case AMDGPU::S_CMP_GT_I32: return AMDGPU::V_CMP_GT_I32_e32;
1285   case AMDGPU::S_CMP_GE_I32: return AMDGPU::V_CMP_GE_I32_e32;
1286   case AMDGPU::S_CMP_LT_I32: return AMDGPU::V_CMP_LT_I32_e32;
1287   case AMDGPU::S_CMP_LE_I32: return AMDGPU::V_CMP_LE_I32_e32;
1288   case AMDGPU::S_LOAD_DWORD_IMM:
1289   case AMDGPU::S_LOAD_DWORD_SGPR: return AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1290   case AMDGPU::S_LOAD_DWORDX2_IMM:
1291   case AMDGPU::S_LOAD_DWORDX2_SGPR: return AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1292   case AMDGPU::S_LOAD_DWORDX4_IMM:
1293   case AMDGPU::S_LOAD_DWORDX4_SGPR: return AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1294   case AMDGPU::S_BCNT1_I32_B32: return AMDGPU::V_BCNT_U32_B32_e32;
1295   case AMDGPU::S_FF1_I32_B32: return AMDGPU::V_FFBL_B32_e32;
1296   case AMDGPU::S_FLBIT_I32_B32: return AMDGPU::V_FFBH_U32_e32;
1297   }
1298 }
1299
1300 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
1301   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
1302 }
1303
1304 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
1305                                                       unsigned OpNo) const {
1306   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
1307   const MCInstrDesc &Desc = get(MI.getOpcode());
1308   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
1309       Desc.OpInfo[OpNo].RegClass == -1) {
1310     unsigned Reg = MI.getOperand(OpNo).getReg();
1311
1312     if (TargetRegisterInfo::isVirtualRegister(Reg))
1313       return MRI.getRegClass(Reg);
1314     return RI.getRegClass(Reg);
1315   }
1316
1317   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
1318   return RI.getRegClass(RCID);
1319 }
1320
1321 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
1322   switch (MI.getOpcode()) {
1323   case AMDGPU::COPY:
1324   case AMDGPU::REG_SEQUENCE:
1325   case AMDGPU::PHI:
1326   case AMDGPU::INSERT_SUBREG:
1327     return RI.hasVGPRs(getOpRegClass(MI, 0));
1328   default:
1329     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
1330   }
1331 }
1332
1333 void SIInstrInfo::legalizeOpWithMove(MachineInstr *MI, unsigned OpIdx) const {
1334   MachineBasicBlock::iterator I = MI;
1335   MachineBasicBlock *MBB = MI->getParent();
1336   MachineOperand &MO = MI->getOperand(OpIdx);
1337   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1338   unsigned RCID = get(MI->getOpcode()).OpInfo[OpIdx].RegClass;
1339   const TargetRegisterClass *RC = RI.getRegClass(RCID);
1340   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
1341   if (MO.isReg())
1342     Opcode = AMDGPU::COPY;
1343   else if (RI.isSGPRClass(RC))
1344     Opcode = AMDGPU::S_MOV_B32;
1345
1346
1347   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
1348   if (RI.getCommonSubClass(&AMDGPU::VReg_64RegClass, VRC))
1349     VRC = &AMDGPU::VReg_64RegClass;
1350   else
1351     VRC = &AMDGPU::VGPR_32RegClass;
1352
1353   unsigned Reg = MRI.createVirtualRegister(VRC);
1354   DebugLoc DL = MBB->findDebugLoc(I);
1355   BuildMI(*MI->getParent(), I, DL, get(Opcode), Reg)
1356     .addOperand(MO);
1357   MO.ChangeToRegister(Reg, false);
1358 }
1359
1360 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
1361                                          MachineRegisterInfo &MRI,
1362                                          MachineOperand &SuperReg,
1363                                          const TargetRegisterClass *SuperRC,
1364                                          unsigned SubIdx,
1365                                          const TargetRegisterClass *SubRC)
1366                                          const {
1367   assert(SuperReg.isReg());
1368
1369   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
1370   unsigned SubReg = MRI.createVirtualRegister(SubRC);
1371
1372   // Just in case the super register is itself a sub-register, copy it to a new
1373   // value so we don't need to worry about merging its subreg index with the
1374   // SubIdx passed to this function. The register coalescer should be able to
1375   // eliminate this extra copy.
1376   MachineBasicBlock *MBB = MI->getParent();
1377   DebugLoc DL = MI->getDebugLoc();
1378
1379   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), NewSuperReg)
1380     .addReg(SuperReg.getReg(), 0, SuperReg.getSubReg());
1381
1382   BuildMI(*MBB, MI, DL, get(TargetOpcode::COPY), SubReg)
1383     .addReg(NewSuperReg, 0, SubIdx);
1384
1385   return SubReg;
1386 }
1387
1388 MachineOperand SIInstrInfo::buildExtractSubRegOrImm(
1389   MachineBasicBlock::iterator MII,
1390   MachineRegisterInfo &MRI,
1391   MachineOperand &Op,
1392   const TargetRegisterClass *SuperRC,
1393   unsigned SubIdx,
1394   const TargetRegisterClass *SubRC) const {
1395   if (Op.isImm()) {
1396     // XXX - Is there a better way to do this?
1397     if (SubIdx == AMDGPU::sub0)
1398       return MachineOperand::CreateImm(Op.getImm() & 0xFFFFFFFF);
1399     if (SubIdx == AMDGPU::sub1)
1400       return MachineOperand::CreateImm(Op.getImm() >> 32);
1401
1402     llvm_unreachable("Unhandled register index for immediate");
1403   }
1404
1405   unsigned SubReg = buildExtractSubReg(MII, MRI, Op, SuperRC,
1406                                        SubIdx, SubRC);
1407   return MachineOperand::CreateReg(SubReg, false);
1408 }
1409
1410 unsigned SIInstrInfo::split64BitImm(SmallVectorImpl<MachineInstr *> &Worklist,
1411                                     MachineBasicBlock::iterator MI,
1412                                     MachineRegisterInfo &MRI,
1413                                     const TargetRegisterClass *RC,
1414                                     const MachineOperand &Op) const {
1415   MachineBasicBlock *MBB = MI->getParent();
1416   DebugLoc DL = MI->getDebugLoc();
1417   unsigned LoDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1418   unsigned HiDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1419   unsigned Dst = MRI.createVirtualRegister(RC);
1420
1421   MachineInstr *Lo = BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32),
1422                              LoDst)
1423     .addImm(Op.getImm() & 0xFFFFFFFF);
1424   MachineInstr *Hi = BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32),
1425                              HiDst)
1426     .addImm(Op.getImm() >> 32);
1427
1428   BuildMI(*MBB, MI, DL, get(TargetOpcode::REG_SEQUENCE), Dst)
1429     .addReg(LoDst)
1430     .addImm(AMDGPU::sub0)
1431     .addReg(HiDst)
1432     .addImm(AMDGPU::sub1);
1433
1434   Worklist.push_back(Lo);
1435   Worklist.push_back(Hi);
1436
1437   return Dst;
1438 }
1439
1440 // Change the order of operands from (0, 1, 2) to (0, 2, 1)
1441 void SIInstrInfo::swapOperands(MachineBasicBlock::iterator Inst) const {
1442   assert(Inst->getNumExplicitOperands() == 3);
1443   MachineOperand Op1 = Inst->getOperand(1);
1444   Inst->RemoveOperand(1);
1445   Inst->addOperand(Op1);
1446 }
1447
1448 bool SIInstrInfo::isOperandLegal(const MachineInstr *MI, unsigned OpIdx,
1449                                  const MachineOperand *MO) const {
1450   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1451   const MCInstrDesc &InstDesc = get(MI->getOpcode());
1452   const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpIdx];
1453   const TargetRegisterClass *DefinedRC =
1454       OpInfo.RegClass != -1 ? RI.getRegClass(OpInfo.RegClass) : nullptr;
1455   if (!MO)
1456     MO = &MI->getOperand(OpIdx);
1457
1458   if (isVALU(InstDesc.Opcode) && usesConstantBus(MRI, *MO)) {
1459     unsigned SGPRUsed =
1460         MO->isReg() ? MO->getReg() : (unsigned)AMDGPU::NoRegister;
1461     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1462       if (i == OpIdx)
1463         continue;
1464       if (usesConstantBus(MRI, MI->getOperand(i)) &&
1465           MI->getOperand(i).isReg() && MI->getOperand(i).getReg() != SGPRUsed) {
1466         return false;
1467       }
1468     }
1469   }
1470
1471   if (MO->isReg()) {
1472     assert(DefinedRC);
1473     const TargetRegisterClass *RC = MRI.getRegClass(MO->getReg());
1474
1475     // In order to be legal, the common sub-class must be equal to the
1476     // class of the current operand.  For example:
1477     //
1478     // v_mov_b32 s0 ; Operand defined as vsrc_32
1479     //              ; RI.getCommonSubClass(s0,vsrc_32) = sgpr ; LEGAL
1480     //
1481     // s_sendmsg 0, s0 ; Operand defined as m0reg
1482     //                 ; RI.getCommonSubClass(s0,m0reg) = m0reg ; NOT LEGAL
1483
1484     return RI.getCommonSubClass(RC, RI.getRegClass(OpInfo.RegClass)) == RC;
1485   }
1486
1487
1488   // Handle non-register types that are treated like immediates.
1489   assert(MO->isImm() || MO->isTargetIndex() || MO->isFI());
1490
1491   if (!DefinedRC) {
1492     // This operand expects an immediate.
1493     return true;
1494   }
1495
1496   return isImmOperandLegal(MI, OpIdx, *MO);
1497 }
1498
1499 void SIInstrInfo::legalizeOperands(MachineInstr *MI) const {
1500   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1501
1502   int Src0Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1503                                            AMDGPU::OpName::src0);
1504   int Src1Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1505                                            AMDGPU::OpName::src1);
1506   int Src2Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
1507                                            AMDGPU::OpName::src2);
1508
1509   // Legalize VOP2
1510   if (isVOP2(MI->getOpcode()) && Src1Idx != -1) {
1511     // Legalize src0
1512     if (!isOperandLegal(MI, Src0Idx))
1513       legalizeOpWithMove(MI, Src0Idx);
1514
1515     // Legalize src1
1516     if (isOperandLegal(MI, Src1Idx))
1517       return;
1518
1519     // Usually src0 of VOP2 instructions allow more types of inputs
1520     // than src1, so try to commute the instruction to decrease our
1521     // chances of having to insert a MOV instruction to legalize src1.
1522     if (MI->isCommutable()) {
1523       if (commuteInstruction(MI))
1524         // If we are successful in commuting, then we know MI is legal, so
1525         // we are done.
1526         return;
1527     }
1528
1529     legalizeOpWithMove(MI, Src1Idx);
1530     return;
1531   }
1532
1533   // XXX - Do any VOP3 instructions read VCC?
1534   // Legalize VOP3
1535   if (isVOP3(MI->getOpcode())) {
1536     int VOP3Idx[3] = { Src0Idx, Src1Idx, Src2Idx };
1537
1538     // Find the one SGPR operand we are allowed to use.
1539     unsigned SGPRReg = findUsedSGPR(MI, VOP3Idx);
1540
1541     for (unsigned i = 0; i < 3; ++i) {
1542       int Idx = VOP3Idx[i];
1543       if (Idx == -1)
1544         break;
1545       MachineOperand &MO = MI->getOperand(Idx);
1546
1547       if (MO.isReg()) {
1548         if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
1549           continue; // VGPRs are legal
1550
1551         assert(MO.getReg() != AMDGPU::SCC && "SCC operand to VOP3 instruction");
1552
1553         if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
1554           SGPRReg = MO.getReg();
1555           // We can use one SGPR in each VOP3 instruction.
1556           continue;
1557         }
1558       } else if (!isLiteralConstant(MO)) {
1559         // If it is not a register and not a literal constant, then it must be
1560         // an inline constant which is always legal.
1561         continue;
1562       }
1563       // If we make it this far, then the operand is not legal and we must
1564       // legalize it.
1565       legalizeOpWithMove(MI, Idx);
1566     }
1567   }
1568
1569   // Legalize REG_SEQUENCE and PHI
1570   // The register class of the operands much be the same type as the register
1571   // class of the output.
1572   if (MI->getOpcode() == AMDGPU::REG_SEQUENCE ||
1573       MI->getOpcode() == AMDGPU::PHI) {
1574     const TargetRegisterClass *RC = nullptr, *SRC = nullptr, *VRC = nullptr;
1575     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
1576       if (!MI->getOperand(i).isReg() ||
1577           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
1578         continue;
1579       const TargetRegisterClass *OpRC =
1580               MRI.getRegClass(MI->getOperand(i).getReg());
1581       if (RI.hasVGPRs(OpRC)) {
1582         VRC = OpRC;
1583       } else {
1584         SRC = OpRC;
1585       }
1586     }
1587
1588     // If any of the operands are VGPR registers, then they all most be
1589     // otherwise we will create illegal VGPR->SGPR copies when legalizing
1590     // them.
1591     if (VRC || !RI.isSGPRClass(getOpRegClass(*MI, 0))) {
1592       if (!VRC) {
1593         assert(SRC);
1594         VRC = RI.getEquivalentVGPRClass(SRC);
1595       }
1596       RC = VRC;
1597     } else {
1598       RC = SRC;
1599     }
1600
1601     // Update all the operands so they have the same type.
1602     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
1603       if (!MI->getOperand(i).isReg() ||
1604           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
1605         continue;
1606       unsigned DstReg = MRI.createVirtualRegister(RC);
1607       MachineBasicBlock *InsertBB;
1608       MachineBasicBlock::iterator Insert;
1609       if (MI->getOpcode() == AMDGPU::REG_SEQUENCE) {
1610         InsertBB = MI->getParent();
1611         Insert = MI;
1612       } else {
1613         // MI is a PHI instruction.
1614         InsertBB = MI->getOperand(i + 1).getMBB();
1615         Insert = InsertBB->getFirstTerminator();
1616       }
1617       BuildMI(*InsertBB, Insert, MI->getDebugLoc(),
1618               get(AMDGPU::COPY), DstReg)
1619               .addOperand(MI->getOperand(i));
1620       MI->getOperand(i).setReg(DstReg);
1621     }
1622   }
1623
1624   // Legalize INSERT_SUBREG
1625   // src0 must have the same register class as dst
1626   if (MI->getOpcode() == AMDGPU::INSERT_SUBREG) {
1627     unsigned Dst = MI->getOperand(0).getReg();
1628     unsigned Src0 = MI->getOperand(1).getReg();
1629     const TargetRegisterClass *DstRC = MRI.getRegClass(Dst);
1630     const TargetRegisterClass *Src0RC = MRI.getRegClass(Src0);
1631     if (DstRC != Src0RC) {
1632       MachineBasicBlock &MBB = *MI->getParent();
1633       unsigned NewSrc0 = MRI.createVirtualRegister(DstRC);
1634       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::COPY), NewSrc0)
1635               .addReg(Src0);
1636       MI->getOperand(1).setReg(NewSrc0);
1637     }
1638     return;
1639   }
1640
1641   // Legalize MUBUF* instructions
1642   // FIXME: If we start using the non-addr64 instructions for compute, we
1643   // may need to legalize them here.
1644   int SRsrcIdx =
1645       AMDGPU::getNamedOperandIdx(MI->getOpcode(), AMDGPU::OpName::srsrc);
1646   if (SRsrcIdx != -1) {
1647     // We have an MUBUF instruction
1648     MachineOperand *SRsrc = &MI->getOperand(SRsrcIdx);
1649     unsigned SRsrcRC = get(MI->getOpcode()).OpInfo[SRsrcIdx].RegClass;
1650     if (RI.getCommonSubClass(MRI.getRegClass(SRsrc->getReg()),
1651                                              RI.getRegClass(SRsrcRC))) {
1652       // The operands are legal.
1653       // FIXME: We may need to legalize operands besided srsrc.
1654       return;
1655     }
1656
1657     MachineBasicBlock &MBB = *MI->getParent();
1658     // Extract the the ptr from the resource descriptor.
1659
1660     // SRsrcPtrLo = srsrc:sub0
1661     unsigned SRsrcPtrLo = buildExtractSubReg(MI, MRI, *SRsrc,
1662         &AMDGPU::VReg_128RegClass, AMDGPU::sub0, &AMDGPU::VGPR_32RegClass);
1663
1664     // SRsrcPtrHi = srsrc:sub1
1665     unsigned SRsrcPtrHi = buildExtractSubReg(MI, MRI, *SRsrc,
1666         &AMDGPU::VReg_128RegClass, AMDGPU::sub1, &AMDGPU::VGPR_32RegClass);
1667
1668     // Create an empty resource descriptor
1669     unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1670     unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1671     unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1672     unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
1673     uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
1674
1675     // Zero64 = 0
1676     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B64),
1677             Zero64)
1678             .addImm(0);
1679
1680     // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
1681     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1682             SRsrcFormatLo)
1683             .addImm(RsrcDataFormat & 0xFFFFFFFF);
1684
1685     // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
1686     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1687             SRsrcFormatHi)
1688             .addImm(RsrcDataFormat >> 32);
1689
1690     // NewSRsrc = {Zero64, SRsrcFormat}
1691     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
1692             NewSRsrc)
1693             .addReg(Zero64)
1694             .addImm(AMDGPU::sub0_sub1)
1695             .addReg(SRsrcFormatLo)
1696             .addImm(AMDGPU::sub2)
1697             .addReg(SRsrcFormatHi)
1698             .addImm(AMDGPU::sub3);
1699
1700     MachineOperand *VAddr = getNamedOperand(*MI, AMDGPU::OpName::vaddr);
1701     unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
1702     unsigned NewVAddrLo;
1703     unsigned NewVAddrHi;
1704     if (VAddr) {
1705       // This is already an ADDR64 instruction so we need to add the pointer
1706       // extracted from the resource descriptor to the current value of VAddr.
1707       NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1708       NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1709
1710       // NewVaddrLo = SRsrcPtrLo + VAddr:sub0
1711       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADD_I32_e32),
1712               NewVAddrLo)
1713               .addReg(SRsrcPtrLo)
1714               .addReg(VAddr->getReg(), 0, AMDGPU::sub0)
1715               .addReg(AMDGPU::VCC, RegState::ImplicitDefine);
1716
1717       // NewVaddrHi = SRsrcPtrHi + VAddr:sub1
1718       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADDC_U32_e32),
1719               NewVAddrHi)
1720               .addReg(SRsrcPtrHi)
1721               .addReg(VAddr->getReg(), 0, AMDGPU::sub1)
1722               .addReg(AMDGPU::VCC, RegState::ImplicitDefine)
1723               .addReg(AMDGPU::VCC, RegState::Implicit);
1724
1725     } else {
1726       // This instructions is the _OFFSET variant, so we need to convert it to
1727       // ADDR64.
1728       MachineOperand *VData = getNamedOperand(*MI, AMDGPU::OpName::vdata);
1729       MachineOperand *Offset = getNamedOperand(*MI, AMDGPU::OpName::offset);
1730       MachineOperand *SOffset = getNamedOperand(*MI, AMDGPU::OpName::soffset);
1731       assert(SOffset->isImm() && SOffset->getImm() == 0 && "Legalizing MUBUF "
1732              "with non-zero soffset is not implemented");
1733       (void)SOffset;
1734
1735       // Create the new instruction.
1736       unsigned Addr64Opcode = AMDGPU::getAddr64Inst(MI->getOpcode());
1737       MachineInstr *Addr64 =
1738           BuildMI(MBB, MI, MI->getDebugLoc(), get(Addr64Opcode))
1739                   .addOperand(*VData)
1740                   .addOperand(*SRsrc)
1741                   .addReg(AMDGPU::NoRegister) // Dummy value for vaddr.
1742                                               // This will be replaced later
1743                                               // with the new value of vaddr.
1744                   .addOperand(*Offset);
1745
1746       MI->removeFromParent();
1747       MI = Addr64;
1748
1749       NewVAddrLo = SRsrcPtrLo;
1750       NewVAddrHi = SRsrcPtrHi;
1751       VAddr = getNamedOperand(*MI, AMDGPU::OpName::vaddr);
1752       SRsrc = getNamedOperand(*MI, AMDGPU::OpName::srsrc);
1753     }
1754
1755     // NewVaddr = {NewVaddrHi, NewVaddrLo}
1756     BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
1757             NewVAddr)
1758             .addReg(NewVAddrLo)
1759             .addImm(AMDGPU::sub0)
1760             .addReg(NewVAddrHi)
1761             .addImm(AMDGPU::sub1);
1762
1763
1764     // Update the instruction to use NewVaddr
1765     VAddr->setReg(NewVAddr);
1766     // Update the instruction to use NewSRsrc
1767     SRsrc->setReg(NewSRsrc);
1768   }
1769 }
1770
1771 void SIInstrInfo::splitSMRD(MachineInstr *MI,
1772                             const TargetRegisterClass *HalfRC,
1773                             unsigned HalfImmOp, unsigned HalfSGPROp,
1774                             MachineInstr *&Lo, MachineInstr *&Hi) const {
1775
1776   DebugLoc DL = MI->getDebugLoc();
1777   MachineBasicBlock *MBB = MI->getParent();
1778   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1779   unsigned RegLo = MRI.createVirtualRegister(HalfRC);
1780   unsigned RegHi = MRI.createVirtualRegister(HalfRC);
1781   unsigned HalfSize = HalfRC->getSize();
1782   const MachineOperand *OffOp =
1783       getNamedOperand(*MI, AMDGPU::OpName::offset);
1784   const MachineOperand *SBase = getNamedOperand(*MI, AMDGPU::OpName::sbase);
1785
1786   // The SMRD has an 8-bit offset in dwords on SI and a 20-bit offset in bytes
1787   // on VI.
1788   if (OffOp) {
1789     bool isVI = RI.ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS;
1790     unsigned OffScale = isVI ? 1 : 4;
1791     // Handle the _IMM variant
1792     unsigned LoOffset = OffOp->getImm() * OffScale;
1793     unsigned HiOffset = LoOffset + HalfSize;
1794     Lo = BuildMI(*MBB, MI, DL, get(HalfImmOp), RegLo)
1795                   .addOperand(*SBase)
1796                   .addImm(LoOffset / OffScale);
1797
1798     if (!isUInt<20>(HiOffset) || (!isVI && !isUInt<8>(HiOffset / OffScale))) {
1799       unsigned OffsetSGPR =
1800           MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
1801       BuildMI(*MBB, MI, DL, get(AMDGPU::S_MOV_B32), OffsetSGPR)
1802               .addImm(HiOffset); // The offset in register is in bytes.
1803       Hi = BuildMI(*MBB, MI, DL, get(HalfSGPROp), RegHi)
1804                     .addOperand(*SBase)
1805                     .addReg(OffsetSGPR);
1806     } else {
1807       Hi = BuildMI(*MBB, MI, DL, get(HalfImmOp), RegHi)
1808                      .addOperand(*SBase)
1809                      .addImm(HiOffset / OffScale);
1810     }
1811   } else {
1812     // Handle the _SGPR variant
1813     MachineOperand *SOff = getNamedOperand(*MI, AMDGPU::OpName::soff);
1814     Lo = BuildMI(*MBB, MI, DL, get(HalfSGPROp), RegLo)
1815                   .addOperand(*SBase)
1816                   .addOperand(*SOff);
1817     unsigned OffsetSGPR = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
1818     BuildMI(*MBB, MI, DL, get(AMDGPU::S_ADD_I32), OffsetSGPR)
1819             .addOperand(*SOff)
1820             .addImm(HalfSize);
1821     Hi = BuildMI(*MBB, MI, DL, get(HalfSGPROp))
1822                   .addOperand(*SBase)
1823                   .addReg(OffsetSGPR);
1824   }
1825
1826   unsigned SubLo, SubHi;
1827   switch (HalfSize) {
1828     case 4:
1829       SubLo = AMDGPU::sub0;
1830       SubHi = AMDGPU::sub1;
1831       break;
1832     case 8:
1833       SubLo = AMDGPU::sub0_sub1;
1834       SubHi = AMDGPU::sub2_sub3;
1835       break;
1836     case 16:
1837       SubLo = AMDGPU::sub0_sub1_sub2_sub3;
1838       SubHi = AMDGPU::sub4_sub5_sub6_sub7;
1839       break;
1840     case 32:
1841       SubLo = AMDGPU::sub0_sub1_sub2_sub3_sub4_sub5_sub6_sub7;
1842       SubHi = AMDGPU::sub8_sub9_sub10_sub11_sub12_sub13_sub14_sub15;
1843       break;
1844     default:
1845       llvm_unreachable("Unhandled HalfSize");
1846   }
1847
1848   BuildMI(*MBB, MI, DL, get(AMDGPU::REG_SEQUENCE))
1849           .addOperand(MI->getOperand(0))
1850           .addReg(RegLo)
1851           .addImm(SubLo)
1852           .addReg(RegHi)
1853           .addImm(SubHi);
1854 }
1855
1856 void SIInstrInfo::moveSMRDToVALU(MachineInstr *MI, MachineRegisterInfo &MRI) const {
1857   MachineBasicBlock *MBB = MI->getParent();
1858   switch (MI->getOpcode()) {
1859     case AMDGPU::S_LOAD_DWORD_IMM:
1860     case AMDGPU::S_LOAD_DWORD_SGPR:
1861     case AMDGPU::S_LOAD_DWORDX2_IMM:
1862     case AMDGPU::S_LOAD_DWORDX2_SGPR:
1863     case AMDGPU::S_LOAD_DWORDX4_IMM:
1864     case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1865       unsigned NewOpcode = getVALUOp(*MI);
1866       unsigned RegOffset;
1867       unsigned ImmOffset;
1868
1869       if (MI->getOperand(2).isReg()) {
1870         RegOffset = MI->getOperand(2).getReg();
1871         ImmOffset = 0;
1872       } else {
1873         assert(MI->getOperand(2).isImm());
1874         // SMRD instructions take a dword offsets on SI and byte offset on VI
1875         // and MUBUF instructions always take a byte offset.
1876         ImmOffset = MI->getOperand(2).getImm();
1877         if (RI.ST.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS)
1878           ImmOffset <<= 2;
1879         RegOffset = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1880
1881         if (isUInt<12>(ImmOffset)) {
1882           BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1883                   RegOffset)
1884                   .addImm(0);
1885         } else {
1886           BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
1887                   RegOffset)
1888                   .addImm(ImmOffset);
1889           ImmOffset = 0;
1890         }
1891       }
1892
1893       unsigned SRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
1894       unsigned DWord0 = RegOffset;
1895       unsigned DWord1 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1896       unsigned DWord2 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1897       unsigned DWord3 = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1898       uint64_t RsrcDataFormat = getDefaultRsrcDataFormat();
1899
1900       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord1)
1901               .addImm(0);
1902       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord2)
1903               .addImm(RsrcDataFormat & 0xFFFFFFFF);
1904       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32), DWord3)
1905               .addImm(RsrcDataFormat >> 32);
1906       BuildMI(*MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE), SRsrc)
1907               .addReg(DWord0)
1908               .addImm(AMDGPU::sub0)
1909               .addReg(DWord1)
1910               .addImm(AMDGPU::sub1)
1911               .addReg(DWord2)
1912               .addImm(AMDGPU::sub2)
1913               .addReg(DWord3)
1914               .addImm(AMDGPU::sub3);
1915       MI->setDesc(get(NewOpcode));
1916       if (MI->getOperand(2).isReg()) {
1917         MI->getOperand(2).setReg(MI->getOperand(1).getReg());
1918       } else {
1919         MI->getOperand(2).ChangeToRegister(MI->getOperand(1).getReg(), false);
1920       }
1921       MI->getOperand(1).setReg(SRsrc);
1922       MI->addOperand(*MBB->getParent(), MachineOperand::CreateImm(ImmOffset));
1923
1924       const TargetRegisterClass *NewDstRC =
1925           RI.getRegClass(get(NewOpcode).OpInfo[0].RegClass);
1926
1927       unsigned DstReg = MI->getOperand(0).getReg();
1928       unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
1929       MRI.replaceRegWith(DstReg, NewDstReg);
1930       break;
1931     }
1932     case AMDGPU::S_LOAD_DWORDX8_IMM:
1933     case AMDGPU::S_LOAD_DWORDX8_SGPR: {
1934       MachineInstr *Lo, *Hi;
1935       splitSMRD(MI, &AMDGPU::SReg_128RegClass, AMDGPU::S_LOAD_DWORDX4_IMM,
1936                 AMDGPU::S_LOAD_DWORDX4_SGPR, Lo, Hi);
1937       MI->eraseFromParent();
1938       moveSMRDToVALU(Lo, MRI);
1939       moveSMRDToVALU(Hi, MRI);
1940       break;
1941     }
1942
1943     case AMDGPU::S_LOAD_DWORDX16_IMM:
1944     case AMDGPU::S_LOAD_DWORDX16_SGPR: {
1945       MachineInstr *Lo, *Hi;
1946       splitSMRD(MI, &AMDGPU::SReg_256RegClass, AMDGPU::S_LOAD_DWORDX8_IMM,
1947                 AMDGPU::S_LOAD_DWORDX8_SGPR, Lo, Hi);
1948       MI->eraseFromParent();
1949       moveSMRDToVALU(Lo, MRI);
1950       moveSMRDToVALU(Hi, MRI);
1951       break;
1952     }
1953   }
1954 }
1955
1956 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
1957   SmallVector<MachineInstr *, 128> Worklist;
1958   Worklist.push_back(&TopInst);
1959
1960   while (!Worklist.empty()) {
1961     MachineInstr *Inst = Worklist.pop_back_val();
1962     MachineBasicBlock *MBB = Inst->getParent();
1963     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1964
1965     unsigned Opcode = Inst->getOpcode();
1966     unsigned NewOpcode = getVALUOp(*Inst);
1967
1968     // Handle some special cases
1969     switch (Opcode) {
1970     default:
1971       if (isSMRD(Inst->getOpcode())) {
1972         moveSMRDToVALU(Inst, MRI);
1973       }
1974       break;
1975     case AMDGPU::S_MOV_B64: {
1976       DebugLoc DL = Inst->getDebugLoc();
1977
1978       // If the source operand is a register we can replace this with a
1979       // copy.
1980       if (Inst->getOperand(1).isReg()) {
1981         MachineInstr *Copy = BuildMI(*MBB, Inst, DL, get(TargetOpcode::COPY))
1982           .addOperand(Inst->getOperand(0))
1983           .addOperand(Inst->getOperand(1));
1984         Worklist.push_back(Copy);
1985       } else {
1986         // Otherwise, we need to split this into two movs, because there is
1987         // no 64-bit VALU move instruction.
1988         unsigned Reg = Inst->getOperand(0).getReg();
1989         unsigned Dst = split64BitImm(Worklist,
1990                                      Inst,
1991                                      MRI,
1992                                      MRI.getRegClass(Reg),
1993                                      Inst->getOperand(1));
1994         MRI.replaceRegWith(Reg, Dst);
1995       }
1996       Inst->eraseFromParent();
1997       continue;
1998     }
1999     case AMDGPU::S_AND_B64:
2000       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_AND_B32);
2001       Inst->eraseFromParent();
2002       continue;
2003
2004     case AMDGPU::S_OR_B64:
2005       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_OR_B32);
2006       Inst->eraseFromParent();
2007       continue;
2008
2009     case AMDGPU::S_XOR_B64:
2010       splitScalar64BitBinaryOp(Worklist, Inst, AMDGPU::S_XOR_B32);
2011       Inst->eraseFromParent();
2012       continue;
2013
2014     case AMDGPU::S_NOT_B64:
2015       splitScalar64BitUnaryOp(Worklist, Inst, AMDGPU::S_NOT_B32);
2016       Inst->eraseFromParent();
2017       continue;
2018
2019     case AMDGPU::S_BCNT1_I32_B64:
2020       splitScalar64BitBCNT(Worklist, Inst);
2021       Inst->eraseFromParent();
2022       continue;
2023
2024     case AMDGPU::S_BFE_I64: {
2025       splitScalar64BitBFE(Worklist, Inst);
2026       Inst->eraseFromParent();
2027       continue;
2028     }
2029
2030     case AMDGPU::S_LSHL_B32:
2031       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
2032         NewOpcode = AMDGPU::V_LSHLREV_B32_e64;
2033         swapOperands(Inst);
2034       }
2035       break;
2036     case AMDGPU::S_ASHR_I32:
2037       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
2038         NewOpcode = AMDGPU::V_ASHRREV_I32_e64;
2039         swapOperands(Inst);
2040       }
2041       break;
2042     case AMDGPU::S_LSHR_B32:
2043       if (ST.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
2044         NewOpcode = AMDGPU::V_LSHRREV_B32_e64;
2045         swapOperands(Inst);
2046       }
2047       break;
2048
2049     case AMDGPU::S_BFE_U64:
2050     case AMDGPU::S_BFM_B64:
2051       llvm_unreachable("Moving this op to VALU not implemented");
2052     }
2053
2054     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
2055       // We cannot move this instruction to the VALU, so we should try to
2056       // legalize its operands instead.
2057       legalizeOperands(Inst);
2058       continue;
2059     }
2060
2061     // Use the new VALU Opcode.
2062     const MCInstrDesc &NewDesc = get(NewOpcode);
2063     Inst->setDesc(NewDesc);
2064
2065     // Remove any references to SCC. Vector instructions can't read from it, and
2066     // We're just about to add the implicit use / defs of VCC, and we don't want
2067     // both.
2068     for (unsigned i = Inst->getNumOperands() - 1; i > 0; --i) {
2069       MachineOperand &Op = Inst->getOperand(i);
2070       if (Op.isReg() && Op.getReg() == AMDGPU::SCC)
2071         Inst->RemoveOperand(i);
2072     }
2073
2074     if (Opcode == AMDGPU::S_SEXT_I32_I8 || Opcode == AMDGPU::S_SEXT_I32_I16) {
2075       // We are converting these to a BFE, so we need to add the missing
2076       // operands for the size and offset.
2077       unsigned Size = (Opcode == AMDGPU::S_SEXT_I32_I8) ? 8 : 16;
2078       Inst->addOperand(MachineOperand::CreateImm(0));
2079       Inst->addOperand(MachineOperand::CreateImm(Size));
2080
2081     } else if (Opcode == AMDGPU::S_BCNT1_I32_B32) {
2082       // The VALU version adds the second operand to the result, so insert an
2083       // extra 0 operand.
2084       Inst->addOperand(MachineOperand::CreateImm(0));
2085     }
2086
2087     addDescImplicitUseDef(NewDesc, Inst);
2088
2089     if (Opcode == AMDGPU::S_BFE_I32 || Opcode == AMDGPU::S_BFE_U32) {
2090       const MachineOperand &OffsetWidthOp = Inst->getOperand(2);
2091       // If we need to move this to VGPRs, we need to unpack the second operand
2092       // back into the 2 separate ones for bit offset and width.
2093       assert(OffsetWidthOp.isImm() &&
2094              "Scalar BFE is only implemented for constant width and offset");
2095       uint32_t Imm = OffsetWidthOp.getImm();
2096
2097       uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2098       uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2099       Inst->RemoveOperand(2); // Remove old immediate.
2100       Inst->addOperand(MachineOperand::CreateImm(Offset));
2101       Inst->addOperand(MachineOperand::CreateImm(BitWidth));
2102     }
2103
2104     // Update the destination register class.
2105
2106     const TargetRegisterClass *NewDstRC = getOpRegClass(*Inst, 0);
2107
2108     switch (Opcode) {
2109       // For target instructions, getOpRegClass just returns the virtual
2110       // register class associated with the operand, so we need to find an
2111       // equivalent VGPR register class in order to move the instruction to the
2112       // VALU.
2113     case AMDGPU::COPY:
2114     case AMDGPU::PHI:
2115     case AMDGPU::REG_SEQUENCE:
2116     case AMDGPU::INSERT_SUBREG:
2117       if (RI.hasVGPRs(NewDstRC))
2118         continue;
2119       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
2120       if (!NewDstRC)
2121         continue;
2122       break;
2123     default:
2124       break;
2125     }
2126
2127     unsigned DstReg = Inst->getOperand(0).getReg();
2128     unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
2129     MRI.replaceRegWith(DstReg, NewDstReg);
2130
2131     // Legalize the operands
2132     legalizeOperands(Inst);
2133
2134     for (MachineRegisterInfo::use_iterator I = MRI.use_begin(NewDstReg),
2135            E = MRI.use_end(); I != E; ++I) {
2136       MachineInstr &UseMI = *I->getParent();
2137       if (!canReadVGPR(UseMI, I.getOperandNo())) {
2138         Worklist.push_back(&UseMI);
2139       }
2140     }
2141   }
2142 }
2143
2144 //===----------------------------------------------------------------------===//
2145 // Indirect addressing callbacks
2146 //===----------------------------------------------------------------------===//
2147
2148 unsigned SIInstrInfo::calculateIndirectAddress(unsigned RegIndex,
2149                                                  unsigned Channel) const {
2150   assert(Channel == 0);
2151   return RegIndex;
2152 }
2153
2154 const TargetRegisterClass *SIInstrInfo::getIndirectAddrRegClass() const {
2155   return &AMDGPU::VGPR_32RegClass;
2156 }
2157
2158 void SIInstrInfo::splitScalar64BitUnaryOp(
2159   SmallVectorImpl<MachineInstr *> &Worklist,
2160   MachineInstr *Inst,
2161   unsigned Opcode) const {
2162   MachineBasicBlock &MBB = *Inst->getParent();
2163   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2164
2165   MachineOperand &Dest = Inst->getOperand(0);
2166   MachineOperand &Src0 = Inst->getOperand(1);
2167   DebugLoc DL = Inst->getDebugLoc();
2168
2169   MachineBasicBlock::iterator MII = Inst;
2170
2171   const MCInstrDesc &InstDesc = get(Opcode);
2172   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2173     MRI.getRegClass(Src0.getReg()) :
2174     &AMDGPU::SGPR_32RegClass;
2175
2176   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2177
2178   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2179                                                        AMDGPU::sub0, Src0SubRC);
2180
2181   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2182   const TargetRegisterClass *DestSubRC = RI.getSubRegClass(DestRC, AMDGPU::sub0);
2183
2184   unsigned DestSub0 = MRI.createVirtualRegister(DestRC);
2185   MachineInstr *LoHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2186     .addOperand(SrcReg0Sub0);
2187
2188   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2189                                                        AMDGPU::sub1, Src0SubRC);
2190
2191   unsigned DestSub1 = MRI.createVirtualRegister(DestSubRC);
2192   MachineInstr *HiHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2193     .addOperand(SrcReg0Sub1);
2194
2195   unsigned FullDestReg = MRI.createVirtualRegister(DestRC);
2196   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2197     .addReg(DestSub0)
2198     .addImm(AMDGPU::sub0)
2199     .addReg(DestSub1)
2200     .addImm(AMDGPU::sub1);
2201
2202   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2203
2204   // Try to legalize the operands in case we need to swap the order to keep it
2205   // valid.
2206   Worklist.push_back(LoHalf);
2207   Worklist.push_back(HiHalf);
2208 }
2209
2210 void SIInstrInfo::splitScalar64BitBinaryOp(
2211   SmallVectorImpl<MachineInstr *> &Worklist,
2212   MachineInstr *Inst,
2213   unsigned Opcode) const {
2214   MachineBasicBlock &MBB = *Inst->getParent();
2215   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2216
2217   MachineOperand &Dest = Inst->getOperand(0);
2218   MachineOperand &Src0 = Inst->getOperand(1);
2219   MachineOperand &Src1 = Inst->getOperand(2);
2220   DebugLoc DL = Inst->getDebugLoc();
2221
2222   MachineBasicBlock::iterator MII = Inst;
2223
2224   const MCInstrDesc &InstDesc = get(Opcode);
2225   const TargetRegisterClass *Src0RC = Src0.isReg() ?
2226     MRI.getRegClass(Src0.getReg()) :
2227     &AMDGPU::SGPR_32RegClass;
2228
2229   const TargetRegisterClass *Src0SubRC = RI.getSubRegClass(Src0RC, AMDGPU::sub0);
2230   const TargetRegisterClass *Src1RC = Src1.isReg() ?
2231     MRI.getRegClass(Src1.getReg()) :
2232     &AMDGPU::SGPR_32RegClass;
2233
2234   const TargetRegisterClass *Src1SubRC = RI.getSubRegClass(Src1RC, AMDGPU::sub0);
2235
2236   MachineOperand SrcReg0Sub0 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2237                                                        AMDGPU::sub0, Src0SubRC);
2238   MachineOperand SrcReg1Sub0 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2239                                                        AMDGPU::sub0, Src1SubRC);
2240
2241   const TargetRegisterClass *DestRC = MRI.getRegClass(Dest.getReg());
2242   const TargetRegisterClass *DestSubRC = RI.getSubRegClass(DestRC, AMDGPU::sub0);
2243
2244   unsigned DestSub0 = MRI.createVirtualRegister(DestRC);
2245   MachineInstr *LoHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub0)
2246     .addOperand(SrcReg0Sub0)
2247     .addOperand(SrcReg1Sub0);
2248
2249   MachineOperand SrcReg0Sub1 = buildExtractSubRegOrImm(MII, MRI, Src0, Src0RC,
2250                                                        AMDGPU::sub1, Src0SubRC);
2251   MachineOperand SrcReg1Sub1 = buildExtractSubRegOrImm(MII, MRI, Src1, Src1RC,
2252                                                        AMDGPU::sub1, Src1SubRC);
2253
2254   unsigned DestSub1 = MRI.createVirtualRegister(DestSubRC);
2255   MachineInstr *HiHalf = BuildMI(MBB, MII, DL, InstDesc, DestSub1)
2256     .addOperand(SrcReg0Sub1)
2257     .addOperand(SrcReg1Sub1);
2258
2259   unsigned FullDestReg = MRI.createVirtualRegister(DestRC);
2260   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), FullDestReg)
2261     .addReg(DestSub0)
2262     .addImm(AMDGPU::sub0)
2263     .addReg(DestSub1)
2264     .addImm(AMDGPU::sub1);
2265
2266   MRI.replaceRegWith(Dest.getReg(), FullDestReg);
2267
2268   // Try to legalize the operands in case we need to swap the order to keep it
2269   // valid.
2270   Worklist.push_back(LoHalf);
2271   Worklist.push_back(HiHalf);
2272 }
2273
2274 void SIInstrInfo::splitScalar64BitBCNT(SmallVectorImpl<MachineInstr *> &Worklist,
2275                                        MachineInstr *Inst) const {
2276   MachineBasicBlock &MBB = *Inst->getParent();
2277   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2278
2279   MachineBasicBlock::iterator MII = Inst;
2280   DebugLoc DL = Inst->getDebugLoc();
2281
2282   MachineOperand &Dest = Inst->getOperand(0);
2283   MachineOperand &Src = Inst->getOperand(1);
2284
2285   const MCInstrDesc &InstDesc = get(AMDGPU::V_BCNT_U32_B32_e32);
2286   const TargetRegisterClass *SrcRC = Src.isReg() ?
2287     MRI.getRegClass(Src.getReg()) :
2288     &AMDGPU::SGPR_32RegClass;
2289
2290   unsigned MidReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2291   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2292
2293   const TargetRegisterClass *SrcSubRC = RI.getSubRegClass(SrcRC, AMDGPU::sub0);
2294
2295   MachineOperand SrcRegSub0 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2296                                                       AMDGPU::sub0, SrcSubRC);
2297   MachineOperand SrcRegSub1 = buildExtractSubRegOrImm(MII, MRI, Src, SrcRC,
2298                                                       AMDGPU::sub1, SrcSubRC);
2299
2300   MachineInstr *First = BuildMI(MBB, MII, DL, InstDesc, MidReg)
2301     .addOperand(SrcRegSub0)
2302     .addImm(0);
2303
2304   MachineInstr *Second = BuildMI(MBB, MII, DL, InstDesc, ResultReg)
2305     .addOperand(SrcRegSub1)
2306     .addReg(MidReg);
2307
2308   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2309
2310   Worklist.push_back(First);
2311   Worklist.push_back(Second);
2312 }
2313
2314 void SIInstrInfo::splitScalar64BitBFE(SmallVectorImpl<MachineInstr *> &Worklist,
2315                                       MachineInstr *Inst) const {
2316   MachineBasicBlock &MBB = *Inst->getParent();
2317   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
2318   MachineBasicBlock::iterator MII = Inst;
2319   DebugLoc DL = Inst->getDebugLoc();
2320
2321   MachineOperand &Dest = Inst->getOperand(0);
2322   uint32_t Imm = Inst->getOperand(2).getImm();
2323   uint32_t Offset = Imm & 0x3f; // Extract bits [5:0].
2324   uint32_t BitWidth = (Imm & 0x7f0000) >> 16; // Extract bits [22:16].
2325
2326   (void) Offset;
2327
2328   // Only sext_inreg cases handled.
2329   assert(Inst->getOpcode() == AMDGPU::S_BFE_I64 &&
2330          BitWidth <= 32 &&
2331          Offset == 0 &&
2332          "Not implemented");
2333
2334   if (BitWidth < 32) {
2335     unsigned MidRegLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2336     unsigned MidRegHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2337     unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2338
2339     BuildMI(MBB, MII, DL, get(AMDGPU::V_BFE_I32), MidRegLo)
2340       .addReg(Inst->getOperand(1).getReg(), 0, AMDGPU::sub0)
2341       .addImm(0)
2342       .addImm(BitWidth);
2343
2344     BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e32), MidRegHi)
2345       .addImm(31)
2346       .addReg(MidRegLo);
2347
2348     BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2349       .addReg(MidRegLo)
2350       .addImm(AMDGPU::sub0)
2351       .addReg(MidRegHi)
2352       .addImm(AMDGPU::sub1);
2353
2354     MRI.replaceRegWith(Dest.getReg(), ResultReg);
2355     return;
2356   }
2357
2358   MachineOperand &Src = Inst->getOperand(1);
2359   unsigned TmpReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2360   unsigned ResultReg = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
2361
2362   BuildMI(MBB, MII, DL, get(AMDGPU::V_ASHRREV_I32_e64), TmpReg)
2363     .addImm(31)
2364     .addReg(Src.getReg(), 0, AMDGPU::sub0);
2365
2366   BuildMI(MBB, MII, DL, get(TargetOpcode::REG_SEQUENCE), ResultReg)
2367     .addReg(Src.getReg(), 0, AMDGPU::sub0)
2368     .addImm(AMDGPU::sub0)
2369     .addReg(TmpReg)
2370     .addImm(AMDGPU::sub1);
2371
2372   MRI.replaceRegWith(Dest.getReg(), ResultReg);
2373 }
2374
2375 void SIInstrInfo::addDescImplicitUseDef(const MCInstrDesc &NewDesc,
2376                                         MachineInstr *Inst) const {
2377   // Add the implict and explicit register definitions.
2378   if (NewDesc.ImplicitUses) {
2379     for (unsigned i = 0; NewDesc.ImplicitUses[i]; ++i) {
2380       unsigned Reg = NewDesc.ImplicitUses[i];
2381       Inst->addOperand(MachineOperand::CreateReg(Reg, false, true));
2382     }
2383   }
2384
2385   if (NewDesc.ImplicitDefs) {
2386     for (unsigned i = 0; NewDesc.ImplicitDefs[i]; ++i) {
2387       unsigned Reg = NewDesc.ImplicitDefs[i];
2388       Inst->addOperand(MachineOperand::CreateReg(Reg, true, true));
2389     }
2390   }
2391 }
2392
2393 unsigned SIInstrInfo::findUsedSGPR(const MachineInstr *MI,
2394                                    int OpIndices[3]) const {
2395   const MCInstrDesc &Desc = get(MI->getOpcode());
2396
2397   // Find the one SGPR operand we are allowed to use.
2398   unsigned SGPRReg = AMDGPU::NoRegister;
2399
2400   // First we need to consider the instruction's operand requirements before
2401   // legalizing. Some operands are required to be SGPRs, such as implicit uses
2402   // of VCC, but we are still bound by the constant bus requirement to only use
2403   // one.
2404   //
2405   // If the operand's class is an SGPR, we can never move it.
2406
2407   for (const MachineOperand &MO : MI->implicit_operands()) {
2408     // We only care about reads.
2409     if (MO.isDef())
2410       continue;
2411
2412     if (MO.getReg() == AMDGPU::VCC)
2413       return AMDGPU::VCC;
2414
2415     if (MO.getReg() == AMDGPU::FLAT_SCR)
2416       return AMDGPU::FLAT_SCR;
2417   }
2418
2419   unsigned UsedSGPRs[3] = { AMDGPU::NoRegister };
2420   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2421
2422   for (unsigned i = 0; i < 3; ++i) {
2423     int Idx = OpIndices[i];
2424     if (Idx == -1)
2425       break;
2426
2427     const MachineOperand &MO = MI->getOperand(Idx);
2428     if (RI.isSGPRClassID(Desc.OpInfo[Idx].RegClass))
2429       SGPRReg = MO.getReg();
2430
2431     if (MO.isReg() && RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
2432       UsedSGPRs[i] = MO.getReg();
2433   }
2434
2435   if (SGPRReg != AMDGPU::NoRegister)
2436     return SGPRReg;
2437
2438   // We don't have a required SGPR operand, so we have a bit more freedom in
2439   // selecting operands to move.
2440
2441   // Try to select the most used SGPR. If an SGPR is equal to one of the
2442   // others, we choose that.
2443   //
2444   // e.g.
2445   // V_FMA_F32 v0, s0, s0, s0 -> No moves
2446   // V_FMA_F32 v0, s0, s1, s0 -> Move s1
2447
2448   if (UsedSGPRs[0] != AMDGPU::NoRegister) {
2449     if (UsedSGPRs[0] == UsedSGPRs[1] || UsedSGPRs[0] == UsedSGPRs[2])
2450       SGPRReg = UsedSGPRs[0];
2451   }
2452
2453   if (SGPRReg == AMDGPU::NoRegister && UsedSGPRs[1] != AMDGPU::NoRegister) {
2454     if (UsedSGPRs[1] == UsedSGPRs[2])
2455       SGPRReg = UsedSGPRs[1];
2456   }
2457
2458   return SGPRReg;
2459 }
2460
2461 MachineInstrBuilder SIInstrInfo::buildIndirectWrite(
2462                                    MachineBasicBlock *MBB,
2463                                    MachineBasicBlock::iterator I,
2464                                    unsigned ValueReg,
2465                                    unsigned Address, unsigned OffsetReg) const {
2466   const DebugLoc &DL = MBB->findDebugLoc(I);
2467   unsigned IndirectBaseReg = AMDGPU::VGPR_32RegClass.getRegister(
2468                                       getIndirectIndexBegin(*MBB->getParent()));
2469
2470   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_DST_V1))
2471           .addReg(IndirectBaseReg, RegState::Define)
2472           .addOperand(I->getOperand(0))
2473           .addReg(IndirectBaseReg)
2474           .addReg(OffsetReg)
2475           .addImm(0)
2476           .addReg(ValueReg);
2477 }
2478
2479 MachineInstrBuilder SIInstrInfo::buildIndirectRead(
2480                                    MachineBasicBlock *MBB,
2481                                    MachineBasicBlock::iterator I,
2482                                    unsigned ValueReg,
2483                                    unsigned Address, unsigned OffsetReg) const {
2484   const DebugLoc &DL = MBB->findDebugLoc(I);
2485   unsigned IndirectBaseReg = AMDGPU::VGPR_32RegClass.getRegister(
2486                                       getIndirectIndexBegin(*MBB->getParent()));
2487
2488   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_SRC))
2489           .addOperand(I->getOperand(0))
2490           .addOperand(I->getOperand(1))
2491           .addReg(IndirectBaseReg)
2492           .addReg(OffsetReg)
2493           .addImm(0);
2494
2495 }
2496
2497 void SIInstrInfo::reserveIndirectRegisters(BitVector &Reserved,
2498                                             const MachineFunction &MF) const {
2499   int End = getIndirectIndexEnd(MF);
2500   int Begin = getIndirectIndexBegin(MF);
2501
2502   if (End == -1)
2503     return;
2504
2505
2506   for (int Index = Begin; Index <= End; ++Index)
2507     Reserved.set(AMDGPU::VGPR_32RegClass.getRegister(Index));
2508
2509   for (int Index = std::max(0, Begin - 1); Index <= End; ++Index)
2510     Reserved.set(AMDGPU::VReg_64RegClass.getRegister(Index));
2511
2512   for (int Index = std::max(0, Begin - 2); Index <= End; ++Index)
2513     Reserved.set(AMDGPU::VReg_96RegClass.getRegister(Index));
2514
2515   for (int Index = std::max(0, Begin - 3); Index <= End; ++Index)
2516     Reserved.set(AMDGPU::VReg_128RegClass.getRegister(Index));
2517
2518   for (int Index = std::max(0, Begin - 7); Index <= End; ++Index)
2519     Reserved.set(AMDGPU::VReg_256RegClass.getRegister(Index));
2520
2521   for (int Index = std::max(0, Begin - 15); Index <= End; ++Index)
2522     Reserved.set(AMDGPU::VReg_512RegClass.getRegister(Index));
2523 }
2524
2525 MachineOperand *SIInstrInfo::getNamedOperand(MachineInstr &MI,
2526                                              unsigned OperandName) const {
2527   int Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), OperandName);
2528   if (Idx == -1)
2529     return nullptr;
2530
2531   return &MI.getOperand(Idx);
2532 }
2533
2534 uint64_t SIInstrInfo::getDefaultRsrcDataFormat() const {
2535   uint64_t RsrcDataFormat = AMDGPU::RSRC_DATA_FORMAT;
2536   if (ST.isAmdHsaOS())
2537     RsrcDataFormat |= (1ULL << 56);
2538
2539   return RsrcDataFormat;
2540 }