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