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