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