05b7b5d9b746947e8399f7b575cfc5ec6cf3dc1b
[oota-llvm.git] / lib / Target / R600 / SIISelLowering.cpp
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
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 Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SIISelLowering.h"
16 #include "AMDGPU.h"
17 #include "AMDILIntrinsicInfo.h"
18 #include "SIInstrInfo.h"
19 #include "SIMachineFunctionInfo.h"
20 #include "SIRegisterInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/IR/Function.h"
26
27 const uint64_t RSRC_DATA_FORMAT = 0xf00000000000LL;
28
29 using namespace llvm;
30
31 SITargetLowering::SITargetLowering(TargetMachine &TM) :
32     AMDGPUTargetLowering(TM) {
33
34   addRegisterClass(MVT::i1, &AMDGPU::SReg_64RegClass);
35   addRegisterClass(MVT::i64, &AMDGPU::VSrc_64RegClass);
36
37   addRegisterClass(MVT::v32i8, &AMDGPU::SReg_256RegClass);
38   addRegisterClass(MVT::v64i8, &AMDGPU::SReg_512RegClass);
39
40   addRegisterClass(MVT::i32, &AMDGPU::VSrc_32RegClass);
41   addRegisterClass(MVT::f32, &AMDGPU::VSrc_32RegClass);
42
43   addRegisterClass(MVT::f64, &AMDGPU::VSrc_64RegClass);
44   addRegisterClass(MVT::v2i32, &AMDGPU::VSrc_64RegClass);
45   addRegisterClass(MVT::v2f32, &AMDGPU::VSrc_64RegClass);
46
47   addRegisterClass(MVT::v4i32, &AMDGPU::VReg_128RegClass);
48   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
49   addRegisterClass(MVT::i128, &AMDGPU::SReg_128RegClass);
50
51   addRegisterClass(MVT::v8i32, &AMDGPU::VReg_256RegClass);
52   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
53
54   addRegisterClass(MVT::v16i32, &AMDGPU::VReg_512RegClass);
55   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
56
57   computeRegisterProperties();
58
59   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
60   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
61   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
62   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
63
64   setOperationAction(ISD::ADD, MVT::i64, Legal);
65   setOperationAction(ISD::ADD, MVT::i32, Legal);
66
67   setOperationAction(ISD::BITCAST, MVT::i128, Legal);
68
69   // We need to custom lower vector stores from local memory
70   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
71   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
72
73   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
74   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
75
76   setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
77
78   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
79   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
80
81   setOperationAction(ISD::SIGN_EXTEND, MVT::i64, Custom);
82   setOperationAction(ISD::ZERO_EXTEND, MVT::i64, Custom);
83
84   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
85   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
86   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
87   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
88
89   setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Expand);
90
91   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
92   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
93   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
94
95   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
96
97   setTargetDAGCombine(ISD::SELECT_CC);
98
99   setTargetDAGCombine(ISD::SETCC);
100
101   setSchedulingPreference(Sched::RegPressure);
102 }
103
104 //===----------------------------------------------------------------------===//
105 // TargetLowering queries
106 //===----------------------------------------------------------------------===//
107
108 bool SITargetLowering::allowsUnalignedMemoryAccesses(EVT  VT,
109                                                      bool *IsFast) const {
110   // XXX: This depends on the address space and also we may want to revist
111   // the alignment values we specify in the DataLayout.
112   return VT.bitsGT(MVT::i32);
113 }
114
115 bool SITargetLowering::shouldSplitVectorElementType(EVT VT) const {
116   return VT.bitsLE(MVT::i8);
117 }
118
119 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT,
120                                          SDLoc DL, SDValue Chain,
121                                          unsigned Offset) const {
122   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
123   PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
124                                             AMDGPUAS::CONSTANT_ADDRESS);
125   EVT ArgVT = MVT::getIntegerVT(VT.getSizeInBits());
126   SDValue BasePtr =  DAG.getCopyFromReg(Chain, DL,
127                            MRI.getLiveInVirtReg(AMDGPU::SGPR0_SGPR1), MVT::i64);
128   SDValue Ptr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
129                                              DAG.getConstant(Offset, MVT::i64));
130   return DAG.getLoad(VT, DL, Chain, Ptr,
131                             MachinePointerInfo(UndefValue::get(PtrTy)),
132                             false, false, false, ArgVT.getSizeInBits() >> 3);
133
134 }
135
136 SDValue SITargetLowering::LowerFormalArguments(
137                                       SDValue Chain,
138                                       CallingConv::ID CallConv,
139                                       bool isVarArg,
140                                       const SmallVectorImpl<ISD::InputArg> &Ins,
141                                       SDLoc DL, SelectionDAG &DAG,
142                                       SmallVectorImpl<SDValue> &InVals) const {
143
144   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
145
146   MachineFunction &MF = DAG.getMachineFunction();
147   FunctionType *FType = MF.getFunction()->getFunctionType();
148   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
149
150   assert(CallConv == CallingConv::C);
151
152   SmallVector<ISD::InputArg, 16> Splits;
153   uint32_t Skipped = 0;
154
155   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
156     const ISD::InputArg &Arg = Ins[i];
157
158     // First check if it's a PS input addr
159     if (Info->ShaderType == ShaderType::PIXEL && !Arg.Flags.isInReg()) {
160
161       assert((PSInputNum <= 15) && "Too many PS inputs!");
162
163       if (!Arg.Used) {
164         // We can savely skip PS inputs
165         Skipped |= 1 << i;
166         ++PSInputNum;
167         continue;
168       }
169
170       Info->PSInputAddr |= 1 << PSInputNum++;
171     }
172
173     // Second split vertices into their elements
174     if (Info->ShaderType != ShaderType::COMPUTE && Arg.VT.isVector()) {
175       ISD::InputArg NewArg = Arg;
176       NewArg.Flags.setSplit();
177       NewArg.VT = Arg.VT.getVectorElementType();
178
179       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
180       // three or five element vertex only needs three or five registers,
181       // NOT four or eigth.
182       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
183       unsigned NumElements = ParamType->getVectorNumElements();
184
185       for (unsigned j = 0; j != NumElements; ++j) {
186         Splits.push_back(NewArg);
187         NewArg.PartOffset += NewArg.VT.getStoreSize();
188       }
189
190     } else {
191       Splits.push_back(Arg);
192     }
193   }
194
195   SmallVector<CCValAssign, 16> ArgLocs;
196   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
197                  getTargetMachine(), ArgLocs, *DAG.getContext());
198
199   // At least one interpolation mode must be enabled or else the GPU will hang.
200   if (Info->ShaderType == ShaderType::PIXEL && (Info->PSInputAddr & 0x7F) == 0) {
201     Info->PSInputAddr |= 1;
202     CCInfo.AllocateReg(AMDGPU::VGPR0);
203     CCInfo.AllocateReg(AMDGPU::VGPR1);
204   }
205
206   // The pointer to the list of arguments is stored in SGPR0, SGPR1
207   if (Info->ShaderType == ShaderType::COMPUTE) {
208     CCInfo.AllocateReg(AMDGPU::SGPR0);
209     CCInfo.AllocateReg(AMDGPU::SGPR1);
210     MF.addLiveIn(AMDGPU::SGPR0_SGPR1, &AMDGPU::SReg_64RegClass);
211   }
212
213   AnalyzeFormalArguments(CCInfo, Splits);
214
215   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
216
217     const ISD::InputArg &Arg = Ins[i];
218     if (Skipped & (1 << i)) {
219       InVals.push_back(DAG.getUNDEF(Arg.VT));
220       continue;
221     }
222
223     CCValAssign &VA = ArgLocs[ArgIdx++];
224     EVT VT = VA.getLocVT();
225
226     if (VA.isMemLoc()) {
227       // The first 36 bytes of the input buffer contains information about
228       // thread group and global sizes.
229       SDValue Arg = LowerParameter(DAG, VT, DL, DAG.getRoot(),
230                                    36 + VA.getLocMemOffset());
231       InVals.push_back(Arg);
232       continue;
233     }
234     assert(VA.isRegLoc() && "Parameter must be in a register!");
235
236     unsigned Reg = VA.getLocReg();
237
238     if (VT == MVT::i64) {
239       // For now assume it is a pointer
240       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
241                                      &AMDGPU::SReg_64RegClass);
242       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
243       InVals.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
244       continue;
245     }
246
247     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
248
249     Reg = MF.addLiveIn(Reg, RC);
250     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
251
252     if (Arg.VT.isVector()) {
253
254       // Build a vector from the registers
255       Type *ParamType = FType->getParamType(Arg.OrigArgIndex);
256       unsigned NumElements = ParamType->getVectorNumElements();
257
258       SmallVector<SDValue, 4> Regs;
259       Regs.push_back(Val);
260       for (unsigned j = 1; j != NumElements; ++j) {
261         Reg = ArgLocs[ArgIdx++].getLocReg();
262         Reg = MF.addLiveIn(Reg, RC);
263         Regs.push_back(DAG.getCopyFromReg(Chain, DL, Reg, VT));
264       }
265
266       // Fill up the missing vector elements
267       NumElements = Arg.VT.getVectorNumElements() - NumElements;
268       for (unsigned j = 0; j != NumElements; ++j)
269         Regs.push_back(DAG.getUNDEF(VT));
270
271       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT,
272                                    Regs.data(), Regs.size()));
273       continue;
274     }
275
276     InVals.push_back(Val);
277   }
278   return Chain;
279 }
280
281 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
282     MachineInstr * MI, MachineBasicBlock * BB) const {
283
284   MachineBasicBlock::iterator I = *MI;
285
286   switch (MI->getOpcode()) {
287   default:
288     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
289   case AMDGPU::BRANCH: return BB;
290   case AMDGPU::SI_ADDR64_RSRC: {
291     const SIInstrInfo *TII =
292       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
293     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
294     unsigned SuperReg = MI->getOperand(0).getReg();
295     unsigned SubRegLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
296     unsigned SubRegHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
297     unsigned SubRegHiHi = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
298     unsigned SubRegHiLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
299     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), SubRegLo)
300             .addOperand(MI->getOperand(1));
301     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiLo)
302             .addImm(0);
303     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), SubRegHiHi)
304             .addImm(RSRC_DATA_FORMAT >> 32);
305     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SubRegHi)
306             .addReg(SubRegHiLo)
307             .addImm(AMDGPU::sub0)
308             .addReg(SubRegHiHi)
309             .addImm(AMDGPU::sub1);
310     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::REG_SEQUENCE), SuperReg)
311             .addReg(SubRegLo)
312             .addImm(AMDGPU::sub0_sub1)
313             .addReg(SubRegHi)
314             .addImm(AMDGPU::sub2_sub3);
315     MI->eraseFromParent();
316     break;
317   }
318   case AMDGPU::V_SUB_F64: {
319     const SIInstrInfo *TII =
320       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
321     BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::V_ADD_F64),
322             MI->getOperand(0).getReg())
323             .addReg(MI->getOperand(1).getReg())
324             .addReg(MI->getOperand(2).getReg())
325             .addImm(0)  /* src2 */
326             .addImm(0)  /* ABS */
327             .addImm(0)  /* CLAMP */
328             .addImm(0)  /* OMOD */
329             .addImm(2); /* NEG */
330     MI->eraseFromParent();
331     break;
332   }
333   }
334   return BB;
335 }
336
337 EVT SITargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
338   if (!VT.isVector()) {
339     return MVT::i1;
340   }
341   return MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
342 }
343
344 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
345   return MVT::i32;
346 }
347
348 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
349   VT = VT.getScalarType();
350
351   if (!VT.isSimple())
352     return false;
353
354   switch (VT.getSimpleVT().SimpleTy) {
355   case MVT::f32:
356     return false; /* There is V_MAD_F32 for f32 */
357   case MVT::f64:
358     return true;
359   default:
360     break;
361   }
362
363   return false;
364 }
365
366 //===----------------------------------------------------------------------===//
367 // Custom DAG Lowering Operations
368 //===----------------------------------------------------------------------===//
369
370 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
371   MachineFunction &MF = DAG.getMachineFunction();
372   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
373   switch (Op.getOpcode()) {
374   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
375   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
376   case ISD::LOAD: {
377     LoadSDNode *Load = dyn_cast<LoadSDNode>(Op);
378     if (Load->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
379         Op.getValueType().isVector()) {
380       SDValue MergedValues[2] = {
381         SplitVectorLoad(Op, DAG),
382         Load->getChain()
383       };
384       return DAG.getMergeValues(MergedValues, 2, SDLoc(Op));
385     } else {
386       return SDValue();
387     }
388   }
389   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
390   case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
391   case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
392   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
393   case ISD::INTRINSIC_WO_CHAIN: {
394     unsigned IntrinsicID =
395                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
396     EVT VT = Op.getValueType();
397     SDLoc DL(Op);
398     //XXX: Hardcoded we only use two to store the pointer to the parameters.
399     unsigned NumUserSGPRs = 2;
400     switch (IntrinsicID) {
401     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
402     case Intrinsic::r600_read_ngroups_x:
403       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 0);
404     case Intrinsic::r600_read_ngroups_y:
405       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 4);
406     case Intrinsic::r600_read_ngroups_z:
407       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 8);
408     case Intrinsic::r600_read_global_size_x:
409       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 12);
410     case Intrinsic::r600_read_global_size_y:
411       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 16);
412     case Intrinsic::r600_read_global_size_z:
413       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 20);
414     case Intrinsic::r600_read_local_size_x:
415       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 24);
416     case Intrinsic::r600_read_local_size_y:
417       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 28);
418     case Intrinsic::r600_read_local_size_z:
419       return LowerParameter(DAG, VT, DL, DAG.getEntryNode(), 32);
420     case Intrinsic::r600_read_tgid_x:
421       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
422                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 0), VT);
423     case Intrinsic::r600_read_tgid_y:
424       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
425                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 1), VT);
426     case Intrinsic::r600_read_tgid_z:
427       return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
428                      AMDGPU::SReg_32RegClass.getRegister(NumUserSGPRs + 2), VT);
429     case Intrinsic::r600_read_tidig_x:
430       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
431                                   AMDGPU::VGPR0, VT);
432     case Intrinsic::r600_read_tidig_y:
433       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
434                                   AMDGPU::VGPR1, VT);
435     case Intrinsic::r600_read_tidig_z:
436       return CreateLiveInRegister(DAG, &AMDGPU::VReg_32RegClass,
437                                   AMDGPU::VGPR2, VT);
438     case AMDGPUIntrinsic::SI_load_const: {
439       SDValue Ops [] = {
440         ResourceDescriptorToi128(Op.getOperand(1), DAG),
441         Op.getOperand(2)
442       };
443
444       MachineMemOperand *MMO = MF.getMachineMemOperand(
445           MachinePointerInfo(),
446           MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
447           VT.getSizeInBits() / 8, 4);
448       return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
449                                      Op->getVTList(), Ops, 2, VT, MMO);
450     }
451     case AMDGPUIntrinsic::SI_sample:
452       return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
453     case AMDGPUIntrinsic::SI_sampleb:
454       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
455     case AMDGPUIntrinsic::SI_sampled:
456       return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
457     case AMDGPUIntrinsic::SI_samplel:
458       return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
459     case AMDGPUIntrinsic::SI_vs_load_input:
460       return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
461                          ResourceDescriptorToi128(Op.getOperand(1), DAG),
462                          Op.getOperand(2),
463                          Op.getOperand(3));
464     }
465   }
466   }
467   return SDValue();
468 }
469
470 /// \brief Helper function for LowerBRCOND
471 static SDNode *findUser(SDValue Value, unsigned Opcode) {
472
473   SDNode *Parent = Value.getNode();
474   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
475        I != E; ++I) {
476
477     if (I.getUse().get() != Value)
478       continue;
479
480     if (I->getOpcode() == Opcode)
481       return *I;
482   }
483   return 0;
484 }
485
486 /// This transforms the control flow intrinsics to get the branch destination as
487 /// last parameter, also switches branch target with BR if the need arise
488 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
489                                       SelectionDAG &DAG) const {
490
491   SDLoc DL(BRCOND);
492
493   SDNode *Intr = BRCOND.getOperand(1).getNode();
494   SDValue Target = BRCOND.getOperand(2);
495   SDNode *BR = 0;
496
497   if (Intr->getOpcode() == ISD::SETCC) {
498     // As long as we negate the condition everything is fine
499     SDNode *SetCC = Intr;
500     assert(SetCC->getConstantOperandVal(1) == 1);
501     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
502            ISD::SETNE);
503     Intr = SetCC->getOperand(0).getNode();
504
505   } else {
506     // Get the target from BR if we don't negate the condition
507     BR = findUser(BRCOND, ISD::BR);
508     Target = BR->getOperand(1);
509   }
510
511   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
512
513   // Build the result and
514   SmallVector<EVT, 4> Res;
515   for (unsigned i = 1, e = Intr->getNumValues(); i != e; ++i)
516     Res.push_back(Intr->getValueType(i));
517
518   // operands of the new intrinsic call
519   SmallVector<SDValue, 4> Ops;
520   Ops.push_back(BRCOND.getOperand(0));
521   for (unsigned i = 1, e = Intr->getNumOperands(); i != e; ++i)
522     Ops.push_back(Intr->getOperand(i));
523   Ops.push_back(Target);
524
525   // build the new intrinsic call
526   SDNode *Result = DAG.getNode(
527     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
528     DAG.getVTList(Res.data(), Res.size()), Ops.data(), Ops.size()).getNode();
529
530   if (BR) {
531     // Give the branch instruction our target
532     SDValue Ops[] = {
533       BR->getOperand(0),
534       BRCOND.getOperand(2)
535     };
536     DAG.MorphNodeTo(BR, ISD::BR, BR->getVTList(), Ops, 2);
537   }
538
539   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
540
541   // Copy the intrinsic results to registers
542   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
543     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
544     if (!CopyToReg)
545       continue;
546
547     Chain = DAG.getCopyToReg(
548       Chain, DL,
549       CopyToReg->getOperand(1),
550       SDValue(Result, i - 1),
551       SDValue());
552
553     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
554   }
555
556   // Remove the old intrinsic from the chain
557   DAG.ReplaceAllUsesOfValueWith(
558     SDValue(Intr, Intr->getNumValues() - 1),
559     Intr->getOperand(0));
560
561   return Chain;
562 }
563
564 SDValue SITargetLowering::ResourceDescriptorToi128(SDValue Op,
565                                              SelectionDAG &DAG) const {
566
567   if (Op.getValueType() == MVT::i128) {
568     return Op;
569   }
570
571   assert(Op.getOpcode() == ISD::UNDEF);
572
573   return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), MVT::i128,
574                      DAG.getConstant(0, MVT::i64),
575                      DAG.getConstant(0, MVT::i64));
576 }
577
578 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
579                                                const SDValue &Op,
580                                                SelectionDAG &DAG) const {
581   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
582                      Op.getOperand(2),
583                      ResourceDescriptorToi128(Op.getOperand(3), DAG),
584                      Op.getOperand(4));
585 }
586
587 SDValue SITargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
588   SDValue LHS = Op.getOperand(0);
589   SDValue RHS = Op.getOperand(1);
590   SDValue True = Op.getOperand(2);
591   SDValue False = Op.getOperand(3);
592   SDValue CC = Op.getOperand(4);
593   EVT VT = Op.getValueType();
594   SDLoc DL(Op);
595
596   // Possible Min/Max pattern
597   SDValue MinMax = LowerMinMax(Op, DAG);
598   if (MinMax.getNode()) {
599     return MinMax;
600   }
601
602   SDValue Cond = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, CC);
603   return DAG.getNode(ISD::SELECT, DL, VT, Cond, True, False);
604 }
605
606 SDValue SITargetLowering::LowerSIGN_EXTEND(SDValue Op,
607                                            SelectionDAG &DAG) const {
608   EVT VT = Op.getValueType();
609   SDLoc DL(Op);
610
611   if (VT != MVT::i64) {
612     return SDValue();
613   }
614
615   SDValue Hi = DAG.getNode(ISD::SRA, DL, MVT::i32, Op.getOperand(0),
616                                                  DAG.getConstant(31, MVT::i32));
617
618   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0), Hi);
619 }
620
621 SDValue SITargetLowering::LowerZERO_EXTEND(SDValue Op,
622                                            SelectionDAG &DAG) const {
623   EVT VT = Op.getValueType();
624   SDLoc DL(Op);
625
626   if (VT != MVT::i64) {
627     return SDValue();
628   }
629
630   return DAG.getNode(ISD::BUILD_PAIR, DL, VT, Op.getOperand(0),
631                                               DAG.getConstant(0, MVT::i32));
632 }
633
634 //===----------------------------------------------------------------------===//
635 // Custom DAG optimizations
636 //===----------------------------------------------------------------------===//
637
638 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
639                                             DAGCombinerInfo &DCI) const {
640   SelectionDAG &DAG = DCI.DAG;
641   SDLoc DL(N);
642   EVT VT = N->getValueType(0);
643
644   switch (N->getOpcode()) {
645     default: break;
646     case ISD::SELECT_CC: {
647       N->dump();
648       ConstantSDNode *True, *False;
649       // i1 selectcc(l, r, -1, 0, cc) -> i1 setcc(l, r, cc)
650       if ((True = dyn_cast<ConstantSDNode>(N->getOperand(2)))
651           && (False = dyn_cast<ConstantSDNode>(N->getOperand(3)))
652           && True->isAllOnesValue()
653           && False->isNullValue()
654           && VT == MVT::i1) {
655         return DAG.getNode(ISD::SETCC, DL, VT, N->getOperand(0),
656                            N->getOperand(1), N->getOperand(4));
657
658       }
659       break;
660     }
661     case ISD::SETCC: {
662       SDValue Arg0 = N->getOperand(0);
663       SDValue Arg1 = N->getOperand(1);
664       SDValue CC = N->getOperand(2);
665       ConstantSDNode * C = NULL;
666       ISD::CondCode CCOp = dyn_cast<CondCodeSDNode>(CC)->get();
667
668       // i1 setcc (sext(i1), 0, setne) -> i1 setcc(i1, 0, setne)
669       if (VT == MVT::i1
670           && Arg0.getOpcode() == ISD::SIGN_EXTEND
671           && Arg0.getOperand(0).getValueType() == MVT::i1
672           && (C = dyn_cast<ConstantSDNode>(Arg1))
673           && C->isNullValue()
674           && CCOp == ISD::SETNE) {
675         return SimplifySetCC(VT, Arg0.getOperand(0),
676                              DAG.getConstant(0, MVT::i1), CCOp, true, DCI, DL);
677       }
678       break;
679     }
680   }
681   return SDValue();
682 }
683
684 /// \brief Test if RegClass is one of the VSrc classes
685 static bool isVSrc(unsigned RegClass) {
686   return AMDGPU::VSrc_32RegClassID == RegClass ||
687          AMDGPU::VSrc_64RegClassID == RegClass;
688 }
689
690 /// \brief Test if RegClass is one of the SSrc classes
691 static bool isSSrc(unsigned RegClass) {
692   return AMDGPU::SSrc_32RegClassID == RegClass ||
693          AMDGPU::SSrc_64RegClassID == RegClass;
694 }
695
696 /// \brief Analyze the possible immediate value Op
697 ///
698 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
699 /// and the immediate value if it's a literal immediate
700 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
701
702   union {
703     int32_t I;
704     float F;
705   } Imm;
706
707   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
708     if (Node->getZExtValue() >> 32) {
709         return -1;
710     }
711     Imm.I = Node->getSExtValue();
712   } else if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N))
713     Imm.F = Node->getValueAPF().convertToFloat();
714   else
715     return -1; // It isn't an immediate
716
717   if ((Imm.I >= -16 && Imm.I <= 64) ||
718       Imm.F == 0.5f || Imm.F == -0.5f ||
719       Imm.F == 1.0f || Imm.F == -1.0f ||
720       Imm.F == 2.0f || Imm.F == -2.0f ||
721       Imm.F == 4.0f || Imm.F == -4.0f)
722     return 0; // It's an inline immediate
723
724   return Imm.I; // It's a literal immediate
725 }
726
727 /// \brief Try to fold an immediate directly into an instruction
728 bool SITargetLowering::foldImm(SDValue &Operand, int32_t &Immediate,
729                                bool &ScalarSlotUsed) const {
730
731   MachineSDNode *Mov = dyn_cast<MachineSDNode>(Operand);
732   const SIInstrInfo *TII =
733     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
734   if (Mov == 0 || !TII->isMov(Mov->getMachineOpcode()))
735     return false;
736
737   const SDValue &Op = Mov->getOperand(0);
738   int32_t Value = analyzeImmediate(Op.getNode());
739   if (Value == -1) {
740     // Not an immediate at all
741     return false;
742
743   } else if (Value == 0) {
744     // Inline immediates can always be fold
745     Operand = Op;
746     return true;
747
748   } else if (Value == Immediate) {
749     // Already fold literal immediate
750     Operand = Op;
751     return true;
752
753   } else if (!ScalarSlotUsed && !Immediate) {
754     // Fold this literal immediate
755     ScalarSlotUsed = true;
756     Immediate = Value;
757     Operand = Op;
758     return true;
759
760   }
761
762   return false;
763 }
764
765 const TargetRegisterClass *SITargetLowering::getRegClassForNode(
766                                    SelectionDAG &DAG, const SDValue &Op) const {
767   const SIInstrInfo *TII =
768     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
769   const SIRegisterInfo &TRI = TII->getRegisterInfo();
770
771   if (!Op->isMachineOpcode()) {
772     switch(Op->getOpcode()) {
773     case ISD::CopyFromReg: {
774       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
775       unsigned Reg = cast<RegisterSDNode>(Op->getOperand(1))->getReg();
776       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
777         return MRI.getRegClass(Reg);
778       }
779       return TRI.getPhysRegClass(Reg);
780     }
781     default:  return NULL;
782     }
783   }
784   const MCInstrDesc &Desc = TII->get(Op->getMachineOpcode());
785   int OpClassID = Desc.OpInfo[Op.getResNo()].RegClass;
786   if (OpClassID != -1) {
787     return TRI.getRegClass(OpClassID);
788   }
789   switch(Op.getMachineOpcode()) {
790   case AMDGPU::COPY_TO_REGCLASS:
791     // Operand 1 is the register class id for COPY_TO_REGCLASS instructions.
792     OpClassID = cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue();
793
794     // If the COPY_TO_REGCLASS instruction is copying to a VSrc register
795     // class, then the register class for the value could be either a
796     // VReg or and SReg.  In order to get a more accurate
797     if (OpClassID == AMDGPU::VSrc_32RegClassID ||
798         OpClassID == AMDGPU::VSrc_64RegClassID) {
799       return getRegClassForNode(DAG, Op.getOperand(0));
800     }
801     return TRI.getRegClass(OpClassID);
802   case AMDGPU::EXTRACT_SUBREG: {
803     int SubIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
804     const TargetRegisterClass *SuperClass =
805       getRegClassForNode(DAG, Op.getOperand(0));
806     return TRI.getSubClassWithSubReg(SuperClass, SubIdx);
807   }
808   case AMDGPU::REG_SEQUENCE:
809     // Operand 0 is the register class id for REG_SEQUENCE instructions.
810     return TRI.getRegClass(
811       cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue());
812   default:
813     return getRegClassFor(Op.getSimpleValueType());
814   }
815 }
816
817 /// \brief Does "Op" fit into register class "RegClass" ?
818 bool SITargetLowering::fitsRegClass(SelectionDAG &DAG, const SDValue &Op,
819                                     unsigned RegClass) const {
820   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
821   const TargetRegisterClass *RC = getRegClassForNode(DAG, Op);
822   if (!RC) {
823     return false;
824   }
825   return TRI->getRegClass(RegClass)->hasSubClassEq(RC);
826 }
827
828 /// \brief Make sure that we don't exeed the number of allowed scalars
829 void SITargetLowering::ensureSRegLimit(SelectionDAG &DAG, SDValue &Operand,
830                                        unsigned RegClass,
831                                        bool &ScalarSlotUsed) const {
832
833   // First map the operands register class to a destination class
834   if (RegClass == AMDGPU::VSrc_32RegClassID)
835     RegClass = AMDGPU::VReg_32RegClassID;
836   else if (RegClass == AMDGPU::VSrc_64RegClassID)
837     RegClass = AMDGPU::VReg_64RegClassID;
838   else
839     return;
840
841   // Nothing todo if they fit naturaly
842   if (fitsRegClass(DAG, Operand, RegClass))
843     return;
844
845   // If the scalar slot isn't used yet use it now
846   if (!ScalarSlotUsed) {
847     ScalarSlotUsed = true;
848     return;
849   }
850
851   // This is a conservative aproach, it is possible that we can't determine
852   // the correct register class and copy too often, but better save than sorry.
853   SDValue RC = DAG.getTargetConstant(RegClass, MVT::i32);
854   SDNode *Node = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS, SDLoc(),
855                                     Operand.getValueType(), Operand, RC);
856   Operand = SDValue(Node, 0);
857 }
858
859 /// \returns true if \p Node's operands are different from the SDValue list
860 /// \p Ops
861 static bool isNodeChanged(const SDNode *Node, const std::vector<SDValue> &Ops) {
862   for (unsigned i = 0, e = Node->getNumOperands(); i < e; ++i) {
863     if (Ops[i].getNode() != Node->getOperand(i).getNode()) {
864       return true;
865     }
866   }
867   return false;
868 }
869
870 /// \brief Try to fold the Nodes operands into the Node
871 SDNode *SITargetLowering::foldOperands(MachineSDNode *Node,
872                                        SelectionDAG &DAG) const {
873
874   // Original encoding (either e32 or e64)
875   int Opcode = Node->getMachineOpcode();
876   const SIInstrInfo *TII =
877     static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
878   const MCInstrDesc *Desc = &TII->get(Opcode);
879
880   unsigned NumDefs = Desc->getNumDefs();
881   unsigned NumOps = Desc->getNumOperands();
882
883   // Commuted opcode if available
884   int OpcodeRev = Desc->isCommutable() ? TII->commuteOpcode(Opcode) : -1;
885   const MCInstrDesc *DescRev = OpcodeRev == -1 ? 0 : &TII->get(OpcodeRev);
886
887   assert(!DescRev || DescRev->getNumDefs() == NumDefs);
888   assert(!DescRev || DescRev->getNumOperands() == NumOps);
889
890   // e64 version if available, -1 otherwise
891   int OpcodeE64 = AMDGPU::getVOPe64(Opcode);
892   const MCInstrDesc *DescE64 = OpcodeE64 == -1 ? 0 : &TII->get(OpcodeE64);
893
894   assert(!DescE64 || DescE64->getNumDefs() == NumDefs);
895   assert(!DescE64 || DescE64->getNumOperands() == (NumOps + 4));
896
897   int32_t Immediate = Desc->getSize() == 4 ? 0 : -1;
898   bool HaveVSrc = false, HaveSSrc = false;
899
900   // First figure out what we alread have in this instruction
901   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
902        i != e && Op < NumOps; ++i, ++Op) {
903
904     unsigned RegClass = Desc->OpInfo[Op].RegClass;
905     if (isVSrc(RegClass))
906       HaveVSrc = true;
907     else if (isSSrc(RegClass))
908       HaveSSrc = true;
909     else
910       continue;
911
912     int32_t Imm = analyzeImmediate(Node->getOperand(i).getNode());
913     if (Imm != -1 && Imm != 0) {
914       // Literal immediate
915       Immediate = Imm;
916     }
917   }
918
919   // If we neither have VSrc nor SSrc it makes no sense to continue
920   if (!HaveVSrc && !HaveSSrc)
921     return Node;
922
923   // No scalar allowed when we have both VSrc and SSrc
924   bool ScalarSlotUsed = HaveVSrc && HaveSSrc;
925
926   // Second go over the operands and try to fold them
927   std::vector<SDValue> Ops;
928   bool Promote2e64 = false;
929   for (unsigned i = 0, e = Node->getNumOperands(), Op = NumDefs;
930        i != e && Op < NumOps; ++i, ++Op) {
931
932     const SDValue &Operand = Node->getOperand(i);
933     Ops.push_back(Operand);
934
935     // Already folded immediate ?
936     if (isa<ConstantSDNode>(Operand.getNode()) ||
937         isa<ConstantFPSDNode>(Operand.getNode()))
938       continue;
939
940     // Is this a VSrc or SSrc operand ?
941     unsigned RegClass = Desc->OpInfo[Op].RegClass;
942     if (isVSrc(RegClass) || isSSrc(RegClass)) {
943       // Try to fold the immediates
944       if (!foldImm(Ops[i], Immediate, ScalarSlotUsed)) {
945         // Folding didn't worked, make sure we don't hit the SReg limit
946         ensureSRegLimit(DAG, Ops[i], RegClass, ScalarSlotUsed);
947       }
948       continue;
949     }
950
951     if (i == 1 && DescRev && fitsRegClass(DAG, Ops[0], RegClass)) {
952
953       unsigned OtherRegClass = Desc->OpInfo[NumDefs].RegClass;
954       assert(isVSrc(OtherRegClass) || isSSrc(OtherRegClass));
955
956       // Test if it makes sense to swap operands
957       if (foldImm(Ops[1], Immediate, ScalarSlotUsed) ||
958           (!fitsRegClass(DAG, Ops[1], RegClass) &&
959            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
960
961         // Swap commutable operands
962         SDValue Tmp = Ops[1];
963         Ops[1] = Ops[0];
964         Ops[0] = Tmp;
965
966         Desc = DescRev;
967         DescRev = 0;
968         continue;
969       }
970     }
971
972     if (DescE64 && !Immediate) {
973
974       // Test if it makes sense to switch to e64 encoding
975       unsigned OtherRegClass = DescE64->OpInfo[Op].RegClass;
976       if (!isVSrc(OtherRegClass) && !isSSrc(OtherRegClass))
977         continue;
978
979       int32_t TmpImm = -1;
980       if (foldImm(Ops[i], TmpImm, ScalarSlotUsed) ||
981           (!fitsRegClass(DAG, Ops[i], RegClass) &&
982            fitsRegClass(DAG, Ops[1], OtherRegClass))) {
983
984         // Switch to e64 encoding
985         Immediate = -1;
986         Promote2e64 = true;
987         Desc = DescE64;
988         DescE64 = 0;
989       }
990     }
991   }
992
993   if (Promote2e64) {
994     // Add the modifier flags while promoting
995     for (unsigned i = 0; i < 4; ++i)
996       Ops.push_back(DAG.getTargetConstant(0, MVT::i32));
997   }
998
999   // Add optional chain and glue
1000   for (unsigned i = NumOps - NumDefs, e = Node->getNumOperands(); i < e; ++i)
1001     Ops.push_back(Node->getOperand(i));
1002
1003   // Nodes that have a glue result are not CSE'd by getMachineNode(), so in
1004   // this case a brand new node is always be created, even if the operands
1005   // are the same as before.  So, manually check if anything has been changed.
1006   if (Desc->Opcode == Opcode && !isNodeChanged(Node, Ops)) {
1007     return Node;
1008   }
1009
1010   // Create a complete new instruction
1011   return DAG.getMachineNode(Desc->Opcode, SDLoc(Node), Node->getVTList(), Ops);
1012 }
1013
1014 /// \brief Helper function for adjustWritemask
1015 static unsigned SubIdx2Lane(unsigned Idx) {
1016   switch (Idx) {
1017   default: return 0;
1018   case AMDGPU::sub0: return 0;
1019   case AMDGPU::sub1: return 1;
1020   case AMDGPU::sub2: return 2;
1021   case AMDGPU::sub3: return 3;
1022   }
1023 }
1024
1025 /// \brief Adjust the writemask of MIMG instructions
1026 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1027                                        SelectionDAG &DAG) const {
1028   SDNode *Users[4] = { };
1029   unsigned Writemask = 0, Lane = 0;
1030
1031   // Try to figure out the used register components
1032   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1033        I != E; ++I) {
1034
1035     // Abort if we can't understand the usage
1036     if (!I->isMachineOpcode() ||
1037         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1038       return;
1039
1040     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1041
1042     // Abort if we have more than one user per component
1043     if (Users[Lane])
1044       return;
1045
1046     Users[Lane] = *I;
1047     Writemask |= 1 << Lane;
1048   }
1049
1050   // Abort if all components are used
1051   if (Writemask == 0xf)
1052     return;
1053
1054   // Adjust the writemask in the node
1055   std::vector<SDValue> Ops;
1056   Ops.push_back(DAG.getTargetConstant(Writemask, MVT::i32));
1057   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1058     Ops.push_back(Node->getOperand(i));
1059   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
1060
1061   // If we only got one lane, replace it with a copy
1062   if (Writemask == (1U << Lane)) {
1063     SDValue RC = DAG.getTargetConstant(AMDGPU::VReg_32RegClassID, MVT::i32);
1064     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1065                                       SDLoc(), Users[Lane]->getValueType(0),
1066                                       SDValue(Node, 0), RC);
1067     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1068     return;
1069   }
1070
1071   // Update the users of the node with the new indices
1072   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
1073
1074     SDNode *User = Users[i];
1075     if (!User)
1076       continue;
1077
1078     SDValue Op = DAG.getTargetConstant(Idx, MVT::i32);
1079     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
1080
1081     switch (Idx) {
1082     default: break;
1083     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
1084     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
1085     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
1086     }
1087   }
1088 }
1089
1090 /// \brief Fold the instructions after slecting them
1091 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
1092                                           SelectionDAG &DAG) const {
1093   const SIInstrInfo *TII =
1094       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1095   Node = AdjustRegClass(Node, DAG);
1096
1097   if (TII->isMIMG(Node->getMachineOpcode()))
1098     adjustWritemask(Node, DAG);
1099
1100   return foldOperands(Node, DAG);
1101 }
1102
1103 /// \brief Assign the register class depending on the number of
1104 /// bits set in the writemask
1105 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
1106                                                      SDNode *Node) const {
1107   const SIInstrInfo *TII =
1108       static_cast<const SIInstrInfo*>(getTargetMachine().getInstrInfo());
1109   if (!TII->isMIMG(MI->getOpcode()))
1110     return;
1111
1112   unsigned VReg = MI->getOperand(0).getReg();
1113   unsigned Writemask = MI->getOperand(1).getImm();
1114   unsigned BitsSet = 0;
1115   for (unsigned i = 0; i < 4; ++i)
1116     BitsSet += Writemask & (1 << i) ? 1 : 0;
1117
1118   const TargetRegisterClass *RC;
1119   switch (BitsSet) {
1120   default: return;
1121   case 1:  RC = &AMDGPU::VReg_32RegClass; break;
1122   case 2:  RC = &AMDGPU::VReg_64RegClass; break;
1123   case 3:  RC = &AMDGPU::VReg_96RegClass; break;
1124   }
1125
1126   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1127   MRI.setRegClass(VReg, RC);
1128 }
1129
1130 MachineSDNode *SITargetLowering::AdjustRegClass(MachineSDNode *N,
1131                                                 SelectionDAG &DAG) const {
1132
1133   SDLoc DL(N);
1134   unsigned NewOpcode = N->getMachineOpcode();
1135
1136   switch (N->getMachineOpcode()) {
1137   default: return N;
1138   case AMDGPU::S_LOAD_DWORD_IMM:
1139     NewOpcode = AMDGPU::BUFFER_LOAD_DWORD_ADDR64;
1140     // Fall-through
1141   case AMDGPU::S_LOAD_DWORDX2_SGPR:
1142     if (NewOpcode == N->getMachineOpcode()) {
1143       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX2_ADDR64;
1144     }
1145     // Fall-through
1146   case AMDGPU::S_LOAD_DWORDX4_IMM:
1147   case AMDGPU::S_LOAD_DWORDX4_SGPR: {
1148     if (NewOpcode == N->getMachineOpcode()) {
1149       NewOpcode = AMDGPU::BUFFER_LOAD_DWORDX4_ADDR64;
1150     }
1151     if (fitsRegClass(DAG, N->getOperand(0), AMDGPU::SReg_64RegClassID)) {
1152       return N;
1153     }
1154     ConstantSDNode *Offset = cast<ConstantSDNode>(N->getOperand(1));
1155     SDValue Ops[] = {
1156       SDValue(DAG.getMachineNode(AMDGPU::SI_ADDR64_RSRC, DL, MVT::i128,
1157                                  DAG.getConstant(0, MVT::i64)), 0),
1158       N->getOperand(0),
1159       DAG.getConstant(Offset->getSExtValue() << 2, MVT::i32)
1160     };
1161     return DAG.getMachineNode(NewOpcode, DL, N->getVTList(), Ops);
1162   }
1163   }
1164 }
1165
1166 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
1167                                                const TargetRegisterClass *RC,
1168                                                unsigned Reg, EVT VT) const {
1169   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
1170
1171   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
1172                             cast<RegisterSDNode>(VReg)->getReg(), VT);
1173 }