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