R600: Always use texture cache for compute shaders
[oota-llvm.git] / lib / Target / R600 / R600InstrInfo.cpp
1 //===-- R600InstrInfo.cpp - R600 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 R600 Implementation of TargetInstrInfo.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "R600InstrInfo.h"
16 #include "AMDGPU.h"
17 #include "AMDGPUSubtarget.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "R600Defines.h"
20 #include "R600MachineFunctionInfo.h"
21 #include "R600RegisterInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25
26 #define GET_INSTRINFO_CTOR
27 #include "AMDGPUGenDFAPacketizer.inc"
28
29 using namespace llvm;
30
31 R600InstrInfo::R600InstrInfo(AMDGPUTargetMachine &tm)
32   : AMDGPUInstrInfo(tm),
33     RI(tm, *this),
34     ST(tm.getSubtarget<AMDGPUSubtarget>())
35   { }
36
37 const R600RegisterInfo &R600InstrInfo::getRegisterInfo() const {
38   return RI;
39 }
40
41 bool R600InstrInfo::isTrig(const MachineInstr &MI) const {
42   return get(MI.getOpcode()).TSFlags & R600_InstFlag::TRIG;
43 }
44
45 bool R600InstrInfo::isVector(const MachineInstr &MI) const {
46   return get(MI.getOpcode()).TSFlags & R600_InstFlag::VECTOR;
47 }
48
49 void
50 R600InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
51                            MachineBasicBlock::iterator MI, DebugLoc DL,
52                            unsigned DestReg, unsigned SrcReg,
53                            bool KillSrc) const {
54   if (AMDGPU::R600_Reg128RegClass.contains(DestReg)
55       && AMDGPU::R600_Reg128RegClass.contains(SrcReg)) {
56     for (unsigned I = 0; I < 4; I++) {
57       unsigned SubRegIndex = RI.getSubRegFromChannel(I);
58       buildDefaultInstruction(MBB, MI, AMDGPU::MOV,
59                               RI.getSubReg(DestReg, SubRegIndex),
60                               RI.getSubReg(SrcReg, SubRegIndex))
61                               .addReg(DestReg,
62                                       RegState::Define | RegState::Implicit);
63     }
64   } else {
65
66     // We can't copy vec4 registers
67     assert(!AMDGPU::R600_Reg128RegClass.contains(DestReg)
68            && !AMDGPU::R600_Reg128RegClass.contains(SrcReg));
69
70     MachineInstr *NewMI = buildDefaultInstruction(MBB, MI, AMDGPU::MOV,
71                                                   DestReg, SrcReg);
72     NewMI->getOperand(getOperandIdx(*NewMI, R600Operands::SRC0))
73                                     .setIsKill(KillSrc);
74   }
75 }
76
77 MachineInstr * R600InstrInfo::getMovImmInstr(MachineFunction *MF,
78                                              unsigned DstReg, int64_t Imm) const {
79   MachineInstr * MI = MF->CreateMachineInstr(get(AMDGPU::MOV), DebugLoc());
80   MachineInstrBuilder MIB(*MF, MI);
81   MIB.addReg(DstReg, RegState::Define);
82   MIB.addReg(AMDGPU::ALU_LITERAL_X);
83   MIB.addImm(Imm);
84   MIB.addReg(0); // PREDICATE_BIT
85
86   return MI;
87 }
88
89 unsigned R600InstrInfo::getIEQOpcode() const {
90   return AMDGPU::SETE_INT;
91 }
92
93 bool R600InstrInfo::isMov(unsigned Opcode) const {
94
95
96   switch(Opcode) {
97   default: return false;
98   case AMDGPU::MOV:
99   case AMDGPU::MOV_IMM_F32:
100   case AMDGPU::MOV_IMM_I32:
101     return true;
102   }
103 }
104
105 // Some instructions act as place holders to emulate operations that the GPU
106 // hardware does automatically. This function can be used to check if
107 // an opcode falls into this category.
108 bool R600InstrInfo::isPlaceHolderOpcode(unsigned Opcode) const {
109   switch (Opcode) {
110   default: return false;
111   case AMDGPU::RETURN:
112     return true;
113   }
114 }
115
116 bool R600InstrInfo::isReductionOp(unsigned Opcode) const {
117   switch(Opcode) {
118     default: return false;
119     case AMDGPU::DOT4_r600_pseudo:
120     case AMDGPU::DOT4_eg_pseudo:
121       return true;
122   }
123 }
124
125 bool R600InstrInfo::isCubeOp(unsigned Opcode) const {
126   switch(Opcode) {
127     default: return false;
128     case AMDGPU::CUBE_r600_pseudo:
129     case AMDGPU::CUBE_r600_real:
130     case AMDGPU::CUBE_eg_pseudo:
131     case AMDGPU::CUBE_eg_real:
132       return true;
133   }
134 }
135
136 bool R600InstrInfo::isALUInstr(unsigned Opcode) const {
137   unsigned TargetFlags = get(Opcode).TSFlags;
138
139   return ((TargetFlags & R600_InstFlag::OP1) |
140           (TargetFlags & R600_InstFlag::OP2) |
141           (TargetFlags & R600_InstFlag::OP3));
142 }
143
144 bool R600InstrInfo::isTransOnly(unsigned Opcode) const {
145   return (get(Opcode).TSFlags & R600_InstFlag::TRANS_ONLY);
146 }
147
148 bool R600InstrInfo::isTransOnly(const MachineInstr *MI) const {
149   return isTransOnly(MI->getOpcode());
150 }
151
152 bool R600InstrInfo::usesVertexCache(unsigned Opcode) const {
153   return ST.hasVertexCache() && get(Opcode).TSFlags & R600_InstFlag::VTX_INST;
154 }
155
156 bool R600InstrInfo::usesVertexCache(const MachineInstr *MI) const {
157   const R600MachineFunctionInfo *MFI = MI->getParent()->getParent()->getInfo<R600MachineFunctionInfo>();
158   return MFI->ShaderType != ShaderType::COMPUTE && usesVertexCache(MI->getOpcode());
159 }
160
161 bool R600InstrInfo::usesTextureCache(unsigned Opcode) const {
162   return (!ST.hasVertexCache() && get(Opcode).TSFlags & R600_InstFlag::VTX_INST) ||
163       (get(Opcode).TSFlags & R600_InstFlag::TEX_INST);
164 }
165
166 bool R600InstrInfo::usesTextureCache(const MachineInstr *MI) const {
167   const R600MachineFunctionInfo *MFI = MI->getParent()->getParent()->getInfo<R600MachineFunctionInfo>();
168   return (MFI->ShaderType == ShaderType::COMPUTE && usesVertexCache(MI->getOpcode())) ||
169          usesTextureCache(MI->getOpcode());
170 }
171
172 bool
173 R600InstrInfo::fitsConstReadLimitations(const std::vector<unsigned> &Consts)
174     const {
175   assert (Consts.size() <= 12 && "Too many operands in instructions group");
176   unsigned Pair1 = 0, Pair2 = 0;
177   for (unsigned i = 0, n = Consts.size(); i < n; ++i) {
178     unsigned ReadConstHalf = Consts[i] & 2;
179     unsigned ReadConstIndex = Consts[i] & (~3);
180     unsigned ReadHalfConst = ReadConstIndex | ReadConstHalf;
181     if (!Pair1) {
182       Pair1 = ReadHalfConst;
183       continue;
184     }
185     if (Pair1 == ReadHalfConst)
186       continue;
187     if (!Pair2) {
188       Pair2 = ReadHalfConst;
189       continue;
190     }
191     if (Pair2 != ReadHalfConst)
192       return false;
193   }
194   return true;
195 }
196
197 bool
198 R600InstrInfo::canBundle(const std::vector<MachineInstr *> &MIs) const {
199   std::vector<unsigned> Consts;
200   for (unsigned i = 0, n = MIs.size(); i < n; i++) {
201     const MachineInstr *MI = MIs[i];
202
203     const R600Operands::Ops OpTable[3][2] = {
204       {R600Operands::SRC0, R600Operands::SRC0_SEL},
205       {R600Operands::SRC1, R600Operands::SRC1_SEL},
206       {R600Operands::SRC2, R600Operands::SRC2_SEL},
207     };
208
209     if (!isALUInstr(MI->getOpcode()))
210       continue;
211
212     for (unsigned j = 0; j < 3; j++) {
213       int SrcIdx = getOperandIdx(MI->getOpcode(), OpTable[j][0]);
214       if (SrcIdx < 0)
215         break;
216       unsigned Reg = MI->getOperand(SrcIdx).getReg();
217       if (Reg == AMDGPU::ALU_CONST) {
218         unsigned Const = MI->getOperand(
219             getOperandIdx(MI->getOpcode(), OpTable[j][1])).getImm();
220         Consts.push_back(Const);
221         continue;
222       }
223       if (AMDGPU::R600_KC0RegClass.contains(Reg) ||
224           AMDGPU::R600_KC1RegClass.contains(Reg)) {
225         unsigned Index = RI.getEncodingValue(Reg) & 0xff;
226         unsigned Chan = RI.getHWRegChan(Reg);
227         Consts.push_back((Index << 2) | Chan);
228         continue;
229       }
230     }
231   }
232   return fitsConstReadLimitations(Consts);
233 }
234
235 DFAPacketizer *R600InstrInfo::CreateTargetScheduleState(const TargetMachine *TM,
236     const ScheduleDAG *DAG) const {
237   const InstrItineraryData *II = TM->getInstrItineraryData();
238   return TM->getSubtarget<AMDGPUSubtarget>().createDFAPacketizer(II);
239 }
240
241 static bool
242 isPredicateSetter(unsigned Opcode) {
243   switch (Opcode) {
244   case AMDGPU::PRED_X:
245     return true;
246   default:
247     return false;
248   }
249 }
250
251 static MachineInstr *
252 findFirstPredicateSetterFrom(MachineBasicBlock &MBB,
253                              MachineBasicBlock::iterator I) {
254   while (I != MBB.begin()) {
255     --I;
256     MachineInstr *MI = I;
257     if (isPredicateSetter(MI->getOpcode()))
258       return MI;
259   }
260
261   return NULL;
262 }
263
264 static
265 bool isJump(unsigned Opcode) {
266   return Opcode == AMDGPU::JUMP || Opcode == AMDGPU::JUMP_COND;
267 }
268
269 bool
270 R600InstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
271                              MachineBasicBlock *&TBB,
272                              MachineBasicBlock *&FBB,
273                              SmallVectorImpl<MachineOperand> &Cond,
274                              bool AllowModify) const {
275   // Most of the following comes from the ARM implementation of AnalyzeBranch
276
277   // If the block has no terminators, it just falls into the block after it.
278   MachineBasicBlock::iterator I = MBB.end();
279   if (I == MBB.begin())
280     return false;
281   --I;
282   while (I->isDebugValue()) {
283     if (I == MBB.begin())
284       return false;
285     --I;
286   }
287   if (!isJump(static_cast<MachineInstr *>(I)->getOpcode())) {
288     return false;
289   }
290
291   // Get the last instruction in the block.
292   MachineInstr *LastInst = I;
293
294   // If there is only one terminator instruction, process it.
295   unsigned LastOpc = LastInst->getOpcode();
296   if (I == MBB.begin() ||
297           !isJump(static_cast<MachineInstr *>(--I)->getOpcode())) {
298     if (LastOpc == AMDGPU::JUMP) {
299       TBB = LastInst->getOperand(0).getMBB();
300       return false;
301     } else if (LastOpc == AMDGPU::JUMP_COND) {
302       MachineInstr *predSet = I;
303       while (!isPredicateSetter(predSet->getOpcode())) {
304         predSet = --I;
305       }
306       TBB = LastInst->getOperand(0).getMBB();
307       Cond.push_back(predSet->getOperand(1));
308       Cond.push_back(predSet->getOperand(2));
309       Cond.push_back(MachineOperand::CreateReg(AMDGPU::PRED_SEL_ONE, false));
310       return false;
311     }
312     return true;  // Can't handle indirect branch.
313   }
314
315   // Get the instruction before it if it is a terminator.
316   MachineInstr *SecondLastInst = I;
317   unsigned SecondLastOpc = SecondLastInst->getOpcode();
318
319   // If the block ends with a B and a Bcc, handle it.
320   if (SecondLastOpc == AMDGPU::JUMP_COND && LastOpc == AMDGPU::JUMP) {
321     MachineInstr *predSet = --I;
322     while (!isPredicateSetter(predSet->getOpcode())) {
323       predSet = --I;
324     }
325     TBB = SecondLastInst->getOperand(0).getMBB();
326     FBB = LastInst->getOperand(0).getMBB();
327     Cond.push_back(predSet->getOperand(1));
328     Cond.push_back(predSet->getOperand(2));
329     Cond.push_back(MachineOperand::CreateReg(AMDGPU::PRED_SEL_ONE, false));
330     return false;
331   }
332
333   // Otherwise, can't handle this.
334   return true;
335 }
336
337 int R600InstrInfo::getBranchInstr(const MachineOperand &op) const {
338   const MachineInstr *MI = op.getParent();
339
340   switch (MI->getDesc().OpInfo->RegClass) {
341   default: // FIXME: fallthrough??
342   case AMDGPU::GPRI32RegClassID: return AMDGPU::BRANCH_COND_i32;
343   case AMDGPU::GPRF32RegClassID: return AMDGPU::BRANCH_COND_f32;
344   };
345 }
346
347 unsigned
348 R600InstrInfo::InsertBranch(MachineBasicBlock &MBB,
349                             MachineBasicBlock *TBB,
350                             MachineBasicBlock *FBB,
351                             const SmallVectorImpl<MachineOperand> &Cond,
352                             DebugLoc DL) const {
353   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
354
355   if (FBB == 0) {
356     if (Cond.empty()) {
357       BuildMI(&MBB, DL, get(AMDGPU::JUMP)).addMBB(TBB);
358       return 1;
359     } else {
360       MachineInstr *PredSet = findFirstPredicateSetterFrom(MBB, MBB.end());
361       assert(PredSet && "No previous predicate !");
362       addFlag(PredSet, 0, MO_FLAG_PUSH);
363       PredSet->getOperand(2).setImm(Cond[1].getImm());
364
365       BuildMI(&MBB, DL, get(AMDGPU::JUMP_COND))
366              .addMBB(TBB)
367              .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
368       return 1;
369     }
370   } else {
371     MachineInstr *PredSet = findFirstPredicateSetterFrom(MBB, MBB.end());
372     assert(PredSet && "No previous predicate !");
373     addFlag(PredSet, 0, MO_FLAG_PUSH);
374     PredSet->getOperand(2).setImm(Cond[1].getImm());
375     BuildMI(&MBB, DL, get(AMDGPU::JUMP_COND))
376             .addMBB(TBB)
377             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
378     BuildMI(&MBB, DL, get(AMDGPU::JUMP)).addMBB(FBB);
379     return 2;
380   }
381 }
382
383 unsigned
384 R600InstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
385
386   // Note : we leave PRED* instructions there.
387   // They may be needed when predicating instructions.
388
389   MachineBasicBlock::iterator I = MBB.end();
390
391   if (I == MBB.begin()) {
392     return 0;
393   }
394   --I;
395   switch (I->getOpcode()) {
396   default:
397     return 0;
398   case AMDGPU::JUMP_COND: {
399     MachineInstr *predSet = findFirstPredicateSetterFrom(MBB, I);
400     clearFlag(predSet, 0, MO_FLAG_PUSH);
401     I->eraseFromParent();
402     break;
403   }
404   case AMDGPU::JUMP:
405     I->eraseFromParent();
406     break;
407   }
408   I = MBB.end();
409
410   if (I == MBB.begin()) {
411     return 1;
412   }
413   --I;
414   switch (I->getOpcode()) {
415     // FIXME: only one case??
416   default:
417     return 1;
418   case AMDGPU::JUMP_COND: {
419     MachineInstr *predSet = findFirstPredicateSetterFrom(MBB, I);
420     clearFlag(predSet, 0, MO_FLAG_PUSH);
421     I->eraseFromParent();
422     break;
423   }
424   case AMDGPU::JUMP:
425     I->eraseFromParent();
426     break;
427   }
428   return 2;
429 }
430
431 bool
432 R600InstrInfo::isPredicated(const MachineInstr *MI) const {
433   int idx = MI->findFirstPredOperandIdx();
434   if (idx < 0)
435     return false;
436
437   unsigned Reg = MI->getOperand(idx).getReg();
438   switch (Reg) {
439   default: return false;
440   case AMDGPU::PRED_SEL_ONE:
441   case AMDGPU::PRED_SEL_ZERO:
442   case AMDGPU::PREDICATE_BIT:
443     return true;
444   }
445 }
446
447 bool
448 R600InstrInfo::isPredicable(MachineInstr *MI) const {
449   // XXX: KILL* instructions can be predicated, but they must be the last
450   // instruction in a clause, so this means any instructions after them cannot
451   // be predicated.  Until we have proper support for instruction clauses in the
452   // backend, we will mark KILL* instructions as unpredicable.
453
454   if (MI->getOpcode() == AMDGPU::KILLGT) {
455     return false;
456   } else if (isVector(*MI)) {
457     return false;
458   } else {
459     return AMDGPUInstrInfo::isPredicable(MI);
460   }
461 }
462
463
464 bool
465 R600InstrInfo::isProfitableToIfCvt(MachineBasicBlock &MBB,
466                                    unsigned NumCyles,
467                                    unsigned ExtraPredCycles,
468                                    const BranchProbability &Probability) const{
469   return true;
470 }
471
472 bool
473 R600InstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
474                                    unsigned NumTCycles,
475                                    unsigned ExtraTCycles,
476                                    MachineBasicBlock &FMBB,
477                                    unsigned NumFCycles,
478                                    unsigned ExtraFCycles,
479                                    const BranchProbability &Probability) const {
480   return true;
481 }
482
483 bool
484 R600InstrInfo::isProfitableToDupForIfCvt(MachineBasicBlock &MBB,
485                                          unsigned NumCyles,
486                                          const BranchProbability &Probability)
487                                          const {
488   return true;
489 }
490
491 bool
492 R600InstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
493                                          MachineBasicBlock &FMBB) const {
494   return false;
495 }
496
497
498 bool
499 R600InstrInfo::ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
500   MachineOperand &MO = Cond[1];
501   switch (MO.getImm()) {
502   case OPCODE_IS_ZERO_INT:
503     MO.setImm(OPCODE_IS_NOT_ZERO_INT);
504     break;
505   case OPCODE_IS_NOT_ZERO_INT:
506     MO.setImm(OPCODE_IS_ZERO_INT);
507     break;
508   case OPCODE_IS_ZERO:
509     MO.setImm(OPCODE_IS_NOT_ZERO);
510     break;
511   case OPCODE_IS_NOT_ZERO:
512     MO.setImm(OPCODE_IS_ZERO);
513     break;
514   default:
515     return true;
516   }
517
518   MachineOperand &MO2 = Cond[2];
519   switch (MO2.getReg()) {
520   case AMDGPU::PRED_SEL_ZERO:
521     MO2.setReg(AMDGPU::PRED_SEL_ONE);
522     break;
523   case AMDGPU::PRED_SEL_ONE:
524     MO2.setReg(AMDGPU::PRED_SEL_ZERO);
525     break;
526   default:
527     return true;
528   }
529   return false;
530 }
531
532 bool
533 R600InstrInfo::DefinesPredicate(MachineInstr *MI,
534                                 std::vector<MachineOperand> &Pred) const {
535   return isPredicateSetter(MI->getOpcode());
536 }
537
538
539 bool
540 R600InstrInfo::SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
541                        const SmallVectorImpl<MachineOperand> &Pred2) const {
542   return false;
543 }
544
545
546 bool
547 R600InstrInfo::PredicateInstruction(MachineInstr *MI,
548                       const SmallVectorImpl<MachineOperand> &Pred) const {
549   int PIdx = MI->findFirstPredOperandIdx();
550
551   if (PIdx != -1) {
552     MachineOperand &PMO = MI->getOperand(PIdx);
553     PMO.setReg(Pred[2].getReg());
554     MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
555     MIB.addReg(AMDGPU::PREDICATE_BIT, RegState::Implicit);
556     return true;
557   }
558
559   return false;
560 }
561
562 unsigned int R600InstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
563                                             const MachineInstr *MI,
564                                             unsigned *PredCost) const {
565   if (PredCost)
566     *PredCost = 2;
567   return 2;
568 }
569
570 int R600InstrInfo::getIndirectIndexBegin(const MachineFunction &MF) const {
571   const MachineRegisterInfo &MRI = MF.getRegInfo();
572   const MachineFrameInfo *MFI = MF.getFrameInfo();
573   int Offset = 0;
574
575   if (MFI->getNumObjects() == 0) {
576     return -1;
577   }
578
579   if (MRI.livein_empty()) {
580     return 0;
581   }
582
583   for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
584                                             LE = MRI.livein_end();
585                                             LI != LE; ++LI) {
586     Offset = std::max(Offset,
587                       GET_REG_INDEX(RI.getEncodingValue(LI->first)));
588   }
589
590   return Offset + 1;
591 }
592
593 int R600InstrInfo::getIndirectIndexEnd(const MachineFunction &MF) const {
594   int Offset = 0;
595   const MachineFrameInfo *MFI = MF.getFrameInfo();
596
597   // Variable sized objects are not supported
598   assert(!MFI->hasVarSizedObjects());
599
600   if (MFI->getNumObjects() == 0) {
601     return -1;
602   }
603
604   Offset = TM.getFrameLowering()->getFrameIndexOffset(MF, -1);
605
606   return getIndirectIndexBegin(MF) + Offset;
607 }
608
609 std::vector<unsigned> R600InstrInfo::getIndirectReservedRegs(
610                                              const MachineFunction &MF) const {
611   const AMDGPUFrameLowering *TFL =
612                  static_cast<const AMDGPUFrameLowering*>(TM.getFrameLowering());
613   std::vector<unsigned> Regs;
614
615   unsigned StackWidth = TFL->getStackWidth(MF);
616   int End = getIndirectIndexEnd(MF);
617
618   if (End == -1) {
619     return Regs;
620   }
621
622   for (int Index = getIndirectIndexBegin(MF); Index <= End; ++Index) {
623     unsigned SuperReg = AMDGPU::R600_Reg128RegClass.getRegister(Index);
624     Regs.push_back(SuperReg);
625     for (unsigned Chan = 0; Chan < StackWidth; ++Chan) {
626       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister((4 * Index) + Chan);
627       Regs.push_back(Reg);
628     }
629   }
630   return Regs;
631 }
632
633 unsigned R600InstrInfo::calculateIndirectAddress(unsigned RegIndex,
634                                                  unsigned Channel) const {
635   // XXX: Remove when we support a stack width > 2
636   assert(Channel == 0);
637   return RegIndex;
638 }
639
640 const TargetRegisterClass * R600InstrInfo::getIndirectAddrStoreRegClass(
641                                                      unsigned SourceReg) const {
642   return &AMDGPU::R600_TReg32RegClass;
643 }
644
645 const TargetRegisterClass *R600InstrInfo::getIndirectAddrLoadRegClass() const {
646   return &AMDGPU::TRegMemRegClass;
647 }
648
649 MachineInstrBuilder R600InstrInfo::buildIndirectWrite(MachineBasicBlock *MBB,
650                                        MachineBasicBlock::iterator I,
651                                        unsigned ValueReg, unsigned Address,
652                                        unsigned OffsetReg) const {
653   unsigned AddrReg = AMDGPU::R600_AddrRegClass.getRegister(Address);
654   MachineInstr *MOVA = buildDefaultInstruction(*MBB, I, AMDGPU::MOVA_INT_eg,
655                                                AMDGPU::AR_X, OffsetReg);
656   setImmOperand(MOVA, R600Operands::WRITE, 0);
657
658   MachineInstrBuilder Mov = buildDefaultInstruction(*MBB, I, AMDGPU::MOV,
659                                       AddrReg, ValueReg)
660                                       .addReg(AMDGPU::AR_X, RegState::Implicit);
661   setImmOperand(Mov, R600Operands::DST_REL, 1);
662   return Mov;
663 }
664
665 MachineInstrBuilder R600InstrInfo::buildIndirectRead(MachineBasicBlock *MBB,
666                                        MachineBasicBlock::iterator I,
667                                        unsigned ValueReg, unsigned Address,
668                                        unsigned OffsetReg) const {
669   unsigned AddrReg = AMDGPU::R600_AddrRegClass.getRegister(Address);
670   MachineInstr *MOVA = buildDefaultInstruction(*MBB, I, AMDGPU::MOVA_INT_eg,
671                                                        AMDGPU::AR_X,
672                                                        OffsetReg);
673   setImmOperand(MOVA, R600Operands::WRITE, 0);
674   MachineInstrBuilder Mov = buildDefaultInstruction(*MBB, I, AMDGPU::MOV,
675                                       ValueReg,
676                                       AddrReg)
677                                       .addReg(AMDGPU::AR_X, RegState::Implicit);
678   setImmOperand(Mov, R600Operands::SRC0_REL, 1);
679
680   return Mov;
681 }
682
683 const TargetRegisterClass *R600InstrInfo::getSuperIndirectRegClass() const {
684   return &AMDGPU::IndirectRegRegClass;
685 }
686
687 unsigned R600InstrInfo::getMaxAlusPerClause() const {
688   return 115;
689 }
690
691 MachineInstrBuilder R600InstrInfo::buildDefaultInstruction(MachineBasicBlock &MBB,
692                                                   MachineBasicBlock::iterator I,
693                                                   unsigned Opcode,
694                                                   unsigned DstReg,
695                                                   unsigned Src0Reg,
696                                                   unsigned Src1Reg) const {
697   MachineInstrBuilder MIB = BuildMI(MBB, I, MBB.findDebugLoc(I), get(Opcode),
698     DstReg);           // $dst
699
700   if (Src1Reg) {
701     MIB.addImm(0)     // $update_exec_mask
702        .addImm(0);    // $update_predicate
703   }
704   MIB.addImm(1)        // $write
705      .addImm(0)        // $omod
706      .addImm(0)        // $dst_rel
707      .addImm(0)        // $dst_clamp
708      .addReg(Src0Reg)  // $src0
709      .addImm(0)        // $src0_neg
710      .addImm(0)        // $src0_rel
711      .addImm(0)        // $src0_abs
712      .addImm(-1);       // $src0_sel
713
714   if (Src1Reg) {
715     MIB.addReg(Src1Reg) // $src1
716        .addImm(0)       // $src1_neg
717        .addImm(0)       // $src1_rel
718        .addImm(0)       // $src1_abs
719        .addImm(-1);      // $src1_sel
720   }
721
722   //XXX: The r600g finalizer expects this to be 1, once we've moved the
723   //scheduling to the backend, we can change the default to 0.
724   MIB.addImm(1)        // $last
725       .addReg(AMDGPU::PRED_SEL_OFF) // $pred_sel
726       .addImm(0)         // $literal
727       .addImm(0);        // $bank_swizzle
728
729   return MIB;
730 }
731
732 MachineInstr *R600InstrInfo::buildMovImm(MachineBasicBlock &BB,
733                                          MachineBasicBlock::iterator I,
734                                          unsigned DstReg,
735                                          uint64_t Imm) const {
736   MachineInstr *MovImm = buildDefaultInstruction(BB, I, AMDGPU::MOV, DstReg,
737                                                   AMDGPU::ALU_LITERAL_X);
738   setImmOperand(MovImm, R600Operands::IMM, Imm);
739   return MovImm;
740 }
741
742 int R600InstrInfo::getOperandIdx(const MachineInstr &MI,
743                                  R600Operands::Ops Op) const {
744   return getOperandIdx(MI.getOpcode(), Op);
745 }
746
747 int R600InstrInfo::getOperandIdx(unsigned Opcode,
748                                  R600Operands::Ops Op) const {
749   unsigned TargetFlags = get(Opcode).TSFlags;
750   unsigned OpTableIdx;
751
752   if (!HAS_NATIVE_OPERANDS(TargetFlags)) {
753     switch (Op) {
754     case R600Operands::DST: return 0;
755     case R600Operands::SRC0: return 1;
756     case R600Operands::SRC1: return 2;
757     case R600Operands::SRC2: return 3;
758     default:
759       assert(!"Unknown operand type for instruction");
760       return -1;
761     }
762   }
763
764   if (TargetFlags & R600_InstFlag::OP1) {
765     OpTableIdx = 0;
766   } else if (TargetFlags & R600_InstFlag::OP2) {
767     OpTableIdx = 1;
768   } else {
769     assert((TargetFlags & R600_InstFlag::OP3) && "OP1, OP2, or OP3 not defined "
770                                                  "for this instruction");
771     OpTableIdx = 2;
772   }
773
774   return R600Operands::ALUOpTable[OpTableIdx][Op];
775 }
776
777 void R600InstrInfo::setImmOperand(MachineInstr *MI, R600Operands::Ops Op,
778                                   int64_t Imm) const {
779   int Idx = getOperandIdx(*MI, Op);
780   assert(Idx != -1 && "Operand not supported for this instruction.");
781   assert(MI->getOperand(Idx).isImm());
782   MI->getOperand(Idx).setImm(Imm);
783 }
784
785 //===----------------------------------------------------------------------===//
786 // Instruction flag getters/setters
787 //===----------------------------------------------------------------------===//
788
789 bool R600InstrInfo::hasFlagOperand(const MachineInstr &MI) const {
790   return GET_FLAG_OPERAND_IDX(get(MI.getOpcode()).TSFlags) != 0;
791 }
792
793 MachineOperand &R600InstrInfo::getFlagOp(MachineInstr *MI, unsigned SrcIdx,
794                                          unsigned Flag) const {
795   unsigned TargetFlags = get(MI->getOpcode()).TSFlags;
796   int FlagIndex = 0;
797   if (Flag != 0) {
798     // If we pass something other than the default value of Flag to this
799     // function, it means we are want to set a flag on an instruction
800     // that uses native encoding.
801     assert(HAS_NATIVE_OPERANDS(TargetFlags));
802     bool IsOP3 = (TargetFlags & R600_InstFlag::OP3) == R600_InstFlag::OP3;
803     switch (Flag) {
804     case MO_FLAG_CLAMP:
805       FlagIndex = getOperandIdx(*MI, R600Operands::CLAMP);
806       break;
807     case MO_FLAG_MASK:
808       FlagIndex = getOperandIdx(*MI, R600Operands::WRITE);
809       break;
810     case MO_FLAG_NOT_LAST:
811     case MO_FLAG_LAST:
812       FlagIndex = getOperandIdx(*MI, R600Operands::LAST);
813       break;
814     case MO_FLAG_NEG:
815       switch (SrcIdx) {
816       case 0: FlagIndex = getOperandIdx(*MI, R600Operands::SRC0_NEG); break;
817       case 1: FlagIndex = getOperandIdx(*MI, R600Operands::SRC1_NEG); break;
818       case 2: FlagIndex = getOperandIdx(*MI, R600Operands::SRC2_NEG); break;
819       }
820       break;
821
822     case MO_FLAG_ABS:
823       assert(!IsOP3 && "Cannot set absolute value modifier for OP3 "
824                        "instructions.");
825       (void)IsOP3;
826       switch (SrcIdx) {
827       case 0: FlagIndex = getOperandIdx(*MI, R600Operands::SRC0_ABS); break;
828       case 1: FlagIndex = getOperandIdx(*MI, R600Operands::SRC1_ABS); break;
829       }
830       break;
831
832     default:
833       FlagIndex = -1;
834       break;
835     }
836     assert(FlagIndex != -1 && "Flag not supported for this instruction");
837   } else {
838       FlagIndex = GET_FLAG_OPERAND_IDX(TargetFlags);
839       assert(FlagIndex != 0 &&
840          "Instruction flags not supported for this instruction");
841   }
842
843   MachineOperand &FlagOp = MI->getOperand(FlagIndex);
844   assert(FlagOp.isImm());
845   return FlagOp;
846 }
847
848 void R600InstrInfo::addFlag(MachineInstr *MI, unsigned Operand,
849                             unsigned Flag) const {
850   unsigned TargetFlags = get(MI->getOpcode()).TSFlags;
851   if (Flag == 0) {
852     return;
853   }
854   if (HAS_NATIVE_OPERANDS(TargetFlags)) {
855     MachineOperand &FlagOp = getFlagOp(MI, Operand, Flag);
856     if (Flag == MO_FLAG_NOT_LAST) {
857       clearFlag(MI, Operand, MO_FLAG_LAST);
858     } else if (Flag == MO_FLAG_MASK) {
859       clearFlag(MI, Operand, Flag);
860     } else {
861       FlagOp.setImm(1);
862     }
863   } else {
864       MachineOperand &FlagOp = getFlagOp(MI, Operand);
865       FlagOp.setImm(FlagOp.getImm() | (Flag << (NUM_MO_FLAGS * Operand)));
866   }
867 }
868
869 void R600InstrInfo::clearFlag(MachineInstr *MI, unsigned Operand,
870                               unsigned Flag) const {
871   unsigned TargetFlags = get(MI->getOpcode()).TSFlags;
872   if (HAS_NATIVE_OPERANDS(TargetFlags)) {
873     MachineOperand &FlagOp = getFlagOp(MI, Operand, Flag);
874     FlagOp.setImm(0);
875   } else {
876     MachineOperand &FlagOp = getFlagOp(MI);
877     unsigned InstFlags = FlagOp.getImm();
878     InstFlags &= ~(Flag << (NUM_MO_FLAGS * Operand));
879     FlagOp.setImm(InstFlags);
880   }
881 }