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