R600/SI: Do abs/neg folding with ComplexPatterns
[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 "AMDGPUSubtarget.h"
18 #include "R600InstrInfo.h"
19 #include "SIDefines.h"
20 #include "SIISelLowering.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "llvm/CodeGen/FunctionLoweringInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/IR/Function.h"
29
30 using namespace llvm;
31
32 //===----------------------------------------------------------------------===//
33 // Instruction Selector Implementation
34 //===----------------------------------------------------------------------===//
35
36 namespace {
37 /// AMDGPU specific code to select AMDGPU machine instructions for
38 /// SelectionDAG operations.
39 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
40   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
41   // make the right decision when generating code for different targets.
42   const AMDGPUSubtarget &Subtarget;
43 public:
44   AMDGPUDAGToDAGISel(TargetMachine &TM);
45   virtual ~AMDGPUDAGToDAGISel();
46
47   SDNode *Select(SDNode *N) override;
48   const char *getPassName() const override;
49   void PostprocessISelDAG() override;
50
51 private:
52   bool isInlineImmediate(SDNode *N) const;
53   inline SDValue getSmallIPtrImm(unsigned Imm);
54   bool FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg, SDValue &Abs,
55                    const R600InstrInfo *TII);
56   bool FoldOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
57   bool FoldDotOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
58
59   // Complex pattern selectors
60   bool SelectADDRParam(SDValue Addr, SDValue& R1, SDValue& R2);
61   bool SelectADDR(SDValue N, SDValue &R1, SDValue &R2);
62   bool SelectADDR64(SDValue N, SDValue &R1, SDValue &R2);
63
64   static bool checkType(const Value *ptr, unsigned int addrspace);
65   static bool checkPrivateAddress(const MachineMemOperand *Op);
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   /// \returns True if the current basic block being selected is at control
81   ///          flow depth 0.  Meaning that the current block dominates the
82   //           exit block.
83   bool isCFDepth0() const;
84
85   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
86   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
87   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
88                                        SDValue& Offset);
89   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
90   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
91   bool SelectMUBUFAddr64(SDValue Addr, SDValue &Ptr, SDValue &Offset,
92                          SDValue &ImmOffset) const;
93   bool SelectMUBUFScratch(SDValue Addr, SDValue &RSrc, SDValue &VAddr,
94                           SDValue &SOffset, SDValue &ImmOffset) const;
95   bool SelectMUBUFAddr32(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
96                          SDValue &SOffset, SDValue &Offset, SDValue &Offen,
97                          SDValue &Idxen, SDValue &GLC, SDValue &SLC,
98                          SDValue &TFE) const;
99   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
100   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
101                        SDValue &Clamp, SDValue &Omod) const;
102
103   SDNode *SelectADD_SUB_I64(SDNode *N);
104   SDNode *SelectDIV_SCALE(SDNode *N);
105
106   // Include the pieces autogenerated from the target description.
107 #include "AMDGPUGenDAGISel.inc"
108 };
109 }  // end anonymous namespace
110
111 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
112 // DAG, ready for instruction scheduling.
113 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM) {
114   return new AMDGPUDAGToDAGISel(TM);
115 }
116
117 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
118   : SelectionDAGISel(TM), Subtarget(TM.getSubtarget<AMDGPUSubtarget>()) {
119 }
120
121 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
122 }
123
124 bool AMDGPUDAGToDAGISel::isInlineImmediate(SDNode *N) const {
125   const SITargetLowering *TL
126       = static_cast<const SITargetLowering *>(getTargetLowering());
127   return TL->analyzeImmediate(N) == 0;
128 }
129
130 /// \brief Determine the register class for \p OpNo
131 /// \returns The register class of the virtual register that will be used for
132 /// the given operand number \OpNo or NULL if the register class cannot be
133 /// determined.
134 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
135                                                           unsigned OpNo) const {
136   if (!N->isMachineOpcode())
137     return nullptr;
138
139   switch (N->getMachineOpcode()) {
140   default: {
141     const MCInstrDesc &Desc = TM.getInstrInfo()->get(N->getMachineOpcode());
142     unsigned OpIdx = Desc.getNumDefs() + OpNo;
143     if (OpIdx >= Desc.getNumOperands())
144       return nullptr;
145     int RegClass = Desc.OpInfo[OpIdx].RegClass;
146     if (RegClass == -1)
147       return nullptr;
148
149     return TM.getRegisterInfo()->getRegClass(RegClass);
150   }
151   case AMDGPU::REG_SEQUENCE: {
152     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
153     const TargetRegisterClass *SuperRC = TM.getRegisterInfo()->getRegClass(RCID);
154
155     SDValue SubRegOp = N->getOperand(OpNo + 1);
156     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
157     return TM.getRegisterInfo()->getSubClassWithSubReg(SuperRC, SubRegIdx);
158   }
159   }
160 }
161
162 SDValue AMDGPUDAGToDAGISel::getSmallIPtrImm(unsigned int Imm) {
163   return CurDAG->getTargetConstant(Imm, MVT::i32);
164 }
165
166 bool AMDGPUDAGToDAGISel::SelectADDRParam(
167   SDValue Addr, SDValue& R1, SDValue& R2) {
168
169   if (Addr.getOpcode() == ISD::FrameIndex) {
170     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
171       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
172       R2 = CurDAG->getTargetConstant(0, MVT::i32);
173     } else {
174       R1 = Addr;
175       R2 = CurDAG->getTargetConstant(0, MVT::i32);
176     }
177   } else if (Addr.getOpcode() == ISD::ADD) {
178     R1 = Addr.getOperand(0);
179     R2 = Addr.getOperand(1);
180   } else {
181     R1 = Addr;
182     R2 = CurDAG->getTargetConstant(0, MVT::i32);
183   }
184   return true;
185 }
186
187 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
188   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
189       Addr.getOpcode() == ISD::TargetGlobalAddress) {
190     return false;
191   }
192   return SelectADDRParam(Addr, R1, R2);
193 }
194
195
196 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
197   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
198       Addr.getOpcode() == ISD::TargetGlobalAddress) {
199     return false;
200   }
201
202   if (Addr.getOpcode() == ISD::FrameIndex) {
203     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
204       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
205       R2 = CurDAG->getTargetConstant(0, MVT::i64);
206     } else {
207       R1 = Addr;
208       R2 = CurDAG->getTargetConstant(0, MVT::i64);
209     }
210   } else if (Addr.getOpcode() == ISD::ADD) {
211     R1 = Addr.getOperand(0);
212     R2 = Addr.getOperand(1);
213   } else {
214     R1 = Addr;
215     R2 = CurDAG->getTargetConstant(0, MVT::i64);
216   }
217   return true;
218 }
219
220 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
221   unsigned int Opc = N->getOpcode();
222   if (N->isMachineOpcode()) {
223     N->setNodeId(-1);
224     return nullptr;   // Already selected.
225   }
226
227   const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
228   switch (Opc) {
229   default: break;
230   // We are selecting i64 ADD here instead of custom lower it during
231   // DAG legalization, so we can fold some i64 ADDs used for address
232   // calculation into the LOAD and STORE instructions.
233   case ISD::ADD:
234   case ISD::SUB: {
235     if (N->getValueType(0) != MVT::i64 ||
236         ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
237       break;
238
239     return SelectADD_SUB_I64(N);
240   }
241   case ISD::SCALAR_TO_VECTOR:
242   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
243   case ISD::BUILD_VECTOR: {
244     unsigned RegClassID;
245     const AMDGPURegisterInfo *TRI =
246                    static_cast<const AMDGPURegisterInfo*>(TM.getRegisterInfo());
247     const SIRegisterInfo *SIRI =
248                    static_cast<const SIRegisterInfo*>(TM.getRegisterInfo());
249     EVT VT = N->getValueType(0);
250     unsigned NumVectorElts = VT.getVectorNumElements();
251     EVT EltVT = VT.getVectorElementType();
252     assert(EltVT.bitsEq(MVT::i32));
253     if (ST.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
254       bool UseVReg = true;
255       for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
256                                                     U != E; ++U) {
257         if (!U->isMachineOpcode()) {
258           continue;
259         }
260         const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
261         if (!RC) {
262           continue;
263         }
264         if (SIRI->isSGPRClass(RC)) {
265           UseVReg = false;
266         }
267       }
268       switch(NumVectorElts) {
269       case 1: RegClassID = UseVReg ? AMDGPU::VReg_32RegClassID :
270                                      AMDGPU::SReg_32RegClassID;
271         break;
272       case 2: RegClassID = UseVReg ? AMDGPU::VReg_64RegClassID :
273                                      AMDGPU::SReg_64RegClassID;
274         break;
275       case 4: RegClassID = UseVReg ? AMDGPU::VReg_128RegClassID :
276                                      AMDGPU::SReg_128RegClassID;
277         break;
278       case 8: RegClassID = UseVReg ? AMDGPU::VReg_256RegClassID :
279                                      AMDGPU::SReg_256RegClassID;
280         break;
281       case 16: RegClassID = UseVReg ? AMDGPU::VReg_512RegClassID :
282                                       AMDGPU::SReg_512RegClassID;
283         break;
284       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
285       }
286     } else {
287       // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
288       // that adds a 128 bits reg copy when going through TwoAddressInstructions
289       // pass. We want to avoid 128 bits copies as much as possible because they
290       // can't be bundled by our scheduler.
291       switch(NumVectorElts) {
292       case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
293       case 4:
294         if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
295           RegClassID = AMDGPU::R600_Reg128VerticalRegClassID;
296         else
297           RegClassID = AMDGPU::R600_Reg128RegClassID;
298         break;
299       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
300       }
301     }
302
303     SDValue RegClass = CurDAG->getTargetConstant(RegClassID, MVT::i32);
304
305     if (NumVectorElts == 1) {
306       return CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT,
307                                   N->getOperand(0), RegClass);
308     }
309
310     assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
311                                   "supported yet");
312     // 16 = Max Num Vector Elements
313     // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
314     // 1 = Vector Register Class
315     SmallVector<SDValue, 16 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
316
317     RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, MVT::i32);
318     bool IsRegSeq = true;
319     unsigned NOps = N->getNumOperands();
320     for (unsigned i = 0; i < NOps; i++) {
321       // XXX: Why is this here?
322       if (dyn_cast<RegisterSDNode>(N->getOperand(i))) {
323         IsRegSeq = false;
324         break;
325       }
326       RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
327       RegSeqArgs[1 + (2 * i) + 1] =
328               CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
329     }
330
331     if (NOps != NumVectorElts) {
332       // Fill in the missing undef elements if this was a scalar_to_vector.
333       assert(Opc == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
334
335       MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
336                                                      SDLoc(N), EltVT);
337       for (unsigned i = NOps; i < NumVectorElts; ++i) {
338         RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
339         RegSeqArgs[1 + (2 * i) + 1] =
340           CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
341       }
342     }
343
344     if (!IsRegSeq)
345       break;
346     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
347                                 RegSeqArgs);
348   }
349   case ISD::BUILD_PAIR: {
350     SDValue RC, SubReg0, SubReg1;
351     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
352       break;
353     }
354     if (N->getValueType(0) == MVT::i128) {
355       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32);
356       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, MVT::i32);
357       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, MVT::i32);
358     } else if (N->getValueType(0) == MVT::i64) {
359       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32);
360       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
361       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
362     } else {
363       llvm_unreachable("Unhandled value type for BUILD_PAIR");
364     }
365     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
366                             N->getOperand(1), SubReg1 };
367     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
368                                   SDLoc(N), N->getValueType(0), Ops);
369   }
370
371   case ISD::Constant:
372   case ISD::ConstantFP: {
373     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
374     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
375         N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
376       break;
377
378     uint64_t Imm;
379     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
380       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
381     else {
382       ConstantSDNode *C = cast<ConstantSDNode>(N);
383       Imm = C->getZExtValue();
384     }
385
386     SDNode *Lo = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
387                                 CurDAG->getConstant(Imm & 0xFFFFFFFF, MVT::i32));
388     SDNode *Hi = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
389                                 CurDAG->getConstant(Imm >> 32, MVT::i32));
390     const SDValue Ops[] = {
391       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
392       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
393       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32)
394     };
395
396     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, SDLoc(N),
397                                   N->getValueType(0), Ops);
398   }
399
400   case AMDGPUISD::REGISTER_LOAD: {
401     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS)
402       break;
403     SDValue Addr, Offset;
404
405     SelectADDRIndirect(N->getOperand(1), Addr, Offset);
406     const SDValue Ops[] = {
407       Addr,
408       Offset,
409       CurDAG->getTargetConstant(0, MVT::i32),
410       N->getOperand(0),
411     };
412     return CurDAG->getMachineNode(AMDGPU::SI_RegisterLoad, SDLoc(N),
413                                   CurDAG->getVTList(MVT::i32, MVT::i64, MVT::Other),
414                                   Ops);
415   }
416   case AMDGPUISD::REGISTER_STORE: {
417     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS)
418       break;
419     SDValue Addr, Offset;
420     SelectADDRIndirect(N->getOperand(2), Addr, Offset);
421     const SDValue Ops[] = {
422       N->getOperand(1),
423       Addr,
424       Offset,
425       CurDAG->getTargetConstant(0, MVT::i32),
426       N->getOperand(0),
427     };
428     return CurDAG->getMachineNode(AMDGPU::SI_RegisterStorePseudo, SDLoc(N),
429                                         CurDAG->getVTList(MVT::Other),
430                                         Ops);
431   }
432
433   case AMDGPUISD::BFE_I32:
434   case AMDGPUISD::BFE_U32: {
435     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
436       break;
437
438     // There is a scalar version available, but unlike the vector version which
439     // has a separate operand for the offset and width, the scalar version packs
440     // the width and offset into a single operand. Try to move to the scalar
441     // version if the offsets are constant, so that we can try to keep extended
442     // loads of kernel arguments in SGPRs.
443
444     // TODO: Technically we could try to pattern match scalar bitshifts of
445     // dynamic values, but it's probably not useful.
446     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
447     if (!Offset)
448       break;
449
450     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
451     if (!Width)
452       break;
453
454     bool Signed = Opc == AMDGPUISD::BFE_I32;
455
456     // Transformation function, pack the offset and width of a BFE into
457     // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
458     // source, bits [5:0] contain the offset and bits [22:16] the width.
459
460     uint32_t OffsetVal = Offset->getZExtValue();
461     uint32_t WidthVal = Width->getZExtValue();
462
463     uint32_t PackedVal = OffsetVal | WidthVal << 16;
464
465     SDValue PackedOffsetWidth = CurDAG->getTargetConstant(PackedVal, MVT::i32);
466     return CurDAG->getMachineNode(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32,
467                                   SDLoc(N),
468                                   MVT::i32,
469                                   N->getOperand(0),
470                                   PackedOffsetWidth);
471
472   }
473   case AMDGPUISD::DIV_SCALE: {
474     return SelectDIV_SCALE(N);
475   }
476   }
477   return SelectCode(N);
478 }
479
480
481 bool AMDGPUDAGToDAGISel::checkType(const Value *Ptr, unsigned AS) {
482   assert(AS != 0 && "Use checkPrivateAddress instead.");
483   if (!Ptr)
484     return false;
485
486   return Ptr->getType()->getPointerAddressSpace() == AS;
487 }
488
489 bool AMDGPUDAGToDAGISel::checkPrivateAddress(const MachineMemOperand *Op) {
490   if (Op->getPseudoValue())
491     return true;
492
493   if (PointerType *PT = dyn_cast<PointerType>(Op->getValue()->getType()))
494     return PT->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS;
495
496   return false;
497 }
498
499 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
500   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
501 }
502
503 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
504   const Value *MemVal = N->getMemOperand()->getValue();
505   return (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
506           !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
507           !checkType(MemVal, AMDGPUAS::REGION_ADDRESS));
508 }
509
510 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
511   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
512 }
513
514 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
515   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
516 }
517
518 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int CbId) const {
519   const Value *MemVal = N->getMemOperand()->getValue();
520   if (CbId == -1)
521     return checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS);
522
523   return checkType(MemVal, AMDGPUAS::CONSTANT_BUFFER_0 + CbId);
524 }
525
526 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
527   if (N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) {
528     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
529     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
530         N->getMemoryVT().bitsLT(MVT::i32)) {
531       return true;
532     }
533   }
534   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
535 }
536
537 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
538   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::PARAM_I_ADDRESS);
539 }
540
541 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
542   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
543 }
544
545 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
546   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
547 }
548
549 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
550   MachineMemOperand *MMO = N->getMemOperand();
551   if (checkPrivateAddress(N->getMemOperand())) {
552     if (MMO) {
553       const PseudoSourceValue *PSV = MMO->getPseudoValue();
554       if (PSV && PSV == PseudoSourceValue::getConstantPool()) {
555         return true;
556       }
557     }
558   }
559   return false;
560 }
561
562 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
563   if (checkPrivateAddress(N->getMemOperand())) {
564     // Check to make sure we are not a constant pool load or a constant load
565     // that is marked as a private load
566     if (isCPLoad(N) || isConstantLoad(N, -1)) {
567       return false;
568     }
569   }
570
571   const Value *MemVal = N->getMemOperand()->getValue();
572   if (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
573       !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
574       !checkType(MemVal, AMDGPUAS::REGION_ADDRESS) &&
575       !checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS) &&
576       !checkType(MemVal, AMDGPUAS::PARAM_D_ADDRESS) &&
577       !checkType(MemVal, AMDGPUAS::PARAM_I_ADDRESS)){
578     return true;
579   }
580   return false;
581 }
582
583 bool AMDGPUDAGToDAGISel::isCFDepth0() const {
584   // FIXME: Figure out a way to use DominatorTree analysis here.
585   const BasicBlock *CurBlock = FuncInfo->MBB->getBasicBlock();
586   const Function *Fn = FuncInfo->Fn;
587   return &Fn->front() == CurBlock || &Fn->back() == CurBlock;
588 }
589
590
591 const char *AMDGPUDAGToDAGISel::getPassName() const {
592   return "AMDGPU DAG->DAG Pattern Instruction Selection";
593 }
594
595 #ifdef DEBUGTMP
596 #undef INT64_C
597 #endif
598 #undef DEBUGTMP
599
600 //===----------------------------------------------------------------------===//
601 // Complex Patterns
602 //===----------------------------------------------------------------------===//
603
604 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
605                                                          SDValue& IntPtr) {
606   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
607     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, true);
608     return true;
609   }
610   return false;
611 }
612
613 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
614     SDValue& BaseReg, SDValue &Offset) {
615   if (!isa<ConstantSDNode>(Addr)) {
616     BaseReg = Addr;
617     Offset = CurDAG->getIntPtrConstant(0, true);
618     return true;
619   }
620   return false;
621 }
622
623 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
624                                            SDValue &Offset) {
625   ConstantSDNode *IMMOffset;
626
627   if (Addr.getOpcode() == ISD::ADD
628       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
629       && isInt<16>(IMMOffset->getZExtValue())) {
630
631       Base = Addr.getOperand(0);
632       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
633       return true;
634   // If the pointer address is constant, we can move it to the offset field.
635   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
636              && isInt<16>(IMMOffset->getZExtValue())) {
637     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
638                                   SDLoc(CurDAG->getEntryNode()),
639                                   AMDGPU::ZERO, MVT::i32);
640     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
641     return true;
642   }
643
644   // Default case, no offset
645   Base = Addr;
646   Offset = CurDAG->getTargetConstant(0, MVT::i32);
647   return true;
648 }
649
650 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
651                                             SDValue &Offset) {
652   ConstantSDNode *C;
653
654   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
655     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
656     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
657   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
658             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
659     Base = Addr.getOperand(0);
660     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
661   } else {
662     Base = Addr;
663     Offset = CurDAG->getTargetConstant(0, MVT::i32);
664   }
665
666   return true;
667 }
668
669 SDNode *AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
670   SDLoc DL(N);
671   SDValue LHS = N->getOperand(0);
672   SDValue RHS = N->getOperand(1);
673
674   bool IsAdd = (N->getOpcode() == ISD::ADD);
675
676   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
677   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
678
679   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
680                                        DL, MVT::i32, LHS, Sub0);
681   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
682                                        DL, MVT::i32, LHS, Sub1);
683
684   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
685                                        DL, MVT::i32, RHS, Sub0);
686   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
687                                        DL, MVT::i32, RHS, Sub1);
688
689   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
690   SDValue AddLoArgs[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
691
692
693   unsigned Opc = IsAdd ? AMDGPU::S_ADD_I32 : AMDGPU::S_SUB_I32;
694   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
695
696   if (!isCFDepth0()) {
697     Opc = IsAdd ? AMDGPU::V_ADD_I32_e32 : AMDGPU::V_SUB_I32_e32;
698     CarryOpc = IsAdd ? AMDGPU::V_ADDC_U32_e32 : AMDGPU::V_SUBB_U32_e32;
699   }
700
701   SDNode *AddLo = CurDAG->getMachineNode( Opc, DL, VTList, AddLoArgs);
702   SDValue Carry(AddLo, 1);
703   SDNode *AddHi
704     = CurDAG->getMachineNode(CarryOpc, DL, MVT::i32,
705                              SDValue(Hi0, 0), SDValue(Hi1, 0), Carry);
706
707   SDValue Args[5] = {
708     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
709     SDValue(AddLo,0),
710     Sub0,
711     SDValue(AddHi,0),
712     Sub1,
713   };
714   return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, MVT::i64, Args);
715 }
716
717 SDNode *AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
718   SDLoc SL(N);
719   EVT VT = N->getValueType(0);
720
721   assert(VT == MVT::f32 || VT == MVT::f64);
722
723   unsigned Opc
724     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
725
726   const SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
727
728   SDValue Ops[] = {
729     N->getOperand(0),
730     N->getOperand(1),
731     N->getOperand(2),
732     Zero,
733     Zero,
734     Zero,
735     Zero
736   };
737
738   return CurDAG->SelectNodeTo(N, Opc, VT, MVT::i1, Ops);
739 }
740
741 static SDValue wrapAddr64Rsrc(SelectionDAG *DAG, SDLoc DL, SDValue Ptr) {
742   return SDValue(DAG->getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::v4i32,
743                                      Ptr), 0);
744 }
745
746 static bool isLegalMUBUFImmOffset(const ConstantSDNode *Imm) {
747   return isUInt<12>(Imm->getZExtValue());
748 }
749
750 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &Ptr,
751                                            SDValue &Offset,
752                                            SDValue &ImmOffset) const {
753   SDLoc DL(Addr);
754
755   if (CurDAG->isBaseWithConstantOffset(Addr)) {
756     SDValue N0 = Addr.getOperand(0);
757     SDValue N1 = Addr.getOperand(1);
758     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
759
760     if (isLegalMUBUFImmOffset(C1)) {
761
762       if (N0.getOpcode() == ISD::ADD) {
763         // (add (add N2, N3), C1)
764         SDValue N2 = N0.getOperand(0);
765         SDValue N3 = N0.getOperand(1);
766         Ptr = wrapAddr64Rsrc(CurDAG, DL, N2);
767         Offset = N3;
768         ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
769         return true;
770       }
771
772       // (add N0, C1)
773       Ptr = wrapAddr64Rsrc(CurDAG, DL, CurDAG->getTargetConstant(0, MVT::i64));;
774       Offset = N0;
775       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
776       return true;
777     }
778   }
779   if (Addr.getOpcode() == ISD::ADD) {
780     // (add N0, N1)
781     SDValue N0 = Addr.getOperand(0);
782     SDValue N1 = Addr.getOperand(1);
783     Ptr = wrapAddr64Rsrc(CurDAG, DL, N0);
784     Offset = N1;
785     ImmOffset = CurDAG->getTargetConstant(0, MVT::i16);
786     return true;
787   }
788
789   // default case
790   Ptr = wrapAddr64Rsrc(CurDAG, DL, CurDAG->getConstant(0, MVT::i64));
791   Offset = Addr;
792   ImmOffset = CurDAG->getTargetConstant(0, MVT::i16);
793   return true;
794 }
795
796 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
797 ///        The TID (Thread ID) is multipled by the stride value (bits [61:48]
798 ///        of the resource descriptor) to create an offset, which is added to the
799 ///        resource ponter.
800 static SDValue buildScratchRSRC(SelectionDAG *DAG, SDLoc DL, SDValue Ptr) {
801
802   uint64_t Rsrc = AMDGPU::RSRC_DATA_FORMAT | AMDGPU::RSRC_TID_ENABLE |
803                   0xffffffff;
804
805   SDValue PtrLo = DAG->getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
806   SDValue PtrHi = DAG->getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
807   SDValue DataLo = DAG->getTargetConstant(
808       Rsrc & APInt::getAllOnesValue(32).getZExtValue(), MVT::i32);
809   SDValue DataHi = DAG->getTargetConstant(Rsrc >> 32, MVT::i32);
810
811   const SDValue Ops[] = { PtrLo, PtrHi, DataLo, DataHi };
812   return SDValue(DAG->getMachineNode(AMDGPU::SI_BUFFER_RSRC, DL,
813                                      MVT::v4i32, Ops), 0);
814 }
815
816 bool AMDGPUDAGToDAGISel::SelectMUBUFScratch(SDValue Addr, SDValue &Rsrc,
817                                             SDValue &VAddr, SDValue &SOffset,
818                                             SDValue &ImmOffset) const {
819
820   SDLoc DL(Addr);
821   MachineFunction &MF = CurDAG->getMachineFunction();
822   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo*>(MF.getTarget().getRegisterInfo());
823   MachineRegisterInfo &MRI = MF.getRegInfo();
824
825
826   unsigned ScratchPtrReg =
827       TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
828   unsigned ScratchOffsetReg =
829       TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET);
830
831   Rsrc = buildScratchRSRC(CurDAG, DL, CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL, MRI.getLiveInVirtReg(ScratchPtrReg), MVT::i64));
832   SOffset = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
833       MRI.getLiveInVirtReg(ScratchOffsetReg), MVT::i32);
834
835   // (add n0, c1)
836   if (CurDAG->isBaseWithConstantOffset(Addr)) {
837     SDValue N1 = Addr.getOperand(1);
838     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
839
840     if (isLegalMUBUFImmOffset(C1)) {
841       VAddr = Addr.getOperand(0);
842       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
843       return true;
844     }
845   }
846
847   // (add FI, n0)
848   if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
849        isa<FrameIndexSDNode>(Addr.getOperand(0))) {
850     VAddr = Addr.getOperand(1);
851     ImmOffset = Addr.getOperand(0);
852     return true;
853   }
854
855   // (FI)
856   if (isa<FrameIndexSDNode>(Addr)) {
857     VAddr = SDValue(CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
858                                           CurDAG->getConstant(0, MVT::i32)), 0);
859     ImmOffset = Addr;
860     return true;
861   }
862
863   // (node)
864   VAddr = Addr;
865   ImmOffset = CurDAG->getTargetConstant(0, MVT::i16);
866   return true;
867 }
868
869 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr32(SDValue Addr, SDValue &SRsrc,
870                                            SDValue &VAddr, SDValue &SOffset,
871                                            SDValue &Offset, SDValue &Offen,
872                                            SDValue &Idxen, SDValue &GLC,
873                                            SDValue &SLC, SDValue &TFE) const {
874
875   GLC = CurDAG->getTargetConstant(0, MVT::i1);
876   SLC = CurDAG->getTargetConstant(0, MVT::i1);
877   TFE = CurDAG->getTargetConstant(0, MVT::i1);
878
879   Idxen = CurDAG->getTargetConstant(0, MVT::i1);
880   Offen = CurDAG->getTargetConstant(1, MVT::i1);
881
882   return SelectMUBUFScratch(Addr, SRsrc, VAddr, SOffset, Offset);
883 }
884
885 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
886                                         SDValue &SrcMods) const {
887
888   unsigned Mods = 0;
889
890   Src = In;
891
892   if (Src.getOpcode() == ISD::FNEG) {
893     Mods |= SISrcMods::NEG;
894     Src = Src.getOperand(0);
895   }
896
897   if (Src.getOpcode() == ISD::FABS) {
898     Mods |= SISrcMods::ABS;
899     Src = Src.getOperand(0);
900   }
901
902   SrcMods = CurDAG->getTargetConstant(Mods, MVT::i32);
903
904   return true;
905 }
906
907 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
908                                          SDValue &SrcMods, SDValue &Clamp,
909                                          SDValue &Omod) const {
910   // FIXME: Handle Clamp and Omod
911   Clamp = CurDAG->getTargetConstant(0, MVT::i32);
912   Omod = CurDAG->getTargetConstant(0, MVT::i32);
913
914   return SelectVOP3Mods(In, Src, SrcMods);
915 }
916
917 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
918   const AMDGPUTargetLowering& Lowering =
919     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
920   bool IsModified = false;
921   do {
922     IsModified = false;
923     // Go over all selected nodes and try to fold them a bit more
924     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
925          E = CurDAG->allnodes_end(); I != E; ++I) {
926
927       SDNode *Node = I;
928
929       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
930       if (!MachineNode)
931         continue;
932
933       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
934       if (ResNode != Node) {
935         ReplaceUses(Node, ResNode);
936         IsModified = true;
937       }
938     }
939     CurDAG->RemoveDeadNodes();
940   } while (IsModified);
941 }