bf1cf8832e72897d2bc9eea818dd289387675ed8
[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 isFlatStore(const StoreSDNode *N);
69   static bool isPrivateStore(const StoreSDNode *N);
70   static bool isLocalStore(const StoreSDNode *N);
71   static bool isRegionStore(const StoreSDNode *N);
72
73   bool isCPLoad(const LoadSDNode *N) const;
74   bool isConstantLoad(const LoadSDNode *N, int cbID) const;
75   bool isGlobalLoad(const LoadSDNode *N) const;
76   bool isFlatLoad(const LoadSDNode *N) const;
77   bool isParamLoad(const LoadSDNode *N) const;
78   bool isPrivateLoad(const LoadSDNode *N) const;
79   bool isLocalLoad(const LoadSDNode *N) const;
80   bool isRegionLoad(const LoadSDNode *N) const;
81
82   /// \returns True if the current basic block being selected is at control
83   ///          flow depth 0.  Meaning that the current block dominates the
84   //           exit block.
85   bool isCFDepth0() const;
86
87   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
88   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
89   bool SelectGlobalValueVariableOffset(SDValue Addr, SDValue &BaseReg,
90                                        SDValue& Offset);
91   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
92   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
93   bool isDSOffsetLegal(const SDValue &Base, unsigned Offset,
94                        unsigned OffsetBits) const;
95   bool SelectDS1Addr1Offset(SDValue Ptr, SDValue &Base, SDValue &Offset) const;
96   bool SelectDS64Bit4ByteAligned(SDValue Ptr, SDValue &Base, SDValue &Offset0,
97                                  SDValue &Offset1) const;
98   void SelectMUBUF(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
99                    SDValue &SOffset, SDValue &Offset, SDValue &Offen,
100                    SDValue &Idxen, SDValue &Addr64, SDValue &GLC, SDValue &SLC,
101                    SDValue &TFE) const;
102   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc, SDValue &VAddr,
103                          SDValue &Offset) const;
104   bool SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
105                          SDValue &VAddr, SDValue &Offset,
106                          SDValue &SLC) const;
107   bool SelectMUBUFScratch(SDValue Addr, SDValue &RSrc, SDValue &VAddr,
108                           SDValue &SOffset, SDValue &ImmOffset) const;
109   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &SOffset,
110                          SDValue &Offset, SDValue &GLC, SDValue &SLC,
111                          SDValue &TFE) const;
112   bool SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc, SDValue &Soffset,
113                          SDValue &Offset, SDValue &GLC) const;
114   SDNode *SelectAddrSpaceCast(SDNode *N);
115   bool SelectVOP3Mods(SDValue In, SDValue &Src, SDValue &SrcMods) const;
116   bool SelectVOP3Mods0(SDValue In, SDValue &Src, SDValue &SrcMods,
117                        SDValue &Clamp, SDValue &Omod) const;
118
119   SDNode *SelectADD_SUB_I64(SDNode *N);
120   SDNode *SelectDIV_SCALE(SDNode *N);
121
122   // Include the pieces autogenerated from the target description.
123 #include "AMDGPUGenDAGISel.inc"
124 };
125 }  // end anonymous namespace
126
127 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
128 // DAG, ready for instruction scheduling.
129 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM) {
130   return new AMDGPUDAGToDAGISel(TM);
131 }
132
133 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
134   : SelectionDAGISel(TM), Subtarget(TM.getSubtarget<AMDGPUSubtarget>()) {
135 }
136
137 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
138 }
139
140 bool AMDGPUDAGToDAGISel::isInlineImmediate(SDNode *N) const {
141   const SITargetLowering *TL
142       = static_cast<const SITargetLowering *>(getTargetLowering());
143   return TL->analyzeImmediate(N) == 0;
144 }
145
146 /// \brief Determine the register class for \p OpNo
147 /// \returns The register class of the virtual register that will be used for
148 /// the given operand number \OpNo or NULL if the register class cannot be
149 /// determined.
150 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
151                                                           unsigned OpNo) const {
152   if (!N->isMachineOpcode())
153     return nullptr;
154
155   switch (N->getMachineOpcode()) {
156   default: {
157     const MCInstrDesc &Desc =
158         TM.getSubtargetImpl()->getInstrInfo()->get(N->getMachineOpcode());
159     unsigned OpIdx = Desc.getNumDefs() + OpNo;
160     if (OpIdx >= Desc.getNumOperands())
161       return nullptr;
162     int RegClass = Desc.OpInfo[OpIdx].RegClass;
163     if (RegClass == -1)
164       return nullptr;
165
166     return TM.getSubtargetImpl()->getRegisterInfo()->getRegClass(RegClass);
167   }
168   case AMDGPU::REG_SEQUENCE: {
169     unsigned RCID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
170     const TargetRegisterClass *SuperRC =
171         TM.getSubtargetImpl()->getRegisterInfo()->getRegClass(RCID);
172
173     SDValue SubRegOp = N->getOperand(OpNo + 1);
174     unsigned SubRegIdx = cast<ConstantSDNode>(SubRegOp)->getZExtValue();
175     return TM.getSubtargetImpl()->getRegisterInfo()->getSubClassWithSubReg(
176         SuperRC, SubRegIdx);
177   }
178   }
179 }
180
181 SDValue AMDGPUDAGToDAGISel::getSmallIPtrImm(unsigned int Imm) {
182   return CurDAG->getTargetConstant(Imm, MVT::i32);
183 }
184
185 bool AMDGPUDAGToDAGISel::SelectADDRParam(
186   SDValue Addr, SDValue& R1, SDValue& R2) {
187
188   if (Addr.getOpcode() == ISD::FrameIndex) {
189     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
190       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
191       R2 = CurDAG->getTargetConstant(0, MVT::i32);
192     } else {
193       R1 = Addr;
194       R2 = CurDAG->getTargetConstant(0, MVT::i32);
195     }
196   } else if (Addr.getOpcode() == ISD::ADD) {
197     R1 = Addr.getOperand(0);
198     R2 = Addr.getOperand(1);
199   } else {
200     R1 = Addr;
201     R2 = CurDAG->getTargetConstant(0, MVT::i32);
202   }
203   return true;
204 }
205
206 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
207   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
208       Addr.getOpcode() == ISD::TargetGlobalAddress) {
209     return false;
210   }
211   return SelectADDRParam(Addr, R1, R2);
212 }
213
214
215 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
216   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
217       Addr.getOpcode() == ISD::TargetGlobalAddress) {
218     return false;
219   }
220
221   if (Addr.getOpcode() == ISD::FrameIndex) {
222     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
223       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
224       R2 = CurDAG->getTargetConstant(0, MVT::i64);
225     } else {
226       R1 = Addr;
227       R2 = CurDAG->getTargetConstant(0, MVT::i64);
228     }
229   } else if (Addr.getOpcode() == ISD::ADD) {
230     R1 = Addr.getOperand(0);
231     R2 = Addr.getOperand(1);
232   } else {
233     R1 = Addr;
234     R2 = CurDAG->getTargetConstant(0, MVT::i64);
235   }
236   return true;
237 }
238
239 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
240   unsigned int Opc = N->getOpcode();
241   if (N->isMachineOpcode()) {
242     N->setNodeId(-1);
243     return nullptr;   // Already selected.
244   }
245
246   const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
247   switch (Opc) {
248   default: break;
249   // We are selecting i64 ADD here instead of custom lower it during
250   // DAG legalization, so we can fold some i64 ADDs used for address
251   // calculation into the LOAD and STORE instructions.
252   case ISD::ADD:
253   case ISD::SUB: {
254     if (N->getValueType(0) != MVT::i64 ||
255         ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
256       break;
257
258     return SelectADD_SUB_I64(N);
259   }
260   case ISD::SCALAR_TO_VECTOR:
261   case AMDGPUISD::BUILD_VERTICAL_VECTOR:
262   case ISD::BUILD_VECTOR: {
263     unsigned RegClassID;
264     const AMDGPURegisterInfo *TRI = static_cast<const AMDGPURegisterInfo *>(
265         TM.getSubtargetImpl()->getRegisterInfo());
266     const SIRegisterInfo *SIRI = static_cast<const SIRegisterInfo *>(
267         TM.getSubtargetImpl()->getRegisterInfo());
268     EVT VT = N->getValueType(0);
269     unsigned NumVectorElts = VT.getVectorNumElements();
270     EVT EltVT = VT.getVectorElementType();
271     assert(EltVT.bitsEq(MVT::i32));
272     if (ST.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
273       bool UseVReg = true;
274       for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
275                                                     U != E; ++U) {
276         if (!U->isMachineOpcode()) {
277           continue;
278         }
279         const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
280         if (!RC) {
281           continue;
282         }
283         if (SIRI->isSGPRClass(RC)) {
284           UseVReg = false;
285         }
286       }
287       switch(NumVectorElts) {
288       case 1: RegClassID = UseVReg ? AMDGPU::VReg_32RegClassID :
289                                      AMDGPU::SReg_32RegClassID;
290         break;
291       case 2: RegClassID = UseVReg ? AMDGPU::VReg_64RegClassID :
292                                      AMDGPU::SReg_64RegClassID;
293         break;
294       case 4: RegClassID = UseVReg ? AMDGPU::VReg_128RegClassID :
295                                      AMDGPU::SReg_128RegClassID;
296         break;
297       case 8: RegClassID = UseVReg ? AMDGPU::VReg_256RegClassID :
298                                      AMDGPU::SReg_256RegClassID;
299         break;
300       case 16: RegClassID = UseVReg ? AMDGPU::VReg_512RegClassID :
301                                       AMDGPU::SReg_512RegClassID;
302         break;
303       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
304       }
305     } else {
306       // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
307       // that adds a 128 bits reg copy when going through TwoAddressInstructions
308       // pass. We want to avoid 128 bits copies as much as possible because they
309       // can't be bundled by our scheduler.
310       switch(NumVectorElts) {
311       case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
312       case 4:
313         if (Opc == AMDGPUISD::BUILD_VERTICAL_VECTOR)
314           RegClassID = AMDGPU::R600_Reg128VerticalRegClassID;
315         else
316           RegClassID = AMDGPU::R600_Reg128RegClassID;
317         break;
318       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
319       }
320     }
321
322     SDValue RegClass = CurDAG->getTargetConstant(RegClassID, MVT::i32);
323
324     if (NumVectorElts == 1) {
325       return CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS, EltVT,
326                                   N->getOperand(0), RegClass);
327     }
328
329     assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
330                                   "supported yet");
331     // 16 = Max Num Vector Elements
332     // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
333     // 1 = Vector Register Class
334     SmallVector<SDValue, 16 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
335
336     RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, MVT::i32);
337     bool IsRegSeq = true;
338     unsigned NOps = N->getNumOperands();
339     for (unsigned i = 0; i < NOps; i++) {
340       // XXX: Why is this here?
341       if (dyn_cast<RegisterSDNode>(N->getOperand(i))) {
342         IsRegSeq = false;
343         break;
344       }
345       RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
346       RegSeqArgs[1 + (2 * i) + 1] =
347               CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
348     }
349
350     if (NOps != NumVectorElts) {
351       // Fill in the missing undef elements if this was a scalar_to_vector.
352       assert(Opc == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
353
354       MachineSDNode *ImpDef = CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,
355                                                      SDLoc(N), EltVT);
356       for (unsigned i = NOps; i < NumVectorElts; ++i) {
357         RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
358         RegSeqArgs[1 + (2 * i) + 1] =
359           CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
360       }
361     }
362
363     if (!IsRegSeq)
364       break;
365     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
366                                 RegSeqArgs);
367   }
368   case ISD::BUILD_PAIR: {
369     SDValue RC, SubReg0, SubReg1;
370     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
371       break;
372     }
373     if (N->getValueType(0) == MVT::i128) {
374       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32);
375       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, MVT::i32);
376       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, MVT::i32);
377     } else if (N->getValueType(0) == MVT::i64) {
378       RC = CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32);
379       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
380       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
381     } else {
382       llvm_unreachable("Unhandled value type for BUILD_PAIR");
383     }
384     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
385                             N->getOperand(1), SubReg1 };
386     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
387                                   SDLoc(N), N->getValueType(0), Ops);
388   }
389
390   case ISD::Constant:
391   case ISD::ConstantFP: {
392     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
393     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
394         N->getValueType(0).getSizeInBits() != 64 || isInlineImmediate(N))
395       break;
396
397     uint64_t Imm;
398     if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(N))
399       Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
400     else {
401       ConstantSDNode *C = cast<ConstantSDNode>(N);
402       Imm = C->getZExtValue();
403     }
404
405     SDNode *Lo = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
406                                 CurDAG->getConstant(Imm & 0xFFFFFFFF, MVT::i32));
407     SDNode *Hi = CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
408                                 CurDAG->getConstant(Imm >> 32, MVT::i32));
409     const SDValue Ops[] = {
410       CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
411       SDValue(Lo, 0), CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
412       SDValue(Hi, 0), CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32)
413     };
414
415     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, SDLoc(N),
416                                   N->getValueType(0), Ops);
417   }
418
419   case AMDGPUISD::REGISTER_LOAD: {
420     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS)
421       break;
422     SDValue Addr, Offset;
423
424     SelectADDRIndirect(N->getOperand(1), Addr, Offset);
425     const SDValue Ops[] = {
426       Addr,
427       Offset,
428       CurDAG->getTargetConstant(0, MVT::i32),
429       N->getOperand(0),
430     };
431     return CurDAG->getMachineNode(AMDGPU::SI_RegisterLoad, SDLoc(N),
432                                   CurDAG->getVTList(MVT::i32, MVT::i64, MVT::Other),
433                                   Ops);
434   }
435   case AMDGPUISD::REGISTER_STORE: {
436     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS)
437       break;
438     SDValue Addr, Offset;
439     SelectADDRIndirect(N->getOperand(2), Addr, Offset);
440     const SDValue Ops[] = {
441       N->getOperand(1),
442       Addr,
443       Offset,
444       CurDAG->getTargetConstant(0, MVT::i32),
445       N->getOperand(0),
446     };
447     return CurDAG->getMachineNode(AMDGPU::SI_RegisterStorePseudo, SDLoc(N),
448                                         CurDAG->getVTList(MVT::Other),
449                                         Ops);
450   }
451
452   case AMDGPUISD::BFE_I32:
453   case AMDGPUISD::BFE_U32: {
454     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS)
455       break;
456
457     // There is a scalar version available, but unlike the vector version which
458     // has a separate operand for the offset and width, the scalar version packs
459     // the width and offset into a single operand. Try to move to the scalar
460     // version if the offsets are constant, so that we can try to keep extended
461     // loads of kernel arguments in SGPRs.
462
463     // TODO: Technically we could try to pattern match scalar bitshifts of
464     // dynamic values, but it's probably not useful.
465     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
466     if (!Offset)
467       break;
468
469     ConstantSDNode *Width = dyn_cast<ConstantSDNode>(N->getOperand(2));
470     if (!Width)
471       break;
472
473     bool Signed = Opc == AMDGPUISD::BFE_I32;
474
475     // Transformation function, pack the offset and width of a BFE into
476     // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
477     // source, bits [5:0] contain the offset and bits [22:16] the width.
478
479     uint32_t OffsetVal = Offset->getZExtValue();
480     uint32_t WidthVal = Width->getZExtValue();
481
482     uint32_t PackedVal = OffsetVal | WidthVal << 16;
483
484     SDValue PackedOffsetWidth = CurDAG->getTargetConstant(PackedVal, MVT::i32);
485     return CurDAG->getMachineNode(Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32,
486                                   SDLoc(N),
487                                   MVT::i32,
488                                   N->getOperand(0),
489                                   PackedOffsetWidth);
490
491   }
492   case AMDGPUISD::DIV_SCALE: {
493     return SelectDIV_SCALE(N);
494   }
495   case ISD::ADDRSPACECAST:
496     return SelectAddrSpaceCast(N);
497   }
498   return SelectCode(N);
499 }
500
501
502 bool AMDGPUDAGToDAGISel::checkType(const Value *Ptr, unsigned AS) {
503   assert(AS != 0 && "Use checkPrivateAddress instead.");
504   if (!Ptr)
505     return false;
506
507   return Ptr->getType()->getPointerAddressSpace() == AS;
508 }
509
510 bool AMDGPUDAGToDAGISel::checkPrivateAddress(const MachineMemOperand *Op) {
511   if (Op->getPseudoValue())
512     return true;
513
514   if (PointerType *PT = dyn_cast<PointerType>(Op->getValue()->getType()))
515     return PT->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS;
516
517   return false;
518 }
519
520 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
521   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
522 }
523
524 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
525   const Value *MemVal = N->getMemOperand()->getValue();
526   return (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
527           !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
528           !checkType(MemVal, AMDGPUAS::REGION_ADDRESS));
529 }
530
531 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
532   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
533 }
534
535 bool AMDGPUDAGToDAGISel::isFlatStore(const StoreSDNode *N) {
536   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::FLAT_ADDRESS);
537 }
538
539 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
540   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
541 }
542
543 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int CbId) const {
544   const Value *MemVal = N->getMemOperand()->getValue();
545   if (CbId == -1)
546     return checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS);
547
548   return checkType(MemVal, AMDGPUAS::CONSTANT_BUFFER_0 + CbId);
549 }
550
551 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
552   if (N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) {
553     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
554     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
555         N->getMemoryVT().bitsLT(MVT::i32)) {
556       return true;
557     }
558   }
559   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::GLOBAL_ADDRESS);
560 }
561
562 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
563   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::PARAM_I_ADDRESS);
564 }
565
566 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
567   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::LOCAL_ADDRESS);
568 }
569
570 bool AMDGPUDAGToDAGISel::isFlatLoad(const  LoadSDNode *N) const {
571   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::FLAT_ADDRESS);
572 }
573
574 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
575   return checkType(N->getMemOperand()->getValue(), AMDGPUAS::REGION_ADDRESS);
576 }
577
578 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
579   MachineMemOperand *MMO = N->getMemOperand();
580   if (checkPrivateAddress(N->getMemOperand())) {
581     if (MMO) {
582       const PseudoSourceValue *PSV = MMO->getPseudoValue();
583       if (PSV && PSV == PseudoSourceValue::getConstantPool()) {
584         return true;
585       }
586     }
587   }
588   return false;
589 }
590
591 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
592   if (checkPrivateAddress(N->getMemOperand())) {
593     // Check to make sure we are not a constant pool load or a constant load
594     // that is marked as a private load
595     if (isCPLoad(N) || isConstantLoad(N, -1)) {
596       return false;
597     }
598   }
599
600   const Value *MemVal = N->getMemOperand()->getValue();
601   if (!checkType(MemVal, AMDGPUAS::LOCAL_ADDRESS) &&
602       !checkType(MemVal, AMDGPUAS::GLOBAL_ADDRESS) &&
603       !checkType(MemVal, AMDGPUAS::FLAT_ADDRESS) &&
604       !checkType(MemVal, AMDGPUAS::REGION_ADDRESS) &&
605       !checkType(MemVal, AMDGPUAS::CONSTANT_ADDRESS) &&
606       !checkType(MemVal, AMDGPUAS::PARAM_D_ADDRESS) &&
607       !checkType(MemVal, AMDGPUAS::PARAM_I_ADDRESS)) {
608     return true;
609   }
610   return false;
611 }
612
613 bool AMDGPUDAGToDAGISel::isCFDepth0() const {
614   // FIXME: Figure out a way to use DominatorTree analysis here.
615   const BasicBlock *CurBlock = FuncInfo->MBB->getBasicBlock();
616   const Function *Fn = FuncInfo->Fn;
617   return &Fn->front() == CurBlock || &Fn->back() == CurBlock;
618 }
619
620
621 const char *AMDGPUDAGToDAGISel::getPassName() const {
622   return "AMDGPU DAG->DAG Pattern Instruction Selection";
623 }
624
625 #ifdef DEBUGTMP
626 #undef INT64_C
627 #endif
628 #undef DEBUGTMP
629
630 //===----------------------------------------------------------------------===//
631 // Complex Patterns
632 //===----------------------------------------------------------------------===//
633
634 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
635                                                          SDValue& IntPtr) {
636   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
637     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, true);
638     return true;
639   }
640   return false;
641 }
642
643 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
644     SDValue& BaseReg, SDValue &Offset) {
645   if (!isa<ConstantSDNode>(Addr)) {
646     BaseReg = Addr;
647     Offset = CurDAG->getIntPtrConstant(0, true);
648     return true;
649   }
650   return false;
651 }
652
653 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
654                                            SDValue &Offset) {
655   ConstantSDNode *IMMOffset;
656
657   if (Addr.getOpcode() == ISD::ADD
658       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
659       && isInt<16>(IMMOffset->getZExtValue())) {
660
661       Base = Addr.getOperand(0);
662       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
663       return true;
664   // If the pointer address is constant, we can move it to the offset field.
665   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
666              && isInt<16>(IMMOffset->getZExtValue())) {
667     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
668                                   SDLoc(CurDAG->getEntryNode()),
669                                   AMDGPU::ZERO, MVT::i32);
670     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
671     return true;
672   }
673
674   // Default case, no offset
675   Base = Addr;
676   Offset = CurDAG->getTargetConstant(0, MVT::i32);
677   return true;
678 }
679
680 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
681                                             SDValue &Offset) {
682   ConstantSDNode *C;
683
684   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
685     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
686     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
687   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
688             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
689     Base = Addr.getOperand(0);
690     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
691   } else {
692     Base = Addr;
693     Offset = CurDAG->getTargetConstant(0, MVT::i32);
694   }
695
696   return true;
697 }
698
699 SDNode *AMDGPUDAGToDAGISel::SelectADD_SUB_I64(SDNode *N) {
700   SDLoc DL(N);
701   SDValue LHS = N->getOperand(0);
702   SDValue RHS = N->getOperand(1);
703
704   bool IsAdd = (N->getOpcode() == ISD::ADD);
705
706   SDValue Sub0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
707   SDValue Sub1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
708
709   SDNode *Lo0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
710                                        DL, MVT::i32, LHS, Sub0);
711   SDNode *Hi0 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
712                                        DL, MVT::i32, LHS, Sub1);
713
714   SDNode *Lo1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
715                                        DL, MVT::i32, RHS, Sub0);
716   SDNode *Hi1 = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
717                                        DL, MVT::i32, RHS, Sub1);
718
719   SDVTList VTList = CurDAG->getVTList(MVT::i32, MVT::Glue);
720   SDValue AddLoArgs[] = { SDValue(Lo0, 0), SDValue(Lo1, 0) };
721
722
723   unsigned Opc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
724   unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
725
726   if (!isCFDepth0()) {
727     Opc = IsAdd ? AMDGPU::V_ADD_I32_e32 : AMDGPU::V_SUB_I32_e32;
728     CarryOpc = IsAdd ? AMDGPU::V_ADDC_U32_e32 : AMDGPU::V_SUBB_U32_e32;
729   }
730
731   SDNode *AddLo = CurDAG->getMachineNode( Opc, DL, VTList, AddLoArgs);
732   SDValue Carry(AddLo, 1);
733   SDNode *AddHi
734     = CurDAG->getMachineNode(CarryOpc, DL, MVT::i32,
735                              SDValue(Hi0, 0), SDValue(Hi1, 0), Carry);
736
737   SDValue Args[5] = {
738     CurDAG->getTargetConstant(AMDGPU::SReg_64RegClassID, MVT::i32),
739     SDValue(AddLo,0),
740     Sub0,
741     SDValue(AddHi,0),
742     Sub1,
743   };
744   return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, MVT::i64, Args);
745 }
746
747 SDNode *AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
748   SDLoc SL(N);
749   EVT VT = N->getValueType(0);
750
751   assert(VT == MVT::f32 || VT == MVT::f64);
752
753   unsigned Opc
754     = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64 : AMDGPU::V_DIV_SCALE_F32;
755
756   const SDValue Zero = CurDAG->getTargetConstant(0, MVT::i32);
757
758   SDValue Ops[] = {
759     N->getOperand(0),
760     N->getOperand(1),
761     N->getOperand(2),
762     Zero,
763     Zero,
764     Zero,
765     Zero
766   };
767
768   return CurDAG->SelectNodeTo(N, Opc, VT, MVT::i1, Ops);
769 }
770
771 bool AMDGPUDAGToDAGISel::isDSOffsetLegal(const SDValue &Base, unsigned Offset,
772                                          unsigned OffsetBits) const {
773   const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
774   if ((OffsetBits == 16 && !isUInt<16>(Offset)) ||
775       (OffsetBits == 8 && !isUInt<8>(Offset)))
776     return false;
777
778   if (ST.getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS)
779     return true;
780
781   // On Southern Islands instruction with a negative base value and an offset
782   // don't seem to work.
783   return CurDAG->SignBitIsZero(Base);
784 }
785
786 bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
787                                               SDValue &Offset) const {
788   if (CurDAG->isBaseWithConstantOffset(Addr)) {
789     SDValue N0 = Addr.getOperand(0);
790     SDValue N1 = Addr.getOperand(1);
791     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
792     if (isDSOffsetLegal(N0, C1->getSExtValue(), 16)) {
793       // (add n0, c0)
794       Base = N0;
795       Offset = N1;
796       return true;
797     }
798   }
799
800   // default case
801   Base = Addr;
802   Offset = CurDAG->getTargetConstant(0, MVT::i16);
803   return true;
804 }
805
806 bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
807                                                    SDValue &Offset0,
808                                                    SDValue &Offset1) const {
809   if (CurDAG->isBaseWithConstantOffset(Addr)) {
810     SDValue N0 = Addr.getOperand(0);
811     SDValue N1 = Addr.getOperand(1);
812     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
813     unsigned DWordOffset0 = C1->getZExtValue() / 4;
814     unsigned DWordOffset1 = DWordOffset0 + 1;
815     // (add n0, c0)
816     if (isDSOffsetLegal(N0, DWordOffset1, 8)) {
817       Base = N0;
818       Offset0 = CurDAG->getTargetConstant(DWordOffset0, MVT::i8);
819       Offset1 = CurDAG->getTargetConstant(DWordOffset1, MVT::i8);
820       return true;
821     }
822   }
823
824   // default case
825   Base = Addr;
826   Offset0 = CurDAG->getTargetConstant(0, MVT::i8);
827   Offset1 = CurDAG->getTargetConstant(1, MVT::i8);
828   return true;
829 }
830
831 static SDValue wrapAddr64Rsrc(SelectionDAG *DAG, SDLoc DL, SDValue Ptr) {
832   return SDValue(DAG->getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::v4i32,
833                                      Ptr), 0);
834 }
835
836 static bool isLegalMUBUFImmOffset(const ConstantSDNode *Imm) {
837   return isUInt<12>(Imm->getZExtValue());
838 }
839
840 void AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr,
841                                      SDValue &VAddr, SDValue &SOffset,
842                                      SDValue &Offset, SDValue &Offen,
843                                      SDValue &Idxen, SDValue &Addr64,
844                                      SDValue &GLC, SDValue &SLC,
845                                      SDValue &TFE) const {
846   SDLoc DL(Addr);
847
848   GLC = CurDAG->getTargetConstant(0, MVT::i1);
849   SLC = CurDAG->getTargetConstant(0, MVT::i1);
850   TFE = CurDAG->getTargetConstant(0, MVT::i1);
851
852   Idxen = CurDAG->getTargetConstant(0, MVT::i1);
853   Offen = CurDAG->getTargetConstant(0, MVT::i1);
854   Addr64 = CurDAG->getTargetConstant(0, MVT::i1);
855   SOffset = CurDAG->getTargetConstant(0, MVT::i32);
856
857   if (CurDAG->isBaseWithConstantOffset(Addr)) {
858     SDValue N0 = Addr.getOperand(0);
859     SDValue N1 = Addr.getOperand(1);
860     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
861
862     if (isLegalMUBUFImmOffset(C1)) {
863
864       if (N0.getOpcode() == ISD::ADD) {
865         // (add (add N2, N3), C1) -> addr64
866         SDValue N2 = N0.getOperand(0);
867         SDValue N3 = N0.getOperand(1);
868         Addr64 = CurDAG->getTargetConstant(1, MVT::i1);
869         Ptr = N2;
870         VAddr = N3;
871         Offset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
872         return;
873       }
874
875       // (add N0, C1) -> offset
876       VAddr = CurDAG->getTargetConstant(0, MVT::i32);
877       Ptr = N0;
878       Offset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
879       return;
880     }
881   }
882   if (Addr.getOpcode() == ISD::ADD) {
883     // (add N0, N1) -> addr64
884     SDValue N0 = Addr.getOperand(0);
885     SDValue N1 = Addr.getOperand(1);
886     Addr64 = CurDAG->getTargetConstant(1, MVT::i1);
887     Ptr = N0;
888     VAddr = N1;
889     Offset = CurDAG->getTargetConstant(0, MVT::i16);
890     return;
891   }
892
893   // default case -> offset
894   VAddr = CurDAG->getTargetConstant(0, MVT::i32);
895   Ptr = Addr;
896   Offset = CurDAG->getTargetConstant(0, MVT::i16);
897
898 }
899
900 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
901                                            SDValue &VAddr,
902                                            SDValue &Offset) const {
903   SDValue Ptr, SOffset, Offen, Idxen, Addr64, GLC, SLC, TFE;
904
905   SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
906               GLC, SLC, TFE);
907
908   ConstantSDNode *C = cast<ConstantSDNode>(Addr64);
909   if (C->getSExtValue()) {
910     SDLoc DL(Addr);
911     SRsrc = wrapAddr64Rsrc(CurDAG, DL, Ptr);
912     return true;
913   }
914   return false;
915 }
916
917 bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
918                                            SDValue &VAddr, SDValue &Offset,
919                                            SDValue &SLC) const {
920   SLC = CurDAG->getTargetConstant(0, MVT::i1);
921
922   return SelectMUBUFAddr64(Addr, SRsrc, VAddr, Offset);
923 }
924
925 static SDValue buildRSRC(SelectionDAG *DAG, SDLoc DL, SDValue Ptr,
926                          uint32_t RsrcDword1, uint64_t RsrcDword2And3) {
927
928   SDValue PtrLo = DAG->getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
929   SDValue PtrHi = DAG->getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
930   if (RsrcDword1)
931     PtrHi = SDValue(DAG->getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
932                                     DAG->getConstant(RsrcDword1, MVT::i32)), 0);
933
934   SDValue DataLo = DAG->getTargetConstant(
935       RsrcDword2And3 & APInt::getAllOnesValue(32).getZExtValue(), MVT::i32);
936   SDValue DataHi = DAG->getTargetConstant(RsrcDword2And3 >> 32, MVT::i32);
937
938   const SDValue Ops[] = { PtrLo, PtrHi, DataLo, DataHi };
939   return SDValue(DAG->getMachineNode(AMDGPU::SI_BUFFER_RSRC, DL,
940                                      MVT::v4i32, Ops), 0);
941 }
942
943 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
944 ///        The TID (Thread ID) is multipled by the stride value (bits [61:48]
945 ///        of the resource descriptor) to create an offset, which is added to the
946 ///        resource ponter.
947 static SDValue buildScratchRSRC(SelectionDAG *DAG, SDLoc DL, SDValue Ptr) {
948
949   uint64_t Rsrc = AMDGPU::RSRC_DATA_FORMAT | AMDGPU::RSRC_TID_ENABLE |
950                   0xffffffff; // Size
951
952   return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
953 }
954
955 bool AMDGPUDAGToDAGISel::SelectMUBUFScratch(SDValue Addr, SDValue &Rsrc,
956                                             SDValue &VAddr, SDValue &SOffset,
957                                             SDValue &ImmOffset) const {
958
959   SDLoc DL(Addr);
960   MachineFunction &MF = CurDAG->getMachineFunction();
961   const SIRegisterInfo *TRI =
962       static_cast<const SIRegisterInfo *>(MF.getSubtarget().getRegisterInfo());
963   MachineRegisterInfo &MRI = MF.getRegInfo();
964   const SITargetLowering& Lowering =
965     *static_cast<const SITargetLowering*>(getTargetLowering());
966
967   unsigned ScratchPtrReg =
968       TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_PTR);
969   unsigned ScratchOffsetReg =
970       TRI->getPreloadedValue(MF, SIRegisterInfo::SCRATCH_WAVE_OFFSET);
971   Lowering.CreateLiveInRegister(*CurDAG, &AMDGPU::SReg_32RegClass,
972                                 ScratchOffsetReg, MVT::i32);
973
974   Rsrc = buildScratchRSRC(CurDAG, DL,
975       CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
976                              MRI.getLiveInVirtReg(ScratchPtrReg), MVT::i64));
977   SOffset = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
978       MRI.getLiveInVirtReg(ScratchOffsetReg), MVT::i32);
979
980   // (add n0, c1)
981   if (CurDAG->isBaseWithConstantOffset(Addr)) {
982     SDValue N1 = Addr.getOperand(1);
983     ConstantSDNode *C1 = cast<ConstantSDNode>(N1);
984
985     if (isLegalMUBUFImmOffset(C1)) {
986       VAddr = Addr.getOperand(0);
987       ImmOffset = CurDAG->getTargetConstant(C1->getZExtValue(), MVT::i16);
988       return true;
989     }
990   }
991
992   // (add FI, n0)
993   if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
994        isa<FrameIndexSDNode>(Addr.getOperand(0))) {
995     VAddr = Addr.getOperand(1);
996     ImmOffset = Addr.getOperand(0);
997     return true;
998   }
999
1000   // (FI)
1001   if (isa<FrameIndexSDNode>(Addr)) {
1002     VAddr = SDValue(CurDAG->getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
1003                                           CurDAG->getConstant(0, MVT::i32)), 0);
1004     ImmOffset = Addr;
1005     return true;
1006   }
1007
1008   // (node)
1009   VAddr = Addr;
1010   ImmOffset = CurDAG->getTargetConstant(0, MVT::i16);
1011   return true;
1012 }
1013
1014 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1015                                            SDValue &SOffset, SDValue &Offset,
1016                                            SDValue &GLC, SDValue &SLC,
1017                                            SDValue &TFE) const {
1018   SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1019
1020   SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64,
1021               GLC, SLC, TFE);
1022
1023   if (!cast<ConstantSDNode>(Offen)->getSExtValue() &&
1024       !cast<ConstantSDNode>(Idxen)->getSExtValue() &&
1025       !cast<ConstantSDNode>(Addr64)->getSExtValue()) {
1026     uint64_t Rsrc = AMDGPU::RSRC_DATA_FORMAT |
1027                     APInt::getAllOnesValue(32).getZExtValue(); // Size
1028     SDLoc DL(Addr);
1029     SRsrc = buildRSRC(CurDAG, DL, Ptr, 0, Rsrc);
1030     return true;
1031   }
1032   return false;
1033 }
1034
1035 bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1036                                            SDValue &Soffset, SDValue &Offset,
1037                                            SDValue &GLC) const {
1038   SDValue SLC, TFE;
1039
1040   return SelectMUBUFOffset(Addr, SRsrc, Soffset, Offset, GLC, SLC, TFE);
1041 }
1042
1043 // FIXME: This is incorrect and only enough to be able to compile.
1044 SDNode *AMDGPUDAGToDAGISel::SelectAddrSpaceCast(SDNode *N) {
1045   AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(N);
1046   SDLoc DL(N);
1047
1048   assert(Subtarget.hasFlatAddressSpace() &&
1049          "addrspacecast only supported with flat address space!");
1050
1051   assert((ASC->getSrcAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
1052           ASC->getDestAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS) &&
1053          "Cannot cast address space to / from constant address!");
1054
1055   assert((ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS ||
1056           ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) &&
1057          "Can only cast to / from flat address space!");
1058
1059   // The flat instructions read the address as the index of the VGPR holding the
1060   // address, so casting should just be reinterpreting the base VGPR, so just
1061   // insert trunc / bitcast / zext.
1062
1063   SDValue Src = ASC->getOperand(0);
1064   EVT DestVT = ASC->getValueType(0);
1065   EVT SrcVT = Src.getValueType();
1066
1067   unsigned SrcSize = SrcVT.getSizeInBits();
1068   unsigned DestSize = DestVT.getSizeInBits();
1069
1070   if (SrcSize > DestSize) {
1071     assert(SrcSize == 64 && DestSize == 32);
1072     return CurDAG->getMachineNode(
1073       TargetOpcode::EXTRACT_SUBREG,
1074       DL,
1075       DestVT,
1076       Src,
1077       CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32));
1078   }
1079
1080
1081   if (DestSize > SrcSize) {
1082     assert(SrcSize == 32 && DestSize == 64);
1083
1084     SDValue RC = CurDAG->getTargetConstant(AMDGPU::VSrc_64RegClassID, MVT::i32);
1085
1086     const SDValue Ops[] = {
1087       RC,
1088       Src,
1089       CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32),
1090       SDValue(CurDAG->getMachineNode(AMDGPU::S_MOV_B32, SDLoc(N), MVT::i32,
1091                                      CurDAG->getConstant(0, MVT::i32)), 0),
1092       CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32)
1093     };
1094
1095     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1096                                   SDLoc(N), N->getValueType(0), Ops);
1097   }
1098
1099   assert(SrcSize == 64 && DestSize == 64);
1100   return CurDAG->getNode(ISD::BITCAST, DL, DestVT, Src).getNode();
1101 }
1102
1103 bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
1104                                         SDValue &SrcMods) const {
1105
1106   unsigned Mods = 0;
1107
1108   Src = In;
1109
1110   if (Src.getOpcode() == ISD::FNEG) {
1111     Mods |= SISrcMods::NEG;
1112     Src = Src.getOperand(0);
1113   }
1114
1115   if (Src.getOpcode() == ISD::FABS) {
1116     Mods |= SISrcMods::ABS;
1117     Src = Src.getOperand(0);
1118   }
1119
1120   SrcMods = CurDAG->getTargetConstant(Mods, MVT::i32);
1121
1122   return true;
1123 }
1124
1125 bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
1126                                          SDValue &SrcMods, SDValue &Clamp,
1127                                          SDValue &Omod) const {
1128   // FIXME: Handle Clamp and Omod
1129   Clamp = CurDAG->getTargetConstant(0, MVT::i32);
1130   Omod = CurDAG->getTargetConstant(0, MVT::i32);
1131
1132   return SelectVOP3Mods(In, Src, SrcMods);
1133 }
1134
1135 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
1136   const AMDGPUTargetLowering& Lowering =
1137     *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
1138   bool IsModified = false;
1139   do {
1140     IsModified = false;
1141     // Go over all selected nodes and try to fold them a bit more
1142     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1143          E = CurDAG->allnodes_end(); I != E; ++I) {
1144
1145       SDNode *Node = I;
1146
1147       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1148       if (!MachineNode)
1149         continue;
1150
1151       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
1152       if (ResNode != Node) {
1153         ReplaceUses(Node, ResNode);
1154         IsModified = true;
1155       }
1156     }
1157     CurDAG->RemoveDeadNodes();
1158   } while (IsModified);
1159 }