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