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