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