R600: Move fabs/fneg/sel folding logic into PostProcessIsel
[oota-llvm.git] / lib / Target / R600 / AMDGPUISelDAGToDAG.cpp
1 //===-- AMDILISelDAGToDAG.cpp - A dag to dag inst selector for AMDIL ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //==-----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Defines an instruction selector for the AMDGPU target.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "AMDGPUInstrInfo.h"
15 #include "AMDGPUISelLowering.h" // For AMDGPUISD
16 #include "AMDGPURegisterInfo.h"
17 #include "R600InstrInfo.h"
18 #include "SIISelLowering.h"
19 #include "llvm/ADT/ValueMap.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/PseudoSourceValue.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/Support/Compiler.h"
26 #include <list>
27 #include <queue>
28
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 // Instruction Selector Implementation
33 //===----------------------------------------------------------------------===//
34
35 namespace {
36 /// AMDGPU specific code to select AMDGPU machine instructions for
37 /// SelectionDAG operations.
38 class AMDGPUDAGToDAGISel : public SelectionDAGISel {
39   // Subtarget - Keep a pointer to the AMDGPU Subtarget around so that we can
40   // make the right decision when generating code for different targets.
41   const AMDGPUSubtarget &Subtarget;
42 public:
43   AMDGPUDAGToDAGISel(TargetMachine &TM);
44   virtual ~AMDGPUDAGToDAGISel();
45
46   SDNode *Select(SDNode *N);
47   virtual const char *getPassName() const;
48   virtual void PostprocessISelDAG();
49
50 private:
51   inline SDValue getSmallIPtrImm(unsigned Imm);
52   bool FoldOperand(SDValue &Src, SDValue &Sel, SDValue &Neg, SDValue &Abs,
53                    const R600InstrInfo *TII);
54   bool FoldOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
55   bool FoldDotOperands(unsigned, const R600InstrInfo *, std::vector<SDValue> &);
56
57   // Complex pattern selectors
58   bool SelectADDRParam(SDValue Addr, SDValue& R1, SDValue& R2);
59   bool SelectADDR(SDValue N, SDValue &R1, SDValue &R2);
60   bool SelectADDR64(SDValue N, SDValue &R1, SDValue &R2);
61   SDValue SimplifyI24(SDValue &Op);
62   bool SelectI24(SDValue Addr, SDValue &Op);
63   bool SelectU24(SDValue Addr, SDValue &Op);
64
65   static bool checkType(const Value *ptr, unsigned int addrspace);
66
67   static bool isGlobalStore(const StoreSDNode *N);
68   static bool isPrivateStore(const StoreSDNode *N);
69   static bool isLocalStore(const StoreSDNode *N);
70   static bool isRegionStore(const StoreSDNode *N);
71
72   bool isCPLoad(const LoadSDNode *N) const;
73   bool isConstantLoad(const LoadSDNode *N, int cbID) const;
74   bool isGlobalLoad(const LoadSDNode *N) const;
75   bool isParamLoad(const LoadSDNode *N) const;
76   bool isPrivateLoad(const LoadSDNode *N) const;
77   bool isLocalLoad(const LoadSDNode *N) const;
78   bool isRegionLoad(const LoadSDNode *N) const;
79
80   const TargetRegisterClass *getOperandRegClass(SDNode *N, unsigned OpNo) const;
81   bool SelectGlobalValueConstantOffset(SDValue Addr, SDValue& IntPtr);
82   bool SelectGlobalValueVariableOffset(SDValue Addr,
83       SDValue &BaseReg, SDValue& Offset);
84   bool SelectADDRVTX_READ(SDValue Addr, SDValue &Base, SDValue &Offset);
85   bool SelectADDRIndirect(SDValue Addr, SDValue &Base, SDValue &Offset);
86
87   // Include the pieces autogenerated from the target description.
88 #include "AMDGPUGenDAGISel.inc"
89 };
90 }  // end anonymous namespace
91
92 /// \brief This pass converts a legalized DAG into a AMDGPU-specific
93 // DAG, ready for instruction scheduling.
94 FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM
95                                        ) {
96   return new AMDGPUDAGToDAGISel(TM);
97 }
98
99 AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM)
100   : SelectionDAGISel(TM), Subtarget(TM.getSubtarget<AMDGPUSubtarget>()) {
101 }
102
103 AMDGPUDAGToDAGISel::~AMDGPUDAGToDAGISel() {
104 }
105
106 /// \brief Determine the register class for \p OpNo
107 /// \returns The register class of the virtual register that will be used for
108 /// the given operand number \OpNo or NULL if the register class cannot be
109 /// determined.
110 const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
111                                                           unsigned OpNo) const {
112   if (!N->isMachineOpcode()) {
113     return NULL;
114   }
115   switch (N->getMachineOpcode()) {
116   default: {
117     const MCInstrDesc &Desc = TM.getInstrInfo()->get(N->getMachineOpcode());
118     unsigned OpIdx = Desc.getNumDefs() + OpNo;
119     if (OpIdx >= Desc.getNumOperands())
120       return NULL;
121     int RegClass = Desc.OpInfo[OpIdx].RegClass;
122     if (RegClass == -1) {
123       return NULL;
124     }
125     return TM.getRegisterInfo()->getRegClass(RegClass);
126   }
127   case AMDGPU::REG_SEQUENCE: {
128     const TargetRegisterClass *SuperRC = TM.getRegisterInfo()->getRegClass(
129                       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
130     unsigned SubRegIdx =
131             dyn_cast<ConstantSDNode>(N->getOperand(OpNo + 1))->getZExtValue();
132     return TM.getRegisterInfo()->getSubClassWithSubReg(SuperRC, SubRegIdx);
133   }
134   }
135 }
136
137 SDValue AMDGPUDAGToDAGISel::getSmallIPtrImm(unsigned int Imm) {
138   return CurDAG->getTargetConstant(Imm, MVT::i32);
139 }
140
141 bool AMDGPUDAGToDAGISel::SelectADDRParam(
142     SDValue Addr, SDValue& R1, SDValue& R2) {
143
144   if (Addr.getOpcode() == ISD::FrameIndex) {
145     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
146       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
147       R2 = CurDAG->getTargetConstant(0, MVT::i32);
148     } else {
149       R1 = Addr;
150       R2 = CurDAG->getTargetConstant(0, MVT::i32);
151     }
152   } else if (Addr.getOpcode() == ISD::ADD) {
153     R1 = Addr.getOperand(0);
154     R2 = Addr.getOperand(1);
155   } else {
156     R1 = Addr;
157     R2 = CurDAG->getTargetConstant(0, MVT::i32);
158   }
159   return true;
160 }
161
162 bool AMDGPUDAGToDAGISel::SelectADDR(SDValue Addr, SDValue& R1, SDValue& R2) {
163   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
164       Addr.getOpcode() == ISD::TargetGlobalAddress) {
165     return false;
166   }
167   return SelectADDRParam(Addr, R1, R2);
168 }
169
170
171 bool AMDGPUDAGToDAGISel::SelectADDR64(SDValue Addr, SDValue& R1, SDValue& R2) {
172   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
173       Addr.getOpcode() == ISD::TargetGlobalAddress) {
174     return false;
175   }
176
177   if (Addr.getOpcode() == ISD::FrameIndex) {
178     if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
179       R1 = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i64);
180       R2 = CurDAG->getTargetConstant(0, MVT::i64);
181     } else {
182       R1 = Addr;
183       R2 = CurDAG->getTargetConstant(0, MVT::i64);
184     }
185   } else if (Addr.getOpcode() == ISD::ADD) {
186     R1 = Addr.getOperand(0);
187     R2 = Addr.getOperand(1);
188   } else {
189     R1 = Addr;
190     R2 = CurDAG->getTargetConstant(0, MVT::i64);
191   }
192   return true;
193 }
194
195 SDNode *AMDGPUDAGToDAGISel::Select(SDNode *N) {
196   const R600InstrInfo *TII =
197                       static_cast<const R600InstrInfo*>(TM.getInstrInfo());
198   unsigned int Opc = N->getOpcode();
199   if (N->isMachineOpcode()) {
200     return NULL;   // Already selected.
201   }
202   switch (Opc) {
203   default: break;
204   case ISD::BUILD_VECTOR: {
205     unsigned RegClassID;
206     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
207     const AMDGPURegisterInfo *TRI =
208                    static_cast<const AMDGPURegisterInfo*>(TM.getRegisterInfo());
209     const SIRegisterInfo *SIRI =
210                    static_cast<const SIRegisterInfo*>(TM.getRegisterInfo());
211     EVT VT = N->getValueType(0);
212     unsigned NumVectorElts = VT.getVectorNumElements();
213     assert(VT.getVectorElementType().bitsEq(MVT::i32));
214     if (ST.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
215       bool UseVReg = true;
216       for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
217                                                     U != E; ++U) {
218         if (!U->isMachineOpcode()) {
219           continue;
220         }
221         const TargetRegisterClass *RC = getOperandRegClass(*U, U.getOperandNo());
222         if (!RC) {
223           continue;
224         }
225         if (SIRI->isSGPRClass(RC)) {
226           UseVReg = false;
227         }
228       }
229       switch(NumVectorElts) {
230       case 1: RegClassID = UseVReg ? AMDGPU::VReg_32RegClassID :
231                                      AMDGPU::SReg_32RegClassID;
232         break;
233       case 2: RegClassID = UseVReg ? AMDGPU::VReg_64RegClassID :
234                                      AMDGPU::SReg_64RegClassID;
235         break;
236       case 4: RegClassID = UseVReg ? AMDGPU::VReg_128RegClassID :
237                                      AMDGPU::SReg_128RegClassID;
238         break;
239       case 8: RegClassID = UseVReg ? AMDGPU::VReg_256RegClassID :
240                                      AMDGPU::SReg_256RegClassID;
241         break;
242       case 16: RegClassID = UseVReg ? AMDGPU::VReg_512RegClassID :
243                                       AMDGPU::SReg_512RegClassID;
244         break;
245       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
246       }
247     } else {
248       // BUILD_VECTOR was lowered into an IMPLICIT_DEF + 4 INSERT_SUBREG
249       // that adds a 128 bits reg copy when going through TwoAddressInstructions
250       // pass. We want to avoid 128 bits copies as much as possible because they
251       // can't be bundled by our scheduler.
252       switch(NumVectorElts) {
253       case 2: RegClassID = AMDGPU::R600_Reg64RegClassID; break;
254       case 4: RegClassID = AMDGPU::R600_Reg128RegClassID; break;
255       default: llvm_unreachable("Do not know how to lower this BUILD_VECTOR");
256       }
257     }
258
259     SDValue RegClass = CurDAG->getTargetConstant(RegClassID, MVT::i32);
260
261     if (NumVectorElts == 1) {
262       return CurDAG->SelectNodeTo(N, AMDGPU::COPY_TO_REGCLASS,
263                                   VT.getVectorElementType(),
264                                   N->getOperand(0), RegClass);
265     }
266
267     assert(NumVectorElts <= 16 && "Vectors with more than 16 elements not "
268                                   "supported yet");
269     // 16 = Max Num Vector Elements
270     // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
271     // 1 = Vector Register Class
272     SDValue RegSeqArgs[16 * 2 + 1];
273
274     RegSeqArgs[0] = CurDAG->getTargetConstant(RegClassID, MVT::i32);
275     bool IsRegSeq = true;
276     for (unsigned i = 0; i < N->getNumOperands(); i++) {
277       // XXX: Why is this here?
278       if (dyn_cast<RegisterSDNode>(N->getOperand(i))) {
279         IsRegSeq = false;
280         break;
281       }
282       RegSeqArgs[1 + (2 * i)] = N->getOperand(i);
283       RegSeqArgs[1 + (2 * i) + 1] =
284               CurDAG->getTargetConstant(TRI->getSubRegFromChannel(i), MVT::i32);
285     }
286     if (!IsRegSeq)
287       break;
288     return CurDAG->SelectNodeTo(N, AMDGPU::REG_SEQUENCE, N->getVTList(),
289         RegSeqArgs, 2 * N->getNumOperands() + 1);
290   }
291   case ISD::BUILD_PAIR: {
292     SDValue RC, SubReg0, SubReg1;
293     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
294     if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
295       break;
296     }
297     if (N->getValueType(0) == MVT::i128) {
298       RC = CurDAG->getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32);
299       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0_sub1, MVT::i32);
300       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub2_sub3, MVT::i32);
301     } else if (N->getValueType(0) == MVT::i64) {
302       RC = CurDAG->getTargetConstant(AMDGPU::VSrc_64RegClassID, MVT::i32);
303       SubReg0 = CurDAG->getTargetConstant(AMDGPU::sub0, MVT::i32);
304       SubReg1 = CurDAG->getTargetConstant(AMDGPU::sub1, MVT::i32);
305     } else {
306       llvm_unreachable("Unhandled value type for BUILD_PAIR");
307     }
308     const SDValue Ops[] = { RC, N->getOperand(0), SubReg0,
309                             N->getOperand(1), SubReg1 };
310     return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
311                                   SDLoc(N), N->getValueType(0), Ops);
312   }
313
314   case ISD::ConstantFP:
315   case ISD::Constant: {
316     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
317     // XXX: Custom immediate lowering not implemented yet.  Instead we use
318     // pseudo instructions defined in SIInstructions.td
319     if (ST.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
320       break;
321     }
322
323     uint64_t ImmValue = 0;
324     unsigned ImmReg = AMDGPU::ALU_LITERAL_X;
325
326     if (N->getOpcode() == ISD::ConstantFP) {
327       // XXX: 64-bit Immediates not supported yet
328       assert(N->getValueType(0) != MVT::f64);
329
330       ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N);
331       APFloat Value = C->getValueAPF();
332       float FloatValue = Value.convertToFloat();
333       if (FloatValue == 0.0) {
334         ImmReg = AMDGPU::ZERO;
335       } else if (FloatValue == 0.5) {
336         ImmReg = AMDGPU::HALF;
337       } else if (FloatValue == 1.0) {
338         ImmReg = AMDGPU::ONE;
339       } else {
340         ImmValue = Value.bitcastToAPInt().getZExtValue();
341       }
342     } else {
343       // XXX: 64-bit Immediates not supported yet
344       assert(N->getValueType(0) != MVT::i64);
345
346       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
347       if (C->getZExtValue() == 0) {
348         ImmReg = AMDGPU::ZERO;
349       } else if (C->getZExtValue() == 1) {
350         ImmReg = AMDGPU::ONE_INT;
351       } else {
352         ImmValue = C->getZExtValue();
353       }
354     }
355
356     for (SDNode::use_iterator Use = N->use_begin(), Next = llvm::next(Use);
357                               Use != SDNode::use_end(); Use = Next) {
358       Next = llvm::next(Use);
359       std::vector<SDValue> Ops;
360       for (unsigned i = 0; i < Use->getNumOperands(); ++i) {
361         Ops.push_back(Use->getOperand(i));
362       }
363
364       if (!Use->isMachineOpcode()) {
365           if (ImmReg == AMDGPU::ALU_LITERAL_X) {
366             // We can only use literal constants (e.g. AMDGPU::ZERO,
367             // AMDGPU::ONE, etc) in machine opcodes.
368             continue;
369           }
370       } else {
371         switch(Use->getMachineOpcode()) {
372         case AMDGPU::REG_SEQUENCE: break;
373         default:
374           if (!TII->isALUInstr(Use->getMachineOpcode()) ||
375               (TII->get(Use->getMachineOpcode()).TSFlags &
376                R600_InstFlag::VECTOR)) {
377             continue;
378           }
379         }
380
381         // Check that we aren't already using an immediate.
382         // XXX: It's possible for an instruction to have more than one
383         // immediate operand, but this is not supported yet.
384         if (ImmReg == AMDGPU::ALU_LITERAL_X) {
385           int ImmIdx = TII->getOperandIdx(Use->getMachineOpcode(),
386                                           AMDGPU::OpName::literal);
387           if (ImmIdx == -1) {
388             continue;
389           }
390
391           if (TII->getOperandIdx(Use->getMachineOpcode(),
392                                  AMDGPU::OpName::dst) != -1) {
393             // subtract one from ImmIdx, because the DST operand is usually index
394             // 0 for MachineInstrs, but we have no DST in the Ops vector.
395             ImmIdx--;
396           }
397           ConstantSDNode *C = dyn_cast<ConstantSDNode>(Use->getOperand(ImmIdx));
398           assert(C);
399
400           if (C->getZExtValue() != 0) {
401             // This instruction is already using an immediate.
402             continue;
403           }
404
405           // Set the immediate value
406           Ops[ImmIdx] = CurDAG->getTargetConstant(ImmValue, MVT::i32);
407         }
408       }
409       // Set the immediate register
410       Ops[Use.getOperandNo()] = CurDAG->getRegister(ImmReg, MVT::i32);
411
412       CurDAG->UpdateNodeOperands(*Use, Ops.data(), Use->getNumOperands());
413     }
414     break;
415   }
416   }
417   SDNode *Result = SelectCode(N);
418
419   // Fold operands of selected node
420
421   const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
422   if (ST.getGeneration() <= AMDGPUSubtarget::NORTHERN_ISLANDS) {
423     const R600InstrInfo *TII =
424         static_cast<const R600InstrInfo*>(TM.getInstrInfo());
425     if (Result && Result->isMachineOpcode() &&
426         !(TII->get(Result->getMachineOpcode()).TSFlags & R600_InstFlag::VECTOR)
427         && TII->hasInstrModifiers(Result->getMachineOpcode())) {
428       // If node has a single use which is CLAMP_R600, folds it
429       if (Result->hasOneUse() && Result->isMachineOpcode()) {
430         SDNode *PotentialClamp = *Result->use_begin();
431         if (PotentialClamp->isMachineOpcode() &&
432             PotentialClamp->getMachineOpcode() == AMDGPU::CLAMP_R600) {
433           unsigned ClampIdx =
434             TII->getOperandIdx(Result->getMachineOpcode(), AMDGPU::OpName::clamp);
435           std::vector<SDValue> Ops;
436           unsigned NumOp = Result->getNumOperands();
437           for (unsigned i = 0; i < NumOp; ++i) {
438             Ops.push_back(Result->getOperand(i));
439           }
440           Ops[ClampIdx - 1] = CurDAG->getTargetConstant(1, MVT::i32);
441           Result = CurDAG->SelectNodeTo(PotentialClamp,
442               Result->getMachineOpcode(), PotentialClamp->getVTList(),
443               Ops.data(), NumOp);
444         }
445       }
446     }
447   }
448
449   return Result;
450 }
451
452
453 bool AMDGPUDAGToDAGISel::checkType(const Value *ptr, unsigned int addrspace) {
454   if (!ptr) {
455     return false;
456   }
457   Type *ptrType = ptr->getType();
458   return dyn_cast<PointerType>(ptrType)->getAddressSpace() == addrspace;
459 }
460
461 bool AMDGPUDAGToDAGISel::isGlobalStore(const StoreSDNode *N) {
462   return checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS);
463 }
464
465 bool AMDGPUDAGToDAGISel::isPrivateStore(const StoreSDNode *N) {
466   return (!checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS)
467           && !checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS)
468           && !checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS));
469 }
470
471 bool AMDGPUDAGToDAGISel::isLocalStore(const StoreSDNode *N) {
472   return checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS);
473 }
474
475 bool AMDGPUDAGToDAGISel::isRegionStore(const StoreSDNode *N) {
476   return checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS);
477 }
478
479 bool AMDGPUDAGToDAGISel::isConstantLoad(const LoadSDNode *N, int CbId) const {
480   if (CbId == -1) {
481     return checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_ADDRESS);
482   }
483   return checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_BUFFER_0 + CbId);
484 }
485
486 bool AMDGPUDAGToDAGISel::isGlobalLoad(const LoadSDNode *N) const {
487   if (N->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) {
488     const AMDGPUSubtarget &ST = TM.getSubtarget<AMDGPUSubtarget>();
489     if (ST.getGeneration() < AMDGPUSubtarget::SOUTHERN_ISLANDS ||
490         N->getMemoryVT().bitsLT(MVT::i32)) {
491       return true;
492     }
493   }
494   return checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS);
495 }
496
497 bool AMDGPUDAGToDAGISel::isParamLoad(const LoadSDNode *N) const {
498   return checkType(N->getSrcValue(), AMDGPUAS::PARAM_I_ADDRESS);
499 }
500
501 bool AMDGPUDAGToDAGISel::isLocalLoad(const  LoadSDNode *N) const {
502   return checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS);
503 }
504
505 bool AMDGPUDAGToDAGISel::isRegionLoad(const  LoadSDNode *N) const {
506   return checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS);
507 }
508
509 bool AMDGPUDAGToDAGISel::isCPLoad(const LoadSDNode *N) const {
510   MachineMemOperand *MMO = N->getMemOperand();
511   if (checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS)) {
512     if (MMO) {
513       const Value *V = MMO->getValue();
514       const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V);
515       if (PSV && PSV == PseudoSourceValue::getConstantPool()) {
516         return true;
517       }
518     }
519   }
520   return false;
521 }
522
523 bool AMDGPUDAGToDAGISel::isPrivateLoad(const LoadSDNode *N) const {
524   if (checkType(N->getSrcValue(), AMDGPUAS::PRIVATE_ADDRESS)) {
525     // Check to make sure we are not a constant pool load or a constant load
526     // that is marked as a private load
527     if (isCPLoad(N) || isConstantLoad(N, -1)) {
528       return false;
529     }
530   }
531   if (!checkType(N->getSrcValue(), AMDGPUAS::LOCAL_ADDRESS)
532       && !checkType(N->getSrcValue(), AMDGPUAS::GLOBAL_ADDRESS)
533       && !checkType(N->getSrcValue(), AMDGPUAS::REGION_ADDRESS)
534       && !checkType(N->getSrcValue(), AMDGPUAS::CONSTANT_ADDRESS)
535       && !checkType(N->getSrcValue(), AMDGPUAS::PARAM_D_ADDRESS)
536       && !checkType(N->getSrcValue(), AMDGPUAS::PARAM_I_ADDRESS)) {
537     return true;
538   }
539   return false;
540 }
541
542 const char *AMDGPUDAGToDAGISel::getPassName() const {
543   return "AMDGPU DAG->DAG Pattern Instruction Selection";
544 }
545
546 #ifdef DEBUGTMP
547 #undef INT64_C
548 #endif
549 #undef DEBUGTMP
550
551 //===----------------------------------------------------------------------===//
552 // Complex Patterns
553 //===----------------------------------------------------------------------===//
554
555 bool AMDGPUDAGToDAGISel::SelectGlobalValueConstantOffset(SDValue Addr,
556     SDValue& IntPtr) {
557   if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Addr)) {
558     IntPtr = CurDAG->getIntPtrConstant(Cst->getZExtValue() / 4, true);
559     return true;
560   }
561   return false;
562 }
563
564 bool AMDGPUDAGToDAGISel::SelectGlobalValueVariableOffset(SDValue Addr,
565     SDValue& BaseReg, SDValue &Offset) {
566   if (!dyn_cast<ConstantSDNode>(Addr)) {
567     BaseReg = Addr;
568     Offset = CurDAG->getIntPtrConstant(0, true);
569     return true;
570   }
571   return false;
572 }
573
574 bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
575                                            SDValue &Offset) {
576   ConstantSDNode * IMMOffset;
577
578   if (Addr.getOpcode() == ISD::ADD
579       && (IMMOffset = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
580       && isInt<16>(IMMOffset->getZExtValue())) {
581
582       Base = Addr.getOperand(0);
583       Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
584       return true;
585   // If the pointer address is constant, we can move it to the offset field.
586   } else if ((IMMOffset = dyn_cast<ConstantSDNode>(Addr))
587              && isInt<16>(IMMOffset->getZExtValue())) {
588     Base = CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
589                                   SDLoc(CurDAG->getEntryNode()),
590                                   AMDGPU::ZERO, MVT::i32);
591     Offset = CurDAG->getTargetConstant(IMMOffset->getZExtValue(), MVT::i32);
592     return true;
593   }
594
595   // Default case, no offset
596   Base = Addr;
597   Offset = CurDAG->getTargetConstant(0, MVT::i32);
598   return true;
599 }
600
601 bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
602                                             SDValue &Offset) {
603   ConstantSDNode *C;
604
605   if ((C = dyn_cast<ConstantSDNode>(Addr))) {
606     Base = CurDAG->getRegister(AMDGPU::INDIRECT_BASE_ADDR, MVT::i32);
607     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
608   } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
609             (C = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))) {
610     Base = Addr.getOperand(0);
611     Offset = CurDAG->getTargetConstant(C->getZExtValue(), MVT::i32);
612   } else {
613     Base = Addr;
614     Offset = CurDAG->getTargetConstant(0, MVT::i32);
615   }
616
617   return true;
618 }
619
620 SDValue AMDGPUDAGToDAGISel::SimplifyI24(SDValue &Op) {
621   APInt Demanded = APInt(32, 0x00FFFFFF);
622   APInt KnownZero, KnownOne;
623   TargetLowering::TargetLoweringOpt TLO(*CurDAG, true, true);
624   const TargetLowering *TLI = getTargetLowering();
625   if (TLI->SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO)) {
626     CurDAG->ReplaceAllUsesWith(Op, TLO.New);
627     CurDAG->RepositionNode(Op.getNode(), TLO.New.getNode());
628     return SimplifyI24(TLO.New);
629   } else {
630     return  Op;
631   }
632 }
633
634 bool AMDGPUDAGToDAGISel::SelectI24(SDValue Op, SDValue &I24) {
635
636   assert(Op.getValueType() == MVT::i32);
637
638   if (CurDAG->ComputeNumSignBits(Op) == 9) {
639     I24 = SimplifyI24(Op);
640     return true;
641   }
642   return false;
643 }
644
645 bool AMDGPUDAGToDAGISel::SelectU24(SDValue Op, SDValue &U24) {
646   APInt KnownZero;
647   APInt KnownOne;
648   CurDAG->ComputeMaskedBits(Op, KnownZero, KnownOne);
649
650   assert (Op.getValueType() == MVT::i32);
651
652   // ANY_EXTEND and EXTLOAD operations can only be done on types smaller than
653   // i32.  These smaller types are legal to use with the i24 instructions.
654   if ((KnownZero & APInt(KnownZero.getBitWidth(), 0xFF000000)) == 0xFF000000 ||
655        Op.getOpcode() == ISD::ANY_EXTEND ||
656        ISD::isEXTLoad(Op.getNode())) {
657     U24 = SimplifyI24(Op);
658     return true;
659   }
660   return false;
661 }
662
663 void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
664   const AMDGPUTargetLowering& Lowering =
665     (*(const AMDGPUTargetLowering*)getTargetLowering());
666   bool IsModified = false;
667   do {
668     IsModified = false;
669     // Go over all selected nodes and try to fold them a bit more
670     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
671          E = CurDAG->allnodes_end(); I != E; ++I) {
672
673       SDNode *Node = I;
674
675       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
676       if (!MachineNode)
677         continue;
678
679       SDNode *ResNode = Lowering.PostISelFolding(MachineNode, *CurDAG);
680       if (ResNode != Node) {
681         ReplaceUses(Node, ResNode);
682         IsModified = true;
683       }
684     }
685     CurDAG->RemoveDeadNodes();
686   } while (IsModified);
687 }