R600/SI: Choose the correct MOV instruction for copying immediates
[oota-llvm.git] / lib / Target / R600 / AMDGPUISelDAGToDAG.cpp
1 //===-- AMDILISelDAGToDAG.cpp - A dag to dag inst selector for AMDIL ------===//
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 Defines an instruction selector for the AMDGPU target.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "AMDGPUInstrInfo.h"
15 #include "AMDGPUISelLowering.h" // For AMDGPUISD
16 #include "AMDGPURegisterInfo.h"
17 #include "R600InstrInfo.h"
18 #include "SIISelLowering.h"
19 #include "llvm/ADT/ValueMap.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/PseudoSourceValue.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/Support/Compiler.h"
26 #include <list>
27 #include <queue>
28
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 // Instruction Selector Implementation
33 //===----------------------------------------------------------------------===//
34
35 namespace {
36 /// AMDGPU specific code to select AMDGPU machine instructions for
37 /// SelectionDAG operations.
38 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
39   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
40   // make the right decision when generating code for different targets.
41   const AMDGPUSubtarget &Subtarget;
42 public:
43   AMDGPUDAGToDAGISel(TargetMachine &TM);
44   virtual ~AMDGPUDAGToDAGISel();
45
46   SDNode *Select(SDNode *N);
47   virtual const char *getPassName() const;
48   virtual void PostprocessISelDAG();
49
50 private:
51   inline SDValue getSmallIPtrImm(unsigned Imm);
52   bool FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg, SDValue &Abs,
53                    const R600InstrInfo *TII);
54   bool FoldOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
55   bool FoldDotOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
56
57   // Complex pattern selectors
58   bool SelectADDRParam(SDValue Addr, SDValue& R1, SDValue& R2);
59   bool SelectADDR(SDValue N, SDValue &R1, SDValue &R2);
60   bool SelectADDR64(SDValue N, SDValue &R1, SDValue &R2);
61   SDValue SimplifyI24(SDValue &Op);
62   bool SelectI24(SDValue Addr, SDValue &Op);
63   bool SelectU24(SDValue Addr, SDValue &Op);
64
65   static bool checkType(const Value *ptr, unsigned int addrspace);
66
67   static bool isGlobalStore(const StoreSDNode *N);
68   static bool isPrivateStore(const StoreSDNode *N);
69   static bool isLocalStore(const StoreSDNode *N);
70   static bool isRegionStore(const StoreSDNode *N);
71
72   bool isCPLoad(const LoadSDNode *N) const;
73   bool isConstantLoad(const LoadSDNode *N, int cbID) const;
74   bool isGlobalLoad(const LoadSDNode *N) const;
75   bool isParamLoad(const LoadSDNode *N) const;
76   bool isPrivateLoad(const LoadSDNode *N) const;
77   bool isLocalLoad(const LoadSDNode *N) const;
78   bool isRegionLoad(const LoadSDNode *N) const;
79
80   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
81   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
82   bool SelectGlobalValueVariableOffset(SDValue Addr,
83       SDValue &BaseReg, SDValue& Offset);
84   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
85   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
86
87   // Include the pieces autogenerated from the target description.
88 #include "AMDGPUGenDAGISel.inc"
89 };
90 }  // end anonymous namespace
91
92 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
93 // DAG, ready for instruction scheduling.
94 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM
95                                        ) {
96   return new AMDGPUDAGToDAGISel(TM);
97 }
98
99 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
100   : SelectionDAGISel(TM), Subtarget(TM.getSubtarget<AMDGPUSubtarget>()) {
101 }
102
103 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
104 }
105
106 /// \brief Determine the register class for \p OpNo
107 /// \returns The register class of the virtual register that will be used for
108 /// the given operand number \OpNo or NULL if the register class cannot be
109 /// determined.
110 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
111                                                           unsigned OpNo) const {
112   if (!N->isMachineOpcode()) {
113     return NULL;
114   }
115   switch (N->getMachineOpcode()) {
116   default: {
117     const MCInstrDesc &Desc = TM.getInstrInfo()->get(N->getMachineOpcode());
118     int RegClass = Desc.OpInfo[Desc.getNumDefs() + OpNo].RegClass;
119     if (RegClass == -1) {
120       return NULL;
121     }
122     return TM.getRegisterInfo()->getRegClass(RegClass);
123   }
124   case AMDGPU::REG_SEQUENCE: {
125     const TargetRegisterClass *SuperRC = TM.getRegisterInfo()->getRegClass(
126                       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
127     unsigned SubRegIdx =
128             dyn_cast<ConstantSDNode>(N->getOperand(OpNo + 1))->getZExtValue();
129     return TM.getRegisterInfo()->getSubClassWithSubReg(SuperRC, SubRegIdx);
130   }
131   }
132 }
133
134 SDValue AMDGPUDAGToDAGISel::getSmallIPtrImm(unsigned int Imm) {
135   return CurDAG->getTargetConstant(Imm, MVT::i32);
136 }
137
138 bool AMDGPUDAGToDAGISel::SelectADDRParam(
139     SDValue Addr, SDValue& R1, SDValue& R2) {
140
141   if (Addr.getOpcode() == ISD::FrameIndex) {
142     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
143       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
144       R2 = CurDAG->getTargetConstant(0, MVT::i32);
145     } else {
146       R1 = Addr;
147       R2 = CurDAG->getTargetConstant(0, MVT::i32);
148     }
149   } else if (Addr.getOpcode() == ISD::ADD) {
150     R1 = Addr.getOperand(0);
151     R2 = Addr.getOperand(1);
152   } else {
153     R1 = Addr;
154     R2 = CurDAG->getTargetConstant(0, MVT::i32);
155   }
156   return true;
157 }
158
159 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
160   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
161       Addr.getOpcode() == ISD::TargetGlobalAddress) {
162     return false;
163   }
164   return SelectADDRParam(Addr, R1, R2);
165 }
166
167
168 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
169   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
170       Addr.getOpcode() == ISD::TargetGlobalAddress) {
171     return false;
172   }
173
174   if (Addr.getOpcode() == ISD::FrameIndex) {
175     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
176       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
177       R2 = CurDAG->getTargetConstant(0, MVT::i64);
178     } else {
179       R1 = Addr;
180       R2 = CurDAG->getTargetConstant(0, MVT::i64);
181     }
182   } else if (Addr.getOpcode() == ISD::ADD) {
183     R1 = Addr.getOperand(0);
184     R2 = Addr.getOperand(1);
185   } else {
186     R1 = Addr;
187     R2 = CurDAG->getTargetConstant(0, MVT::i64);
188   }
189   return true;
190 }
191
192 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
193   const R600InstrInfo *TII =
194                       static_cast<const R600InstrInfo*>(TM.getInstrInfo());
195   unsigned int Opc = N->getOpcode();
196   if (N->isMachineOpcode()) {
197     return NULL;   // Already selected.
198   }
199   switch (Opc) {
200   default: break;
201   case AMDGPUISD::CONST_ADDRESS: {
202     for (SDNode::use_iterator I = N->use_begin(), Next = llvm::next(I);
203                               I != SDNode::use_end(); I = Next) {
204       Next = llvm::next(I);
205       if (!I->isMachineOpcode()) {
206         continue;
207       }
208       unsigned Opcode = I->getMachineOpcode();
209       bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
210       int SrcIdx = I.getOperandNo();
211       int SelIdx;
212       // Unlike MachineInstrs, SDNodes do not have results in their operand
213       // list, so we need to increment the SrcIdx, since
214       // R600InstrInfo::getOperandIdx is based on the MachineInstr indices.
215       if (HasDst) {
216         SrcIdx++;
217       }
218
219       SelIdx = TII->getSelIdx(I->getMachineOpcode(), SrcIdx);
220       if (SelIdx < 0) {
221         continue;
222       }
223
224       SDValue CstOffset;
225       if (N->getValueType(0).isVector() ||
226           !SelectGlobalValueConstantOffset(N->getOperand(0), CstOffset))
227         continue;
228
229       // Gather constants values
230       int SrcIndices[] = {
231         TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
232         TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
233         TII->getOperandIdx(Opcode, AMDGPU::OpName::src2),
234         TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_X),
235         TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Y),
236         TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Z),
237         TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_W),
238         TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_X),
239         TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Y),
240         TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Z),
241         TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_W)
242       };
243       std::vector<unsigned> Consts;
244       for (unsigned i = 0; i < sizeof(SrcIndices) / sizeof(int); i++) {
245         int OtherSrcIdx = SrcIndices[i];
246         int OtherSelIdx = TII->getSelIdx(Opcode, OtherSrcIdx);
247         if (OtherSrcIdx < 0 || OtherSelIdx < 0) {
248           continue;
249         }
250         if (HasDst) {
251           OtherSrcIdx--;
252           OtherSelIdx--;
253         }
254         if (RegisterSDNode *Reg =
255                          dyn_cast<RegisterSDNode>(I->getOperand(OtherSrcIdx))) {
256           if (Reg->getReg() == AMDGPU::ALU_CONST) {
257             ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(I->getOperand(OtherSelIdx));
258             Consts.push_back(Cst->getZExtValue());
259           }
260         }
261       }
262
263       ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(CstOffset);
264       Consts.push_back(Cst->getZExtValue());
265       if (!TII->fitsConstReadLimitations(Consts))
266         continue;
267
268       // Convert back to SDNode indices
269       if (HasDst) {
270         SrcIdx--;
271         SelIdx--;
272       }
273       std::vector<SDValue> Ops;
274       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
275         if (i == SrcIdx) {
276           Ops.push_back(CurDAG->getRegister(AMDGPU::ALU_CONST, MVT::f32));
277         } else if (i == SelIdx) {
278           Ops.push_back(CstOffset);
279         } else {
280           Ops.push_back(I->getOperand(i));
281         }
282       }
283       CurDAG->UpdateNodeOperands(*I, Ops.data(), Ops.size());
284     }
285     break;
286   }
287   case ISD::BUILD_VECTOR: {
288     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
289     if (ST.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
290       break;
291     }
292
293     unsigned RegClassID;
294     switch(N->getValueType(0).getVectorNumElements()) {
295     case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
296     case 4: RegClassID = AMDGPU::R600_Reg128RegClassID; break;
297     default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
298     }
299     // BUILD_VECTOR is usually lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
300     // that adds a 128 bits reg copy when going through TwoAddressInstructions
301     // pass. We want to avoid 128 bits copies as much as possible because they
302     // can't be bundled by our scheduler.
303     SDValue RegSeqArgs[9] = {
304       CurDAG->getTargetConstant(RegClassID, MVT::i32),
305       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
306       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32),
307       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub2, MVT::i32),
308       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub3, MVT::i32)
309     };
310     bool IsRegSeq = true;
311     for (unsigned i = 0; i < N->getNumOperands(); i++) {
312       if (dyn_cast<RegisterSDNode>(N->getOperand(i))) {
313         IsRegSeq = false;
314         break;
315       }
316       RegSeqArgs[2 * i + 1] = N->getOperand(i);
317     }
318     if (!IsRegSeq)
319       break;
320     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
321         RegSeqArgs, 2 * N->getNumOperands() + 1);
322   }
323   case ISD::BUILD_PAIR: {
324     SDValue RC, SubReg0, SubReg1;
325     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
326     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
327       break;
328     }
329     if (N->getValueType(0) == MVT::i128) {
330       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32);
331       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, MVT::i32);
332       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, MVT::i32);
333     } else if (N->getValueType(0) == MVT::i64) {
334       RC = CurDAG->getTargetConstant(AMDGPU::VSrc_64RegClassID, MVT::i32);
335       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
336       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
337     } else {
338       llvm_unreachable("Unhandled value type for BUILD_PAIR");
339     }
340     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
341                             N->getOperand(1), SubReg1 };
342     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
343                                   SDLoc(N), N->getValueType(0), Ops);
344   }
345
346   case ISD::ConstantFP:
347   case ISD::Constant: {
348     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
349     // XXX: Custom immediate lowering not implemented yet.  Instead we use
350     // pseudo instructions defined in SIInstructions.td
351     if (ST.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
352       break;
353     }
354
355     uint64_t ImmValue = 0;
356     unsigned ImmReg = AMDGPU::ALU_LITERAL_X;
357
358     if (N->getOpcode() == ISD::ConstantFP) {
359       // XXX: 64-bit Immediates not supported yet
360       assert(N->getValueType(0) != MVT::f64);
361
362       ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N);
363       APFloat Value = C->getValueAPF();
364       float FloatValue = Value.convertToFloat();
365       if (FloatValue == 0.0) {
366         ImmReg = AMDGPU::ZERO;
367       } else if (FloatValue == 0.5) {
368         ImmReg = AMDGPU::HALF;
369       } else if (FloatValue == 1.0) {
370         ImmReg = AMDGPU::ONE;
371       } else {
372         ImmValue = Value.bitcastToAPInt().getZExtValue();
373       }
374     } else {
375       // XXX: 64-bit Immediates not supported yet
376       assert(N->getValueType(0) != MVT::i64);
377
378       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
379       if (C->getZExtValue() == 0) {
380         ImmReg = AMDGPU::ZERO;
381       } else if (C->getZExtValue() == 1) {
382         ImmReg = AMDGPU::ONE_INT;
383       } else {
384         ImmValue = C->getZExtValue();
385       }
386     }
387
388     for (SDNode::use_iterator Use = N->use_begin(), Next = llvm::next(Use);
389                               Use != SDNode::use_end(); Use = Next) {
390       Next = llvm::next(Use);
391       std::vector<SDValue> Ops;
392       for (unsigned i = 0; i < Use->getNumOperands(); ++i) {
393         Ops.push_back(Use->getOperand(i));
394       }
395
396       if (!Use->isMachineOpcode()) {
397           if (ImmReg == AMDGPU::ALU_LITERAL_X) {
398             // We can only use literal constants (e.g. AMDGPU::ZERO,
399             // AMDGPU::ONE, etc) in machine opcodes.
400             continue;
401           }
402       } else {
403         if (!TII->isALUInstr(Use->getMachineOpcode()) ||
404             (TII->get(Use->getMachineOpcode()).TSFlags &
405             R600_InstFlag::VECTOR)) {
406           continue;
407         }
408
409         int ImmIdx = TII->getOperandIdx(Use->getMachineOpcode(),
410                                         AMDGPU::OpName::literal);
411         if (ImmIdx == -1) {
412           continue;
413         }
414
415         if (TII->getOperandIdx(Use->getMachineOpcode(),
416                                AMDGPU::OpName::dst) != -1) {
417           // subtract one from ImmIdx, because the DST operand is usually index
418           // 0 for MachineInstrs, but we have no DST in the Ops vector.
419           ImmIdx--;
420         }
421
422         // Check that we aren't already using an immediate.
423         // XXX: It's possible for an instruction to have more than one
424         // immediate operand, but this is not supported yet.
425         if (ImmReg == AMDGPU::ALU_LITERAL_X) {
426           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Use->getOperand(ImmIdx));
427           assert(C);
428
429           if (C->getZExtValue() != 0) {
430             // This instruction is already using an immediate.
431             continue;
432           }
433
434           // Set the immediate value
435           Ops[ImmIdx] = CurDAG->getTargetConstant(ImmValue, MVT::i32);
436         }
437       }
438       // Set the immediate register
439       Ops[Use.getOperandNo()] = CurDAG->getRegister(ImmReg, MVT::i32);
440
441       CurDAG->UpdateNodeOperands(*Use, Ops.data(), Use->getNumOperands());
442     }
443     break;
444   }
445   }
446   SDNode *Result = SelectCode(N);
447
448   // Fold operands of selected node
449
450   const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
451   if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
452     const R600InstrInfo *TII =
453         static_cast<const R600InstrInfo*>(TM.getInstrInfo());
454     if (Result && Result->isMachineOpcode() && Result->getMachineOpcode() == AMDGPU::DOT_4) {
455       bool IsModified = false;
456       do {
457         std::vector<SDValue> Ops;
458         for(SDNode::op_iterator I = Result->op_begin(), E = Result->op_end();
459             I != E; ++I)
460           Ops.push_back(*I);
461         IsModified = FoldDotOperands(Result->getMachineOpcode(), TII, Ops);
462         if (IsModified) {
463           Result = CurDAG->UpdateNodeOperands(Result, Ops.data(), Ops.size());
464         }
465       } while (IsModified);
466
467     }
468     if (Result && Result->isMachineOpcode() &&
469         !(TII->get(Result->getMachineOpcode()).TSFlags & R600_InstFlag::VECTOR)
470         && TII->hasInstrModifiers(Result->getMachineOpcode())) {
471       // Fold FNEG/FABS
472       // TODO: Isel can generate multiple MachineInst, we need to recursively
473       // parse Result
474       bool IsModified = false;
475       do {
476         std::vector<SDValue> Ops;
477         for(SDNode::op_iterator I = Result->op_begin(), E = Result->op_end();
478             I != E; ++I)
479           Ops.push_back(*I);
480         IsModified = FoldOperands(Result->getMachineOpcode(), TII, Ops);
481         if (IsModified) {
482           Result = CurDAG->UpdateNodeOperands(Result, Ops.data(), Ops.size());
483         }
484       } while (IsModified);
485
486       // If node has a single use which is CLAMP_R600, folds it
487       if (Result->hasOneUse() && Result->isMachineOpcode()) {
488         SDNode *PotentialClamp = *Result->use_begin();
489         if (PotentialClamp->isMachineOpcode() &&
490             PotentialClamp->getMachineOpcode() == AMDGPU::CLAMP_R600) {
491           unsigned ClampIdx =
492             TII->getOperandIdx(Result->getMachineOpcode(), AMDGPU::OpName::clamp);
493           std::vector<SDValue> Ops;
494           unsigned NumOp = Result->getNumOperands();
495           for (unsigned i = 0; i < NumOp; ++i) {
496             Ops.push_back(Result->getOperand(i));
497           }
498           Ops[ClampIdx - 1] = CurDAG->getTargetConstant(1, MVT::i32);
499           Result = CurDAG->SelectNodeTo(PotentialClamp,
500               Result->getMachineOpcode(), PotentialClamp->getVTList(),
501               Ops.data(), NumOp);
502         }
503       }
504     }
505   }
506
507   return Result;
508 }
509
510 bool AMDGPUDAGToDAGISel::FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg,
511                                      SDValue &Abs, const R600InstrInfo *TII) {
512   switch (Src.getOpcode()) {
513   case ISD::FNEG:
514     Src = Src.getOperand(0);
515     Neg = CurDAG->getTargetConstant(1, MVT::i32);
516     return true;
517   case ISD::FABS:
518     if (!Abs.getNode())
519       return false;
520     Src = Src.getOperand(0);
521     Abs = CurDAG->getTargetConstant(1, MVT::i32);
522     return true;
523   case ISD::BITCAST:
524     Src = Src.getOperand(0);
525     return true;
526   default:
527     return false;
528   }
529 }
530
531 bool AMDGPUDAGToDAGISel::FoldOperands(unsigned Opcode,
532     const R600InstrInfo *TII, std::vector<SDValue> &Ops) {
533   int OperandIdx[] = {
534     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
535     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
536     TII->getOperandIdx(Opcode, AMDGPU::OpName::src2)
537   };
538   int SelIdx[] = {
539     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_sel),
540     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_sel),
541     TII->getOperandIdx(Opcode, AMDGPU::OpName::src2_sel)
542   };
543   int NegIdx[] = {
544     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg),
545     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg),
546     TII->getOperandIdx(Opcode, AMDGPU::OpName::src2_neg)
547   };
548   int AbsIdx[] = {
549     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs),
550     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs),
551     -1
552   };
553
554
555   for (unsigned i = 0; i < 3; i++) {
556     if (OperandIdx[i] < 0)
557       return false;
558     SDValue &Src = Ops[OperandIdx[i] - 1];
559     SDValue &Sel = Ops[SelIdx[i] - 1];
560     SDValue &Neg = Ops[NegIdx[i] - 1];
561     SDValue FakeAbs;
562     SDValue &Abs = (AbsIdx[i] > -1) ? Ops[AbsIdx[i] - 1] : FakeAbs;
563     if (FoldOperand(Src, Sel, Neg, Abs, TII))
564       return true;
565   }
566   return false;
567 }
568
569 bool AMDGPUDAGToDAGISel::FoldDotOperands(unsigned Opcode,
570     const R600InstrInfo *TII, std::vector<SDValue> &Ops) {
571   int OperandIdx[] = {
572     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_X),
573     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Y),
574     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Z),
575     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_W),
576     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_X),
577     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Y),
578     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Z),
579     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_W)
580   };
581   int SelIdx[] = {
582     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_sel_X),
583     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_sel_Y),
584     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_sel_Z),
585     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_sel_W),
586     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_sel_X),
587     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_sel_Y),
588     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_sel_Z),
589     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_sel_W)
590   };
591   int NegIdx[] = {
592     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_X),
593     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_Y),
594     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_Z),
595     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_W),
596     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_X),
597     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_Y),
598     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_Z),
599     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_W)
600   };
601   int AbsIdx[] = {
602     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_X),
603     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_Y),
604     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_Z),
605     TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_W),
606     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_X),
607     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_Y),
608     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_Z),
609     TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_W)
610   };
611
612   for (unsigned i = 0; i < 8; i++) {
613     if (OperandIdx[i] < 0)
614       return false;
615     SDValue &Src = Ops[OperandIdx[i] - 1];
616     SDValue &Sel = Ops[SelIdx[i] - 1];
617     SDValue &Neg = Ops[NegIdx[i] - 1];
618     SDValue &Abs = Ops[AbsIdx[i] - 1];
619     if (FoldOperand(Src, Sel, Neg, Abs, TII))
620       return true;
621   }
622   return false;
623 }
624
625 bool AMDGPUDAGToDAGISel::checkType(const Value *ptr, unsigned int addrspace) {
626   if (!ptr) {
627     return false;
628   }
629   Type *ptrType = ptr->getType();
630   return dyn_cast<PointerType>(ptrType)->getAddressSpace() == addrspace;
631 }
632
633 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
634   return checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS);
635 }
636
637 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
638   return (!checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS)
639           && !checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS)
640           && !checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS));
641 }
642
643 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
644   return checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS);
645 }
646
647 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
648   return checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS);
649 }
650
651 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int CbId) const {
652   if (CbId == -1) {
653     return checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_ADDRESS);
654   }
655   return checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_BUFFER_0 + CbId);
656 }
657
658 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
659   if (N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) {
660     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
661     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
662         N->getMemoryVT().bitsLT(MVT::i32)) {
663       return true;
664     }
665   }
666   return checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS);
667 }
668
669 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
670   return checkType(N->getSrcValue(), AMDGPUAS::PARAM_I_ADDRESS);
671 }
672
673 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
674   return checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS);
675 }
676
677 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
678   return checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS);
679 }
680
681 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
682   MachineMemOperand *MMO = N->getMemOperand();
683   if (checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS)) {
684     if (MMO) {
685       const Value *V = MMO->getValue();
686       const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V);
687       if (PSV && PSV == PseudoSourceValue::getConstantPool()) {
688         return true;
689       }
690     }
691   }
692   return false;
693 }
694
695 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
696   if (checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS)) {
697     // Check to make sure we are not a constant pool load or a constant load
698     // that is marked as a private load
699     if (isCPLoad(N) || isConstantLoad(N, -1)) {
700       return false;
701     }
702   }
703   if (!checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS)
704       && !checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS)
705       && !checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS)
706       && !checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_ADDRESS)
707       && !checkType(N->getSrcValue(), AMDGPUAS::PARAM_D_ADDRESS)
708       && !checkType(N->getSrcValue(), AMDGPUAS::PARAM_I_ADDRESS)) {
709     return true;
710   }
711   return false;
712 }
713
714 const char *AMDGPUDAGToDAGISel::getPassName() const {
715   return "AMDGPU DAG->DAG Pattern Instruction Selection";
716 }
717
718 #ifdef DEBUGTMP
719 #undef INT64_C
720 #endif
721 #undef DEBUGTMP
722
723 //===----------------------------------------------------------------------===//
724 // Complex Patterns
725 //===----------------------------------------------------------------------===//
726
727 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
728     SDValue& IntPtr) {
729   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
730     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, true);
731     return true;
732   }
733   return false;
734 }
735
736 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
737     SDValue& BaseReg, SDValue &Offset) {
738   if (!dyn_cast<ConstantSDNode>(Addr)) {
739     BaseReg = Addr;
740     Offset = CurDAG->getIntPtrConstant(0, true);
741     return true;
742   }
743   return false;
744 }
745
746 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
747                                            SDValue &Offset) {
748   ConstantSDNode * IMMOffset;
749
750   if (Addr.getOpcode() == ISD::ADD
751       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
752       && isInt<16>(IMMOffset->getZExtValue())) {
753
754       Base = Addr.getOperand(0);
755       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
756       return true;
757   // If the pointer address is constant, we can move it to the offset field.
758   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
759              && isInt<16>(IMMOffset->getZExtValue())) {
760     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
761                                   SDLoc(CurDAG->getEntryNode()),
762                                   AMDGPU::ZERO, MVT::i32);
763     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
764     return true;
765   }
766
767   // Default case, no offset
768   Base = Addr;
769   Offset = CurDAG->getTargetConstant(0, MVT::i32);
770   return true;
771 }
772
773 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
774                                             SDValue &Offset) {
775   ConstantSDNode *C;
776
777   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
778     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
779     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
780   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
781             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
782     Base = Addr.getOperand(0);
783     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
784   } else {
785     Base = Addr;
786     Offset = CurDAG->getTargetConstant(0, MVT::i32);
787   }
788
789   return true;
790 }
791
792 SDValue AMDGPUDAGToDAGISel::SimplifyI24(SDValue &Op) {
793   APInt Demanded = APInt(32, 0x00FFFFFF);
794   APInt KnownZero, KnownOne;
795   TargetLowering::TargetLoweringOpt TLO(*CurDAG, true, true);
796   const TargetLowering *TLI = getTargetLowering();
797   if (TLI->SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) {
798     CurDAG->ReplaceAllUsesWith(Op, TLO.New);
799     CurDAG->RepositionNode(Op.getNode(), TLO.New.getNode());
800     return SimplifyI24(TLO.New);
801   } else {
802     return  Op;
803   }
804 }
805
806 bool AMDGPUDAGToDAGISel::SelectI24(SDValue Op, SDValue &I24) {
807
808   assert(Op.getValueType() == MVT::i32);
809
810   if (CurDAG->ComputeNumSignBits(Op) == 9) {
811     I24 = SimplifyI24(Op);
812     return true;
813   }
814   return false;
815 }
816
817 bool AMDGPUDAGToDAGISel::SelectU24(SDValue Op, SDValue &U24) {
818   APInt KnownZero;
819   APInt KnownOne;
820   CurDAG->ComputeMaskedBits(Op, KnownZero, KnownOne);
821
822   assert (Op.getValueType() == MVT::i32);
823
824   // ANY_EXTEND and EXTLOAD operations can only be done on types smaller than
825   // i32.  These smaller types are legal to use with the i24 instructions.
826   if ((KnownZero & APInt(KnownZero.getBitWidth(), 0xFF000000)) == 0xFF000000 ||
827        Op.getOpcode() == ISD::ANY_EXTEND ||
828        ISD::isEXTLoad(Op.getNode())) {
829     U24 = SimplifyI24(Op);
830     return true;
831   }
832   return false;
833 }
834
835 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
836
837   if (Subtarget.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS) {
838     return;
839   }
840
841   // Go over all selected nodes and try to fold them a bit more
842   const AMDGPUTargetLowering& Lowering =
843     (*(const AMDGPUTargetLowering*)getTargetLowering());
844   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
845        E = CurDAG->allnodes_end(); I != E; ++I) {
846
847     SDNode *Node = I;
848
849     MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
850     if (!MachineNode)
851       continue;
852
853     SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
854     if (ResNode != Node) {
855       ReplaceUses(Node, ResNode);
856     }
857   }
858 }