R600: Fold zero/one in export 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 SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
307   switch (Op.getOpcode()) {
308   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
309   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
310   case ISD::ROTL: return LowerROTL(Op, DAG);
311   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
312   case ISD::SELECT: return LowerSELECT(Op, DAG);
313   case ISD::SETCC: return LowerSETCC(Op, DAG);
314   case ISD::STORE: return LowerSTORE(Op, DAG);
315   case ISD::LOAD: return LowerLOAD(Op, DAG);
316   case ISD::FPOW: return LowerFPOW(Op, DAG);
317   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
318   case ISD::INTRINSIC_VOID: {
319     SDValue Chain = Op.getOperand(0);
320     unsigned IntrinsicID =
321                          cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
322     switch (IntrinsicID) {
323     case AMDGPUIntrinsic::AMDGPU_store_output: {
324       MachineFunction &MF = DAG.getMachineFunction();
325       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
326       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
327       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
328       MFI->LiveOuts.push_back(Reg);
329       return DAG.getCopyToReg(Chain, Op.getDebugLoc(), Reg, Op.getOperand(2));
330     }
331     case AMDGPUIntrinsic::R600_store_swizzle: {
332       const SDValue Args[8] = {
333         Chain,
334         Op.getOperand(2), // Export Value
335         Op.getOperand(3), // ArrayBase
336         Op.getOperand(4), // Type
337         DAG.getConstant(0, MVT::i32), // SWZ_X
338         DAG.getConstant(1, MVT::i32), // SWZ_Y
339         DAG.getConstant(2, MVT::i32), // SWZ_Z
340         DAG.getConstant(3, MVT::i32) // SWZ_W
341       };
342       return DAG.getNode(AMDGPUISD::EXPORT, Op.getDebugLoc(), Op.getValueType(),
343           Args, 8);
344     }
345
346     // default for switch(IntrinsicID)
347     default: break;
348     }
349     // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
350     break;
351   }
352   case ISD::INTRINSIC_WO_CHAIN: {
353     unsigned IntrinsicID =
354                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
355     EVT VT = Op.getValueType();
356     DebugLoc DL = Op.getDebugLoc();
357     switch(IntrinsicID) {
358     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
359     case AMDGPUIntrinsic::R600_load_input: {
360       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
361       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
362       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass, Reg, VT);
363     }
364
365     case AMDGPUIntrinsic::R600_interp_input: {
366       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
367       int ijb = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
368       MachineSDNode *interp;
369       if (ijb < 0) {
370         interp = DAG.getMachineNode(AMDGPU::INTERP_VEC_LOAD, DL,
371             MVT::v4f32, DAG.getTargetConstant(slot / 4 , MVT::i32));
372         return DAG.getTargetExtractSubreg(
373             TII->getRegisterInfo().getSubRegFromChannel(slot % 4),
374             DL, MVT::f32, SDValue(interp, 0));
375       }
376
377       if (slot % 4 < 2)
378         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
379             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
380             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
381                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
382             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
383                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
384       else
385         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
386             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
387             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
388                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
389             CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
390                 AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
391
392       return SDValue(interp, slot % 2);
393     }
394
395     case r600_read_ngroups_x:
396       return LowerImplicitParameter(DAG, VT, DL, 0);
397     case r600_read_ngroups_y:
398       return LowerImplicitParameter(DAG, VT, DL, 1);
399     case r600_read_ngroups_z:
400       return LowerImplicitParameter(DAG, VT, DL, 2);
401     case r600_read_global_size_x:
402       return LowerImplicitParameter(DAG, VT, DL, 3);
403     case r600_read_global_size_y:
404       return LowerImplicitParameter(DAG, VT, DL, 4);
405     case r600_read_global_size_z:
406       return LowerImplicitParameter(DAG, VT, DL, 5);
407     case r600_read_local_size_x:
408       return LowerImplicitParameter(DAG, VT, DL, 6);
409     case r600_read_local_size_y:
410       return LowerImplicitParameter(DAG, VT, DL, 7);
411     case r600_read_local_size_z:
412       return LowerImplicitParameter(DAG, VT, DL, 8);
413
414     case r600_read_tgid_x:
415       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
416                                   AMDGPU::T1_X, VT);
417     case r600_read_tgid_y:
418       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
419                                   AMDGPU::T1_Y, VT);
420     case r600_read_tgid_z:
421       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
422                                   AMDGPU::T1_Z, VT);
423     case r600_read_tidig_x:
424       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
425                                   AMDGPU::T0_X, VT);
426     case r600_read_tidig_y:
427       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
428                                   AMDGPU::T0_Y, VT);
429     case r600_read_tidig_z:
430       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
431                                   AMDGPU::T0_Z, VT);
432     }
433     // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
434     break;
435   }
436   } // end switch(Op.getOpcode())
437   return SDValue();
438 }
439
440 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
441                                             SmallVectorImpl<SDValue> &Results,
442                                             SelectionDAG &DAG) const {
443   switch (N->getOpcode()) {
444   default: return;
445   case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
446     return;
447   case ISD::LOAD: {
448     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
449     Results.push_back(SDValue(Node, 0));
450     Results.push_back(SDValue(Node, 1));
451     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
452     // function
453     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
454     return;
455   }
456   case ISD::STORE:
457     SDNode *Node = LowerSTORE(SDValue(N, 0), DAG).getNode();
458     Results.push_back(SDValue(Node, 0));
459     return;
460   }
461 }
462
463 SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
464   return DAG.getNode(
465       ISD::SETCC,
466       Op.getDebugLoc(),
467       MVT::i1,
468       Op, DAG.getConstantFP(0.0f, MVT::f32),
469       DAG.getCondCode(ISD::SETNE)
470       );
471 }
472
473 SDValue R600TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
474   SDValue Chain = Op.getOperand(0);
475   SDValue CC = Op.getOperand(1);
476   SDValue LHS   = Op.getOperand(2);
477   SDValue RHS   = Op.getOperand(3);
478   SDValue JumpT  = Op.getOperand(4);
479   SDValue CmpValue;
480   SDValue Result;
481
482   if (LHS.getValueType() == MVT::i32) {
483     CmpValue = DAG.getNode(
484         ISD::SELECT_CC,
485         Op.getDebugLoc(),
486         MVT::i32,
487         LHS, RHS,
488         DAG.getConstant(-1, MVT::i32),
489         DAG.getConstant(0, MVT::i32),
490         CC);
491   } else if (LHS.getValueType() == MVT::f32) {
492     CmpValue = DAG.getNode(
493         ISD::SELECT_CC,
494         Op.getDebugLoc(),
495         MVT::f32,
496         LHS, RHS,
497         DAG.getConstantFP(1.0f, MVT::f32),
498         DAG.getConstantFP(0.0f, MVT::f32),
499         CC);
500   } else {
501     assert(0 && "Not valid type for br_cc");
502   }
503   Result = DAG.getNode(
504       AMDGPUISD::BRANCH_COND,
505       CmpValue.getDebugLoc(),
506       MVT::Other, Chain,
507       JumpT, CmpValue);
508   return Result;
509 }
510
511 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
512                                                    DebugLoc DL,
513                                                    unsigned DwordOffset) const {
514   unsigned ByteOffset = DwordOffset * 4;
515   PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
516                                       AMDGPUAS::PARAM_I_ADDRESS);
517
518   // We shouldn't be using an offset wider than 16-bits for implicit parameters.
519   assert(isInt<16>(ByteOffset));
520
521   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
522                      DAG.getConstant(ByteOffset, MVT::i32), // PTR
523                      MachinePointerInfo(ConstantPointerNull::get(PtrType)),
524                      false, false, false, 0);
525 }
526
527 SDValue R600TargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
528
529   MachineFunction &MF = DAG.getMachineFunction();
530   const AMDGPUFrameLowering *TFL =
531    static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());
532
533   FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
534   assert(FIN);
535
536   unsigned FrameIndex = FIN->getIndex();
537   unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
538   return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF), MVT::i32);
539 }
540
541 SDValue R600TargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
542   DebugLoc DL = Op.getDebugLoc();
543   EVT VT = Op.getValueType();
544
545   return DAG.getNode(AMDGPUISD::BITALIGN, DL, VT,
546                      Op.getOperand(0),
547                      Op.getOperand(0),
548                      DAG.getNode(ISD::SUB, DL, VT,
549                                  DAG.getConstant(32, MVT::i32),
550                                  Op.getOperand(1)));
551 }
552
553 bool R600TargetLowering::isZero(SDValue Op) const {
554   if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
555     return Cst->isNullValue();
556   } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
557     return CstFP->isZero();
558   } else {
559     return false;
560   }
561 }
562
563 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
564   DebugLoc DL = Op.getDebugLoc();
565   EVT VT = Op.getValueType();
566
567   SDValue LHS = Op.getOperand(0);
568   SDValue RHS = Op.getOperand(1);
569   SDValue True = Op.getOperand(2);
570   SDValue False = Op.getOperand(3);
571   SDValue CC = Op.getOperand(4);
572   SDValue Temp;
573
574   // LHS and RHS are guaranteed to be the same value type
575   EVT CompareVT = LHS.getValueType();
576
577   // Check if we can lower this to a native operation.
578
579   // Try to lower to a CND* instruction:
580   // CND* instructions requires RHS to be zero.  Some SELECT_CC nodes that
581   // can be lowered to CND* instructions can also be lowered to SET*
582   // instructions.  CND* instructions are cheaper, because they dont't
583   // require additional instructions to convert their result to the correct
584   // value type, so this check should be first.
585   if (isZero(LHS) || isZero(RHS)) {
586     SDValue Cond = (isZero(LHS) ? RHS : LHS);
587     SDValue Zero = (isZero(LHS) ? LHS : RHS);
588     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
589     if (CompareVT != VT) {
590       // Bitcast True / False to the correct types.  This will end up being
591       // a nop, but it allows us to define only a single pattern in the
592       // .TD files for each CND* instruction rather than having to have
593       // one pattern for integer True/False and one for fp True/False
594       True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
595       False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
596     }
597     if (isZero(LHS)) {
598       CCOpcode = ISD::getSetCCSwappedOperands(CCOpcode);
599     }
600
601     switch (CCOpcode) {
602     case ISD::SETONE:
603     case ISD::SETUNE:
604     case ISD::SETNE:
605     case ISD::SETULE:
606     case ISD::SETULT:
607     case ISD::SETOLE:
608     case ISD::SETOLT:
609     case ISD::SETLE:
610     case ISD::SETLT:
611       CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
612       Temp = True;
613       True = False;
614       False = Temp;
615       break;
616     default:
617       break;
618     }
619     SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
620         Cond, Zero,
621         True, False,
622         DAG.getCondCode(CCOpcode));
623     return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
624   }
625
626   // Try to lower to a SET* instruction:
627   //
628   // CompareVT == MVT::f32 and VT == MVT::i32 is supported by the hardware,
629   // but for the other case where CompareVT != VT, all operands of
630   // SELECT_CC need to have the same value type, so we need to change True and
631   // False to be the same type as LHS and RHS, and then convert the result of
632   // the select_cc back to the correct type.
633
634   // Move hardware True/False values to the correct operand.
635   if (isHWTrueValue(False) && isHWFalseValue(True)) {
636     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
637     std::swap(False, True);
638     CC = DAG.getCondCode(ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32));
639   }
640
641   if (isHWTrueValue(True) && isHWFalseValue(False)) {
642     if (CompareVT !=  VT && VT == MVT::f32 && CompareVT == MVT::i32) {
643       SDValue Boolean = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
644           LHS, RHS,
645           DAG.getConstant(-1, MVT::i32),
646           DAG.getConstant(0, MVT::i32),
647           CC);
648       // Convert integer values of true (-1) and false (0) to fp values of
649       // true (1.0f) and false (0.0f).
650       SDValue LSB = DAG.getNode(ISD::AND, DL, MVT::i32, Boolean,
651                                                 DAG.getConstant(1, MVT::i32));
652       return DAG.getNode(ISD::UINT_TO_FP, DL, VT, LSB);
653     } else {
654       // This SELECT_CC is already legal.
655       return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
656     }
657   }
658
659   // Possible Min/Max pattern
660   SDValue MinMax = LowerMinMax(Op, DAG);
661   if (MinMax.getNode()) {
662     return MinMax;
663   }
664
665   // If we make it this for it means we have no native instructions to handle
666   // this SELECT_CC, so we must lower it.
667   SDValue HWTrue, HWFalse;
668
669   if (CompareVT == MVT::f32) {
670     HWTrue = DAG.getConstantFP(1.0f, CompareVT);
671     HWFalse = DAG.getConstantFP(0.0f, CompareVT);
672   } else if (CompareVT == MVT::i32) {
673     HWTrue = DAG.getConstant(-1, CompareVT);
674     HWFalse = DAG.getConstant(0, CompareVT);
675   }
676   else {
677     assert(!"Unhandled value type in LowerSELECT_CC");
678   }
679
680   // Lower this unsupported SELECT_CC into a combination of two supported
681   // SELECT_CC operations.
682   SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);
683
684   return DAG.getNode(ISD::SELECT_CC, DL, VT,
685       Cond, HWFalse,
686       True, False,
687       DAG.getCondCode(ISD::SETNE));
688 }
689
690 SDValue R600TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
691   return DAG.getNode(ISD::SELECT_CC,
692       Op.getDebugLoc(),
693       Op.getValueType(),
694       Op.getOperand(0),
695       DAG.getConstant(0, MVT::i32),
696       Op.getOperand(1),
697       Op.getOperand(2),
698       DAG.getCondCode(ISD::SETNE));
699 }
700
701 SDValue R600TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
702   SDValue Cond;
703   SDValue LHS = Op.getOperand(0);
704   SDValue RHS = Op.getOperand(1);
705   SDValue CC  = Op.getOperand(2);
706   DebugLoc DL = Op.getDebugLoc();
707   assert(Op.getValueType() == MVT::i32);
708   if (LHS.getValueType() == MVT::i32) {
709     Cond = DAG.getNode(
710         ISD::SELECT_CC,
711         Op.getDebugLoc(),
712         MVT::i32,
713         LHS, RHS,
714         DAG.getConstant(-1, MVT::i32),
715         DAG.getConstant(0, MVT::i32),
716         CC);
717   } else if (LHS.getValueType() == MVT::f32) {
718     Cond = DAG.getNode(
719         ISD::SELECT_CC,
720         Op.getDebugLoc(),
721         MVT::f32,
722         LHS, RHS,
723         DAG.getConstantFP(1.0f, MVT::f32),
724         DAG.getConstantFP(0.0f, MVT::f32),
725         CC);
726     Cond = DAG.getNode(
727         ISD::FP_TO_SINT,
728         DL,
729         MVT::i32,
730         Cond);
731   } else {
732     assert(0 && "Not valid type for set_cc");
733   }
734   Cond = DAG.getNode(
735       ISD::AND,
736       DL,
737       MVT::i32,
738       DAG.getConstant(1, MVT::i32),
739       Cond);
740   return Cond;
741 }
742
743 /// LLVM generates byte-addresed pointers.  For indirect addressing, we need to
744 /// convert these pointers to a register index.  Each register holds
745 /// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
746 /// \p StackWidth, which tells us how many of the 4 sub-registrers will be used
747 /// for indirect addressing.
748 SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
749                                                unsigned StackWidth,
750                                                SelectionDAG &DAG) const {
751   unsigned SRLPad;
752   switch(StackWidth) {
753   case 1:
754     SRLPad = 2;
755     break;
756   case 2:
757     SRLPad = 3;
758     break;
759   case 4:
760     SRLPad = 4;
761     break;
762   default: llvm_unreachable("Invalid stack width");
763   }
764
765   return DAG.getNode(ISD::SRL, Ptr.getDebugLoc(), Ptr.getValueType(), Ptr,
766                      DAG.getConstant(SRLPad, MVT::i32));
767 }
768
769 void R600TargetLowering::getStackAddress(unsigned StackWidth,
770                                          unsigned ElemIdx,
771                                          unsigned &Channel,
772                                          unsigned &PtrIncr) const {
773   switch (StackWidth) {
774   default:
775   case 1:
776     Channel = 0;
777     if (ElemIdx > 0) {
778       PtrIncr = 1;
779     } else {
780       PtrIncr = 0;
781     }
782     break;
783   case 2:
784     Channel = ElemIdx % 2;
785     if (ElemIdx == 2) {
786       PtrIncr = 1;
787     } else {
788       PtrIncr = 0;
789     }
790     break;
791   case 4:
792     Channel = ElemIdx;
793     PtrIncr = 0;
794     break;
795   }
796 }
797
798 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
799   DebugLoc DL = Op.getDebugLoc();
800   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
801   SDValue Chain = Op.getOperand(0);
802   SDValue Value = Op.getOperand(1);
803   SDValue Ptr = Op.getOperand(2);
804
805   if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
806       Ptr->getOpcode() != AMDGPUISD::DWORDADDR) {
807     // Convert pointer from byte address to dword address.
808     Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
809                       DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
810                                   Ptr, DAG.getConstant(2, MVT::i32)));
811
812     if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
813       assert(!"Truncated and indexed stores not supported yet");
814     } else {
815       Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
816     }
817     return Chain;
818   }
819
820   EVT ValueVT = Value.getValueType();
821
822   if (StoreNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
823     return SDValue();
824   }
825
826   // Lowering for indirect addressing
827
828   const MachineFunction &MF = DAG.getMachineFunction();
829   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
830                                          getTargetMachine().getFrameLowering());
831   unsigned StackWidth = TFL->getStackWidth(MF);
832
833   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
834
835   if (ValueVT.isVector()) {
836     unsigned NumElemVT = ValueVT.getVectorNumElements();
837     EVT ElemVT = ValueVT.getVectorElementType();
838     SDValue Stores[4];
839
840     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
841                                       "vector width in load");
842
843     for (unsigned i = 0; i < NumElemVT; ++i) {
844       unsigned Channel, PtrIncr;
845       getStackAddress(StackWidth, i, Channel, PtrIncr);
846       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
847                         DAG.getConstant(PtrIncr, MVT::i32));
848       SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT,
849                                  Value, DAG.getConstant(i, MVT::i32));
850
851       Stores[i] = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
852                               Chain, Elem, Ptr,
853                               DAG.getTargetConstant(Channel, MVT::i32));
854     }
855      Chain =  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores, NumElemVT);
856    } else {
857     if (ValueVT == MVT::i8) {
858       Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Value);
859     }
860     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other, Chain, Value, Ptr,
861     DAG.getTargetConstant(0, MVT::i32)); // Channel 
862   }
863
864   return Chain;
865 }
866
867 // return (512 + (kc_bank << 12)
868 static int
869 ConstantAddressBlock(unsigned AddressSpace) {
870   switch (AddressSpace) {
871   case AMDGPUAS::CONSTANT_BUFFER_0:
872     return 512;
873   case AMDGPUAS::CONSTANT_BUFFER_1:
874     return 512 + 4096;
875   case AMDGPUAS::CONSTANT_BUFFER_2:
876     return 512 + 4096 * 2;
877   case AMDGPUAS::CONSTANT_BUFFER_3:
878     return 512 + 4096 * 3;
879   case AMDGPUAS::CONSTANT_BUFFER_4:
880     return 512 + 4096 * 4;
881   case AMDGPUAS::CONSTANT_BUFFER_5:
882     return 512 + 4096 * 5;
883   case AMDGPUAS::CONSTANT_BUFFER_6:
884     return 512 + 4096 * 6;
885   case AMDGPUAS::CONSTANT_BUFFER_7:
886     return 512 + 4096 * 7;
887   case AMDGPUAS::CONSTANT_BUFFER_8:
888     return 512 + 4096 * 8;
889   case AMDGPUAS::CONSTANT_BUFFER_9:
890     return 512 + 4096 * 9;
891   case AMDGPUAS::CONSTANT_BUFFER_10:
892     return 512 + 4096 * 10;
893   case AMDGPUAS::CONSTANT_BUFFER_11:
894     return 512 + 4096 * 11;
895   case AMDGPUAS::CONSTANT_BUFFER_12:
896     return 512 + 4096 * 12;
897   case AMDGPUAS::CONSTANT_BUFFER_13:
898     return 512 + 4096 * 13;
899   case AMDGPUAS::CONSTANT_BUFFER_14:
900     return 512 + 4096 * 14;
901   case AMDGPUAS::CONSTANT_BUFFER_15:
902     return 512 + 4096 * 15;
903   default:
904     return -1;
905   }
906 }
907
908 SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
909 {
910   EVT VT = Op.getValueType();
911   DebugLoc DL = Op.getDebugLoc();
912   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
913   SDValue Chain = Op.getOperand(0);
914   SDValue Ptr = Op.getOperand(1);
915   SDValue LoweredLoad;
916
917   int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
918   if (ConstantBlock > -1) {
919     SDValue Result;
920     if (dyn_cast<ConstantExpr>(LoadNode->getSrcValue()) ||
921         dyn_cast<Constant>(LoadNode->getSrcValue())) {
922       SDValue Slots[4];
923       for (unsigned i = 0; i < 4; i++) {
924         // We want Const position encoded with the following formula :
925         // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
926         // const_index is Ptr computed by llvm using an alignment of 16.
927         // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
928         // then div by 4 at the ISel step
929         SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
930             DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
931         Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
932       }
933       Result = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Slots, 4);
934     } else {
935       // non constant ptr cant be folded, keeps it as a v4f32 load
936       Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
937           DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32))
938           );
939     }
940
941     if (!VT.isVector()) {
942       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
943           DAG.getConstant(0, MVT::i32));
944     }
945
946     SDValue MergedValues[2] = {
947         Result,
948         Chain
949     };
950     return DAG.getMergeValues(MergedValues, 2, DL);
951   }
952
953   if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
954     return SDValue();
955   }
956
957   // Lowering for indirect addressing
958   const MachineFunction &MF = DAG.getMachineFunction();
959   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
960                                          getTargetMachine().getFrameLowering());
961   unsigned StackWidth = TFL->getStackWidth(MF);
962
963   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
964
965   if (VT.isVector()) {
966     unsigned NumElemVT = VT.getVectorNumElements();
967     EVT ElemVT = VT.getVectorElementType();
968     SDValue Loads[4];
969
970     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
971                                       "vector width in load");
972
973     for (unsigned i = 0; i < NumElemVT; ++i) {
974       unsigned Channel, PtrIncr;
975       getStackAddress(StackWidth, i, Channel, PtrIncr);
976       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
977                         DAG.getConstant(PtrIncr, MVT::i32));
978       Loads[i] = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, ElemVT,
979                              Chain, Ptr,
980                              DAG.getTargetConstant(Channel, MVT::i32),
981                              Op.getOperand(2));
982     }
983     for (unsigned i = NumElemVT; i < 4; ++i) {
984       Loads[i] = DAG.getUNDEF(ElemVT);
985     }
986     EVT TargetVT = EVT::getVectorVT(*DAG.getContext(), ElemVT, 4);
987     LoweredLoad = DAG.getNode(ISD::BUILD_VECTOR, DL, TargetVT, Loads, 4);
988   } else {
989     LoweredLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, VT,
990                               Chain, Ptr,
991                               DAG.getTargetConstant(0, MVT::i32), // Channel
992                               Op.getOperand(2));
993   }
994
995   SDValue Ops[2];
996   Ops[0] = LoweredLoad;
997   Ops[1] = Chain;
998
999   return DAG.getMergeValues(Ops, 2, DL);
1000 }
1001
1002 SDValue R600TargetLowering::LowerFPOW(SDValue Op,
1003     SelectionDAG &DAG) const {
1004   DebugLoc DL = Op.getDebugLoc();
1005   EVT VT = Op.getValueType();
1006   SDValue LogBase = DAG.getNode(ISD::FLOG2, DL, VT, Op.getOperand(0));
1007   SDValue MulLogBase = DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), LogBase);
1008   return DAG.getNode(ISD::FEXP2, DL, VT, MulLogBase);
1009 }
1010
1011 /// XXX Only kernel functions are supported, so we can assume for now that
1012 /// every function is a kernel function, but in the future we should use
1013 /// separate calling conventions for kernel and non-kernel functions.
1014 SDValue R600TargetLowering::LowerFormalArguments(
1015                                       SDValue Chain,
1016                                       CallingConv::ID CallConv,
1017                                       bool isVarArg,
1018                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1019                                       DebugLoc DL, SelectionDAG &DAG,
1020                                       SmallVectorImpl<SDValue> &InVals) const {
1021   unsigned ParamOffsetBytes = 36;
1022   Function::const_arg_iterator FuncArg =
1023                             DAG.getMachineFunction().getFunction()->arg_begin();
1024   for (unsigned i = 0, e = Ins.size(); i < e; ++i, ++FuncArg) {
1025     EVT VT = Ins[i].VT;
1026     Type *ArgType = FuncArg->getType();
1027     unsigned ArgSizeInBits = ArgType->isPointerTy() ?
1028                              32 : ArgType->getPrimitiveSizeInBits();
1029     unsigned ArgBytes = ArgSizeInBits >> 3;
1030     EVT ArgVT;
1031     if (ArgSizeInBits < VT.getSizeInBits()) {
1032       assert(!ArgType->isFloatTy() &&
1033              "Extending floating point arguments not supported yet");
1034       ArgVT = MVT::getIntegerVT(ArgSizeInBits);
1035     } else {
1036       ArgVT = VT;
1037     }
1038     PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
1039                                                     AMDGPUAS::PARAM_I_ADDRESS);
1040     SDValue Arg = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getRoot(),
1041                                 DAG.getConstant(ParamOffsetBytes, MVT::i32),
1042                                        MachinePointerInfo(new Argument(PtrTy)),
1043                                        ArgVT, false, false, ArgBytes);
1044     InVals.push_back(Arg);
1045     ParamOffsetBytes += ArgBytes;
1046   }
1047   return Chain;
1048 }
1049
1050 EVT R600TargetLowering::getSetCCResultType(EVT VT) const {
1051    if (!VT.isVector()) return MVT::i32;
1052    return VT.changeVectorElementTypeToInteger();
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 // Custom DAG Optimizations
1057 //===----------------------------------------------------------------------===//
1058
1059 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
1060                                               DAGCombinerInfo &DCI) const {
1061   SelectionDAG &DAG = DCI.DAG;
1062
1063   switch (N->getOpcode()) {
1064   // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
1065   case ISD::FP_ROUND: {
1066       SDValue Arg = N->getOperand(0);
1067       if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
1068         return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), N->getValueType(0),
1069                            Arg.getOperand(0));
1070       }
1071       break;
1072     }
1073
1074   // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
1075   // (i32 select_cc f32, f32, -1, 0 cc)
1076   //
1077   // Mesa's GLSL frontend generates the above pattern a lot and we can lower
1078   // this to one of the SET*_DX10 instructions.
1079   case ISD::FP_TO_SINT: {
1080     SDValue FNeg = N->getOperand(0);
1081     if (FNeg.getOpcode() != ISD::FNEG) {
1082       return SDValue();
1083     }
1084     SDValue SelectCC = FNeg.getOperand(0);
1085     if (SelectCC.getOpcode() != ISD::SELECT_CC ||
1086         SelectCC.getOperand(0).getValueType() != MVT::f32 || // LHS
1087         SelectCC.getOperand(2).getValueType() != MVT::f32 || // True
1088         !isHWTrueValue(SelectCC.getOperand(2)) ||
1089         !isHWFalseValue(SelectCC.getOperand(3))) {
1090       return SDValue();
1091     }
1092
1093     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N->getValueType(0),
1094                            SelectCC.getOperand(0), // LHS
1095                            SelectCC.getOperand(1), // RHS
1096                            DAG.getConstant(-1, MVT::i32), // True
1097                            DAG.getConstant(0, MVT::i32),  // Flase
1098                            SelectCC.getOperand(4)); // CC
1099
1100     break;
1101   }
1102   // Extract_vec (Build_vector) generated by custom lowering
1103   // also needs to be customly combined
1104   case ISD::EXTRACT_VECTOR_ELT: {
1105     SDValue Arg = N->getOperand(0);
1106     if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
1107       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1108         unsigned Element = Const->getZExtValue();
1109         return Arg->getOperand(Element);
1110       }
1111     }
1112     if (Arg.getOpcode() == ISD::BITCAST &&
1113         Arg.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
1114       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1115         unsigned Element = Const->getZExtValue();
1116         return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getVTList(),
1117             Arg->getOperand(0).getOperand(Element));
1118       }
1119     }
1120   }
1121
1122   case ISD::SELECT_CC: {
1123     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1124     //      selectcc x, y, a, b, inv(cc)
1125     SDValue LHS = N->getOperand(0);
1126     if (LHS.getOpcode() != ISD::SELECT_CC) {
1127       return SDValue();
1128     }
1129
1130     SDValue RHS = N->getOperand(1);
1131     SDValue True = N->getOperand(2);
1132     SDValue False = N->getOperand(3);
1133
1134     if (LHS.getOperand(2).getNode() != True.getNode() ||
1135         LHS.getOperand(3).getNode() != False.getNode() ||
1136         RHS.getNode() != False.getNode() ||
1137         cast<CondCodeSDNode>(N->getOperand(4))->get() != ISD::SETEQ) {
1138       return SDValue();
1139     }
1140
1141     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(LHS->getOperand(4))->get();
1142     CCOpcode = ISD::getSetCCInverse(
1143                         CCOpcode, LHS.getOperand(0).getValueType().isInteger());
1144     return DAG.getSelectCC(N->getDebugLoc(),
1145                            LHS.getOperand(0),
1146                            LHS.getOperand(1),
1147                            LHS.getOperand(2),
1148                            LHS.getOperand(3),
1149                            CCOpcode);
1150     }
1151   case AMDGPUISD::EXPORT: {
1152     SDValue Arg = N->getOperand(1);
1153     if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1154       break;
1155     SDValue NewBldVec[4] = {
1156         DAG.getUNDEF(MVT::f32),
1157         DAG.getUNDEF(MVT::f32),
1158         DAG.getUNDEF(MVT::f32),
1159         DAG.getUNDEF(MVT::f32)
1160       };
1161     SDValue NewArgs[8] = {
1162       N->getOperand(0), // Chain
1163       SDValue(),
1164       N->getOperand(2), // ArrayBase
1165       N->getOperand(3), // Type
1166       N->getOperand(4), // SWZ_X
1167       N->getOperand(5), // SWZ_Y
1168       N->getOperand(6), // SWZ_Z
1169       N->getOperand(7) // SWZ_W
1170     };
1171     for (unsigned i = 0; i < Arg.getNumOperands(); i++) {
1172       if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Arg.getOperand(i))) {
1173         if (C->isZero()) {
1174           NewArgs[4 + i] = DAG.getConstant(4, MVT::i32); // SEL_0
1175         } else if (C->isExactlyValue(1.0)) {
1176           NewArgs[4 + i] = DAG.getConstant(5, MVT::i32); // SEL_0
1177         } else {
1178           NewBldVec[i] = Arg.getOperand(i);
1179         }
1180       } else {
1181         NewBldVec[i] = Arg.getOperand(i);
1182       }
1183     }
1184     DebugLoc DL = N->getDebugLoc();
1185     NewArgs[1] = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4f32, NewBldVec, 4);
1186     return DAG.getNode(AMDGPUISD::EXPORT, DL, N->getVTList(), NewArgs, 8);
1187   }
1188   }
1189   return SDValue();
1190 }