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