R600: Add support for SET*_DX10 instructions
[oota-llvm.git] / lib / Target / R600 / R600ISelLowering.cpp
1 //===-- R600ISelLowering.cpp - R600 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 R600
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "R600ISelLowering.h"
16 #include "R600Defines.h"
17 #include "R600InstrInfo.h"
18 #include "R600MachineFunctionInfo.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Function.h"
25
26 using namespace llvm;
27
28 R600TargetLowering::R600TargetLowering(TargetMachine &TM) :
29     AMDGPUTargetLowering(TM),
30     TII(static_cast<const R600InstrInfo*>(TM.getInstrInfo())) {
31   setOperationAction(ISD::MUL, MVT::i64, Expand);
32   addRegisterClass(MVT::v4f32, &AMDGPU::R600_Reg128RegClass);
33   addRegisterClass(MVT::f32, &AMDGPU::R600_Reg32RegClass);
34   addRegisterClass(MVT::v4i32, &AMDGPU::R600_Reg128RegClass);
35   addRegisterClass(MVT::i32, &AMDGPU::R600_Reg32RegClass);
36   computeRegisterProperties();
37
38   setOperationAction(ISD::FADD, MVT::v4f32, Expand);
39   setOperationAction(ISD::FMUL, MVT::v4f32, Expand);
40   setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
41   setOperationAction(ISD::FSUB, MVT::v4f32, Expand);
42
43   setOperationAction(ISD::ADD,  MVT::v4i32, Expand);
44   setOperationAction(ISD::AND,  MVT::v4i32, Expand);
45   setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Expand);
46   setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Expand);
47   setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Expand);
48   setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Expand);
49   setOperationAction(ISD::UDIV, MVT::v4i32, Expand);
50   setOperationAction(ISD::UREM, MVT::v4i32, Expand);
51   setOperationAction(ISD::SETCC, MVT::v4i32, Expand);
52
53   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
54   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
55
56   setOperationAction(ISD::FSUB, MVT::f32, Expand);
57
58   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
59   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
60   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i1, Custom);
61   setOperationAction(ISD::FPOW, MVT::f32, Custom);
62
63   setOperationAction(ISD::ROTL, MVT::i32, Custom);
64
65   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
66   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
67
68   setOperationAction(ISD::SETCC, MVT::i32, Custom);
69   setOperationAction(ISD::SETCC, MVT::f32, Custom);
70   setOperationAction(ISD::FP_TO_UINT, MVT::i1, Custom);
71
72   setOperationAction(ISD::SELECT, MVT::i32, Custom);
73   setOperationAction(ISD::SELECT, MVT::f32, Custom);
74
75   // Legalize loads and stores to the private address space.
76   setOperationAction(ISD::LOAD, MVT::i32, Custom);
77   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
78   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
79   setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
80   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
81   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
82   setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Custom);
83   setOperationAction(ISD::STORE, MVT::i8, Custom);
84   setOperationAction(ISD::STORE, MVT::i32, Custom);
85   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
86   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
87
88   setOperationAction(ISD::LOAD, MVT::i32, Custom);
89   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
90   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
91
92   setTargetDAGCombine(ISD::FP_ROUND);
93   setTargetDAGCombine(ISD::FP_TO_SINT);
94   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
95   setTargetDAGCombine(ISD::SELECT_CC);
96
97   setSchedulingPreference(Sched::VLIW);
98 }
99
100 MachineBasicBlock * R600TargetLowering::EmitInstrWithCustomInserter(
101     MachineInstr * MI, MachineBasicBlock * BB) const {
102   MachineFunction * MF = BB->getParent();
103   MachineRegisterInfo &MRI = MF->getRegInfo();
104   MachineBasicBlock::iterator I = *MI;
105
106   switch (MI->getOpcode()) {
107   default: return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
108   case AMDGPU::SHADER_TYPE: break;
109   case AMDGPU::CLAMP_R600: {
110     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
111                                                    AMDGPU::MOV,
112                                                    MI->getOperand(0).getReg(),
113                                                    MI->getOperand(1).getReg());
114     TII->addFlag(NewMI, 0, MO_FLAG_CLAMP);
115     break;
116   }
117
118   case AMDGPU::FABS_R600: {
119     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
120                                                     AMDGPU::MOV,
121                                                     MI->getOperand(0).getReg(),
122                                                     MI->getOperand(1).getReg());
123     TII->addFlag(NewMI, 0, MO_FLAG_ABS);
124     break;
125   }
126
127   case AMDGPU::FNEG_R600: {
128     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
129                                                     AMDGPU::MOV,
130                                                     MI->getOperand(0).getReg(),
131                                                     MI->getOperand(1).getReg());
132     TII->addFlag(NewMI, 0, MO_FLAG_NEG);
133     break;
134   }
135
136   case AMDGPU::MASK_WRITE: {
137     unsigned maskedRegister = MI->getOperand(0).getReg();
138     assert(TargetRegisterInfo::isVirtualRegister(maskedRegister));
139     MachineInstr * defInstr = MRI.getVRegDef(maskedRegister);
140     TII->addFlag(defInstr, 0, MO_FLAG_MASK);
141     break;
142   }
143
144   case AMDGPU::MOV_IMM_F32:
145     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
146                      MI->getOperand(1).getFPImm()->getValueAPF()
147                          .bitcastToAPInt().getZExtValue());
148     break;
149   case AMDGPU::MOV_IMM_I32:
150     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
151                      MI->getOperand(1).getImm());
152     break;
153
154
155   case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
156   case AMDGPU::RAT_WRITE_CACHELESS_128_eg: {
157     unsigned EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;
158
159     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
160             .addOperand(MI->getOperand(0))
161             .addOperand(MI->getOperand(1))
162             .addImm(EOP); // Set End of program bit
163     break;
164   }
165
166   case AMDGPU::TXD: {
167     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
168     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
169
170     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
171             .addOperand(MI->getOperand(3))
172             .addOperand(MI->getOperand(4))
173             .addOperand(MI->getOperand(5))
174             .addOperand(MI->getOperand(6));
175     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
176             .addOperand(MI->getOperand(2))
177             .addOperand(MI->getOperand(4))
178             .addOperand(MI->getOperand(5))
179             .addOperand(MI->getOperand(6));
180     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_G))
181             .addOperand(MI->getOperand(0))
182             .addOperand(MI->getOperand(1))
183             .addOperand(MI->getOperand(4))
184             .addOperand(MI->getOperand(5))
185             .addOperand(MI->getOperand(6))
186             .addReg(T0, RegState::Implicit)
187             .addReg(T1, RegState::Implicit);
188     break;
189   }
190
191   case AMDGPU::TXD_SHADOW: {
192     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
193     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
194
195     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
196             .addOperand(MI->getOperand(3))
197             .addOperand(MI->getOperand(4))
198             .addOperand(MI->getOperand(5))
199             .addOperand(MI->getOperand(6));
200     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
201             .addOperand(MI->getOperand(2))
202             .addOperand(MI->getOperand(4))
203             .addOperand(MI->getOperand(5))
204             .addOperand(MI->getOperand(6));
205     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_C_G))
206             .addOperand(MI->getOperand(0))
207             .addOperand(MI->getOperand(1))
208             .addOperand(MI->getOperand(4))
209             .addOperand(MI->getOperand(5))
210             .addOperand(MI->getOperand(6))
211             .addReg(T0, RegState::Implicit)
212             .addReg(T1, RegState::Implicit);
213     break;
214   }
215
216   case AMDGPU::BRANCH:
217       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
218               .addOperand(MI->getOperand(0))
219               .addReg(0);
220       break;
221
222   case AMDGPU::BRANCH_COND_f32: {
223     MachineInstr *NewMI =
224       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
225               AMDGPU::PREDICATE_BIT)
226               .addOperand(MI->getOperand(1))
227               .addImm(OPCODE_IS_NOT_ZERO)
228               .addImm(0); // Flags
229     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
230     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
231             .addOperand(MI->getOperand(0))
232             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
233     break;
234   }
235
236   case AMDGPU::BRANCH_COND_i32: {
237     MachineInstr *NewMI =
238       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
239             AMDGPU::PREDICATE_BIT)
240             .addOperand(MI->getOperand(1))
241             .addImm(OPCODE_IS_NOT_ZERO_INT)
242             .addImm(0); // Flags
243     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
244     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
245            .addOperand(MI->getOperand(0))
246             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
247     break;
248   }
249
250   case AMDGPU::EG_ExportSwz:
251   case AMDGPU::R600_ExportSwz: {
252     // Instruction is left unmodified if its not the last one of its type
253     bool isLastInstructionOfItsType = true;
254     unsigned InstExportType = MI->getOperand(1).getImm();
255     for (MachineBasicBlock::iterator NextExportInst = llvm::next(I),
256          EndBlock = BB->end(); NextExportInst != EndBlock;
257          NextExportInst = llvm::next(NextExportInst)) {
258       if (NextExportInst->getOpcode() == AMDGPU::EG_ExportSwz ||
259           NextExportInst->getOpcode() == AMDGPU::R600_ExportSwz) {
260         unsigned CurrentInstExportType = NextExportInst->getOperand(1)
261             .getImm();
262         if (CurrentInstExportType == InstExportType) {
263           isLastInstructionOfItsType = false;
264           break;
265         }
266       }
267     }
268     bool EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN)? 1 : 0;
269     if (!EOP && !isLastInstructionOfItsType)
270       return BB;
271     unsigned CfInst = (MI->getOpcode() == AMDGPU::EG_ExportSwz)? 84 : 40;
272     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
273             .addOperand(MI->getOperand(0))
274             .addOperand(MI->getOperand(1))
275             .addOperand(MI->getOperand(2))
276             .addOperand(MI->getOperand(3))
277             .addOperand(MI->getOperand(4))
278             .addOperand(MI->getOperand(5))
279             .addOperand(MI->getOperand(6))
280             .addImm(CfInst)
281             .addImm(EOP);
282     break;
283   }
284   case AMDGPU::RETURN: {
285     // RETURN instructions must have the live-out registers as implicit uses,
286     // otherwise they appear dead.
287     R600MachineFunctionInfo *MFI = MF->getInfo<R600MachineFunctionInfo>();
288     MachineInstrBuilder MIB(*MF, MI);
289     for (unsigned i = 0, e = MFI->LiveOuts.size(); i != e; ++i)
290       MIB.addReg(MFI->LiveOuts[i], RegState::Implicit);
291     return BB;
292   }
293   }
294
295   MI->eraseFromParent();
296   return BB;
297 }
298
299 //===----------------------------------------------------------------------===//
300 // Custom DAG Lowering Operations
301 //===----------------------------------------------------------------------===//
302
303 using namespace llvm::Intrinsic;
304 using namespace llvm::AMDGPUIntrinsic;
305
306 static SDValue
307 InsertScalarToRegisterExport(SelectionDAG &DAG, DebugLoc DL, SDNode **ExportMap,
308     unsigned Slot, unsigned Channel, unsigned Inst, unsigned Type,
309     SDValue Scalar, SDValue Chain) {
310   if (!ExportMap[Slot]) {
311     SDValue Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT,
312       DL, MVT::v4f32,
313       DAG.getUNDEF(MVT::v4f32),
314       Scalar,
315       DAG.getConstant(Channel, MVT::i32));
316
317     unsigned Mask = 1 << Channel;
318
319     const SDValue Ops[] = {Chain, Vector, DAG.getConstant(Inst, MVT::i32),
320         DAG.getConstant(Type, MVT::i32), DAG.getConstant(Slot, MVT::i32),
321         DAG.getConstant(Mask, MVT::i32)};
322
323     SDValue Res =  DAG.getNode(
324         AMDGPUISD::EXPORT,
325         DL,
326         MVT::Other,
327         Ops, 6);
328      ExportMap[Slot] = Res.getNode();
329      return Res;
330   }
331
332   SDNode *ExportInstruction = (SDNode *) ExportMap[Slot] ;
333   SDValue PreviousVector = ExportInstruction->getOperand(1);
334   SDValue Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT,
335       DL, MVT::v4f32,
336       PreviousVector,
337       Scalar,
338       DAG.getConstant(Channel, MVT::i32));
339
340   unsigned Mask = dyn_cast<ConstantSDNode>(ExportInstruction->getOperand(5))
341       ->getZExtValue();
342   Mask |= (1 << Channel);
343
344   const SDValue Ops[] = {ExportInstruction->getOperand(0), Vector,
345       DAG.getConstant(Inst, MVT::i32),
346       DAG.getConstant(Type, MVT::i32),
347       DAG.getConstant(Slot, MVT::i32),
348       DAG.getConstant(Mask, MVT::i32)};
349
350   DAG.UpdateNodeOperands(ExportInstruction,
351       Ops, 6);
352
353   return Chain;
354
355 }
356
357 SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
358   switch (Op.getOpcode()) {
359   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
360   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
361   case ISD::ROTL: return LowerROTL(Op, DAG);
362   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
363   case ISD::SELECT: return LowerSELECT(Op, DAG);
364   case ISD::SETCC: return LowerSETCC(Op, DAG);
365   case ISD::STORE: return LowerSTORE(Op, DAG);
366   case ISD::LOAD: return LowerLOAD(Op, DAG);
367   case ISD::FPOW: return LowerFPOW(Op, DAG);
368   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
369   case ISD::INTRINSIC_VOID: {
370     SDValue Chain = Op.getOperand(0);
371     unsigned IntrinsicID =
372                          cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
373     switch (IntrinsicID) {
374     case AMDGPUIntrinsic::AMDGPU_store_output: {
375       MachineFunction &MF = DAG.getMachineFunction();
376       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
377       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
378       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
379       MFI->LiveOuts.push_back(Reg);
380       return DAG.getCopyToReg(Chain, Op.getDebugLoc(), Reg, Op.getOperand(2));
381     }
382     case AMDGPUIntrinsic::R600_store_pixel_color: {
383       MachineFunction &MF = DAG.getMachineFunction();
384       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
385       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
386
387       SDNode **OutputsMap = MFI->Outputs;
388       return InsertScalarToRegisterExport(DAG, Op.getDebugLoc(), OutputsMap,
389           RegIndex / 4, RegIndex % 4, 0, 0, Op.getOperand(2),
390           Chain);
391
392     }
393
394     // default for switch(IntrinsicID)
395     default: break;
396     }
397     // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
398     break;
399   }
400   case ISD::INTRINSIC_WO_CHAIN: {
401     unsigned IntrinsicID =
402                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
403     EVT VT = Op.getValueType();
404     DebugLoc DL = Op.getDebugLoc();
405     switch(IntrinsicID) {
406     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
407     case AMDGPUIntrinsic::R600_load_input: {
408       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
409       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
410       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass, Reg, VT);
411     }
412
413     case AMDGPUIntrinsic::R600_interp_input: {
414       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
415       int ijb = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
416       MachineSDNode *interp;
417       if (ijb < 0) {
418         interp = DAG.getMachineNode(AMDGPU::INTERP_VEC_LOAD, DL,
419             MVT::v4f32, DAG.getTargetConstant(slot / 4 , MVT::i32));
420         return DAG.getTargetExtractSubreg(
421             TII->getRegisterInfo().getSubRegFromChannel(slot % 4),
422             DL, MVT::f32, SDValue(interp, 0));
423       }
424
425       if (slot % 4 < 2)
426         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
427             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
428             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
429                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
430             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
431                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
432       else
433         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
434             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
435             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
436                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
437             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
438                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
439
440       return SDValue(interp, slot % 2);
441     }
442
443     case r600_read_ngroups_x:
444       return LowerImplicitParameter(DAG, VT, DL, 0);
445     case r600_read_ngroups_y:
446       return LowerImplicitParameter(DAG, VT, DL, 1);
447     case r600_read_ngroups_z:
448       return LowerImplicitParameter(DAG, VT, DL, 2);
449     case r600_read_global_size_x:
450       return LowerImplicitParameter(DAG, VT, DL, 3);
451     case r600_read_global_size_y:
452       return LowerImplicitParameter(DAG, VT, DL, 4);
453     case r600_read_global_size_z:
454       return LowerImplicitParameter(DAG, VT, DL, 5);
455     case r600_read_local_size_x:
456       return LowerImplicitParameter(DAG, VT, DL, 6);
457     case r600_read_local_size_y:
458       return LowerImplicitParameter(DAG, VT, DL, 7);
459     case r600_read_local_size_z:
460       return LowerImplicitParameter(DAG, VT, DL, 8);
461
462     case r600_read_tgid_x:
463       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
464                                   AMDGPU::T1_X, VT);
465     case r600_read_tgid_y:
466       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
467                                   AMDGPU::T1_Y, VT);
468     case r600_read_tgid_z:
469       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
470                                   AMDGPU::T1_Z, VT);
471     case r600_read_tidig_x:
472       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
473                                   AMDGPU::T0_X, VT);
474     case r600_read_tidig_y:
475       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
476                                   AMDGPU::T0_Y, VT);
477     case r600_read_tidig_z:
478       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
479                                   AMDGPU::T0_Z, VT);
480     }
481     // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
482     break;
483   }
484   } // end switch(Op.getOpcode())
485   return SDValue();
486 }
487
488 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
489                                             SmallVectorImpl<SDValue> &Results,
490                                             SelectionDAG &DAG) const {
491   switch (N->getOpcode()) {
492   default: return;
493   case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
494     return;
495   case ISD::LOAD: {
496     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
497     Results.push_back(SDValue(Node, 0));
498     Results.push_back(SDValue(Node, 1));
499     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
500     // function
501     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
502     return;
503   }
504   case ISD::STORE:
505     SDNode *Node = LowerSTORE(SDValue(N, 0), DAG).getNode();
506     Results.push_back(SDValue(Node, 0));
507     return;
508   }
509 }
510
511 SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
512   return DAG.getNode(
513       ISD::SETCC,
514       Op.getDebugLoc(),
515       MVT::i1,
516       Op, DAG.getConstantFP(0.0f, MVT::f32),
517       DAG.getCondCode(ISD::SETNE)
518       );
519 }
520
521 SDValue R600TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
522   SDValue Chain = Op.getOperand(0);
523   SDValue CC = Op.getOperand(1);
524   SDValue LHS   = Op.getOperand(2);
525   SDValue RHS   = Op.getOperand(3);
526   SDValue JumpT  = Op.getOperand(4);
527   SDValue CmpValue;
528   SDValue Result;
529
530   if (LHS.getValueType() == MVT::i32) {
531     CmpValue = DAG.getNode(
532         ISD::SELECT_CC,
533         Op.getDebugLoc(),
534         MVT::i32,
535         LHS, RHS,
536         DAG.getConstant(-1, MVT::i32),
537         DAG.getConstant(0, MVT::i32),
538         CC);
539   } else if (LHS.getValueType() == MVT::f32) {
540     CmpValue = DAG.getNode(
541         ISD::SELECT_CC,
542         Op.getDebugLoc(),
543         MVT::f32,
544         LHS, RHS,
545         DAG.getConstantFP(1.0f, MVT::f32),
546         DAG.getConstantFP(0.0f, MVT::f32),
547         CC);
548   } else {
549     assert(0 && "Not valid type for br_cc");
550   }
551   Result = DAG.getNode(
552       AMDGPUISD::BRANCH_COND,
553       CmpValue.getDebugLoc(),
554       MVT::Other, Chain,
555       JumpT, CmpValue);
556   return Result;
557 }
558
559 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
560                                                    DebugLoc DL,
561                                                    unsigned DwordOffset) const {
562   unsigned ByteOffset = DwordOffset * 4;
563   PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
564                                       AMDGPUAS::PARAM_I_ADDRESS);
565
566   // We shouldn't be using an offset wider than 16-bits for implicit parameters.
567   assert(isInt<16>(ByteOffset));
568
569   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
570                      DAG.getConstant(ByteOffset, MVT::i32), // PTR
571                      MachinePointerInfo(ConstantPointerNull::get(PtrType)),
572                      false, false, false, 0);
573 }
574
575 SDValue R600TargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
576
577   MachineFunction &MF = DAG.getMachineFunction();
578   const AMDGPUFrameLowering *TFL =
579    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
580
581   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
582   assert(FIN);
583
584   unsigned FrameIndex = FIN->getIndex();
585   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
586   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF), MVT::i32);
587 }
588
589 SDValue R600TargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
590   DebugLoc DL = Op.getDebugLoc();
591   EVT VT = Op.getValueType();
592
593   return DAG.getNode(AMDGPUISD::BITALIGN, DL, VT,
594                      Op.getOperand(0),
595                      Op.getOperand(0),
596                      DAG.getNode(ISD::SUB, DL, VT,
597                                  DAG.getConstant(32, MVT::i32),
598                                  Op.getOperand(1)));
599 }
600
601 bool R600TargetLowering::isZero(SDValue Op) const {
602   if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
603     return Cst->isNullValue();
604   } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
605     return CstFP->isZero();
606   } else {
607     return false;
608   }
609 }
610
611 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
612   DebugLoc DL = Op.getDebugLoc();
613   EVT VT = Op.getValueType();
614
615   SDValue LHS = Op.getOperand(0);
616   SDValue RHS = Op.getOperand(1);
617   SDValue True = Op.getOperand(2);
618   SDValue False = Op.getOperand(3);
619   SDValue CC = Op.getOperand(4);
620   SDValue Temp;
621
622   // LHS and RHS are guaranteed to be the same value type
623   EVT CompareVT = LHS.getValueType();
624
625   // Check if we can lower this to a native operation.
626
627   // Try to lower to a CND* instruction:
628   // CND* instructions requires RHS to be zero.  Some SELECT_CC nodes that
629   // can be lowered to CND* instructions can also be lowered to SET*
630   // instructions.  CND* instructions are cheaper, because they dont't
631   // require additional instructions to convert their result to the correct
632   // value type, so this check should be first.
633   if (isZero(LHS) || isZero(RHS)) {
634     SDValue Cond = (isZero(LHS) ? RHS : LHS);
635     SDValue Zero = (isZero(LHS) ? LHS : RHS);
636     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
637     if (CompareVT != VT) {
638       // Bitcast True / False to the correct types.  This will end up being
639       // a nop, but it allows us to define only a single pattern in the
640       // .TD files for each CND* instruction rather than having to have
641       // one pattern for integer True/False and one for fp True/False
642       True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
643       False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
644     }
645     if (isZero(LHS)) {
646       CCOpcode = ISD::getSetCCSwappedOperands(CCOpcode);
647     }
648
649     switch (CCOpcode) {
650     case ISD::SETONE:
651     case ISD::SETUNE:
652     case ISD::SETNE:
653     case ISD::SETULE:
654     case ISD::SETULT:
655     case ISD::SETOLE:
656     case ISD::SETOLT:
657     case ISD::SETLE:
658     case ISD::SETLT:
659       CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
660       Temp = True;
661       True = False;
662       False = Temp;
663       break;
664     default:
665       break;
666     }
667     SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
668         Cond, Zero,
669         True, False,
670         DAG.getCondCode(CCOpcode));
671     return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
672   }
673
674   // Try to lower to a SET* instruction:
675   //
676   // CompareVT == MVT::f32 and VT == MVT::i32 is supported by the hardware,
677   // but for the other case where CompareVT != VT, all operands of
678   // SELECT_CC need to have the same value type, so we need to change True and
679   // False to be the same type as LHS and RHS, and then convert the result of
680   // the select_cc back to the correct type.
681
682   // Move hardware True/False values to the correct operand.
683   if (isHWTrueValue(False) && isHWFalseValue(True)) {
684     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
685     std::swap(False, True);
686     CC = DAG.getCondCode(ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32));
687   }
688
689   if (isHWTrueValue(True) && isHWFalseValue(False)) {
690     if (CompareVT !=  VT && VT == MVT::f32 && CompareVT == MVT::i32) {
691       SDValue Boolean = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
692           LHS, RHS,
693           DAG.getConstant(-1, MVT::i32),
694           DAG.getConstant(0, MVT::i32),
695           CC);
696       // Convert integer values of true (-1) and false (0) to fp values of
697       // true (1.0f) and false (0.0f).
698       SDValue LSB = DAG.getNode(ISD::AND, DL, MVT::i32, Boolean,
699                                                 DAG.getConstant(1, MVT::i32));
700       return DAG.getNode(ISD::UINT_TO_FP, DL, VT, LSB);
701     } else {
702       // This SELECT_CC is already legal.
703       return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
704     }
705   }
706
707   // Possible Min/Max pattern
708   SDValue MinMax = LowerMinMax(Op, DAG);
709   if (MinMax.getNode()) {
710     return MinMax;
711   }
712
713   // If we make it this for it means we have no native instructions to handle
714   // this SELECT_CC, so we must lower it.
715   SDValue HWTrue, HWFalse;
716
717   if (CompareVT == MVT::f32) {
718     HWTrue = DAG.getConstantFP(1.0f, CompareVT);
719     HWFalse = DAG.getConstantFP(0.0f, CompareVT);
720   } else if (CompareVT == MVT::i32) {
721     HWTrue = DAG.getConstant(-1, CompareVT);
722     HWFalse = DAG.getConstant(0, CompareVT);
723   }
724   else {
725     assert(!"Unhandled value type in LowerSELECT_CC");
726   }
727
728   // Lower this unsupported SELECT_CC into a combination of two supported
729   // SELECT_CC operations.
730   SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);
731
732   return DAG.getNode(ISD::SELECT_CC, DL, VT,
733       Cond, HWFalse,
734       True, False,
735       DAG.getCondCode(ISD::SETNE));
736 }
737
738 SDValue R600TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
739   return DAG.getNode(ISD::SELECT_CC,
740       Op.getDebugLoc(),
741       Op.getValueType(),
742       Op.getOperand(0),
743       DAG.getConstant(0, MVT::i32),
744       Op.getOperand(1),
745       Op.getOperand(2),
746       DAG.getCondCode(ISD::SETNE));
747 }
748
749 SDValue R600TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
750   SDValue Cond;
751   SDValue LHS = Op.getOperand(0);
752   SDValue RHS = Op.getOperand(1);
753   SDValue CC  = Op.getOperand(2);
754   DebugLoc DL = Op.getDebugLoc();
755   assert(Op.getValueType() == MVT::i32);
756   if (LHS.getValueType() == MVT::i32) {
757     Cond = DAG.getNode(
758         ISD::SELECT_CC,
759         Op.getDebugLoc(),
760         MVT::i32,
761         LHS, RHS,
762         DAG.getConstant(-1, MVT::i32),
763         DAG.getConstant(0, MVT::i32),
764         CC);
765   } else if (LHS.getValueType() == MVT::f32) {
766     Cond = DAG.getNode(
767         ISD::SELECT_CC,
768         Op.getDebugLoc(),
769         MVT::f32,
770         LHS, RHS,
771         DAG.getConstantFP(1.0f, MVT::f32),
772         DAG.getConstantFP(0.0f, MVT::f32),
773         CC);
774     Cond = DAG.getNode(
775         ISD::FP_TO_SINT,
776         DL,
777         MVT::i32,
778         Cond);
779   } else {
780     assert(0 && "Not valid type for set_cc");
781   }
782   Cond = DAG.getNode(
783       ISD::AND,
784       DL,
785       MVT::i32,
786       DAG.getConstant(1, MVT::i32),
787       Cond);
788   return Cond;
789 }
790
791 /// LLVM generates byte-addresed pointers.  For indirect addressing, we need to
792 /// convert these pointers to a register index.  Each register holds
793 /// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
794 /// \p StackWidth, which tells us how many of the 4 sub-registrers will be used
795 /// for indirect addressing.
796 SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
797                                                unsigned StackWidth,
798                                                SelectionDAG &DAG) const {
799   unsigned SRLPad;
800   switch(StackWidth) {
801   case 1:
802     SRLPad = 2;
803     break;
804   case 2:
805     SRLPad = 3;
806     break;
807   case 4:
808     SRLPad = 4;
809     break;
810   default: llvm_unreachable("Invalid stack width");
811   }
812
813   return DAG.getNode(ISD::SRL, Ptr.getDebugLoc(), Ptr.getValueType(), Ptr,
814                      DAG.getConstant(SRLPad, MVT::i32));
815 }
816
817 void R600TargetLowering::getStackAddress(unsigned StackWidth,
818                                          unsigned ElemIdx,
819                                          unsigned &Channel,
820                                          unsigned &PtrIncr) const {
821   switch (StackWidth) {
822   default:
823   case 1:
824     Channel = 0;
825     if (ElemIdx > 0) {
826       PtrIncr = 1;
827     } else {
828       PtrIncr = 0;
829     }
830     break;
831   case 2:
832     Channel = ElemIdx % 2;
833     if (ElemIdx == 2) {
834       PtrIncr = 1;
835     } else {
836       PtrIncr = 0;
837     }
838     break;
839   case 4:
840     Channel = ElemIdx;
841     PtrIncr = 0;
842     break;
843   }
844 }
845
846 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
847   DebugLoc DL = Op.getDebugLoc();
848   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
849   SDValue Chain = Op.getOperand(0);
850   SDValue Value = Op.getOperand(1);
851   SDValue Ptr = Op.getOperand(2);
852
853   if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
854       Ptr->getOpcode() != AMDGPUISD::DWORDADDR) {
855     // Convert pointer from byte address to dword address.
856     Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
857                       DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
858                                   Ptr, DAG.getConstant(2, MVT::i32)));
859
860     if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
861       assert(!"Truncated and indexed stores not supported yet");
862     } else {
863       Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
864     }
865     return Chain;
866   }
867
868   EVT ValueVT = Value.getValueType();
869
870   if (StoreNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
871     return SDValue();
872   }
873
874   // Lowering for indirect addressing
875
876   const MachineFunction &MF = DAG.getMachineFunction();
877   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
878                                          getTargetMachine().getFrameLowering());
879   unsigned StackWidth = TFL->getStackWidth(MF);
880
881   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
882
883   if (ValueVT.isVector()) {
884     unsigned NumElemVT = ValueVT.getVectorNumElements();
885     EVT ElemVT = ValueVT.getVectorElementType();
886     SDValue Stores[4];
887
888     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
889                                       "vector width in load");
890
891     for (unsigned i = 0; i < NumElemVT; ++i) {
892       unsigned Channel, PtrIncr;
893       getStackAddress(StackWidth, i, Channel, PtrIncr);
894       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
895                         DAG.getConstant(PtrIncr, MVT::i32));
896       SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT,
897                                  Value, DAG.getConstant(i, MVT::i32));
898
899       Stores[i] = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
900                               Chain, Elem, Ptr,
901                               DAG.getTargetConstant(Channel, MVT::i32));
902     }
903      Chain =  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores, NumElemVT);
904    } else {
905     if (ValueVT == MVT::i8) {
906       Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Value);
907     }
908     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other, Chain, Value, Ptr,
909     DAG.getTargetConstant(0, MVT::i32)); // Channel 
910   }
911
912   return Chain;
913 }
914
915 // return (512 + (kc_bank << 12)
916 static int
917 ConstantAddressBlock(unsigned AddressSpace) {
918   switch (AddressSpace) {
919   case AMDGPUAS::CONSTANT_BUFFER_0:
920     return 512;
921   case AMDGPUAS::CONSTANT_BUFFER_1:
922     return 512 + 4096;
923   case AMDGPUAS::CONSTANT_BUFFER_2:
924     return 512 + 4096 * 2;
925   case AMDGPUAS::CONSTANT_BUFFER_3:
926     return 512 + 4096 * 3;
927   case AMDGPUAS::CONSTANT_BUFFER_4:
928     return 512 + 4096 * 4;
929   case AMDGPUAS::CONSTANT_BUFFER_5:
930     return 512 + 4096 * 5;
931   case AMDGPUAS::CONSTANT_BUFFER_6:
932     return 512 + 4096 * 6;
933   case AMDGPUAS::CONSTANT_BUFFER_7:
934     return 512 + 4096 * 7;
935   case AMDGPUAS::CONSTANT_BUFFER_8:
936     return 512 + 4096 * 8;
937   case AMDGPUAS::CONSTANT_BUFFER_9:
938     return 512 + 4096 * 9;
939   case AMDGPUAS::CONSTANT_BUFFER_10:
940     return 512 + 4096 * 10;
941   case AMDGPUAS::CONSTANT_BUFFER_11:
942     return 512 + 4096 * 11;
943   case AMDGPUAS::CONSTANT_BUFFER_12:
944     return 512 + 4096 * 12;
945   case AMDGPUAS::CONSTANT_BUFFER_13:
946     return 512 + 4096 * 13;
947   case AMDGPUAS::CONSTANT_BUFFER_14:
948     return 512 + 4096 * 14;
949   case AMDGPUAS::CONSTANT_BUFFER_15:
950     return 512 + 4096 * 15;
951   default:
952     return -1;
953   }
954 }
955
956 SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
957 {
958   EVT VT = Op.getValueType();
959   DebugLoc DL = Op.getDebugLoc();
960   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
961   SDValue Chain = Op.getOperand(0);
962   SDValue Ptr = Op.getOperand(1);
963   SDValue LoweredLoad;
964
965   int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
966   if (ConstantBlock > -1) {
967     SDValue Result;
968     if (dyn_cast<ConstantExpr>(LoadNode->getSrcValue()) ||
969         dyn_cast<Constant>(LoadNode->getSrcValue())) {
970       SDValue Slots[4];
971       for (unsigned i = 0; i < 4; i++) {
972         // We want Const position encoded with the following formula :
973         // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
974         // const_index is Ptr computed by llvm using an alignment of 16.
975         // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
976         // then div by 4 at the ISel step
977         SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
978             DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
979         Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
980       }
981       Result = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Slots, 4);
982     } else {
983       // non constant ptr cant be folded, keeps it as a v4f32 load
984       Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
985           DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32))
986           );
987     }
988
989     if (!VT.isVector()) {
990       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
991           DAG.getConstant(0, MVT::i32));
992     }
993
994     SDValue MergedValues[2] = {
995         Result,
996         Chain
997     };
998     return DAG.getMergeValues(MergedValues, 2, DL);
999   }
1000
1001   if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
1002     return SDValue();
1003   }
1004
1005   // Lowering for indirect addressing
1006   const MachineFunction &MF = DAG.getMachineFunction();
1007   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
1008                                          getTargetMachine().getFrameLowering());
1009   unsigned StackWidth = TFL->getStackWidth(MF);
1010
1011   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
1012
1013   if (VT.isVector()) {
1014     unsigned NumElemVT = VT.getVectorNumElements();
1015     EVT ElemVT = VT.getVectorElementType();
1016     SDValue Loads[4];
1017
1018     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
1019                                       "vector width in load");
1020
1021     for (unsigned i = 0; i < NumElemVT; ++i) {
1022       unsigned Channel, PtrIncr;
1023       getStackAddress(StackWidth, i, Channel, PtrIncr);
1024       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
1025                         DAG.getConstant(PtrIncr, MVT::i32));
1026       Loads[i] = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, ElemVT,
1027                              Chain, Ptr,
1028                              DAG.getTargetConstant(Channel, MVT::i32),
1029                              Op.getOperand(2));
1030     }
1031     for (unsigned i = NumElemVT; i < 4; ++i) {
1032       Loads[i] = DAG.getUNDEF(ElemVT);
1033     }
1034     EVT TargetVT = EVT::getVectorVT(*DAG.getContext(), ElemVT, 4);
1035     LoweredLoad = DAG.getNode(ISD::BUILD_VECTOR, DL, TargetVT, Loads, 4);
1036   } else {
1037     LoweredLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, VT,
1038                               Chain, Ptr,
1039                               DAG.getTargetConstant(0, MVT::i32), // Channel
1040                               Op.getOperand(2));
1041   }
1042
1043   SDValue Ops[2];
1044   Ops[0] = LoweredLoad;
1045   Ops[1] = Chain;
1046
1047   return DAG.getMergeValues(Ops, 2, DL);
1048 }
1049
1050 SDValue R600TargetLowering::LowerFPOW(SDValue Op,
1051     SelectionDAG &DAG) const {
1052   DebugLoc DL = Op.getDebugLoc();
1053   EVT VT = Op.getValueType();
1054   SDValue LogBase = DAG.getNode(ISD::FLOG2, DL, VT, Op.getOperand(0));
1055   SDValue MulLogBase = DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), LogBase);
1056   return DAG.getNode(ISD::FEXP2, DL, VT, MulLogBase);
1057 }
1058
1059 /// XXX Only kernel functions are supported, so we can assume for now that
1060 /// every function is a kernel function, but in the future we should use
1061 /// separate calling conventions for kernel and non-kernel functions.
1062 SDValue R600TargetLowering::LowerFormalArguments(
1063                                       SDValue Chain,
1064                                       CallingConv::ID CallConv,
1065                                       bool isVarArg,
1066                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1067                                       DebugLoc DL, SelectionDAG &DAG,
1068                                       SmallVectorImpl<SDValue> &InVals) const {
1069   unsigned ParamOffsetBytes = 36;
1070   Function::const_arg_iterator FuncArg =
1071                             DAG.getMachineFunction().getFunction()->arg_begin();
1072   for (unsigned i = 0, e = Ins.size(); i < e; ++i, ++FuncArg) {
1073     EVT VT = Ins[i].VT;
1074     Type *ArgType = FuncArg->getType();
1075     unsigned ArgSizeInBits = ArgType->isPointerTy() ?
1076                              32 : ArgType->getPrimitiveSizeInBits();
1077     unsigned ArgBytes = ArgSizeInBits >> 3;
1078     EVT ArgVT;
1079     if (ArgSizeInBits < VT.getSizeInBits()) {
1080       assert(!ArgType->isFloatTy() &&
1081              "Extending floating point arguments not supported yet");
1082       ArgVT = MVT::getIntegerVT(ArgSizeInBits);
1083     } else {
1084       ArgVT = VT;
1085     }
1086     PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
1087                                                     AMDGPUAS::PARAM_I_ADDRESS);
1088     SDValue Arg = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getRoot(),
1089                                 DAG.getConstant(ParamOffsetBytes, MVT::i32),
1090                                        MachinePointerInfo(new Argument(PtrTy)),
1091                                        ArgVT, false, false, ArgBytes);
1092     InVals.push_back(Arg);
1093     ParamOffsetBytes += ArgBytes;
1094   }
1095   return Chain;
1096 }
1097
1098 EVT R600TargetLowering::getSetCCResultType(EVT VT) const {
1099    if (!VT.isVector()) return MVT::i32;
1100    return VT.changeVectorElementTypeToInteger();
1101 }
1102
1103 //===----------------------------------------------------------------------===//
1104 // Custom DAG Optimizations
1105 //===----------------------------------------------------------------------===//
1106
1107 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
1108                                               DAGCombinerInfo &DCI) const {
1109   SelectionDAG &DAG = DCI.DAG;
1110
1111   switch (N->getOpcode()) {
1112   // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
1113   case ISD::FP_ROUND: {
1114       SDValue Arg = N->getOperand(0);
1115       if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
1116         return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), N->getValueType(0),
1117                            Arg.getOperand(0));
1118       }
1119       break;
1120     }
1121
1122   // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
1123   // (i32 select_cc f32, f32, -1, 0 cc)
1124   //
1125   // Mesa's GLSL frontend generates the above pattern a lot and we can lower
1126   // this to one of the SET*_DX10 instructions.
1127   case ISD::FP_TO_SINT: {
1128     SDValue FNeg = N->getOperand(0);
1129     if (FNeg.getOpcode() != ISD::FNEG) {
1130       return SDValue();
1131     }
1132     SDValue SelectCC = FNeg.getOperand(0);
1133     if (SelectCC.getOpcode() != ISD::SELECT_CC ||
1134         SelectCC.getOperand(0).getValueType() != MVT::f32 || // LHS
1135         SelectCC.getOperand(2).getValueType() != MVT::f32 || // True
1136         !isHWTrueValue(SelectCC.getOperand(2)) ||
1137         !isHWFalseValue(SelectCC.getOperand(3))) {
1138       return SDValue();
1139     }
1140
1141     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N->getValueType(0),
1142                            SelectCC.getOperand(0), // LHS
1143                            SelectCC.getOperand(1), // RHS
1144                            DAG.getConstant(-1, MVT::i32), // True
1145                            DAG.getConstant(0, MVT::i32),  // Flase
1146                            SelectCC.getOperand(4)); // CC
1147
1148     break;
1149   }
1150   // Extract_vec (Build_vector) generated by custom lowering
1151   // also needs to be customly combined
1152   case ISD::EXTRACT_VECTOR_ELT: {
1153     SDValue Arg = N->getOperand(0);
1154     if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
1155       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1156         unsigned Element = Const->getZExtValue();
1157         return Arg->getOperand(Element);
1158       }
1159     }
1160     if (Arg.getOpcode() == ISD::BITCAST &&
1161         Arg.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
1162       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1163         unsigned Element = Const->getZExtValue();
1164         return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getVTList(),
1165             Arg->getOperand(0).getOperand(Element));
1166       }
1167     }
1168   }
1169
1170   case ISD::SELECT_CC: {
1171     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1172     //      selectcc x, y, a, b, inv(cc)
1173     SDValue LHS = N->getOperand(0);
1174     if (LHS.getOpcode() != ISD::SELECT_CC) {
1175       return SDValue();
1176     }
1177
1178     SDValue RHS = N->getOperand(1);
1179     SDValue True = N->getOperand(2);
1180     SDValue False = N->getOperand(3);
1181
1182     if (LHS.getOperand(2).getNode() != True.getNode() ||
1183         LHS.getOperand(3).getNode() != False.getNode() ||
1184         RHS.getNode() != False.getNode() ||
1185         cast<CondCodeSDNode>(N->getOperand(4))->get() != ISD::SETEQ) {
1186       return SDValue();
1187     }
1188
1189     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(LHS->getOperand(4))->get();
1190     CCOpcode = ISD::getSetCCInverse(
1191                         CCOpcode, LHS.getOperand(0).getValueType().isInteger());
1192     return DAG.getSelectCC(N->getDebugLoc(),
1193                            LHS.getOperand(0),
1194                            LHS.getOperand(1),
1195                            LHS.getOperand(2),
1196                            LHS.getOperand(3),
1197                            CCOpcode);
1198
1199   }
1200   }
1201   return SDValue();
1202 }