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