6460043477ce6b9ec7c33fe5952948c50726da12
[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/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/MC/MCInstrDesc.h"
23
24 using namespace llvm;
25
26 SIInstrInfo::SIInstrInfo(AMDGPUTargetMachine &tm)
27   : AMDGPUInstrInfo(tm),
28     RI(tm) { }
29
30 //===----------------------------------------------------------------------===//
31 // TargetInstrInfo callbacks
32 //===----------------------------------------------------------------------===//
33
34 void
35 SIInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
36                          MachineBasicBlock::iterator MI, DebugLoc DL,
37                          unsigned DestReg, unsigned SrcReg,
38                          bool KillSrc) const {
39
40   // If we are trying to copy to or from SCC, there is a bug somewhere else in
41   // the backend.  While it may be theoretically possible to do this, it should
42   // never be necessary.
43   assert(DestReg != AMDGPU::SCC && SrcReg != AMDGPU::SCC);
44
45   static const int16_t Sub0_15[] = {
46     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
47     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7,
48     AMDGPU::sub8, AMDGPU::sub9, AMDGPU::sub10, AMDGPU::sub11,
49     AMDGPU::sub12, AMDGPU::sub13, AMDGPU::sub14, AMDGPU::sub15, 0
50   };
51
52   static const int16_t Sub0_7[] = {
53     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3,
54     AMDGPU::sub4, AMDGPU::sub5, AMDGPU::sub6, AMDGPU::sub7, 0
55   };
56
57   static const int16_t Sub0_3[] = {
58     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, AMDGPU::sub3, 0
59   };
60
61   static const int16_t Sub0_2[] = {
62     AMDGPU::sub0, AMDGPU::sub1, AMDGPU::sub2, 0
63   };
64
65   static const int16_t Sub0_1[] = {
66     AMDGPU::sub0, AMDGPU::sub1, 0
67   };
68
69   unsigned Opcode;
70   const int16_t *SubIndices;
71
72   if (AMDGPU::M0 == DestReg) {
73     // Check if M0 isn't already set to this value
74     for (MachineBasicBlock::reverse_iterator E = MBB.rend(),
75       I = MachineBasicBlock::reverse_iterator(MI); I != E; ++I) {
76
77       if (!I->definesRegister(AMDGPU::M0))
78         continue;
79
80       unsigned Opc = I->getOpcode();
81       if (Opc != TargetOpcode::COPY && Opc != AMDGPU::S_MOV_B32)
82         break;
83
84       if (!I->readsRegister(SrcReg))
85         break;
86
87       // The copy isn't necessary
88       return;
89     }
90   }
91
92   if (AMDGPU::SReg_32RegClass.contains(DestReg)) {
93     assert(AMDGPU::SReg_32RegClass.contains(SrcReg));
94     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B32), DestReg)
95             .addReg(SrcReg, getKillRegState(KillSrc));
96     return;
97
98   } else if (AMDGPU::SReg_64RegClass.contains(DestReg)) {
99     assert(AMDGPU::SReg_64RegClass.contains(SrcReg));
100     BuildMI(MBB, MI, DL, get(AMDGPU::S_MOV_B64), DestReg)
101             .addReg(SrcReg, getKillRegState(KillSrc));
102     return;
103
104   } else if (AMDGPU::SReg_128RegClass.contains(DestReg)) {
105     assert(AMDGPU::SReg_128RegClass.contains(SrcReg));
106     Opcode = AMDGPU::S_MOV_B32;
107     SubIndices = Sub0_3;
108
109   } else if (AMDGPU::SReg_256RegClass.contains(DestReg)) {
110     assert(AMDGPU::SReg_256RegClass.contains(SrcReg));
111     Opcode = AMDGPU::S_MOV_B32;
112     SubIndices = Sub0_7;
113
114   } else if (AMDGPU::SReg_512RegClass.contains(DestReg)) {
115     assert(AMDGPU::SReg_512RegClass.contains(SrcReg));
116     Opcode = AMDGPU::S_MOV_B32;
117     SubIndices = Sub0_15;
118
119   } else if (AMDGPU::VReg_32RegClass.contains(DestReg)) {
120     assert(AMDGPU::VReg_32RegClass.contains(SrcReg) ||
121            AMDGPU::SReg_32RegClass.contains(SrcReg));
122     BuildMI(MBB, MI, DL, get(AMDGPU::V_MOV_B32_e32), DestReg)
123             .addReg(SrcReg, getKillRegState(KillSrc));
124     return;
125
126   } else if (AMDGPU::VReg_64RegClass.contains(DestReg)) {
127     assert(AMDGPU::VReg_64RegClass.contains(SrcReg) ||
128            AMDGPU::SReg_64RegClass.contains(SrcReg));
129     Opcode = AMDGPU::V_MOV_B32_e32;
130     SubIndices = Sub0_1;
131
132   } else if (AMDGPU::VReg_96RegClass.contains(DestReg)) {
133     assert(AMDGPU::VReg_96RegClass.contains(SrcReg));
134     Opcode = AMDGPU::V_MOV_B32_e32;
135     SubIndices = Sub0_2;
136
137   } else if (AMDGPU::VReg_128RegClass.contains(DestReg)) {
138     assert(AMDGPU::VReg_128RegClass.contains(SrcReg) ||
139            AMDGPU::SReg_128RegClass.contains(SrcReg));
140     Opcode = AMDGPU::V_MOV_B32_e32;
141     SubIndices = Sub0_3;
142
143   } else if (AMDGPU::VReg_256RegClass.contains(DestReg)) {
144     assert(AMDGPU::VReg_256RegClass.contains(SrcReg) ||
145            AMDGPU::SReg_256RegClass.contains(SrcReg));
146     Opcode = AMDGPU::V_MOV_B32_e32;
147     SubIndices = Sub0_7;
148
149   } else if (AMDGPU::VReg_512RegClass.contains(DestReg)) {
150     assert(AMDGPU::VReg_512RegClass.contains(SrcReg) ||
151            AMDGPU::SReg_512RegClass.contains(SrcReg));
152     Opcode = AMDGPU::V_MOV_B32_e32;
153     SubIndices = Sub0_15;
154
155   } else {
156     llvm_unreachable("Can't copy register!");
157   }
158
159   while (unsigned SubIdx = *SubIndices++) {
160     MachineInstrBuilder Builder = BuildMI(MBB, MI, DL,
161       get(Opcode), RI.getSubReg(DestReg, SubIdx));
162
163     Builder.addReg(RI.getSubReg(SrcReg, SubIdx), getKillRegState(KillSrc));
164
165     if (*SubIndices)
166       Builder.addReg(DestReg, RegState::Define | RegState::Implicit);
167   }
168 }
169
170 unsigned SIInstrInfo::commuteOpcode(unsigned Opcode) const {
171   int NewOpc;
172
173   // Try to map original to commuted opcode
174   if ((NewOpc = AMDGPU::getCommuteRev(Opcode)) != -1)
175     return NewOpc;
176
177   // Try to map commuted to original opcode
178   if ((NewOpc = AMDGPU::getCommuteOrig(Opcode)) != -1)
179     return NewOpc;
180
181   return Opcode;
182 }
183
184 void SIInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
185                                       MachineBasicBlock::iterator MI,
186                                       unsigned SrcReg, bool isKill,
187                                       int FrameIndex,
188                                       const TargetRegisterClass *RC,
189                                       const TargetRegisterInfo *TRI) const {
190   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
191   SIMachineFunctionInfo *MFI = MBB.getParent()->getInfo<SIMachineFunctionInfo>();
192   DebugLoc DL = MBB.findDebugLoc(MI);
193   unsigned KillFlag = isKill ? RegState::Kill : 0;
194
195   if (TRI->getCommonSubClass(RC, &AMDGPU::SGPR_32RegClass)) {
196     unsigned Lane = MFI->SpillTracker.getNextLane(MRI);
197     BuildMI(MBB, MI, DL, get(AMDGPU::V_WRITELANE_B32),
198             MFI->SpillTracker.LaneVGPR)
199             .addReg(SrcReg, KillFlag)
200             .addImm(Lane);
201     MFI->SpillTracker.addSpilledReg(FrameIndex, MFI->SpillTracker.LaneVGPR,
202                                     Lane);
203   } else {
204     for (unsigned i = 0, e = RC->getSize() / 4; i != e; ++i) {
205       unsigned SubReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
206       BuildMI(MBB, MI, MBB.findDebugLoc(MI), get(AMDGPU::COPY), SubReg)
207               .addReg(SrcReg, 0, RI.getSubRegFromChannel(i));
208       storeRegToStackSlot(MBB, MI, SubReg, isKill, FrameIndex + i,
209                           &AMDGPU::SReg_32RegClass, TRI);
210     }
211   }
212 }
213
214 void SIInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
215                                        MachineBasicBlock::iterator MI,
216                                        unsigned DestReg, int FrameIndex,
217                                        const TargetRegisterClass *RC,
218                                        const TargetRegisterInfo *TRI) const {
219   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
220   SIMachineFunctionInfo *MFI = MBB.getParent()->getInfo<SIMachineFunctionInfo>();
221   DebugLoc DL = MBB.findDebugLoc(MI);
222   if (TRI->getCommonSubClass(RC, &AMDGPU::SReg_32RegClass)) {
223      SIMachineFunctionInfo::SpilledReg Spill =
224         MFI->SpillTracker.getSpilledReg(FrameIndex);
225     assert(Spill.VGPR);
226     BuildMI(MBB, MI, DL, get(AMDGPU::V_READLANE_B32), DestReg)
227             .addReg(Spill.VGPR)
228             .addImm(Spill.Lane);
229   } else {
230     for (unsigned i = 0, e = RC->getSize() / 4; i != e; ++i) {
231       unsigned Flags = RegState::Define;
232       if (i == 0) {
233         Flags |= RegState::Undef;
234       }
235       unsigned SubReg = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
236       loadRegFromStackSlot(MBB, MI, SubReg, FrameIndex + i,
237                            &AMDGPU::SReg_32RegClass, TRI);
238       BuildMI(MBB, MI, DL, get(AMDGPU::COPY))
239               .addReg(DestReg, Flags, RI.getSubRegFromChannel(i))
240               .addReg(SubReg);
241     }
242   }
243 }
244
245 MachineInstr *SIInstrInfo::commuteInstruction(MachineInstr *MI,
246                                               bool NewMI) const {
247
248   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
249   if (MI->getNumOperands() < 3 || !MI->getOperand(1).isReg())
250     return 0;
251
252   // Cannot commute VOP2 if src0 is SGPR.
253   if (isVOP2(MI->getOpcode()) && MI->getOperand(1).isReg() &&
254       RI.isSGPRClass(MRI.getRegClass(MI->getOperand(1).getReg())))
255    return 0;
256
257   if (!MI->getOperand(2).isReg()) {
258     // XXX: Commute instructions with FPImm operands
259     if (NewMI || MI->getOperand(2).isFPImm() ||
260        (!isVOP2(MI->getOpcode()) && !isVOP3(MI->getOpcode()))) {
261       return 0;
262     }
263
264     // XXX: Commute VOP3 instructions with abs and neg set.
265     if (isVOP3(MI->getOpcode()) &&
266         (MI->getOperand(AMDGPU::getNamedOperandIdx(MI->getOpcode(),
267                         AMDGPU::OpName::abs)).getImm() ||
268          MI->getOperand(AMDGPU::getNamedOperandIdx(MI->getOpcode(),
269                         AMDGPU::OpName::neg)).getImm()))
270       return 0;
271
272     unsigned Reg = MI->getOperand(1).getReg();
273     unsigned SubReg = MI->getOperand(1).getSubReg();
274     MI->getOperand(1).ChangeToImmediate(MI->getOperand(2).getImm());
275     MI->getOperand(2).ChangeToRegister(Reg, false);
276     MI->getOperand(2).setSubReg(SubReg);
277   } else {
278     MI = TargetInstrInfo::commuteInstruction(MI, NewMI);
279   }
280
281   if (MI)
282     MI->setDesc(get(commuteOpcode(MI->getOpcode())));
283
284   return MI;
285 }
286
287 MachineInstr *SIInstrInfo::buildMovInstr(MachineBasicBlock *MBB,
288                                          MachineBasicBlock::iterator I,
289                                          unsigned DstReg,
290                                          unsigned SrcReg) const {
291   return BuildMI(*MBB, I, MBB->findDebugLoc(I), get(AMDGPU::V_MOV_B32_e32),
292                  DstReg) .addReg(SrcReg);
293 }
294
295 bool SIInstrInfo::isMov(unsigned Opcode) const {
296   switch(Opcode) {
297   default: return false;
298   case AMDGPU::S_MOV_B32:
299   case AMDGPU::S_MOV_B64:
300   case AMDGPU::V_MOV_B32_e32:
301   case AMDGPU::V_MOV_B32_e64:
302     return true;
303   }
304 }
305
306 bool
307 SIInstrInfo::isSafeToMoveRegClassDefs(const TargetRegisterClass *RC) const {
308   return RC != &AMDGPU::EXECRegRegClass;
309 }
310
311 namespace llvm {
312 namespace AMDGPU {
313 // Helper function generated by tablegen.  We are wrapping this with
314 // an SIInstrInfo function that reutrns bool rather than int.
315 int isDS(uint16_t Opcode);
316 }
317 }
318
319 bool SIInstrInfo::isDS(uint16_t Opcode) const {
320   return ::AMDGPU::isDS(Opcode) != -1;
321 }
322
323 int SIInstrInfo::isMIMG(uint16_t Opcode) const {
324   return get(Opcode).TSFlags & SIInstrFlags::MIMG;
325 }
326
327 int SIInstrInfo::isSMRD(uint16_t Opcode) const {
328   return get(Opcode).TSFlags & SIInstrFlags::SMRD;
329 }
330
331 bool SIInstrInfo::isVOP1(uint16_t Opcode) const {
332   return get(Opcode).TSFlags & SIInstrFlags::VOP1;
333 }
334
335 bool SIInstrInfo::isVOP2(uint16_t Opcode) const {
336   return get(Opcode).TSFlags & SIInstrFlags::VOP2;
337 }
338
339 bool SIInstrInfo::isVOP3(uint16_t Opcode) const {
340   return get(Opcode).TSFlags & SIInstrFlags::VOP3;
341 }
342
343 bool SIInstrInfo::isVOPC(uint16_t Opcode) const {
344   return get(Opcode).TSFlags & SIInstrFlags::VOPC;
345 }
346
347 bool SIInstrInfo::isSALUInstr(const MachineInstr &MI) const {
348   return get(MI.getOpcode()).TSFlags & SIInstrFlags::SALU;
349 }
350
351 bool SIInstrInfo::isInlineConstant(const MachineOperand &MO) const {
352
353   union {
354     int32_t I;
355     float F;
356   } Imm;
357
358   if (MO.isImm()) {
359     Imm.I = MO.getImm();
360   } else if (MO.isFPImm()) {
361     Imm.F = MO.getFPImm()->getValueAPF().convertToFloat();
362   } else {
363     return false;
364   }
365
366   // The actual type of the operand does not seem to matter as long
367   // as the bits match one of the inline immediate values.  For example:
368   //
369   // -nan has the hexadecimal encoding of 0xfffffffe which is -2 in decimal,
370   // so it is a legal inline immediate.
371   //
372   // 1065353216 has the hexadecimal encoding 0x3f800000 which is 1.0f in
373   // floating-point, so it is a legal inline immediate.
374   return (Imm.I >= -16 && Imm.I <= 64) ||
375           Imm.F == 0.0f || Imm.F == 0.5f || Imm.F == -0.5f || Imm.F == 1.0f ||
376           Imm.F == -1.0f || Imm.F == 2.0f || Imm.F == -2.0f || Imm.F == 4.0f ||
377           Imm.F == -4.0f;
378 }
379
380 bool SIInstrInfo::isLiteralConstant(const MachineOperand &MO) const {
381   return (MO.isImm() || MO.isFPImm()) && !isInlineConstant(MO);
382 }
383
384 bool SIInstrInfo::verifyInstruction(const MachineInstr *MI,
385                                     StringRef &ErrInfo) const {
386   uint16_t Opcode = MI->getOpcode();
387   int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
388   int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
389   int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
390
391   // Make sure the number of operands is correct.
392   const MCInstrDesc &Desc = get(Opcode);
393   if (!Desc.isVariadic() &&
394       Desc.getNumOperands() != MI->getNumExplicitOperands()) {
395      ErrInfo = "Instruction has wrong number of operands.";
396      return false;
397   }
398
399   // Make sure the register classes are correct
400   for (unsigned i = 0, e = Desc.getNumOperands(); i != e; ++i) {
401     switch (Desc.OpInfo[i].OperandType) {
402     case MCOI::OPERAND_REGISTER:
403       break;
404     case MCOI::OPERAND_IMMEDIATE:
405       if (!MI->getOperand(i).isImm() && !MI->getOperand(i).isFPImm()) {
406         ErrInfo = "Expected immediate, but got non-immediate";
407         return false;
408       }
409       // Fall-through
410     default:
411       continue;
412     }
413
414     if (!MI->getOperand(i).isReg())
415       continue;
416
417     int RegClass = Desc.OpInfo[i].RegClass;
418     if (RegClass != -1) {
419       unsigned Reg = MI->getOperand(i).getReg();
420       if (TargetRegisterInfo::isVirtualRegister(Reg))
421         continue;
422
423       const TargetRegisterClass *RC = RI.getRegClass(RegClass);
424       if (!RC->contains(Reg)) {
425         ErrInfo = "Operand has incorrect register class.";
426         return false;
427       }
428     }
429   }
430
431
432   // Verify VOP*
433   if (isVOP1(Opcode) || isVOP2(Opcode) || isVOP3(Opcode) || isVOPC(Opcode)) {
434     unsigned ConstantBusCount = 0;
435     unsigned SGPRUsed = AMDGPU::NoRegister;
436     for (int i = 0, e = MI->getNumOperands(); i != e; ++i) {
437       const MachineOperand &MO = MI->getOperand(i);
438       if (MO.isReg() && MO.isUse() &&
439           !TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
440
441         // EXEC register uses the constant bus.
442         if (!MO.isImplicit() && MO.getReg() == AMDGPU::EXEC)
443           ++ConstantBusCount;
444
445         // SGPRs use the constant bus
446         if (MO.getReg() == AMDGPU::M0 || MO.getReg() == AMDGPU::VCC ||
447             (!MO.isImplicit() &&
448             (AMDGPU::SGPR_32RegClass.contains(MO.getReg()) ||
449             AMDGPU::SGPR_64RegClass.contains(MO.getReg())))) {
450           if (SGPRUsed != MO.getReg()) {
451             ++ConstantBusCount;
452             SGPRUsed = MO.getReg();
453           }
454         }
455       }
456       // Literal constants use the constant bus.
457       if (isLiteralConstant(MO))
458         ++ConstantBusCount;
459     }
460     if (ConstantBusCount > 1) {
461       ErrInfo = "VOP* instruction uses the constant bus more than once";
462       return false;
463     }
464   }
465
466   // Verify SRC1 for VOP2 and VOPC
467   if (Src1Idx != -1 && (isVOP2(Opcode) || isVOPC(Opcode))) {
468     const MachineOperand &Src1 = MI->getOperand(Src1Idx);
469     if (Src1.isImm() || Src1.isFPImm()) {
470       ErrInfo = "VOP[2C] src1 cannot be an immediate.";
471       return false;
472     }
473   }
474
475   // Verify VOP3
476   if (isVOP3(Opcode)) {
477     if (Src0Idx != -1 && isLiteralConstant(MI->getOperand(Src0Idx))) {
478       ErrInfo = "VOP3 src0 cannot be a literal constant.";
479       return false;
480     }
481     if (Src1Idx != -1 && isLiteralConstant(MI->getOperand(Src1Idx))) {
482       ErrInfo = "VOP3 src1 cannot be a literal constant.";
483       return false;
484     }
485     if (Src2Idx != -1 && isLiteralConstant(MI->getOperand(Src2Idx))) {
486       ErrInfo = "VOP3 src2 cannot be a literal constant.";
487       return false;
488     }
489   }
490   return true;
491 }
492
493 unsigned SIInstrInfo::getVALUOp(const MachineInstr &MI) {
494   switch (MI.getOpcode()) {
495   default: return AMDGPU::INSTRUCTION_LIST_END;
496   case AMDGPU::REG_SEQUENCE: return AMDGPU::REG_SEQUENCE;
497   case AMDGPU::COPY: return AMDGPU::COPY;
498   case AMDGPU::PHI: return AMDGPU::PHI;
499   case AMDGPU::S_MOV_B32:
500     return MI.getOperand(1).isReg() ?
501            AMDGPU::COPY : AMDGPU::V_MOV_B32_e32;
502   case AMDGPU::S_ADD_I32: return AMDGPU::V_ADD_I32_e32;
503   case AMDGPU::S_ADDC_U32: return AMDGPU::V_ADDC_U32_e32;
504   case AMDGPU::S_SUB_I32: return AMDGPU::V_SUB_I32_e32;
505   case AMDGPU::S_SUBB_U32: return AMDGPU::V_SUBB_U32_e32;
506   case AMDGPU::S_AND_B32: return AMDGPU::V_AND_B32_e32;
507   case AMDGPU::S_OR_B32: return AMDGPU::V_OR_B32_e32;
508   case AMDGPU::S_XOR_B32: return AMDGPU::V_XOR_B32_e32;
509   case AMDGPU::S_MIN_I32: return AMDGPU::V_MIN_I32_e32;
510   case AMDGPU::S_MIN_U32: return AMDGPU::V_MIN_U32_e32;
511   case AMDGPU::S_MAX_I32: return AMDGPU::V_MAX_I32_e32;
512   case AMDGPU::S_MAX_U32: return AMDGPU::V_MAX_U32_e32;
513   case AMDGPU::S_ASHR_I32: return AMDGPU::V_ASHR_I32_e32;
514   case AMDGPU::S_ASHR_I64: return AMDGPU::V_ASHR_I64;
515   case AMDGPU::S_LSHL_B32: return AMDGPU::V_LSHL_B32_e32;
516   case AMDGPU::S_LSHL_B64: return AMDGPU::V_LSHL_B64;
517   case AMDGPU::S_LSHR_B32: return AMDGPU::V_LSHR_B32_e32;
518   case AMDGPU::S_LSHR_B64: return AMDGPU::V_LSHR_B64;
519   }
520 }
521
522 bool SIInstrInfo::isSALUOpSupportedOnVALU(const MachineInstr &MI) const {
523   return getVALUOp(MI) != AMDGPU::INSTRUCTION_LIST_END;
524 }
525
526 const TargetRegisterClass *SIInstrInfo::getOpRegClass(const MachineInstr &MI,
527                                                       unsigned OpNo) const {
528   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
529   const MCInstrDesc &Desc = get(MI.getOpcode());
530   if (MI.isVariadic() || OpNo >= Desc.getNumOperands() ||
531       Desc.OpInfo[OpNo].RegClass == -1)
532     return MRI.getRegClass(MI.getOperand(OpNo).getReg());
533
534   unsigned RCID = Desc.OpInfo[OpNo].RegClass;
535   return RI.getRegClass(RCID);
536 }
537
538 bool SIInstrInfo::canReadVGPR(const MachineInstr &MI, unsigned OpNo) const {
539   switch (MI.getOpcode()) {
540   case AMDGPU::COPY:
541   case AMDGPU::REG_SEQUENCE:
542     return RI.hasVGPRs(getOpRegClass(MI, 0));
543   default:
544     return RI.hasVGPRs(getOpRegClass(MI, OpNo));
545   }
546 }
547
548 void SIInstrInfo::legalizeOpWithMove(MachineInstr *MI, unsigned OpIdx) const {
549   MachineBasicBlock::iterator I = MI;
550   MachineOperand &MO = MI->getOperand(OpIdx);
551   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
552   unsigned RCID = get(MI->getOpcode()).OpInfo[OpIdx].RegClass;
553   const TargetRegisterClass *RC = RI.getRegClass(RCID);
554   unsigned Opcode = AMDGPU::V_MOV_B32_e32;
555   if (MO.isReg()) {
556     Opcode = AMDGPU::COPY;
557   } else if (RI.isSGPRClass(RC)) {
558     Opcode = AMDGPU::S_MOV_B32;
559   }
560
561   const TargetRegisterClass *VRC = RI.getEquivalentVGPRClass(RC);
562   unsigned Reg = MRI.createVirtualRegister(VRC);
563   BuildMI(*MI->getParent(), I, MI->getParent()->findDebugLoc(I), get(Opcode),
564           Reg).addOperand(MO);
565   MO.ChangeToRegister(Reg, false);
566 }
567
568 unsigned SIInstrInfo::buildExtractSubReg(MachineBasicBlock::iterator MI,
569                                          MachineRegisterInfo &MRI,
570                                          MachineOperand &SuperReg,
571                                          const TargetRegisterClass *SuperRC,
572                                          unsigned SubIdx,
573                                          const TargetRegisterClass *SubRC)
574                                          const {
575   assert(SuperReg.isReg());
576
577   unsigned NewSuperReg = MRI.createVirtualRegister(SuperRC);
578   unsigned SubReg = MRI.createVirtualRegister(SubRC);
579
580   // Just in case the super register is itself a sub-register, copy it to a new
581   // value so we don't need to wory about merging its subreg index with the
582   // SubIdx passed to this function.  The register coalescer should be able to
583   // eliminate this extra copy.
584   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(TargetOpcode::COPY),
585           NewSuperReg)
586           .addOperand(SuperReg);
587
588   BuildMI(*MI->getParent(), MI, MI->getDebugLoc(), get(TargetOpcode::COPY),
589           SubReg)
590           .addReg(NewSuperReg, 0, SubIdx);
591   return SubReg;
592 }
593
594 void SIInstrInfo::legalizeOperands(MachineInstr *MI) const {
595   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
596   int Src0Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
597                                            AMDGPU::OpName::src0);
598   int Src1Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
599                                            AMDGPU::OpName::src1);
600   int Src2Idx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
601                                            AMDGPU::OpName::src2);
602
603   // Legalize VOP2
604   if (isVOP2(MI->getOpcode()) && Src1Idx != -1) {
605     MachineOperand &Src0 = MI->getOperand(Src0Idx);
606     MachineOperand &Src1 = MI->getOperand(Src1Idx);
607
608     // If the instruction implicitly reads VCC, we can't have any SGPR operands,
609     // so move any.
610     bool ReadsVCC = MI->readsRegister(AMDGPU::VCC, &RI);
611     if (ReadsVCC && Src0.isReg() &&
612         RI.isSGPRClass(MRI.getRegClass(Src0.getReg()))) {
613       legalizeOpWithMove(MI, Src0Idx);
614       return;
615     }
616
617     if (ReadsVCC && Src1.isReg() &&
618         RI.isSGPRClass(MRI.getRegClass(Src1.getReg()))) {
619       legalizeOpWithMove(MI, Src1Idx);
620       return;
621     }
622
623     // Legalize VOP2 instructions where src1 is not a VGPR. An SGPR input must
624     // be the first operand, and there can only be one.
625     if (Src1.isImm() || Src1.isFPImm() ||
626         (Src1.isReg() && RI.isSGPRClass(MRI.getRegClass(Src1.getReg())))) {
627       if (MI->isCommutable()) {
628         if (commuteInstruction(MI))
629           return;
630       }
631       legalizeOpWithMove(MI, Src1Idx);
632     }
633   }
634
635   // XXX - Do any VOP3 instructions read VCC?
636   // Legalize VOP3
637   if (isVOP3(MI->getOpcode())) {
638     int VOP3Idx[3] = {Src0Idx, Src1Idx, Src2Idx};
639     unsigned SGPRReg = AMDGPU::NoRegister;
640     for (unsigned i = 0; i < 3; ++i) {
641       int Idx = VOP3Idx[i];
642       if (Idx == -1)
643         continue;
644       MachineOperand &MO = MI->getOperand(Idx);
645
646       if (MO.isReg()) {
647         if (!RI.isSGPRClass(MRI.getRegClass(MO.getReg())))
648           continue; // VGPRs are legal
649
650         assert(MO.getReg() != AMDGPU::SCC && "SCC operand to VOP3 instruction");
651
652         if (SGPRReg == AMDGPU::NoRegister || SGPRReg == MO.getReg()) {
653           SGPRReg = MO.getReg();
654           // We can use one SGPR in each VOP3 instruction.
655           continue;
656         }
657       } else if (!isLiteralConstant(MO)) {
658         // If it is not a register and not a literal constant, then it must be
659         // an inline constant which is always legal.
660         continue;
661       }
662       // If we make it this far, then the operand is not legal and we must
663       // legalize it.
664       legalizeOpWithMove(MI, Idx);
665     }
666   }
667
668   // Legalize REG_SEQUENCE
669   // The register class of the operands much be the same type as the register
670   // class of the output.
671   if (MI->getOpcode() == AMDGPU::REG_SEQUENCE) {
672     const TargetRegisterClass *RC = NULL, *SRC = NULL, *VRC = NULL;
673     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
674       if (!MI->getOperand(i).isReg() ||
675           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
676         continue;
677       const TargetRegisterClass *OpRC =
678               MRI.getRegClass(MI->getOperand(i).getReg());
679       if (RI.hasVGPRs(OpRC)) {
680         VRC = OpRC;
681       } else {
682         SRC = OpRC;
683       }
684     }
685
686     // If any of the operands are VGPR registers, then they all most be
687     // otherwise we will create illegal VGPR->SGPR copies when legalizing
688     // them.
689     if (VRC || !RI.isSGPRClass(getOpRegClass(*MI, 0))) {
690       if (!VRC) {
691         assert(SRC);
692         VRC = RI.getEquivalentVGPRClass(SRC);
693       }
694       RC = VRC;
695     } else {
696       RC = SRC;
697     }
698
699     // Update all the operands so they have the same type.
700     for (unsigned i = 1, e = MI->getNumOperands(); i != e; i+=2) {
701       if (!MI->getOperand(i).isReg() ||
702           !TargetRegisterInfo::isVirtualRegister(MI->getOperand(i).getReg()))
703         continue;
704       unsigned DstReg = MRI.createVirtualRegister(RC);
705       BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
706               get(AMDGPU::COPY), DstReg)
707               .addOperand(MI->getOperand(i));
708       MI->getOperand(i).setReg(DstReg);
709     }
710   }
711
712   // Legalize MUBUF* instructions
713   // FIXME: If we start using the non-addr64 instructions for compute, we
714   // may need to legalize them here.
715
716   int SRsrcIdx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
717                                             AMDGPU::OpName::srsrc);
718   int VAddrIdx = AMDGPU::getNamedOperandIdx(MI->getOpcode(),
719                                              AMDGPU::OpName::vaddr);
720   if (SRsrcIdx != -1 && VAddrIdx != -1) {
721     const TargetRegisterClass *VAddrRC =
722         RI.getRegClass(get(MI->getOpcode()).OpInfo[VAddrIdx].RegClass);
723
724     if(VAddrRC->getSize() == 8 &&
725        MRI.getRegClass(MI->getOperand(SRsrcIdx).getReg()) != VAddrRC) {
726       // We have a MUBUF instruction that uses a 64-bit vaddr register and
727       // srsrc has the incorrect register class.  In order to fix this, we
728       // need to extract the pointer from the resource descriptor (srsrc),
729       // add it to the value of vadd,  then store the result in the vaddr
730       // operand.  Then, we need to set the pointer field of the resource
731       // descriptor to zero.
732
733       MachineBasicBlock &MBB = *MI->getParent();
734       MachineOperand &SRsrcOp = MI->getOperand(SRsrcIdx);
735       MachineOperand &VAddrOp = MI->getOperand(VAddrIdx);
736       unsigned SRsrcPtrLo, SRsrcPtrHi, VAddrLo, VAddrHi;
737       unsigned NewVAddrLo = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
738       unsigned NewVAddrHi = MRI.createVirtualRegister(&AMDGPU::VReg_32RegClass);
739       unsigned NewVAddr = MRI.createVirtualRegister(&AMDGPU::VReg_64RegClass);
740       unsigned Zero64 = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
741       unsigned SRsrcFormatLo = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
742       unsigned SRsrcFormatHi = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
743       unsigned NewSRsrc = MRI.createVirtualRegister(&AMDGPU::SReg_128RegClass);
744
745       // SRsrcPtrLo = srsrc:sub0
746       SRsrcPtrLo = buildExtractSubReg(MI, MRI, SRsrcOp,
747           &AMDGPU::VReg_128RegClass, AMDGPU::sub0, &AMDGPU::VReg_32RegClass);
748
749       // SRsrcPtrHi = srsrc:sub1
750       SRsrcPtrHi = buildExtractSubReg(MI, MRI, SRsrcOp,
751           &AMDGPU::VReg_128RegClass, AMDGPU::sub1, &AMDGPU::VReg_32RegClass);
752
753       // VAddrLo = vaddr:sub0
754       VAddrLo = buildExtractSubReg(MI, MRI, VAddrOp,
755           &AMDGPU::VReg_64RegClass, AMDGPU::sub0, &AMDGPU::VReg_32RegClass);
756
757       // VAddrHi = vaddr:sub1
758       VAddrHi = buildExtractSubReg(MI, MRI, VAddrOp,
759           &AMDGPU::VReg_64RegClass, AMDGPU::sub1, &AMDGPU::VReg_32RegClass);
760
761       // NewVaddrLo = SRsrcPtrLo + VAddrLo
762       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADD_I32_e32),
763               NewVAddrLo)
764               .addReg(SRsrcPtrLo)
765               .addReg(VAddrLo)
766               .addReg(AMDGPU::VCC, RegState::Define | RegState::Implicit);
767
768       // NewVaddrHi = SRsrcPtrHi + VAddrHi
769       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::V_ADDC_U32_e32),
770               NewVAddrHi)
771               .addReg(SRsrcPtrHi)
772               .addReg(VAddrHi)
773               .addReg(AMDGPU::VCC, RegState::ImplicitDefine)
774               .addReg(AMDGPU::VCC, RegState::Implicit);
775
776       // NewVaddr = {NewVaddrHi, NewVaddrLo}
777       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
778               NewVAddr)
779               .addReg(NewVAddrLo)
780               .addImm(AMDGPU::sub0)
781               .addReg(NewVAddrHi)
782               .addImm(AMDGPU::sub1);
783
784       // Zero64 = 0
785       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B64),
786               Zero64)
787               .addImm(0);
788
789       // SRsrcFormatLo = RSRC_DATA_FORMAT{31-0}
790       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
791               SRsrcFormatLo)
792               .addImm(AMDGPU::RSRC_DATA_FORMAT & 0xFFFFFFFF);
793
794       // SRsrcFormatHi = RSRC_DATA_FORMAT{63-32}
795       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::S_MOV_B32),
796               SRsrcFormatHi)
797               .addImm(AMDGPU::RSRC_DATA_FORMAT >> 32);
798
799       // NewSRsrc = {Zero64, SRsrcFormat}
800       BuildMI(MBB, MI, MI->getDebugLoc(), get(AMDGPU::REG_SEQUENCE),
801               NewSRsrc)
802               .addReg(Zero64)
803               .addImm(AMDGPU::sub0_sub1)
804               .addReg(SRsrcFormatLo)
805               .addImm(AMDGPU::sub2)
806               .addReg(SRsrcFormatHi)
807               .addImm(AMDGPU::sub3);
808
809       // Update the instruction to use NewVaddr
810       MI->getOperand(VAddrIdx).setReg(NewVAddr);
811       // Update the instruction to use NewSRsrc
812       MI->getOperand(SRsrcIdx).setReg(NewSRsrc);
813     }
814   }
815 }
816
817 void SIInstrInfo::moveToVALU(MachineInstr &TopInst) const {
818   SmallVector<MachineInstr *, 128> Worklist;
819   Worklist.push_back(&TopInst);
820
821   while (!Worklist.empty()) {
822     MachineInstr *Inst = Worklist.pop_back_val();
823     MachineBasicBlock *MBB = Inst->getParent();
824     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
825
826     // Handle some special cases
827     switch(Inst->getOpcode()) {
828       case AMDGPU::S_MOV_B64: {
829         DebugLoc DL = Inst->getDebugLoc();
830
831         // If the source operand is a register we can replace this with a
832         // copy
833         if (Inst->getOperand(1).isReg()) {
834           MachineInstr *Copy = BuildMI(*MBB, Inst, DL,
835                                        get(TargetOpcode::COPY))
836                                        .addOperand(Inst->getOperand(0))
837                                        .addOperand(Inst->getOperand(1));
838           Worklist.push_back(Copy);
839         } else {
840           // Otherwise, we need to split this into two movs, because there is
841           // no 64-bit VALU move instruction.
842           unsigned LoDst, HiDst, Dst;
843           LoDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
844           HiDst = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
845           Dst = MRI.createVirtualRegister(
846               MRI.getRegClass(Inst->getOperand(0).getReg()));
847
848           MachineInstr *Lo = BuildMI(*MBB, Inst, DL, get(AMDGPU::S_MOV_B32),
849                                      LoDst)
850                              .addImm(Inst->getOperand(1).getImm() & 0xFFFFFFFF);
851           MachineInstr *Hi = BuildMI(*MBB, Inst, DL, get(AMDGPU::S_MOV_B32),
852                                      HiDst)
853                                     .addImm(Inst->getOperand(1).getImm() >> 32);
854
855           BuildMI(*MBB, Inst, DL, get(TargetOpcode::REG_SEQUENCE), Dst)
856                   .addReg(LoDst)
857                   .addImm(AMDGPU::sub0)
858                   .addReg(HiDst)
859                   .addImm(AMDGPU::sub1);
860
861           MRI.replaceRegWith(Inst->getOperand(0).getReg(), Dst);
862           Worklist.push_back(Lo);
863           Worklist.push_back(Hi);
864         }
865         Inst->eraseFromParent();
866         continue;
867       }
868     }
869
870     unsigned NewOpcode = getVALUOp(*Inst);
871     if (NewOpcode == AMDGPU::INSTRUCTION_LIST_END) {
872       // We cannot move this instruction to the VALU, so we should try to
873       // legalize its operands instead.
874       legalizeOperands(Inst);
875       continue;
876     }
877
878     // Use the new VALU Opcode.
879     const MCInstrDesc &NewDesc = get(NewOpcode);
880     Inst->setDesc(NewDesc);
881
882     // Remove any references to SCC. Vector instructions can't read from it, and
883     // We're just about to add the implicit use / defs of VCC, and we don't want
884     // both.
885     for (unsigned i = Inst->getNumOperands() - 1; i > 0; --i) {
886       MachineOperand &Op = Inst->getOperand(i);
887       if (Op.isReg() && Op.getReg() == AMDGPU::SCC)
888         Inst->RemoveOperand(i);
889     }
890
891     // Add the implict and explicit register definitions.
892     if (NewDesc.ImplicitUses) {
893       for (unsigned i = 0; NewDesc.ImplicitUses[i]; ++i) {
894         unsigned Reg = NewDesc.ImplicitUses[i];
895         Inst->addOperand(MachineOperand::CreateReg(Reg, false, true));
896       }
897     }
898
899     if (NewDesc.ImplicitDefs) {
900       for (unsigned i = 0; NewDesc.ImplicitDefs[i]; ++i) {
901         unsigned Reg = NewDesc.ImplicitDefs[i];
902         Inst->addOperand(MachineOperand::CreateReg(Reg, true, true));
903       }
904     }
905
906     legalizeOperands(Inst);
907
908     // Update the destination register class.
909     const TargetRegisterClass *NewDstRC = getOpRegClass(*Inst, 0);
910
911     switch (Inst->getOpcode()) {
912       // For target instructions, getOpRegClass just returns the virtual
913       // register class associated with the operand, so we need to find an
914       // equivalent VGPR register class in order to move the instruction to the
915       // VALU.
916     case AMDGPU::COPY:
917     case AMDGPU::PHI:
918     case AMDGPU::REG_SEQUENCE:
919       if (RI.hasVGPRs(NewDstRC))
920         continue;
921       NewDstRC = RI.getEquivalentVGPRClass(NewDstRC);
922       if (!NewDstRC)
923         continue;
924       break;
925     default:
926       break;
927     }
928
929     unsigned DstReg = Inst->getOperand(0).getReg();
930     unsigned NewDstReg = MRI.createVirtualRegister(NewDstRC);
931     MRI.replaceRegWith(DstReg, NewDstReg);
932
933     for (MachineRegisterInfo::use_iterator I = MRI.use_begin(NewDstReg),
934            E = MRI.use_end(); I != E; ++I) {
935       MachineInstr &UseMI = *I->getParent();
936       if (!canReadVGPR(UseMI, I.getOperandNo())) {
937         Worklist.push_back(&UseMI);
938       }
939     }
940   }
941 }
942
943 //===----------------------------------------------------------------------===//
944 // Indirect addressing callbacks
945 //===----------------------------------------------------------------------===//
946
947 unsigned SIInstrInfo::calculateIndirectAddress(unsigned RegIndex,
948                                                  unsigned Channel) const {
949   assert(Channel == 0);
950   return RegIndex;
951 }
952
953 const TargetRegisterClass *SIInstrInfo::getIndirectAddrRegClass() const {
954   return &AMDGPU::VReg_32RegClass;
955 }
956
957 MachineInstrBuilder SIInstrInfo::buildIndirectWrite(
958                                    MachineBasicBlock *MBB,
959                                    MachineBasicBlock::iterator I,
960                                    unsigned ValueReg,
961                                    unsigned Address, unsigned OffsetReg) const {
962   const DebugLoc &DL = MBB->findDebugLoc(I);
963   unsigned IndirectBaseReg = AMDGPU::VReg_32RegClass.getRegister(
964                                       getIndirectIndexBegin(*MBB->getParent()));
965
966   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_DST_V1))
967           .addReg(IndirectBaseReg, RegState::Define)
968           .addOperand(I->getOperand(0))
969           .addReg(IndirectBaseReg)
970           .addReg(OffsetReg)
971           .addImm(0)
972           .addReg(ValueReg);
973 }
974
975 MachineInstrBuilder SIInstrInfo::buildIndirectRead(
976                                    MachineBasicBlock *MBB,
977                                    MachineBasicBlock::iterator I,
978                                    unsigned ValueReg,
979                                    unsigned Address, unsigned OffsetReg) const {
980   const DebugLoc &DL = MBB->findDebugLoc(I);
981   unsigned IndirectBaseReg = AMDGPU::VReg_32RegClass.getRegister(
982                                       getIndirectIndexBegin(*MBB->getParent()));
983
984   return BuildMI(*MBB, I, DL, get(AMDGPU::SI_INDIRECT_SRC))
985           .addOperand(I->getOperand(0))
986           .addOperand(I->getOperand(1))
987           .addReg(IndirectBaseReg)
988           .addReg(OffsetReg)
989           .addImm(0);
990
991 }
992
993 void SIInstrInfo::reserveIndirectRegisters(BitVector &Reserved,
994                                             const MachineFunction &MF) const {
995   int End = getIndirectIndexEnd(MF);
996   int Begin = getIndirectIndexBegin(MF);
997
998   if (End == -1)
999     return;
1000
1001
1002   for (int Index = Begin; Index <= End; ++Index)
1003     Reserved.set(AMDGPU::VReg_32RegClass.getRegister(Index));
1004
1005   for (int Index = std::max(0, Begin - 1); Index <= End; ++Index)
1006     Reserved.set(AMDGPU::VReg_64RegClass.getRegister(Index));
1007
1008   for (int Index = std::max(0, Begin - 2); Index <= End; ++Index)
1009     Reserved.set(AMDGPU::VReg_96RegClass.getRegister(Index));
1010
1011   for (int Index = std::max(0, Begin - 3); Index <= End; ++Index)
1012     Reserved.set(AMDGPU::VReg_128RegClass.getRegister(Index));
1013
1014   for (int Index = std::max(0, Begin - 7); Index <= End; ++Index)
1015     Reserved.set(AMDGPU::VReg_256RegClass.getRegister(Index));
1016
1017   for (int Index = std::max(0, Begin - 15); Index <= End; ++Index)
1018     Reserved.set(AMDGPU::VReg_512RegClass.getRegister(Index));
1019 }