R600/SI: Expand and of v2i32/v4i32 for SI
[oota-llvm.git] / lib / Target / R600 / AMDILISelDAGToDAG.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, std::vector<unsigned> Cst);
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
62   static bool checkType(const Value *ptr, unsigned int addrspace);
63
64   static bool isGlobalStore(const StoreSDNode *N);
65   static bool isPrivateStore(const StoreSDNode *N);
66   static bool isLocalStore(const StoreSDNode *N);
67   static bool isRegionStore(const StoreSDNode *N);
68
69   bool isCPLoad(const LoadSDNode *N) const;
70   bool isConstantLoad(const LoadSDNode *N, int cbID) const;
71   bool isGlobalLoad(const LoadSDNode *N) const;
72   bool isParamLoad(const LoadSDNode *N) const;
73   bool isPrivateLoad(const LoadSDNode *N) const;
74   bool isLocalLoad(const LoadSDNode *N) const;
75   bool isRegionLoad(const LoadSDNode *N) const;
76
77   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
78   bool SelectGlobalValueVariableOffset(SDValue Addr,
79       SDValue &BaseReg, SDValue& Offset);
80   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
81   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
82
83   // Include the pieces autogenerated from the target description.
84 #include "AMDGPUGenDAGISel.inc"
85 };
86 }  // end anonymous namespace
87
88 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
89 // DAG, ready for instruction scheduling.
90 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM
91                                        ) {
92   return new AMDGPUDAGToDAGISel(TM);
93 }
94
95 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
96   : SelectionDAGISel(TM), Subtarget(TM.getSubtarget<AMDGPUSubtarget>()) {
97 }
98
99 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
100 }
101
102 SDValue AMDGPUDAGToDAGISel::getSmallIPtrImm(unsigned int Imm) {
103   return CurDAG->getTargetConstant(Imm, MVT::i32);
104 }
105
106 bool AMDGPUDAGToDAGISel::SelectADDRParam(
107     SDValue Addr, SDValue& R1, SDValue& R2) {
108
109   if (Addr.getOpcode() == ISD::FrameIndex) {
110     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
111       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
112       R2 = CurDAG->getTargetConstant(0, MVT::i32);
113     } else {
114       R1 = Addr;
115       R2 = CurDAG->getTargetConstant(0, MVT::i32);
116     }
117   } else if (Addr.getOpcode() == ISD::ADD) {
118     R1 = Addr.getOperand(0);
119     R2 = Addr.getOperand(1);
120   } else {
121     R1 = Addr;
122     R2 = CurDAG->getTargetConstant(0, MVT::i32);
123   }
124   return true;
125 }
126
127 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
128   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
129       Addr.getOpcode() == ISD::TargetGlobalAddress) {
130     return false;
131   }
132   return SelectADDRParam(Addr, R1, R2);
133 }
134
135
136 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
137   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
138       Addr.getOpcode() == ISD::TargetGlobalAddress) {
139     return false;
140   }
141
142   if (Addr.getOpcode() == ISD::FrameIndex) {
143     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
144       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
145       R2 = CurDAG->getTargetConstant(0, MVT::i64);
146     } else {
147       R1 = Addr;
148       R2 = CurDAG->getTargetConstant(0, MVT::i64);
149     }
150   } else if (Addr.getOpcode() == ISD::ADD) {
151     R1 = Addr.getOperand(0);
152     R2 = Addr.getOperand(1);
153   } else {
154     R1 = Addr;
155     R2 = CurDAG->getTargetConstant(0, MVT::i64);
156   }
157   return true;
158 }
159
160 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
161   unsigned int Opc = N->getOpcode();
162   if (N->isMachineOpcode()) {
163     return NULL;   // Already selected.
164   }
165   switch (Opc) {
166   default: break;
167   case ISD::BUILD_VECTOR: {
168     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
169     if (ST.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
170       break;
171     }
172     // BUILD_VECTOR is usually lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
173     // that adds a 128 bits reg copy when going through TwoAddressInstructions
174     // pass. We want to avoid 128 bits copies as much as possible because they
175     // can't be bundled by our scheduler.
176     SDValue RegSeqArgs[9] = {
177       CurDAG->getTargetConstant(AMDGPU::R600_Reg128RegClassID, MVT::i32),
178       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
179       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32),
180       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub2, MVT::i32),
181       SDValue(), CurDAG->getTargetConstant(AMDGPU::sub3, MVT::i32)
182     };
183     bool IsRegSeq = true;
184     for (unsigned i = 0; i < N->getNumOperands(); i++) {
185       if (dyn_cast<RegisterSDNode>(N->getOperand(i))) {
186         IsRegSeq = false;
187         break;
188       }
189       RegSeqArgs[2 * i + 1] = N->getOperand(i);
190     }
191     if (!IsRegSeq)
192       break;
193     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
194         RegSeqArgs, 2 * N->getNumOperands() + 1);
195   }
196   case ISD::BUILD_PAIR: {
197     SDValue RC, SubReg0, SubReg1;
198     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
199     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
200       break;
201     }
202     if (N->getValueType(0) == MVT::i128) {
203       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32);
204       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, MVT::i32);
205       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, MVT::i32);
206     } else if (N->getValueType(0) == MVT::i64) {
207       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32);
208       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
209       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
210     } else {
211       llvm_unreachable("Unhandled value type for BUILD_PAIR");
212     }
213     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
214                             N->getOperand(1), SubReg1 };
215     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
216                                   SDLoc(N), N->getValueType(0), Ops);
217   }
218
219   case ISD::ConstantFP:
220   case ISD::Constant: {
221     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
222     // XXX: Custom immediate lowering not implemented yet.  Instead we use
223     // pseudo instructions defined in SIInstructions.td
224     if (ST.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
225       break;
226     }
227     const R600InstrInfo *TII = static_cast<const R600InstrInfo*>(TM.getInstrInfo());
228
229     uint64_t ImmValue = 0;
230     unsigned ImmReg = AMDGPU::ALU_LITERAL_X;
231
232     if (N->getOpcode() == ISD::ConstantFP) {
233       // XXX: 64-bit Immediates not supported yet
234       assert(N->getValueType(0) != MVT::f64);
235
236       ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N);
237       APFloat Value = C->getValueAPF();
238       float FloatValue = Value.convertToFloat();
239       if (FloatValue == 0.0) {
240         ImmReg = AMDGPU::ZERO;
241       } else if (FloatValue == 0.5) {
242         ImmReg = AMDGPU::HALF;
243       } else if (FloatValue == 1.0) {
244         ImmReg = AMDGPU::ONE;
245       } else {
246         ImmValue = Value.bitcastToAPInt().getZExtValue();
247       }
248     } else {
249       // XXX: 64-bit Immediates not supported yet
250       assert(N->getValueType(0) != MVT::i64);
251
252       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
253       if (C->getZExtValue() == 0) {
254         ImmReg = AMDGPU::ZERO;
255       } else if (C->getZExtValue() == 1) {
256         ImmReg = AMDGPU::ONE_INT;
257       } else {
258         ImmValue = C->getZExtValue();
259       }
260     }
261
262     for (SDNode::use_iterator Use = N->use_begin(), Next = llvm::next(Use);
263                               Use != SDNode::use_end(); Use = Next) {
264       Next = llvm::next(Use);
265       std::vector<SDValue> Ops;
266       for (unsigned i = 0; i < Use->getNumOperands(); ++i) {
267         Ops.push_back(Use->getOperand(i));
268       }
269
270       if (!Use->isMachineOpcode()) {
271           if (ImmReg == AMDGPU::ALU_LITERAL_X) {
272             // We can only use literal constants (e.g. AMDGPU::ZERO,
273             // AMDGPU::ONE, etc) in machine opcodes.
274             continue;
275           }
276       } else {
277         if (!TII->isALUInstr(Use->getMachineOpcode()) ||
278             (TII->get(Use->getMachineOpcode()).TSFlags &
279             R600_InstFlag::VECTOR)) {
280           continue;
281         }
282
283         int ImmIdx = TII->getOperandIdx(Use->getMachineOpcode(), R600Operands::IMM);
284         assert(ImmIdx != -1);
285
286         // subtract one from ImmIdx, because the DST operand is usually index
287         // 0 for MachineInstrs, but we have no DST in the Ops vector.
288         ImmIdx--;
289
290         // Check that we aren't already using an immediate.
291         // XXX: It's possible for an instruction to have more than one
292         // immediate operand, but this is not supported yet.
293         if (ImmReg == AMDGPU::ALU_LITERAL_X) {
294           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Use->getOperand(ImmIdx));
295           assert(C);
296
297           if (C->getZExtValue() != 0) {
298             // This instruction is already using an immediate.
299             continue;
300           }
301
302           // Set the immediate value
303           Ops[ImmIdx] = CurDAG->getTargetConstant(ImmValue, MVT::i32);
304         }
305       }
306       // Set the immediate register
307       Ops[Use.getOperandNo()] = CurDAG->getRegister(ImmReg, MVT::i32);
308
309       CurDAG->UpdateNodeOperands(*Use, Ops.data(), Use->getNumOperands());
310     }
311     break;
312   }
313   }
314   SDNode *Result = SelectCode(N);
315
316   // Fold operands of selected node
317
318   const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
319   if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
320     const R600InstrInfo *TII =
321         static_cast<const R600InstrInfo*>(TM.getInstrInfo());
322     if (Result && Result->isMachineOpcode() && Result->getMachineOpcode() == AMDGPU::DOT_4) {
323       bool IsModified = false;
324       do {
325         std::vector<SDValue> Ops;
326         for(SDNode::op_iterator I = Result->op_begin(), E = Result->op_end();
327             I != E; ++I)
328           Ops.push_back(*I);
329         IsModified = FoldDotOperands(Result->getMachineOpcode(), TII, Ops);
330         if (IsModified) {
331           Result = CurDAG->UpdateNodeOperands(Result, Ops.data(), Ops.size());
332         }
333       } while (IsModified);
334
335     }
336     if (Result && Result->isMachineOpcode() &&
337         !(TII->get(Result->getMachineOpcode()).TSFlags & R600_InstFlag::VECTOR)
338         && TII->isALUInstr(Result->getMachineOpcode())) {
339       // Fold FNEG/FABS/CONST_ADDRESS
340       // TODO: Isel can generate multiple MachineInst, we need to recursively
341       // parse Result
342       bool IsModified = false;
343       do {
344         std::vector<SDValue> Ops;
345         for(SDNode::op_iterator I = Result->op_begin(), E = Result->op_end();
346             I != E; ++I)
347           Ops.push_back(*I);
348         IsModified = FoldOperands(Result->getMachineOpcode(), TII, Ops);
349         if (IsModified) {
350           Result = CurDAG->UpdateNodeOperands(Result, Ops.data(), Ops.size());
351         }
352       } while (IsModified);
353
354       // If node has a single use which is CLAMP_R600, folds it
355       if (Result->hasOneUse() && Result->isMachineOpcode()) {
356         SDNode *PotentialClamp = *Result->use_begin();
357         if (PotentialClamp->isMachineOpcode() &&
358             PotentialClamp->getMachineOpcode() == AMDGPU::CLAMP_R600) {
359           unsigned ClampIdx =
360             TII->getOperandIdx(Result->getMachineOpcode(), R600Operands::CLAMP);
361           std::vector<SDValue> Ops;
362           unsigned NumOp = Result->getNumOperands();
363           for (unsigned i = 0; i < NumOp; ++i) {
364             Ops.push_back(Result->getOperand(i));
365           }
366           Ops[ClampIdx - 1] = CurDAG->getTargetConstant(1, MVT::i32);
367           Result = CurDAG->SelectNodeTo(PotentialClamp,
368               Result->getMachineOpcode(), PotentialClamp->getVTList(),
369               Ops.data(), NumOp);
370         }
371       }
372     }
373   }
374
375   return Result;
376 }
377
378 bool AMDGPUDAGToDAGISel::FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg,
379                                      SDValue &Abs, const R600InstrInfo *TII,
380                                      std::vector<unsigned> Consts) {
381   switch (Src.getOpcode()) {
382   case AMDGPUISD::CONST_ADDRESS: {
383     SDValue CstOffset;
384     if (Src.getValueType().isVector() ||
385         !SelectGlobalValueConstantOffset(Src.getOperand(0), CstOffset))
386       return false;
387
388     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(CstOffset);
389     Consts.push_back(Cst->getZExtValue());
390     if (!TII->fitsConstReadLimitations(Consts))
391       return false;
392
393     Src = CurDAG->getRegister(AMDGPU::ALU_CONST, MVT::f32);
394     Sel = CstOffset;
395     return true;
396     }
397   case ISD::FNEG:
398     Src = Src.getOperand(0);
399     Neg = CurDAG->getTargetConstant(1, MVT::i32);
400     return true;
401   case ISD::FABS:
402     if (!Abs.getNode())
403       return false;
404     Src = Src.getOperand(0);
405     Abs = CurDAG->getTargetConstant(1, MVT::i32);
406     return true;
407   case ISD::BITCAST:
408     Src = Src.getOperand(0);
409     return true;
410   default:
411     return false;
412   }
413 }
414
415 bool AMDGPUDAGToDAGISel::FoldOperands(unsigned Opcode,
416     const R600InstrInfo *TII, std::vector<SDValue> &Ops) {
417   int OperandIdx[] = {
418     TII->getOperandIdx(Opcode, R600Operands::SRC0),
419     TII->getOperandIdx(Opcode, R600Operands::SRC1),
420     TII->getOperandIdx(Opcode, R600Operands::SRC2)
421   };
422   int SelIdx[] = {
423     TII->getOperandIdx(Opcode, R600Operands::SRC0_SEL),
424     TII->getOperandIdx(Opcode, R600Operands::SRC1_SEL),
425     TII->getOperandIdx(Opcode, R600Operands::SRC2_SEL)
426   };
427   int NegIdx[] = {
428     TII->getOperandIdx(Opcode, R600Operands::SRC0_NEG),
429     TII->getOperandIdx(Opcode, R600Operands::SRC1_NEG),
430     TII->getOperandIdx(Opcode, R600Operands::SRC2_NEG)
431   };
432   int AbsIdx[] = {
433     TII->getOperandIdx(Opcode, R600Operands::SRC0_ABS),
434     TII->getOperandIdx(Opcode, R600Operands::SRC1_ABS),
435     -1
436   };
437
438   // Gather constants values
439   std::vector<unsigned> Consts;
440   for (unsigned j = 0; j < 3; j++) {
441     int SrcIdx = OperandIdx[j];
442     if (SrcIdx < 0)
443       break;
444     if (RegisterSDNode *Reg = dyn_cast<RegisterSDNode>(Ops[SrcIdx - 1])) {
445       if (Reg->getReg() == AMDGPU::ALU_CONST) {
446         ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Ops[SelIdx[j] - 1]);
447         Consts.push_back(Cst->getZExtValue());
448       }
449     }
450   }
451
452   for (unsigned i = 0; i < 3; i++) {
453     if (OperandIdx[i] < 0)
454       return false;
455     SDValue &Src = Ops[OperandIdx[i] - 1];
456     SDValue &Sel = Ops[SelIdx[i] - 1];
457     SDValue &Neg = Ops[NegIdx[i] - 1];
458     SDValue FakeAbs;
459     SDValue &Abs = (AbsIdx[i] > -1) ? Ops[AbsIdx[i] - 1] : FakeAbs;
460     if (FoldOperand(Src, Sel, Neg, Abs, TII, Consts))
461       return true;
462   }
463   return false;
464 }
465
466 bool AMDGPUDAGToDAGISel::FoldDotOperands(unsigned Opcode,
467     const R600InstrInfo *TII, std::vector<SDValue> &Ops) {
468   int OperandIdx[] = {
469     TII->getOperandIdx(Opcode, R600Operands::SRC0_X),
470     TII->getOperandIdx(Opcode, R600Operands::SRC0_Y),
471     TII->getOperandIdx(Opcode, R600Operands::SRC0_Z),
472     TII->getOperandIdx(Opcode, R600Operands::SRC0_W),
473     TII->getOperandIdx(Opcode, R600Operands::SRC1_X),
474     TII->getOperandIdx(Opcode, R600Operands::SRC1_Y),
475     TII->getOperandIdx(Opcode, R600Operands::SRC1_Z),
476     TII->getOperandIdx(Opcode, R600Operands::SRC1_W)
477   };
478   int SelIdx[] = {
479     TII->getOperandIdx(Opcode, R600Operands::SRC0_SEL_X),
480     TII->getOperandIdx(Opcode, R600Operands::SRC0_SEL_Y),
481     TII->getOperandIdx(Opcode, R600Operands::SRC0_SEL_Z),
482     TII->getOperandIdx(Opcode, R600Operands::SRC0_SEL_W),
483     TII->getOperandIdx(Opcode, R600Operands::SRC1_SEL_X),
484     TII->getOperandIdx(Opcode, R600Operands::SRC1_SEL_Y),
485     TII->getOperandIdx(Opcode, R600Operands::SRC1_SEL_Z),
486     TII->getOperandIdx(Opcode, R600Operands::SRC1_SEL_W)
487   };
488   int NegIdx[] = {
489     TII->getOperandIdx(Opcode, R600Operands::SRC0_NEG_X),
490     TII->getOperandIdx(Opcode, R600Operands::SRC0_NEG_Y),
491     TII->getOperandIdx(Opcode, R600Operands::SRC0_NEG_Z),
492     TII->getOperandIdx(Opcode, R600Operands::SRC0_NEG_W),
493     TII->getOperandIdx(Opcode, R600Operands::SRC1_NEG_X),
494     TII->getOperandIdx(Opcode, R600Operands::SRC1_NEG_Y),
495     TII->getOperandIdx(Opcode, R600Operands::SRC1_NEG_Z),
496     TII->getOperandIdx(Opcode, R600Operands::SRC1_NEG_W)
497   };
498   int AbsIdx[] = {
499     TII->getOperandIdx(Opcode, R600Operands::SRC0_ABS_X),
500     TII->getOperandIdx(Opcode, R600Operands::SRC0_ABS_Y),
501     TII->getOperandIdx(Opcode, R600Operands::SRC0_ABS_Z),
502     TII->getOperandIdx(Opcode, R600Operands::SRC0_ABS_W),
503     TII->getOperandIdx(Opcode, R600Operands::SRC1_ABS_X),
504     TII->getOperandIdx(Opcode, R600Operands::SRC1_ABS_Y),
505     TII->getOperandIdx(Opcode, R600Operands::SRC1_ABS_Z),
506     TII->getOperandIdx(Opcode, R600Operands::SRC1_ABS_W)
507   };
508
509   // Gather constants values
510   std::vector<unsigned> Consts;
511   for (unsigned j = 0; j < 8; j++) {
512     int SrcIdx = OperandIdx[j];
513     if (SrcIdx < 0)
514       break;
515     if (RegisterSDNode *Reg = dyn_cast<RegisterSDNode>(Ops[SrcIdx - 1])) {
516       if (Reg->getReg() == AMDGPU::ALU_CONST) {
517         ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Ops[SelIdx[j] - 1]);
518         Consts.push_back(Cst->getZExtValue());
519       }
520     }
521   }
522
523   for (unsigned i = 0; i < 8; i++) {
524     if (OperandIdx[i] < 0)
525       return false;
526     SDValue &Src = Ops[OperandIdx[i] - 1];
527     SDValue &Sel = Ops[SelIdx[i] - 1];
528     SDValue &Neg = Ops[NegIdx[i] - 1];
529     SDValue &Abs = Ops[AbsIdx[i] - 1];
530     if (FoldOperand(Src, Sel, Neg, Abs, TII, Consts))
531       return true;
532   }
533   return false;
534 }
535
536 bool AMDGPUDAGToDAGISel::checkType(const Value *ptr, unsigned int addrspace) {
537   if (!ptr) {
538     return false;
539   }
540   Type *ptrType = ptr->getType();
541   return dyn_cast<PointerType>(ptrType)->getAddressSpace() == addrspace;
542 }
543
544 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
545   return checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS);
546 }
547
548 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
549   return (!checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS)
550           && !checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS)
551           && !checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS));
552 }
553
554 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
555   return checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS);
556 }
557
558 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
559   return checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS);
560 }
561
562 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int cbID) const {
563   if (checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_ADDRESS)) {
564     return true;
565   }
566
567   const DataLayout *DL = TM.getDataLayout();
568   MachineMemOperand *MMO = N->getMemOperand();
569   const Value *V = MMO->getValue();
570   const Value *BV = GetUnderlyingObject(V, DL, 0);
571   if (MMO
572       && MMO->getValue()
573       && ((V && dyn_cast<GlobalValue>(V))
574           || (BV && dyn_cast<GlobalValue>(
575                 GetUnderlyingObject(MMO->getValue(), DL, 0))))) {
576     return checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS);
577   } else {
578     return false;
579   }
580 }
581
582 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
583   return checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS);
584 }
585
586 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
587   return checkType(N->getSrcValue(), AMDGPUAS::PARAM_I_ADDRESS);
588 }
589
590 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
591   return checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS);
592 }
593
594 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
595   return checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS);
596 }
597
598 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
599   MachineMemOperand *MMO = N->getMemOperand();
600   if (checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS)) {
601     if (MMO) {
602       const Value *V = MMO->getValue();
603       const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V);
604       if (PSV && PSV == PseudoSourceValue::getConstantPool()) {
605         return true;
606       }
607     }
608   }
609   return false;
610 }
611
612 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
613   if (checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS)) {
614     // Check to make sure we are not a constant pool load or a constant load
615     // that is marked as a private load
616     if (isCPLoad(N) || isConstantLoad(N, -1)) {
617       return false;
618     }
619   }
620   if (!checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS)
621       && !checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS)
622       && !checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS)
623       && !checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_ADDRESS)
624       && !checkType(N->getSrcValue(), AMDGPUAS::PARAM_D_ADDRESS)
625       && !checkType(N->getSrcValue(), AMDGPUAS::PARAM_I_ADDRESS)) {
626     return true;
627   }
628   return false;
629 }
630
631 const char *AMDGPUDAGToDAGISel::getPassName() const {
632   return "AMDGPU DAG->DAG Pattern Instruction Selection";
633 }
634
635 #ifdef DEBUGTMP
636 #undef INT64_C
637 #endif
638 #undef DEBUGTMP
639
640 ///==== AMDGPU Functions ====///
641
642 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
643     SDValue& IntPtr) {
644   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
645     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, true);
646     return true;
647   }
648   return false;
649 }
650
651 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
652     SDValue& BaseReg, SDValue &Offset) {
653   if (!dyn_cast<ConstantSDNode>(Addr)) {
654     BaseReg = Addr;
655     Offset = CurDAG->getIntPtrConstant(0, true);
656     return true;
657   }
658   return false;
659 }
660
661 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
662                                            SDValue &Offset) {
663   ConstantSDNode * IMMOffset;
664
665   if (Addr.getOpcode() == ISD::ADD
666       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
667       && isInt<16>(IMMOffset->getZExtValue())) {
668
669       Base = Addr.getOperand(0);
670       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
671       return true;
672   // If the pointer address is constant, we can move it to the offset field.
673   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
674              && isInt<16>(IMMOffset->getZExtValue())) {
675     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
676                                   SDLoc(CurDAG->getEntryNode()),
677                                   AMDGPU::ZERO, MVT::i32);
678     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
679     return true;
680   }
681
682   // Default case, no offset
683   Base = Addr;
684   Offset = CurDAG->getTargetConstant(0, MVT::i32);
685   return true;
686 }
687
688 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
689                                             SDValue &Offset) {
690   ConstantSDNode *C;
691
692   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
693     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
694     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
695   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
696             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
697     Base = Addr.getOperand(0);
698     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
699   } else {
700     Base = Addr;
701     Offset = CurDAG->getTargetConstant(0, MVT::i32);
702   }
703
704   return true;
705 }
706
707 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
708
709   if (Subtarget.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS) {
710     return;
711   }
712
713   // Go over all selected nodes and try to fold them a bit more
714   const AMDGPUTargetLowering& Lowering =
715     (*(const AMDGPUTargetLowering*)getTargetLowering());
716   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
717        E = CurDAG->allnodes_end(); I != E; ++I) {
718
719     SDNode *Node = I;
720     switch (Node->getOpcode()) {
721     // Fix the register class in copy to CopyToReg nodes - ISel will always
722     // use SReg classes for 64-bit copies, but this is not always what we want.
723     case ISD::CopyToReg: {
724       unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
725       SDValue Val = Node->getOperand(2);
726       const TargetRegisterClass *RC = RegInfo->getRegClass(Reg);
727       if (RC != &AMDGPU::SReg_64RegClass) {
728         continue;
729       }
730
731       if (!Val.getNode()->isMachineOpcode() ||
732           Val.getNode()->getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
733         continue;
734       }
735
736       const MCInstrDesc Desc = TM.getInstrInfo()->get(Val.getNode()->getMachineOpcode());
737       const TargetRegisterInfo *TRI = TM.getRegisterInfo();
738       RegInfo->setRegClass(Reg, TRI->getRegClass(Desc.OpInfo[0].RegClass));
739       continue;
740     }
741     }
742
743     MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
744     if (!MachineNode)
745       continue;
746
747     SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
748     if (ResNode != Node) {
749       ReplaceUses(Node, ResNode);
750     }
751   }
752 }