R600/SI: Add support for private address space load/store
[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   addRegisterClass(MVT::v2f32, &AMDGPU::R600_Reg64RegClass);
37   addRegisterClass(MVT::v2i32, &AMDGPU::R600_Reg64RegClass);
38
39   computeRegisterProperties();
40
41   // Set condition code actions
42   setCondCodeAction(ISD::SETO,   MVT::f32, Expand);
43   setCondCodeAction(ISD::SETUO,  MVT::f32, Expand);
44   setCondCodeAction(ISD::SETLT,  MVT::f32, Expand);
45   setCondCodeAction(ISD::SETLE,  MVT::f32, Expand);
46   setCondCodeAction(ISD::SETOLT, MVT::f32, Expand);
47   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
48   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
49   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
50   setCondCodeAction(ISD::SETUGE, MVT::f32, Expand);
51   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
52   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
53   setCondCodeAction(ISD::SETULE, MVT::f32, Expand);
54
55   setCondCodeAction(ISD::SETLE, MVT::i32, Expand);
56   setCondCodeAction(ISD::SETLT, MVT::i32, Expand);
57   setCondCodeAction(ISD::SETULE, MVT::i32, Expand);
58   setCondCodeAction(ISD::SETULT, MVT::i32, Expand);
59
60   setOperationAction(ISD::FCOS, MVT::f32, Custom);
61   setOperationAction(ISD::FSIN, MVT::f32, Custom);
62
63   setOperationAction(ISD::SETCC, MVT::v4i32, Expand);
64   setOperationAction(ISD::SETCC, 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, Expand);
83   setOperationAction(ISD::SELECT, MVT::f32, Expand);
84   setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
85   setOperationAction(ISD::SELECT, MVT::v2f32, Expand);
86   setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
87   setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
88
89   // Legalize loads and stores to the private address space.
90   setOperationAction(ISD::LOAD, MVT::i32, Custom);
91   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
92   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
93
94   // EXTLOAD should be the same as ZEXTLOAD. It is legal for some address
95   // spaces, so it is custom lowered to handle those where it isn't.
96   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Custom);
97   setLoadExtAction(ISD::SEXTLOAD, MVT::i16, Custom);
98   setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
99   setLoadExtAction(ISD::ZEXTLOAD, MVT::i16, Custom);
100   setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
101   setLoadExtAction(ISD::EXTLOAD, MVT::i16, Custom);
102
103   setOperationAction(ISD::STORE, MVT::i8, Custom);
104   setOperationAction(ISD::STORE, MVT::i32, Custom);
105   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
106   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
107   setTruncStoreAction(MVT::i32, MVT::i8, Custom);
108   setTruncStoreAction(MVT::i32, MVT::i16, Custom);
109
110   setOperationAction(ISD::LOAD, MVT::i32, Custom);
111   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
112   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
113
114   setTargetDAGCombine(ISD::FP_ROUND);
115   setTargetDAGCombine(ISD::FP_TO_SINT);
116   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
117   setTargetDAGCombine(ISD::SELECT_CC);
118   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
119
120   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
121
122   setBooleanContents(ZeroOrNegativeOneBooleanContent);
123   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
124   setSchedulingPreference(Sched::Source);
125 }
126
127 MachineBasicBlock * R600TargetLowering::EmitInstrWithCustomInserter(
128     MachineInstr * MI, MachineBasicBlock * BB) const {
129   MachineFunction * MF = BB->getParent();
130   MachineRegisterInfo &MRI = MF->getRegInfo();
131   MachineBasicBlock::iterator I = *MI;
132   const R600InstrInfo *TII =
133     static_cast<const R600InstrInfo*>(MF->getTarget().getInstrInfo());
134
135   switch (MI->getOpcode()) {
136   default:
137     if (TII->isLDSInstr(MI->getOpcode()) &&
138         TII->getOperandIdx(MI->getOpcode(), AMDGPU::OpName::dst) != -1) {
139       int DstIdx = TII->getOperandIdx(MI->getOpcode(), AMDGPU::OpName::dst);
140       assert(DstIdx != -1);
141       MachineInstrBuilder NewMI;
142       if (!MRI.use_empty(MI->getOperand(DstIdx).getReg())) {
143         NewMI = BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()),
144                         AMDGPU::OQAP);
145         TII->buildDefaultInstruction(*BB, I, AMDGPU::MOV,
146                                      MI->getOperand(0).getReg(),
147                                      AMDGPU::OQAP);
148       } else {
149         NewMI = BuildMI(*BB, I, BB->findDebugLoc(I),
150                         TII->get(AMDGPU::getLDSNoRetOp(MI->getOpcode())));
151       }
152       for (unsigned i = 1, e = MI->getNumOperands(); i < e; ++i) {
153         NewMI.addOperand(MI->getOperand(i));
154       }
155     } else {
156       return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
157     }
158     break;
159   case AMDGPU::CLAMP_R600: {
160     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
161                                                    AMDGPU::MOV,
162                                                    MI->getOperand(0).getReg(),
163                                                    MI->getOperand(1).getReg());
164     TII->addFlag(NewMI, 0, MO_FLAG_CLAMP);
165     break;
166   }
167
168   case AMDGPU::FABS_R600: {
169     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
170                                                     AMDGPU::MOV,
171                                                     MI->getOperand(0).getReg(),
172                                                     MI->getOperand(1).getReg());
173     TII->addFlag(NewMI, 0, MO_FLAG_ABS);
174     break;
175   }
176
177   case AMDGPU::FNEG_R600: {
178     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
179                                                     AMDGPU::MOV,
180                                                     MI->getOperand(0).getReg(),
181                                                     MI->getOperand(1).getReg());
182     TII->addFlag(NewMI, 0, MO_FLAG_NEG);
183     break;
184   }
185
186   case AMDGPU::MASK_WRITE: {
187     unsigned maskedRegister = MI->getOperand(0).getReg();
188     assert(TargetRegisterInfo::isVirtualRegister(maskedRegister));
189     MachineInstr * defInstr = MRI.getVRegDef(maskedRegister);
190     TII->addFlag(defInstr, 0, MO_FLAG_MASK);
191     break;
192   }
193
194   case AMDGPU::MOV_IMM_F32:
195     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
196                      MI->getOperand(1).getFPImm()->getValueAPF()
197                          .bitcastToAPInt().getZExtValue());
198     break;
199   case AMDGPU::MOV_IMM_I32:
200     TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
201                      MI->getOperand(1).getImm());
202     break;
203   case AMDGPU::CONST_COPY: {
204     MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, MI, AMDGPU::MOV,
205         MI->getOperand(0).getReg(), AMDGPU::ALU_CONST);
206     TII->setImmOperand(NewMI, AMDGPU::OpName::src0_sel,
207         MI->getOperand(1).getImm());
208     break;
209   }
210
211   case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
212   case AMDGPU::RAT_WRITE_CACHELESS_64_eg:
213   case AMDGPU::RAT_WRITE_CACHELESS_128_eg: {
214     unsigned EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;
215
216     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
217             .addOperand(MI->getOperand(0))
218             .addOperand(MI->getOperand(1))
219             .addImm(EOP); // Set End of program bit
220     break;
221   }
222
223   case AMDGPU::TXD: {
224     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
225     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
226     MachineOperand &RID = MI->getOperand(4);
227     MachineOperand &SID = MI->getOperand(5);
228     unsigned TextureId = MI->getOperand(6).getImm();
229     unsigned SrcX = 0, SrcY = 1, SrcZ = 2, SrcW = 3;
230     unsigned CTX = 1, CTY = 1, CTZ = 1, CTW = 1;
231
232     switch (TextureId) {
233     case 5: // Rect
234       CTX = CTY = 0;
235       break;
236     case 6: // Shadow1D
237       SrcW = SrcZ;
238       break;
239     case 7: // Shadow2D
240       SrcW = SrcZ;
241       break;
242     case 8: // ShadowRect
243       CTX = CTY = 0;
244       SrcW = SrcZ;
245       break;
246     case 9: // 1DArray
247       SrcZ = SrcY;
248       CTZ = 0;
249       break;
250     case 10: // 2DArray
251       CTZ = 0;
252       break;
253     case 11: // Shadow1DArray
254       SrcZ = SrcY;
255       CTZ = 0;
256       break;
257     case 12: // Shadow2DArray
258       CTZ = 0;
259       break;
260     }
261     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
262             .addOperand(MI->getOperand(3))
263             .addImm(SrcX)
264             .addImm(SrcY)
265             .addImm(SrcZ)
266             .addImm(SrcW)
267             .addImm(0)
268             .addImm(0)
269             .addImm(0)
270             .addImm(0)
271             .addImm(1)
272             .addImm(2)
273             .addImm(3)
274             .addOperand(RID)
275             .addOperand(SID)
276             .addImm(CTX)
277             .addImm(CTY)
278             .addImm(CTZ)
279             .addImm(CTW);
280     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
281             .addOperand(MI->getOperand(2))
282             .addImm(SrcX)
283             .addImm(SrcY)
284             .addImm(SrcZ)
285             .addImm(SrcW)
286             .addImm(0)
287             .addImm(0)
288             .addImm(0)
289             .addImm(0)
290             .addImm(1)
291             .addImm(2)
292             .addImm(3)
293             .addOperand(RID)
294             .addOperand(SID)
295             .addImm(CTX)
296             .addImm(CTY)
297             .addImm(CTZ)
298             .addImm(CTW);
299     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_G))
300             .addOperand(MI->getOperand(0))
301             .addOperand(MI->getOperand(1))
302             .addImm(SrcX)
303             .addImm(SrcY)
304             .addImm(SrcZ)
305             .addImm(SrcW)
306             .addImm(0)
307             .addImm(0)
308             .addImm(0)
309             .addImm(0)
310             .addImm(1)
311             .addImm(2)
312             .addImm(3)
313             .addOperand(RID)
314             .addOperand(SID)
315             .addImm(CTX)
316             .addImm(CTY)
317             .addImm(CTZ)
318             .addImm(CTW)
319             .addReg(T0, RegState::Implicit)
320             .addReg(T1, RegState::Implicit);
321     break;
322   }
323
324   case AMDGPU::TXD_SHADOW: {
325     unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
326     unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
327     MachineOperand &RID = MI->getOperand(4);
328     MachineOperand &SID = MI->getOperand(5);
329     unsigned TextureId = MI->getOperand(6).getImm();
330     unsigned SrcX = 0, SrcY = 1, SrcZ = 2, SrcW = 3;
331     unsigned CTX = 1, CTY = 1, CTZ = 1, CTW = 1;
332
333     switch (TextureId) {
334     case 5: // Rect
335       CTX = CTY = 0;
336       break;
337     case 6: // Shadow1D
338       SrcW = SrcZ;
339       break;
340     case 7: // Shadow2D
341       SrcW = SrcZ;
342       break;
343     case 8: // ShadowRect
344       CTX = CTY = 0;
345       SrcW = SrcZ;
346       break;
347     case 9: // 1DArray
348       SrcZ = SrcY;
349       CTZ = 0;
350       break;
351     case 10: // 2DArray
352       CTZ = 0;
353       break;
354     case 11: // Shadow1DArray
355       SrcZ = SrcY;
356       CTZ = 0;
357       break;
358     case 12: // Shadow2DArray
359       CTZ = 0;
360       break;
361     }
362
363     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
364             .addOperand(MI->getOperand(3))
365             .addImm(SrcX)
366             .addImm(SrcY)
367             .addImm(SrcZ)
368             .addImm(SrcW)
369             .addImm(0)
370             .addImm(0)
371             .addImm(0)
372             .addImm(0)
373             .addImm(1)
374             .addImm(2)
375             .addImm(3)
376             .addOperand(RID)
377             .addOperand(SID)
378             .addImm(CTX)
379             .addImm(CTY)
380             .addImm(CTZ)
381             .addImm(CTW);
382     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
383             .addOperand(MI->getOperand(2))
384             .addImm(SrcX)
385             .addImm(SrcY)
386             .addImm(SrcZ)
387             .addImm(SrcW)
388             .addImm(0)
389             .addImm(0)
390             .addImm(0)
391             .addImm(0)
392             .addImm(1)
393             .addImm(2)
394             .addImm(3)
395             .addOperand(RID)
396             .addOperand(SID)
397             .addImm(CTX)
398             .addImm(CTY)
399             .addImm(CTZ)
400             .addImm(CTW);
401     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_C_G))
402             .addOperand(MI->getOperand(0))
403             .addOperand(MI->getOperand(1))
404             .addImm(SrcX)
405             .addImm(SrcY)
406             .addImm(SrcZ)
407             .addImm(SrcW)
408             .addImm(0)
409             .addImm(0)
410             .addImm(0)
411             .addImm(0)
412             .addImm(1)
413             .addImm(2)
414             .addImm(3)
415             .addOperand(RID)
416             .addOperand(SID)
417             .addImm(CTX)
418             .addImm(CTY)
419             .addImm(CTZ)
420             .addImm(CTW)
421             .addReg(T0, RegState::Implicit)
422             .addReg(T1, RegState::Implicit);
423     break;
424   }
425
426   case AMDGPU::BRANCH:
427       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
428               .addOperand(MI->getOperand(0));
429       break;
430
431   case AMDGPU::BRANCH_COND_f32: {
432     MachineInstr *NewMI =
433       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
434               AMDGPU::PREDICATE_BIT)
435               .addOperand(MI->getOperand(1))
436               .addImm(OPCODE_IS_NOT_ZERO)
437               .addImm(0); // Flags
438     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
439     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP_COND))
440             .addOperand(MI->getOperand(0))
441             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
442     break;
443   }
444
445   case AMDGPU::BRANCH_COND_i32: {
446     MachineInstr *NewMI =
447       BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
448             AMDGPU::PREDICATE_BIT)
449             .addOperand(MI->getOperand(1))
450             .addImm(OPCODE_IS_NOT_ZERO_INT)
451             .addImm(0); // Flags
452     TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
453     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP_COND))
454            .addOperand(MI->getOperand(0))
455             .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
456     break;
457   }
458
459   case AMDGPU::EG_ExportSwz:
460   case AMDGPU::R600_ExportSwz: {
461     // Instruction is left unmodified if its not the last one of its type
462     bool isLastInstructionOfItsType = true;
463     unsigned InstExportType = MI->getOperand(1).getImm();
464     for (MachineBasicBlock::iterator NextExportInst = llvm::next(I),
465          EndBlock = BB->end(); NextExportInst != EndBlock;
466          NextExportInst = llvm::next(NextExportInst)) {
467       if (NextExportInst->getOpcode() == AMDGPU::EG_ExportSwz ||
468           NextExportInst->getOpcode() == AMDGPU::R600_ExportSwz) {
469         unsigned CurrentInstExportType = NextExportInst->getOperand(1)
470             .getImm();
471         if (CurrentInstExportType == InstExportType) {
472           isLastInstructionOfItsType = false;
473           break;
474         }
475       }
476     }
477     bool EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN)? 1 : 0;
478     if (!EOP && !isLastInstructionOfItsType)
479       return BB;
480     unsigned CfInst = (MI->getOpcode() == AMDGPU::EG_ExportSwz)? 84 : 40;
481     BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
482             .addOperand(MI->getOperand(0))
483             .addOperand(MI->getOperand(1))
484             .addOperand(MI->getOperand(2))
485             .addOperand(MI->getOperand(3))
486             .addOperand(MI->getOperand(4))
487             .addOperand(MI->getOperand(5))
488             .addOperand(MI->getOperand(6))
489             .addImm(CfInst)
490             .addImm(EOP);
491     break;
492   }
493   case AMDGPU::RETURN: {
494     // RETURN instructions must have the live-out registers as implicit uses,
495     // otherwise they appear dead.
496     R600MachineFunctionInfo *MFI = MF->getInfo<R600MachineFunctionInfo>();
497     MachineInstrBuilder MIB(*MF, MI);
498     for (unsigned i = 0, e = MFI->LiveOuts.size(); i != e; ++i)
499       MIB.addReg(MFI->LiveOuts[i], RegState::Implicit);
500     return BB;
501   }
502   }
503
504   MI->eraseFromParent();
505   return BB;
506 }
507
508 //===----------------------------------------------------------------------===//
509 // Custom DAG Lowering Operations
510 //===----------------------------------------------------------------------===//
511
512 SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
513   MachineFunction &MF = DAG.getMachineFunction();
514   R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
515   switch (Op.getOpcode()) {
516   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
517   case ISD::FCOS:
518   case ISD::FSIN: return LowerTrig(Op, DAG);
519   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
520   case ISD::STORE: return LowerSTORE(Op, DAG);
521   case ISD::LOAD: return LowerLOAD(Op, DAG);
522   case ISD::GlobalAddress: return LowerGlobalAddress(MFI, Op, DAG);
523   case ISD::INTRINSIC_VOID: {
524     SDValue Chain = Op.getOperand(0);
525     unsigned IntrinsicID =
526                          cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
527     switch (IntrinsicID) {
528     case AMDGPUIntrinsic::AMDGPU_store_output: {
529       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
530       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
531       MFI->LiveOuts.push_back(Reg);
532       return DAG.getCopyToReg(Chain, SDLoc(Op), Reg, Op.getOperand(2));
533     }
534     case AMDGPUIntrinsic::R600_store_swizzle: {
535       const SDValue Args[8] = {
536         Chain,
537         Op.getOperand(2), // Export Value
538         Op.getOperand(3), // ArrayBase
539         Op.getOperand(4), // Type
540         DAG.getConstant(0, MVT::i32), // SWZ_X
541         DAG.getConstant(1, MVT::i32), // SWZ_Y
542         DAG.getConstant(2, MVT::i32), // SWZ_Z
543         DAG.getConstant(3, MVT::i32) // SWZ_W
544       };
545       return DAG.getNode(AMDGPUISD::EXPORT, SDLoc(Op), Op.getValueType(),
546           Args, 8);
547     }
548
549     // default for switch(IntrinsicID)
550     default: break;
551     }
552     // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
553     break;
554   }
555   case ISD::INTRINSIC_WO_CHAIN: {
556     unsigned IntrinsicID =
557                          cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
558     EVT VT = Op.getValueType();
559     SDLoc DL(Op);
560     switch(IntrinsicID) {
561     default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
562     case AMDGPUIntrinsic::R600_load_input: {
563       int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
564       unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
565       MachineFunction &MF = DAG.getMachineFunction();
566       MachineRegisterInfo &MRI = MF.getRegInfo();
567       MRI.addLiveIn(Reg);
568       return DAG.getCopyFromReg(DAG.getEntryNode(),
569           SDLoc(DAG.getEntryNode()), Reg, VT);
570     }
571
572     case AMDGPUIntrinsic::R600_interp_input: {
573       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
574       int ijb = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
575       MachineSDNode *interp;
576       if (ijb < 0) {
577         const MachineFunction &MF = DAG.getMachineFunction();
578         const R600InstrInfo *TII =
579           static_cast<const R600InstrInfo*>(MF.getTarget().getInstrInfo());
580         interp = DAG.getMachineNode(AMDGPU::INTERP_VEC_LOAD, DL,
581             MVT::v4f32, DAG.getTargetConstant(slot / 4 , MVT::i32));
582         return DAG.getTargetExtractSubreg(
583             TII->getRegisterInfo().getSubRegFromChannel(slot % 4),
584             DL, MVT::f32, SDValue(interp, 0));
585       }
586       MachineFunction &MF = DAG.getMachineFunction();
587       MachineRegisterInfo &MRI = MF.getRegInfo();
588       unsigned RegisterI = AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb);
589       unsigned RegisterJ = AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1);
590       MRI.addLiveIn(RegisterI);
591       MRI.addLiveIn(RegisterJ);
592       SDValue RegisterINode = DAG.getCopyFromReg(DAG.getEntryNode(),
593           SDLoc(DAG.getEntryNode()), RegisterI, MVT::f32);
594       SDValue RegisterJNode = DAG.getCopyFromReg(DAG.getEntryNode(),
595           SDLoc(DAG.getEntryNode()), RegisterJ, MVT::f32);
596
597       if (slot % 4 < 2)
598         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
599             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
600             RegisterJNode, RegisterINode);
601       else
602         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
603             MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
604             RegisterJNode, RegisterINode);
605       return SDValue(interp, slot % 2);
606     }
607     case AMDGPUIntrinsic::R600_interp_xy:
608     case AMDGPUIntrinsic::R600_interp_zw: {
609       int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
610       MachineSDNode *interp;
611       SDValue RegisterINode = Op.getOperand(2);
612       SDValue RegisterJNode = Op.getOperand(3);
613
614       if (IntrinsicID == AMDGPUIntrinsic::R600_interp_xy)
615         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
616             MVT::f32, MVT::f32, DAG.getTargetConstant(slot, MVT::i32),
617             RegisterJNode, RegisterINode);
618       else
619         interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
620             MVT::f32, MVT::f32, DAG.getTargetConstant(slot, MVT::i32),
621             RegisterJNode, RegisterINode);
622       return DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32,
623           SDValue(interp, 0), SDValue(interp, 1));
624     }
625     case AMDGPUIntrinsic::R600_tex:
626     case AMDGPUIntrinsic::R600_texc:
627     case AMDGPUIntrinsic::R600_txl:
628     case AMDGPUIntrinsic::R600_txlc:
629     case AMDGPUIntrinsic::R600_txb:
630     case AMDGPUIntrinsic::R600_txbc:
631     case AMDGPUIntrinsic::R600_txf:
632     case AMDGPUIntrinsic::R600_txq:
633     case AMDGPUIntrinsic::R600_ddx:
634     case AMDGPUIntrinsic::R600_ddy:
635     case AMDGPUIntrinsic::R600_ldptr: {
636       unsigned TextureOp;
637       switch (IntrinsicID) {
638       case AMDGPUIntrinsic::R600_tex:
639         TextureOp = 0;
640         break;
641       case AMDGPUIntrinsic::R600_texc:
642         TextureOp = 1;
643         break;
644       case AMDGPUIntrinsic::R600_txl:
645         TextureOp = 2;
646         break;
647       case AMDGPUIntrinsic::R600_txlc:
648         TextureOp = 3;
649         break;
650       case AMDGPUIntrinsic::R600_txb:
651         TextureOp = 4;
652         break;
653       case AMDGPUIntrinsic::R600_txbc:
654         TextureOp = 5;
655         break;
656       case AMDGPUIntrinsic::R600_txf:
657         TextureOp = 6;
658         break;
659       case AMDGPUIntrinsic::R600_txq:
660         TextureOp = 7;
661         break;
662       case AMDGPUIntrinsic::R600_ddx:
663         TextureOp = 8;
664         break;
665       case AMDGPUIntrinsic::R600_ddy:
666         TextureOp = 9;
667         break;
668       case AMDGPUIntrinsic::R600_ldptr:
669         TextureOp = 10;
670         break;
671       default:
672         llvm_unreachable("Unknow Texture Operation");
673       }
674
675       SDValue TexArgs[19] = {
676         DAG.getConstant(TextureOp, MVT::i32),
677         Op.getOperand(1),
678         DAG.getConstant(0, MVT::i32),
679         DAG.getConstant(1, MVT::i32),
680         DAG.getConstant(2, MVT::i32),
681         DAG.getConstant(3, MVT::i32),
682         Op.getOperand(2),
683         Op.getOperand(3),
684         Op.getOperand(4),
685         DAG.getConstant(0, MVT::i32),
686         DAG.getConstant(1, MVT::i32),
687         DAG.getConstant(2, MVT::i32),
688         DAG.getConstant(3, MVT::i32),
689         Op.getOperand(5),
690         Op.getOperand(6),
691         Op.getOperand(7),
692         Op.getOperand(8),
693         Op.getOperand(9),
694         Op.getOperand(10)
695       };
696       return DAG.getNode(AMDGPUISD::TEXTURE_FETCH, DL, MVT::v4f32, TexArgs, 19);
697     }
698     case AMDGPUIntrinsic::AMDGPU_dp4: {
699       SDValue Args[8] = {
700       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
701           DAG.getConstant(0, MVT::i32)),
702       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
703           DAG.getConstant(0, MVT::i32)),
704       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
705           DAG.getConstant(1, MVT::i32)),
706       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
707           DAG.getConstant(1, MVT::i32)),
708       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
709           DAG.getConstant(2, MVT::i32)),
710       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
711           DAG.getConstant(2, MVT::i32)),
712       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(1),
713           DAG.getConstant(3, MVT::i32)),
714       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Op.getOperand(2),
715           DAG.getConstant(3, MVT::i32))
716       };
717       return DAG.getNode(AMDGPUISD::DOT4, DL, MVT::f32, Args, 8);
718     }
719
720     case Intrinsic::r600_read_ngroups_x:
721       return LowerImplicitParameter(DAG, VT, DL, 0);
722     case Intrinsic::r600_read_ngroups_y:
723       return LowerImplicitParameter(DAG, VT, DL, 1);
724     case Intrinsic::r600_read_ngroups_z:
725       return LowerImplicitParameter(DAG, VT, DL, 2);
726     case Intrinsic::r600_read_global_size_x:
727       return LowerImplicitParameter(DAG, VT, DL, 3);
728     case Intrinsic::r600_read_global_size_y:
729       return LowerImplicitParameter(DAG, VT, DL, 4);
730     case Intrinsic::r600_read_global_size_z:
731       return LowerImplicitParameter(DAG, VT, DL, 5);
732     case Intrinsic::r600_read_local_size_x:
733       return LowerImplicitParameter(DAG, VT, DL, 6);
734     case Intrinsic::r600_read_local_size_y:
735       return LowerImplicitParameter(DAG, VT, DL, 7);
736     case Intrinsic::r600_read_local_size_z:
737       return LowerImplicitParameter(DAG, VT, DL, 8);
738
739     case Intrinsic::r600_read_tgid_x:
740       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
741                                   AMDGPU::T1_X, VT);
742     case Intrinsic::r600_read_tgid_y:
743       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
744                                   AMDGPU::T1_Y, VT);
745     case Intrinsic::r600_read_tgid_z:
746       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
747                                   AMDGPU::T1_Z, VT);
748     case Intrinsic::r600_read_tidig_x:
749       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
750                                   AMDGPU::T0_X, VT);
751     case Intrinsic::r600_read_tidig_y:
752       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
753                                   AMDGPU::T0_Y, VT);
754     case Intrinsic::r600_read_tidig_z:
755       return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
756                                   AMDGPU::T0_Z, VT);
757     }
758     // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
759     break;
760   }
761   } // end switch(Op.getOpcode())
762   return SDValue();
763 }
764
765 void R600TargetLowering::ReplaceNodeResults(SDNode *N,
766                                             SmallVectorImpl<SDValue> &Results,
767                                             SelectionDAG &DAG) const {
768   switch (N->getOpcode()) {
769   default: return;
770   case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
771     return;
772   case ISD::LOAD: {
773     SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
774     Results.push_back(SDValue(Node, 0));
775     Results.push_back(SDValue(Node, 1));
776     // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
777     // function
778     DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
779     return;
780   }
781   case ISD::STORE:
782     SDNode *Node = LowerSTORE(SDValue(N, 0), DAG).getNode();
783     Results.push_back(SDValue(Node, 0));
784     return;
785   }
786 }
787
788 SDValue R600TargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
789   // On hw >= R700, COS/SIN input must be between -1. and 1.
790   // Thus we lower them to TRIG ( FRACT ( x / 2Pi + 0.5) - 0.5)
791   EVT VT = Op.getValueType();
792   SDValue Arg = Op.getOperand(0);
793   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, SDLoc(Op), VT,
794       DAG.getNode(ISD::FADD, SDLoc(Op), VT,
795         DAG.getNode(ISD::FMUL, SDLoc(Op), VT, Arg,
796           DAG.getConstantFP(0.15915494309, MVT::f32)),
797         DAG.getConstantFP(0.5, MVT::f32)));
798   unsigned TrigNode;
799   switch (Op.getOpcode()) {
800   case ISD::FCOS:
801     TrigNode = AMDGPUISD::COS_HW;
802     break;
803   case ISD::FSIN:
804     TrigNode = AMDGPUISD::SIN_HW;
805     break;
806   default:
807     llvm_unreachable("Wrong trig opcode");
808   }
809   SDValue TrigVal = DAG.getNode(TrigNode, SDLoc(Op), VT,
810       DAG.getNode(ISD::FADD, SDLoc(Op), VT, FractPart,
811         DAG.getConstantFP(-0.5, MVT::f32)));
812   if (Gen >= AMDGPUSubtarget::R700)
813     return TrigVal;
814   // On R600 hw, COS/SIN input must be between -Pi and Pi.
815   return DAG.getNode(ISD::FMUL, SDLoc(Op), VT, TrigVal,
816       DAG.getConstantFP(3.14159265359, MVT::f32));
817 }
818
819 SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
820   return DAG.getNode(
821       ISD::SETCC,
822       SDLoc(Op),
823       MVT::i1,
824       Op, DAG.getConstantFP(0.0f, MVT::f32),
825       DAG.getCondCode(ISD::SETNE)
826       );
827 }
828
829 SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
830                                                    SDLoc DL,
831                                                    unsigned DwordOffset) const {
832   unsigned ByteOffset = DwordOffset * 4;
833   PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
834                                       AMDGPUAS::CONSTANT_BUFFER_0);
835
836   // We shouldn't be using an offset wider than 16-bits for implicit parameters.
837   assert(isInt<16>(ByteOffset));
838
839   return DAG.getLoad(VT, DL, DAG.getEntryNode(),
840                      DAG.getConstant(ByteOffset, MVT::i32), // PTR
841                      MachinePointerInfo(ConstantPointerNull::get(PtrType)),
842                      false, false, false, 0);
843 }
844
845 bool R600TargetLowering::isZero(SDValue Op) const {
846   if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
847     return Cst->isNullValue();
848   } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
849     return CstFP->isZero();
850   } else {
851     return false;
852   }
853 }
854
855 SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
856   SDLoc DL(Op);
857   EVT VT = Op.getValueType();
858
859   SDValue LHS = Op.getOperand(0);
860   SDValue RHS = Op.getOperand(1);
861   SDValue True = Op.getOperand(2);
862   SDValue False = Op.getOperand(3);
863   SDValue CC = Op.getOperand(4);
864   SDValue Temp;
865
866   // LHS and RHS are guaranteed to be the same value type
867   EVT CompareVT = LHS.getValueType();
868
869   // Check if we can lower this to a native operation.
870
871   // Try to lower to a SET* instruction:
872   //
873   // SET* can match the following patterns:
874   //
875   // select_cc f32, f32, -1,  0, cc_supported
876   // select_cc f32, f32, 1.0f, 0.0f, cc_supported
877   // select_cc i32, i32, -1,  0, cc_supported
878   //
879
880   // Move hardware True/False values to the correct operand.
881   ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
882   ISD::CondCode InverseCC =
883      ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
884   if (isHWTrueValue(False) && isHWFalseValue(True)) {
885     if (isCondCodeLegal(InverseCC, CompareVT.getSimpleVT())) {
886       std::swap(False, True);
887       CC = DAG.getCondCode(InverseCC);
888     } else {
889       ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InverseCC);
890       if (isCondCodeLegal(SwapInvCC, CompareVT.getSimpleVT())) {
891         std::swap(False, True);
892         std::swap(LHS, RHS);
893         CC = DAG.getCondCode(SwapInvCC);
894       }
895     }
896   }
897
898   if (isHWTrueValue(True) && isHWFalseValue(False) &&
899       (CompareVT == VT || VT == MVT::i32)) {
900     // This can be matched by a SET* instruction.
901     return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
902   }
903
904   // Try to lower to a CND* instruction:
905   //
906   // CND* can match the following patterns:
907   //
908   // select_cc f32, 0.0, f32, f32, cc_supported
909   // select_cc f32, 0.0, i32, i32, cc_supported
910   // select_cc i32, 0,   f32, f32, cc_supported
911   // select_cc i32, 0,   i32, i32, cc_supported
912   //
913
914   // Try to move the zero value to the RHS
915   if (isZero(LHS)) {
916     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
917     // Try swapping the operands
918     ISD::CondCode CCSwapped = ISD::getSetCCSwappedOperands(CCOpcode);
919     if (isCondCodeLegal(CCSwapped, CompareVT.getSimpleVT())) {
920       std::swap(LHS, RHS);
921       CC = DAG.getCondCode(CCSwapped);
922     } else {
923       // Try inverting the conditon and then swapping the operands
924       ISD::CondCode CCInv = ISD::getSetCCInverse(CCOpcode, CompareVT.isInteger());
925       CCSwapped = ISD::getSetCCSwappedOperands(CCInv);
926       if (isCondCodeLegal(CCSwapped, CompareVT.getSimpleVT())) {
927         std::swap(True, False);
928         std::swap(LHS, RHS);
929         CC = DAG.getCondCode(CCSwapped);
930       }
931     }
932   }
933   if (isZero(RHS)) {
934     SDValue Cond = LHS;
935     SDValue Zero = RHS;
936     ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
937     if (CompareVT != VT) {
938       // Bitcast True / False to the correct types.  This will end up being
939       // a nop, but it allows us to define only a single pattern in the
940       // .TD files for each CND* instruction rather than having to have
941       // one pattern for integer True/False and one for fp True/False
942       True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
943       False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
944     }
945
946     switch (CCOpcode) {
947     case ISD::SETONE:
948     case ISD::SETUNE:
949     case ISD::SETNE:
950       CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
951       Temp = True;
952       True = False;
953       False = Temp;
954       break;
955     default:
956       break;
957     }
958     SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
959         Cond, Zero,
960         True, False,
961         DAG.getCondCode(CCOpcode));
962     return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
963   }
964
965
966   // Possible Min/Max pattern
967   SDValue MinMax = LowerMinMax(Op, DAG);
968   if (MinMax.getNode()) {
969     return MinMax;
970   }
971
972   // If we make it this for it means we have no native instructions to handle
973   // this SELECT_CC, so we must lower it.
974   SDValue HWTrue, HWFalse;
975
976   if (CompareVT == MVT::f32) {
977     HWTrue = DAG.getConstantFP(1.0f, CompareVT);
978     HWFalse = DAG.getConstantFP(0.0f, CompareVT);
979   } else if (CompareVT == MVT::i32) {
980     HWTrue = DAG.getConstant(-1, CompareVT);
981     HWFalse = DAG.getConstant(0, CompareVT);
982   }
983   else {
984     assert(!"Unhandled value type in LowerSELECT_CC");
985   }
986
987   // Lower this unsupported SELECT_CC into a combination of two supported
988   // SELECT_CC operations.
989   SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);
990
991   return DAG.getNode(ISD::SELECT_CC, DL, VT,
992       Cond, HWFalse,
993       True, False,
994       DAG.getCondCode(ISD::SETNE));
995 }
996
997 /// LLVM generates byte-addresed pointers.  For indirect addressing, we need to
998 /// convert these pointers to a register index.  Each register holds
999 /// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
1000 /// \p StackWidth, which tells us how many of the 4 sub-registrers will be used
1001 /// for indirect addressing.
1002 SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
1003                                                unsigned StackWidth,
1004                                                SelectionDAG &DAG) const {
1005   unsigned SRLPad;
1006   switch(StackWidth) {
1007   case 1:
1008     SRLPad = 2;
1009     break;
1010   case 2:
1011     SRLPad = 3;
1012     break;
1013   case 4:
1014     SRLPad = 4;
1015     break;
1016   default: llvm_unreachable("Invalid stack width");
1017   }
1018
1019   return DAG.getNode(ISD::SRL, SDLoc(Ptr), Ptr.getValueType(), Ptr,
1020                      DAG.getConstant(SRLPad, MVT::i32));
1021 }
1022
1023 void R600TargetLowering::getStackAddress(unsigned StackWidth,
1024                                          unsigned ElemIdx,
1025                                          unsigned &Channel,
1026                                          unsigned &PtrIncr) const {
1027   switch (StackWidth) {
1028   default:
1029   case 1:
1030     Channel = 0;
1031     if (ElemIdx > 0) {
1032       PtrIncr = 1;
1033     } else {
1034       PtrIncr = 0;
1035     }
1036     break;
1037   case 2:
1038     Channel = ElemIdx % 2;
1039     if (ElemIdx == 2) {
1040       PtrIncr = 1;
1041     } else {
1042       PtrIncr = 0;
1043     }
1044     break;
1045   case 4:
1046     Channel = ElemIdx;
1047     PtrIncr = 0;
1048     break;
1049   }
1050 }
1051
1052 SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1053   SDLoc DL(Op);
1054   StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
1055   SDValue Chain = Op.getOperand(0);
1056   SDValue Value = Op.getOperand(1);
1057   SDValue Ptr = Op.getOperand(2);
1058
1059   SDValue Result = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1060   if (Result.getNode()) {
1061     return Result;
1062   }
1063
1064   if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS) {
1065     if (StoreNode->isTruncatingStore()) {
1066       EVT VT = Value.getValueType();
1067       assert(VT.bitsLE(MVT::i32));
1068       EVT MemVT = StoreNode->getMemoryVT();
1069       SDValue MaskConstant;
1070       if (MemVT == MVT::i8) {
1071         MaskConstant = DAG.getConstant(0xFF, MVT::i32);
1072       } else {
1073         assert(MemVT == MVT::i16);
1074         MaskConstant = DAG.getConstant(0xFFFF, MVT::i32);
1075       }
1076       SDValue DWordAddr = DAG.getNode(ISD::SRL, DL, VT, Ptr,
1077                                       DAG.getConstant(2, MVT::i32));
1078       SDValue ByteIndex = DAG.getNode(ISD::AND, DL, Ptr.getValueType(), Ptr,
1079                                       DAG.getConstant(0x00000003, VT));
1080       SDValue TruncValue = DAG.getNode(ISD::AND, DL, VT, Value, MaskConstant);
1081       SDValue Shift = DAG.getNode(ISD::SHL, DL, VT, ByteIndex,
1082                                    DAG.getConstant(3, VT));
1083       SDValue ShiftedValue = DAG.getNode(ISD::SHL, DL, VT, TruncValue, Shift);
1084       SDValue Mask = DAG.getNode(ISD::SHL, DL, VT, MaskConstant, Shift);
1085       // XXX: If we add a 64-bit ZW register class, then we could use a 2 x i32
1086       // vector instead.
1087       SDValue Src[4] = {
1088         ShiftedValue,
1089         DAG.getConstant(0, MVT::i32),
1090         DAG.getConstant(0, MVT::i32),
1091         Mask
1092       };
1093       SDValue Input = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Src, 4);
1094       SDValue Args[3] = { Chain, Input, DWordAddr };
1095       return DAG.getMemIntrinsicNode(AMDGPUISD::STORE_MSKOR, DL,
1096                                      Op->getVTList(), Args, 3, MemVT,
1097                                      StoreNode->getMemOperand());
1098     } else if (Ptr->getOpcode() != AMDGPUISD::DWORDADDR &&
1099                Value.getValueType().bitsGE(MVT::i32)) {
1100       // Convert pointer from byte address to dword address.
1101       Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
1102                         DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
1103                                     Ptr, DAG.getConstant(2, MVT::i32)));
1104
1105       if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
1106         assert(!"Truncated and indexed stores not supported yet");
1107       } else {
1108         Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
1109       }
1110       return Chain;
1111     }
1112   }
1113
1114   EVT ValueVT = Value.getValueType();
1115
1116   if (StoreNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
1117     return SDValue();
1118   }
1119
1120   // Lowering for indirect addressing
1121
1122   const MachineFunction &MF = DAG.getMachineFunction();
1123   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
1124                                          getTargetMachine().getFrameLowering());
1125   unsigned StackWidth = TFL->getStackWidth(MF);
1126
1127   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
1128
1129   if (ValueVT.isVector()) {
1130     unsigned NumElemVT = ValueVT.getVectorNumElements();
1131     EVT ElemVT = ValueVT.getVectorElementType();
1132     SDValue Stores[4];
1133
1134     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
1135                                       "vector width in load");
1136
1137     for (unsigned i = 0; i < NumElemVT; ++i) {
1138       unsigned Channel, PtrIncr;
1139       getStackAddress(StackWidth, i, Channel, PtrIncr);
1140       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
1141                         DAG.getConstant(PtrIncr, MVT::i32));
1142       SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT,
1143                                  Value, DAG.getConstant(i, MVT::i32));
1144
1145       Stores[i] = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
1146                               Chain, Elem, Ptr,
1147                               DAG.getTargetConstant(Channel, MVT::i32));
1148     }
1149      Chain =  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores, NumElemVT);
1150    } else {
1151     if (ValueVT == MVT::i8) {
1152       Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Value);
1153     }
1154     Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other, Chain, Value, Ptr,
1155     DAG.getTargetConstant(0, MVT::i32)); // Channel
1156   }
1157
1158   return Chain;
1159 }
1160
1161 // return (512 + (kc_bank << 12)
1162 static int
1163 ConstantAddressBlock(unsigned AddressSpace) {
1164   switch (AddressSpace) {
1165   case AMDGPUAS::CONSTANT_BUFFER_0:
1166     return 512;
1167   case AMDGPUAS::CONSTANT_BUFFER_1:
1168     return 512 + 4096;
1169   case AMDGPUAS::CONSTANT_BUFFER_2:
1170     return 512 + 4096 * 2;
1171   case AMDGPUAS::CONSTANT_BUFFER_3:
1172     return 512 + 4096 * 3;
1173   case AMDGPUAS::CONSTANT_BUFFER_4:
1174     return 512 + 4096 * 4;
1175   case AMDGPUAS::CONSTANT_BUFFER_5:
1176     return 512 + 4096 * 5;
1177   case AMDGPUAS::CONSTANT_BUFFER_6:
1178     return 512 + 4096 * 6;
1179   case AMDGPUAS::CONSTANT_BUFFER_7:
1180     return 512 + 4096 * 7;
1181   case AMDGPUAS::CONSTANT_BUFFER_8:
1182     return 512 + 4096 * 8;
1183   case AMDGPUAS::CONSTANT_BUFFER_9:
1184     return 512 + 4096 * 9;
1185   case AMDGPUAS::CONSTANT_BUFFER_10:
1186     return 512 + 4096 * 10;
1187   case AMDGPUAS::CONSTANT_BUFFER_11:
1188     return 512 + 4096 * 11;
1189   case AMDGPUAS::CONSTANT_BUFFER_12:
1190     return 512 + 4096 * 12;
1191   case AMDGPUAS::CONSTANT_BUFFER_13:
1192     return 512 + 4096 * 13;
1193   case AMDGPUAS::CONSTANT_BUFFER_14:
1194     return 512 + 4096 * 14;
1195   case AMDGPUAS::CONSTANT_BUFFER_15:
1196     return 512 + 4096 * 15;
1197   default:
1198     return -1;
1199   }
1200 }
1201
1202 SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
1203 {
1204   EVT VT = Op.getValueType();
1205   SDLoc DL(Op);
1206   LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
1207   SDValue Chain = Op.getOperand(0);
1208   SDValue Ptr = Op.getOperand(1);
1209   SDValue LoweredLoad;
1210
1211   if (LoadNode->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && VT.isVector()) {
1212     SDValue MergedValues[2] = {
1213       SplitVectorLoad(Op, DAG),
1214       Chain
1215     };
1216     return DAG.getMergeValues(MergedValues, 2, DL);
1217   }
1218
1219   int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
1220   if (ConstantBlock > -1 &&
1221       ((LoadNode->getExtensionType() == ISD::NON_EXTLOAD) ||
1222        (LoadNode->getExtensionType() == ISD::ZEXTLOAD))) {
1223     SDValue Result;
1224     if (isa<ConstantExpr>(LoadNode->getSrcValue()) ||
1225         isa<Constant>(LoadNode->getSrcValue()) ||
1226         isa<ConstantSDNode>(Ptr)) {
1227       SDValue Slots[4];
1228       for (unsigned i = 0; i < 4; i++) {
1229         // We want Const position encoded with the following formula :
1230         // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
1231         // const_index is Ptr computed by llvm using an alignment of 16.
1232         // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
1233         // then div by 4 at the ISel step
1234         SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
1235             DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
1236         Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
1237       }
1238       EVT NewVT = MVT::v4i32;
1239       unsigned NumElements = 4;
1240       if (VT.isVector()) {
1241         NewVT = VT;
1242         NumElements = VT.getVectorNumElements();
1243       }
1244       Result = DAG.getNode(ISD::BUILD_VECTOR, DL, NewVT, Slots, NumElements);
1245     } else {
1246       // non constant ptr cant be folded, keeps it as a v4f32 load
1247       Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
1248           DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32)),
1249           DAG.getConstant(LoadNode->getAddressSpace() -
1250                           AMDGPUAS::CONSTANT_BUFFER_0, MVT::i32)
1251           );
1252     }
1253
1254     if (!VT.isVector()) {
1255       Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
1256           DAG.getConstant(0, MVT::i32));
1257     }
1258
1259     SDValue MergedValues[2] = {
1260         Result,
1261         Chain
1262     };
1263     return DAG.getMergeValues(MergedValues, 2, DL);
1264   }
1265
1266   // For most operations returning SDValue() will result in the node being
1267   // expanded by the DAG Legalizer. This is not the case for ISD::LOAD, so we
1268   // need to manually expand loads that may be legal in some address spaces and
1269   // illegal in others. SEXT loads from CONSTANT_BUFFER_0 are supported for
1270   // compute shaders, since the data is sign extended when it is uploaded to the
1271   // buffer. However SEXT loads from other address spaces are not supported, so
1272   // we need to expand them here.
1273   if (LoadNode->getExtensionType() == ISD::SEXTLOAD) {
1274     EVT MemVT = LoadNode->getMemoryVT();
1275     assert(!MemVT.isVector() && (MemVT == MVT::i16 || MemVT == MVT::i8));
1276     SDValue ShiftAmount =
1277           DAG.getConstant(VT.getSizeInBits() - MemVT.getSizeInBits(), MVT::i32);
1278     SDValue NewLoad = DAG.getExtLoad(ISD::EXTLOAD, DL, VT, Chain, Ptr,
1279                                   LoadNode->getPointerInfo(), MemVT,
1280                                   LoadNode->isVolatile(),
1281                                   LoadNode->isNonTemporal(),
1282                                   LoadNode->getAlignment());
1283     SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, NewLoad, ShiftAmount);
1284     SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Shl, ShiftAmount);
1285
1286     SDValue MergedValues[2] = { Sra, Chain };
1287     return DAG.getMergeValues(MergedValues, 2, DL);
1288   }
1289
1290   if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
1291     return SDValue();
1292   }
1293
1294   // Lowering for indirect addressing
1295   const MachineFunction &MF = DAG.getMachineFunction();
1296   const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
1297                                          getTargetMachine().getFrameLowering());
1298   unsigned StackWidth = TFL->getStackWidth(MF);
1299
1300   Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);
1301
1302   if (VT.isVector()) {
1303     unsigned NumElemVT = VT.getVectorNumElements();
1304     EVT ElemVT = VT.getVectorElementType();
1305     SDValue Loads[4];
1306
1307     assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
1308                                       "vector width in load");
1309
1310     for (unsigned i = 0; i < NumElemVT; ++i) {
1311       unsigned Channel, PtrIncr;
1312       getStackAddress(StackWidth, i, Channel, PtrIncr);
1313       Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
1314                         DAG.getConstant(PtrIncr, MVT::i32));
1315       Loads[i] = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, ElemVT,
1316                              Chain, Ptr,
1317                              DAG.getTargetConstant(Channel, MVT::i32),
1318                              Op.getOperand(2));
1319     }
1320     for (unsigned i = NumElemVT; i < 4; ++i) {
1321       Loads[i] = DAG.getUNDEF(ElemVT);
1322     }
1323     EVT TargetVT = EVT::getVectorVT(*DAG.getContext(), ElemVT, 4);
1324     LoweredLoad = DAG.getNode(ISD::BUILD_VECTOR, DL, TargetVT, Loads, 4);
1325   } else {
1326     LoweredLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, VT,
1327                               Chain, Ptr,
1328                               DAG.getTargetConstant(0, MVT::i32), // Channel
1329                               Op.getOperand(2));
1330   }
1331
1332   SDValue Ops[2];
1333   Ops[0] = LoweredLoad;
1334   Ops[1] = Chain;
1335
1336   return DAG.getMergeValues(Ops, 2, DL);
1337 }
1338
1339 /// XXX Only kernel functions are supported, so we can assume for now that
1340 /// every function is a kernel function, but in the future we should use
1341 /// separate calling conventions for kernel and non-kernel functions.
1342 SDValue R600TargetLowering::LowerFormalArguments(
1343                                       SDValue Chain,
1344                                       CallingConv::ID CallConv,
1345                                       bool isVarArg,
1346                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1347                                       SDLoc DL, SelectionDAG &DAG,
1348                                       SmallVectorImpl<SDValue> &InVals) const {
1349   SmallVector<CCValAssign, 16> ArgLocs;
1350   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1351                  getTargetMachine(), ArgLocs, *DAG.getContext());
1352   MachineFunction &MF = DAG.getMachineFunction();
1353   unsigned ShaderType = MF.getInfo<R600MachineFunctionInfo>()->ShaderType;
1354
1355   SmallVector<ISD::InputArg, 8> LocalIns;
1356
1357   getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
1358                           LocalIns);
1359
1360   AnalyzeFormalArguments(CCInfo, LocalIns);
1361
1362   for (unsigned i = 0, e = Ins.size(); i < e; ++i) {
1363     CCValAssign &VA = ArgLocs[i];
1364     EVT VT = Ins[i].VT;
1365     EVT MemVT = LocalIns[i].VT;
1366
1367     if (ShaderType != ShaderType::COMPUTE) {
1368       unsigned Reg = MF.addLiveIn(VA.getLocReg(), &AMDGPU::R600_Reg128RegClass);
1369       SDValue Register = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1370       InVals.push_back(Register);
1371       continue;
1372     }
1373
1374     PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
1375                                                    AMDGPUAS::CONSTANT_BUFFER_0);
1376
1377     // The first 36 bytes of the input buffer contains information about
1378     // thread group and global sizes.
1379     SDValue Arg = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, Chain,
1380                                  DAG.getConstant(36 + VA.getLocMemOffset(), MVT::i32),
1381                                  MachinePointerInfo(UndefValue::get(PtrTy)),
1382                                  MemVT, false, false, 4);
1383                                  // 4 is the prefered alignment for
1384                                  // the CONSTANT memory space.
1385     InVals.push_back(Arg);
1386   }
1387   return Chain;
1388 }
1389
1390 EVT R600TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1391    if (!VT.isVector()) return MVT::i32;
1392    return VT.changeVectorElementTypeToInteger();
1393 }
1394
1395 static SDValue
1396 CompactSwizzlableVector(SelectionDAG &DAG, SDValue VectorEntry,
1397                         DenseMap<unsigned, unsigned> &RemapSwizzle) {
1398   assert(VectorEntry.getOpcode() == ISD::BUILD_VECTOR);
1399   assert(RemapSwizzle.empty());
1400   SDValue NewBldVec[4] = {
1401       VectorEntry.getOperand(0),
1402       VectorEntry.getOperand(1),
1403       VectorEntry.getOperand(2),
1404       VectorEntry.getOperand(3)
1405   };
1406
1407   for (unsigned i = 0; i < 4; i++) {
1408     if (NewBldVec[i].getOpcode() == ISD::UNDEF)
1409       // We mask write here to teach later passes that the ith element of this
1410       // vector is undef. Thus we can use it to reduce 128 bits reg usage,
1411       // break false dependencies and additionnaly make assembly easier to read.
1412       RemapSwizzle[i] = 7; // SEL_MASK_WRITE
1413     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(NewBldVec[i])) {
1414       if (C->isZero()) {
1415         RemapSwizzle[i] = 4; // SEL_0
1416         NewBldVec[i] = DAG.getUNDEF(MVT::f32);
1417       } else if (C->isExactlyValue(1.0)) {
1418         RemapSwizzle[i] = 5; // SEL_1
1419         NewBldVec[i] = DAG.getUNDEF(MVT::f32);
1420       }
1421     }
1422
1423     if (NewBldVec[i].getOpcode() == ISD::UNDEF)
1424       continue;
1425     for (unsigned j = 0; j < i; j++) {
1426       if (NewBldVec[i] == NewBldVec[j]) {
1427         NewBldVec[i] = DAG.getUNDEF(NewBldVec[i].getValueType());
1428         RemapSwizzle[i] = j;
1429         break;
1430       }
1431     }
1432   }
1433
1434   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(VectorEntry),
1435       VectorEntry.getValueType(), NewBldVec, 4);
1436 }
1437
1438 static SDValue ReorganizeVector(SelectionDAG &DAG, SDValue VectorEntry,
1439                                 DenseMap<unsigned, unsigned> &RemapSwizzle) {
1440   assert(VectorEntry.getOpcode() == ISD::BUILD_VECTOR);
1441   assert(RemapSwizzle.empty());
1442   SDValue NewBldVec[4] = {
1443       VectorEntry.getOperand(0),
1444       VectorEntry.getOperand(1),
1445       VectorEntry.getOperand(2),
1446       VectorEntry.getOperand(3)
1447   };
1448   bool isUnmovable[4] = { false, false, false, false };
1449   for (unsigned i = 0; i < 4; i++)
1450     RemapSwizzle[i] = i;
1451
1452   for (unsigned i = 0; i < 4; i++) {
1453     if (NewBldVec[i].getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
1454       unsigned Idx = dyn_cast<ConstantSDNode>(NewBldVec[i].getOperand(1))
1455           ->getZExtValue();
1456       if (i == Idx) {
1457         isUnmovable[Idx] = true;
1458         continue;
1459       }
1460       if (isUnmovable[Idx])
1461         continue;
1462       // Swap i and Idx
1463       std::swap(NewBldVec[Idx], NewBldVec[i]);
1464       std::swap(RemapSwizzle[i], RemapSwizzle[Idx]);
1465       break;
1466     }
1467   }
1468
1469   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(VectorEntry),
1470       VectorEntry.getValueType(), NewBldVec, 4);
1471 }
1472
1473
1474 SDValue R600TargetLowering::OptimizeSwizzle(SDValue BuildVector,
1475 SDValue Swz[4], SelectionDAG &DAG) const {
1476   assert(BuildVector.getOpcode() == ISD::BUILD_VECTOR);
1477   // Old -> New swizzle values
1478   DenseMap<unsigned, unsigned> SwizzleRemap;
1479
1480   BuildVector = CompactSwizzlableVector(DAG, BuildVector, SwizzleRemap);
1481   for (unsigned i = 0; i < 4; i++) {
1482     unsigned Idx = dyn_cast<ConstantSDNode>(Swz[i])->getZExtValue();
1483     if (SwizzleRemap.find(Idx) != SwizzleRemap.end())
1484       Swz[i] = DAG.getConstant(SwizzleRemap[Idx], MVT::i32);
1485   }
1486
1487   SwizzleRemap.clear();
1488   BuildVector = ReorganizeVector(DAG, BuildVector, SwizzleRemap);
1489   for (unsigned i = 0; i < 4; i++) {
1490     unsigned Idx = dyn_cast<ConstantSDNode>(Swz[i])->getZExtValue();
1491     if (SwizzleRemap.find(Idx) != SwizzleRemap.end())
1492       Swz[i] = DAG.getConstant(SwizzleRemap[Idx], MVT::i32);
1493   }
1494
1495   return BuildVector;
1496 }
1497
1498
1499 //===----------------------------------------------------------------------===//
1500 // Custom DAG Optimizations
1501 //===----------------------------------------------------------------------===//
1502
1503 SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
1504                                               DAGCombinerInfo &DCI) const {
1505   SelectionDAG &DAG = DCI.DAG;
1506
1507   switch (N->getOpcode()) {
1508   // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
1509   case ISD::FP_ROUND: {
1510       SDValue Arg = N->getOperand(0);
1511       if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
1512         return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), N->getValueType(0),
1513                            Arg.getOperand(0));
1514       }
1515       break;
1516     }
1517
1518   // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
1519   // (i32 select_cc f32, f32, -1, 0 cc)
1520   //
1521   // Mesa's GLSL frontend generates the above pattern a lot and we can lower
1522   // this to one of the SET*_DX10 instructions.
1523   case ISD::FP_TO_SINT: {
1524     SDValue FNeg = N->getOperand(0);
1525     if (FNeg.getOpcode() != ISD::FNEG) {
1526       return SDValue();
1527     }
1528     SDValue SelectCC = FNeg.getOperand(0);
1529     if (SelectCC.getOpcode() != ISD::SELECT_CC ||
1530         SelectCC.getOperand(0).getValueType() != MVT::f32 || // LHS
1531         SelectCC.getOperand(2).getValueType() != MVT::f32 || // True
1532         !isHWTrueValue(SelectCC.getOperand(2)) ||
1533         !isHWFalseValue(SelectCC.getOperand(3))) {
1534       return SDValue();
1535     }
1536
1537     return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N->getValueType(0),
1538                            SelectCC.getOperand(0), // LHS
1539                            SelectCC.getOperand(1), // RHS
1540                            DAG.getConstant(-1, MVT::i32), // True
1541                            DAG.getConstant(0, MVT::i32),  // Flase
1542                            SelectCC.getOperand(4)); // CC
1543
1544     break;
1545   }
1546
1547   // insert_vector_elt (build_vector elt0, ... , eltN), NewEltIdx, idx
1548   // => build_vector elt0, ... , NewEltIdx, ... , eltN
1549   case ISD::INSERT_VECTOR_ELT: {
1550     SDValue InVec = N->getOperand(0);
1551     SDValue InVal = N->getOperand(1);
1552     SDValue EltNo = N->getOperand(2);
1553     SDLoc dl(N);
1554
1555     // If the inserted element is an UNDEF, just use the input vector.
1556     if (InVal.getOpcode() == ISD::UNDEF)
1557       return InVec;
1558
1559     EVT VT = InVec.getValueType();
1560
1561     // If we can't generate a legal BUILD_VECTOR, exit
1562     if (!isOperationLegal(ISD::BUILD_VECTOR, VT))
1563       return SDValue();
1564
1565     // Check that we know which element is being inserted
1566     if (!isa<ConstantSDNode>(EltNo))
1567       return SDValue();
1568     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
1569
1570     // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
1571     // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
1572     // vector elements.
1573     SmallVector<SDValue, 8> Ops;
1574     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
1575       Ops.append(InVec.getNode()->op_begin(),
1576                  InVec.getNode()->op_end());
1577     } else if (InVec.getOpcode() == ISD::UNDEF) {
1578       unsigned NElts = VT.getVectorNumElements();
1579       Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
1580     } else {
1581       return SDValue();
1582     }
1583
1584     // Insert the element
1585     if (Elt < Ops.size()) {
1586       // All the operands of BUILD_VECTOR must have the same type;
1587       // we enforce that here.
1588       EVT OpVT = Ops[0].getValueType();
1589       if (InVal.getValueType() != OpVT)
1590         InVal = OpVT.bitsGT(InVal.getValueType()) ?
1591           DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
1592           DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
1593       Ops[Elt] = InVal;
1594     }
1595
1596     // Return the new vector
1597     return DAG.getNode(ISD::BUILD_VECTOR, dl,
1598                        VT, &Ops[0], Ops.size());
1599   }
1600
1601   // Extract_vec (Build_vector) generated by custom lowering
1602   // also needs to be customly combined
1603   case ISD::EXTRACT_VECTOR_ELT: {
1604     SDValue Arg = N->getOperand(0);
1605     if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
1606       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1607         unsigned Element = Const->getZExtValue();
1608         return Arg->getOperand(Element);
1609       }
1610     }
1611     if (Arg.getOpcode() == ISD::BITCAST &&
1612         Arg.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
1613       if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
1614         unsigned Element = Const->getZExtValue();
1615         return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getVTList(),
1616             Arg->getOperand(0).getOperand(Element));
1617       }
1618     }
1619   }
1620
1621   case ISD::SELECT_CC: {
1622     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
1623     //      selectcc x, y, a, b, inv(cc)
1624     //
1625     // fold selectcc (selectcc x, y, a, b, cc), b, a, b, setne ->
1626     //      selectcc x, y, a, b, cc
1627     SDValue LHS = N->getOperand(0);
1628     if (LHS.getOpcode() != ISD::SELECT_CC) {
1629       return SDValue();
1630     }
1631
1632     SDValue RHS = N->getOperand(1);
1633     SDValue True = N->getOperand(2);
1634     SDValue False = N->getOperand(3);
1635     ISD::CondCode NCC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1636
1637     if (LHS.getOperand(2).getNode() != True.getNode() ||
1638         LHS.getOperand(3).getNode() != False.getNode() ||
1639         RHS.getNode() != False.getNode()) {
1640       return SDValue();
1641     }
1642
1643     switch (NCC) {
1644     default: return SDValue();
1645     case ISD::SETNE: return LHS;
1646     case ISD::SETEQ: {
1647       ISD::CondCode LHSCC = cast<CondCodeSDNode>(LHS.getOperand(4))->get();
1648       LHSCC = ISD::getSetCCInverse(LHSCC,
1649                                   LHS.getOperand(0).getValueType().isInteger());
1650       if (DCI.isBeforeLegalizeOps() ||
1651           isCondCodeLegal(LHSCC, LHS.getOperand(0).getSimpleValueType()))
1652         return DAG.getSelectCC(SDLoc(N),
1653                                LHS.getOperand(0),
1654                                LHS.getOperand(1),
1655                                LHS.getOperand(2),
1656                                LHS.getOperand(3),
1657                                LHSCC);
1658       break;
1659     }
1660     }
1661     return SDValue();
1662   }
1663
1664   case AMDGPUISD::EXPORT: {
1665     SDValue Arg = N->getOperand(1);
1666     if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1667       break;
1668
1669     SDValue NewArgs[8] = {
1670       N->getOperand(0), // Chain
1671       SDValue(),
1672       N->getOperand(2), // ArrayBase
1673       N->getOperand(3), // Type
1674       N->getOperand(4), // SWZ_X
1675       N->getOperand(5), // SWZ_Y
1676       N->getOperand(6), // SWZ_Z
1677       N->getOperand(7) // SWZ_W
1678     };
1679     SDLoc DL(N);
1680     NewArgs[1] = OptimizeSwizzle(N->getOperand(1), &NewArgs[4], DAG);
1681     return DAG.getNode(AMDGPUISD::EXPORT, DL, N->getVTList(), NewArgs, 8);
1682   }
1683   case AMDGPUISD::TEXTURE_FETCH: {
1684     SDValue Arg = N->getOperand(1);
1685     if (Arg.getOpcode() != ISD::BUILD_VECTOR)
1686       break;
1687
1688     SDValue NewArgs[19] = {
1689       N->getOperand(0),
1690       N->getOperand(1),
1691       N->getOperand(2),
1692       N->getOperand(3),
1693       N->getOperand(4),
1694       N->getOperand(5),
1695       N->getOperand(6),
1696       N->getOperand(7),
1697       N->getOperand(8),
1698       N->getOperand(9),
1699       N->getOperand(10),
1700       N->getOperand(11),
1701       N->getOperand(12),
1702       N->getOperand(13),
1703       N->getOperand(14),
1704       N->getOperand(15),
1705       N->getOperand(16),
1706       N->getOperand(17),
1707       N->getOperand(18),
1708     };
1709     NewArgs[1] = OptimizeSwizzle(N->getOperand(1), &NewArgs[2], DAG);
1710     return DAG.getNode(AMDGPUISD::TEXTURE_FETCH, SDLoc(N), N->getVTList(),
1711         NewArgs, 19);
1712   }
1713   }
1714   return SDValue();
1715 }
1716
1717 static bool
1718 FoldOperand(SDNode *ParentNode, unsigned SrcIdx, SDValue &Src, SDValue &Neg,
1719             SDValue &Abs, SDValue &Sel, SDValue &Imm, SelectionDAG &DAG) {
1720   const R600InstrInfo *TII =
1721       static_cast<const R600InstrInfo *>(DAG.getTarget().getInstrInfo());
1722   if (!Src.isMachineOpcode())
1723     return false;
1724   switch (Src.getMachineOpcode()) {
1725   case AMDGPU::FNEG_R600:
1726     if (!Neg.getNode())
1727       return false;
1728     Src = Src.getOperand(0);
1729     Neg = DAG.getTargetConstant(1, MVT::i32);
1730     return true;
1731   case AMDGPU::FABS_R600:
1732     if (!Abs.getNode())
1733       return false;
1734     Src = Src.getOperand(0);
1735     Abs = DAG.getTargetConstant(1, MVT::i32);
1736     return true;
1737   case AMDGPU::CONST_COPY: {
1738     unsigned Opcode = ParentNode->getMachineOpcode();
1739     bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
1740
1741     if (!Sel.getNode())
1742       return false;
1743
1744     SDValue CstOffset = Src.getOperand(0);
1745     if (ParentNode->getValueType(0).isVector())
1746       return false;
1747
1748     // Gather constants values
1749     int SrcIndices[] = {
1750       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
1751       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
1752       TII->getOperandIdx(Opcode, AMDGPU::OpName::src2),
1753       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_X),
1754       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Y),
1755       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Z),
1756       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_W),
1757       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_X),
1758       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Y),
1759       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Z),
1760       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_W)
1761     };
1762     std::vector<unsigned> Consts;
1763     for (unsigned i = 0; i < sizeof(SrcIndices) / sizeof(int); i++) {
1764       int OtherSrcIdx = SrcIndices[i];
1765       int OtherSelIdx = TII->getSelIdx(Opcode, OtherSrcIdx);
1766       if (OtherSrcIdx < 0 || OtherSelIdx < 0)
1767         continue;
1768       if (HasDst) {
1769         OtherSrcIdx--;
1770         OtherSelIdx--;
1771       }
1772       if (RegisterSDNode *Reg =
1773           dyn_cast<RegisterSDNode>(ParentNode->getOperand(OtherSrcIdx))) {
1774         if (Reg->getReg() == AMDGPU::ALU_CONST) {
1775           ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(
1776               ParentNode->getOperand(OtherSelIdx));
1777           Consts.push_back(Cst->getZExtValue());
1778         }
1779       }
1780     }
1781
1782     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(CstOffset);
1783     Consts.push_back(Cst->getZExtValue());
1784     if (!TII->fitsConstReadLimitations(Consts)) {
1785       return false;
1786     }
1787
1788     Sel = CstOffset;
1789     Src = DAG.getRegister(AMDGPU::ALU_CONST, MVT::f32);
1790     return true;
1791   }
1792   case AMDGPU::MOV_IMM_I32:
1793   case AMDGPU::MOV_IMM_F32: {
1794     unsigned ImmReg = AMDGPU::ALU_LITERAL_X;
1795     uint64_t ImmValue = 0;
1796
1797
1798     if (Src.getMachineOpcode() == AMDGPU::MOV_IMM_F32) {
1799       ConstantFPSDNode *FPC = dyn_cast<ConstantFPSDNode>(Src.getOperand(0));
1800       float FloatValue = FPC->getValueAPF().convertToFloat();
1801       if (FloatValue == 0.0) {
1802         ImmReg = AMDGPU::ZERO;
1803       } else if (FloatValue == 0.5) {
1804         ImmReg = AMDGPU::HALF;
1805       } else if (FloatValue == 1.0) {
1806         ImmReg = AMDGPU::ONE;
1807       } else {
1808         ImmValue = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
1809       }
1810     } else {
1811       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src.getOperand(0));
1812       uint64_t Value = C->getZExtValue();
1813       if (Value == 0) {
1814         ImmReg = AMDGPU::ZERO;
1815       } else if (Value == 1) {
1816         ImmReg = AMDGPU::ONE_INT;
1817       } else {
1818         ImmValue = Value;
1819       }
1820     }
1821
1822     // Check that we aren't already using an immediate.
1823     // XXX: It's possible for an instruction to have more than one
1824     // immediate operand, but this is not supported yet.
1825     if (ImmReg == AMDGPU::ALU_LITERAL_X) {
1826       if (!Imm.getNode())
1827         return false;
1828       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Imm);
1829       assert(C);
1830       if (C->getZExtValue())
1831         return false;
1832       Imm = DAG.getTargetConstant(ImmValue, MVT::i32);
1833     }
1834     Src = DAG.getRegister(ImmReg, MVT::i32);
1835     return true;
1836   }
1837   default:
1838     return false;
1839   }
1840 }
1841
1842
1843 /// \brief Fold the instructions after selecting them
1844 SDNode *R600TargetLowering::PostISelFolding(MachineSDNode *Node,
1845                                             SelectionDAG &DAG) const {
1846   const R600InstrInfo *TII =
1847       static_cast<const R600InstrInfo *>(DAG.getTarget().getInstrInfo());
1848   if (!Node->isMachineOpcode())
1849     return Node;
1850   unsigned Opcode = Node->getMachineOpcode();
1851   SDValue FakeOp;
1852
1853   std::vector<SDValue> Ops;
1854   for(SDNode::op_iterator I = Node->op_begin(), E = Node->op_end();
1855               I != E; ++I)
1856           Ops.push_back(*I);
1857
1858   if (Opcode == AMDGPU::DOT_4) {
1859     int OperandIdx[] = {
1860       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_X),
1861       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Y),
1862       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_Z),
1863       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_W),
1864       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_X),
1865       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Y),
1866       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_Z),
1867       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_W)
1868         };
1869     int NegIdx[] = {
1870       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_X),
1871       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_Y),
1872       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_Z),
1873       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg_W),
1874       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_X),
1875       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_Y),
1876       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_Z),
1877       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg_W)
1878     };
1879     int AbsIdx[] = {
1880       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_X),
1881       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_Y),
1882       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_Z),
1883       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs_W),
1884       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_X),
1885       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_Y),
1886       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_Z),
1887       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs_W)
1888     };
1889     for (unsigned i = 0; i < 8; i++) {
1890       if (OperandIdx[i] < 0)
1891         return Node;
1892       SDValue &Src = Ops[OperandIdx[i] - 1];
1893       SDValue &Neg = Ops[NegIdx[i] - 1];
1894       SDValue &Abs = Ops[AbsIdx[i] - 1];
1895       bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
1896       int SelIdx = TII->getSelIdx(Opcode, OperandIdx[i]);
1897       if (HasDst)
1898         SelIdx--;
1899       SDValue &Sel = (SelIdx > -1) ? Ops[SelIdx] : FakeOp;
1900       if (FoldOperand(Node, i, Src, Neg, Abs, Sel, FakeOp, DAG))
1901         return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
1902     }
1903   } else if (Opcode == AMDGPU::REG_SEQUENCE) {
1904     for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2) {
1905       SDValue &Src = Ops[i];
1906       if (FoldOperand(Node, i, Src, FakeOp, FakeOp, FakeOp, FakeOp, DAG))
1907         return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
1908     }
1909   } else if (Opcode == AMDGPU::CLAMP_R600) {
1910     SDValue Src = Node->getOperand(0);
1911     if (!Src.isMachineOpcode() ||
1912         !TII->hasInstrModifiers(Src.getMachineOpcode()))
1913       return Node;
1914     int ClampIdx = TII->getOperandIdx(Src.getMachineOpcode(),
1915         AMDGPU::OpName::clamp);
1916     if (ClampIdx < 0)
1917       return Node;
1918     std::vector<SDValue> Ops;
1919     unsigned NumOp = Src.getNumOperands();
1920     for(unsigned i = 0; i < NumOp; ++i)
1921           Ops.push_back(Src.getOperand(i));
1922     Ops[ClampIdx - 1] = DAG.getTargetConstant(1, MVT::i32);
1923     return DAG.getMachineNode(Src.getMachineOpcode(), SDLoc(Node),
1924         Node->getVTList(), Ops);
1925   } else {
1926     if (!TII->hasInstrModifiers(Opcode))
1927       return Node;
1928     int OperandIdx[] = {
1929       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0),
1930       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1),
1931       TII->getOperandIdx(Opcode, AMDGPU::OpName::src2)
1932     };
1933     int NegIdx[] = {
1934       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_neg),
1935       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_neg),
1936       TII->getOperandIdx(Opcode, AMDGPU::OpName::src2_neg)
1937     };
1938     int AbsIdx[] = {
1939       TII->getOperandIdx(Opcode, AMDGPU::OpName::src0_abs),
1940       TII->getOperandIdx(Opcode, AMDGPU::OpName::src1_abs),
1941       -1
1942     };
1943     for (unsigned i = 0; i < 3; i++) {
1944       if (OperandIdx[i] < 0)
1945         return Node;
1946       SDValue &Src = Ops[OperandIdx[i] - 1];
1947       SDValue &Neg = Ops[NegIdx[i] - 1];
1948       SDValue FakeAbs;
1949       SDValue &Abs = (AbsIdx[i] > -1) ? Ops[AbsIdx[i] - 1] : FakeAbs;
1950       bool HasDst = TII->getOperandIdx(Opcode, AMDGPU::OpName::dst) > -1;
1951       int SelIdx = TII->getSelIdx(Opcode, OperandIdx[i]);
1952       int ImmIdx = TII->getOperandIdx(Opcode, AMDGPU::OpName::literal);
1953       if (HasDst) {
1954         SelIdx--;
1955         ImmIdx--;
1956       }
1957       SDValue &Sel = (SelIdx > -1) ? Ops[SelIdx] : FakeOp;
1958       SDValue &Imm = Ops[ImmIdx];
1959       if (FoldOperand(Node, i, Src, Neg, Abs, Sel, Imm, DAG))
1960         return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
1961     }
1962   }
1963
1964   return Node;
1965 }