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