summaryrefslogtreecommitdiff
path: root/lib/Target/R600/R600ISelLowering.cpp
blob: 51b20ba1d0765337d2201cd7928d29a658fd8bee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
//===-- R600ISelLowering.cpp - R600 DAG Lowering Implementation -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// \brief Custom DAG lowering for R600
//
//===----------------------------------------------------------------------===//

#include "R600ISelLowering.h"
#include "R600Defines.h"
#include "R600InstrInfo.h"
#include "R600MachineFunctionInfo.h"
#include "llvm/Argument.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"

using namespace llvm;

R600TargetLowering::R600TargetLowering(TargetMachine &TM) :
    AMDGPUTargetLowering(TM),
    TII(static_cast<const R600InstrInfo*>(TM.getInstrInfo())) {
  setOperationAction(ISD::MUL, MVT::i64, Expand);
  addRegisterClass(MVT::v4f32, &AMDGPU::R600_Reg128RegClass);
  addRegisterClass(MVT::f32, &AMDGPU::R600_Reg32RegClass);
  addRegisterClass(MVT::v4i32, &AMDGPU::R600_Reg128RegClass);
  addRegisterClass(MVT::i32, &AMDGPU::R600_Reg32RegClass);
  addRegisterClass(MVT::i1, &AMDGPU::R600_Reg1RegClass);
  computeRegisterProperties();

  setOperationAction(ISD::FADD, MVT::v4f32, Expand);
  setOperationAction(ISD::FMUL, MVT::v4f32, Expand);
  setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
  setOperationAction(ISD::FSUB, MVT::v4f32, Expand);

  setOperationAction(ISD::ADD,  MVT::v4i32, Expand);
  setOperationAction(ISD::AND,  MVT::v4i32, Expand);

  setOperationAction(ISD::CopyToReg, MVT::Other, Custom);

  setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Expand);
  setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Expand);
  setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Expand);
  setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Expand);
  setOperationAction(ISD::UDIV, MVT::v4i32, Expand);
  setOperationAction(ISD::UREM, MVT::v4i32, Expand);
  setOperationAction(ISD::SETCC, MVT::v4i32, Expand);

//  setOperationAction(ISD::BR_CC, MVT::i32, Custom);
//  setOperationAction(ISD::BR_CC, MVT::f32, Custom);

  setOperationAction(ISD::BR_CC, MVT::i32, Expand);
  setOperationAction(ISD::BR_CC, MVT::f32, Expand);
//  setOperationAction(ISD::BR_CC, MVT::i1, Expand);
//  setOperationAction(ISD::BR_CC, MVT::Other, Expand);

  setOperationAction(ISD::FSUB, MVT::f32, Expand);

  setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i1, Custom);
  setOperationAction(ISD::FPOW, MVT::f32, Custom);

  setOperationAction(ISD::ROTL, MVT::i32, Custom);

  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);

  setOperationAction(ISD::SETCC, MVT::i32, Custom);
  setOperationAction(ISD::SETCC, MVT::f32, Custom);
  setOperationAction(ISD::SETCC, MVT::i1, Custom);
  setOperationAction(ISD::FP_TO_UINT, MVT::i1, Custom);

  setOperationAction(ISD::SELECT, MVT::i32, Custom);
  setOperationAction(ISD::SELECT, MVT::f32, Custom);

  // Legalize loads and stores to the private address space.
  setOperationAction(ISD::LOAD, MVT::i32, Custom);
  setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
  setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
  setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
  setLoadExtAction(ISD::EXTLOAD, MVT::i8, Custom);
  setLoadExtAction(ISD::ZEXTLOAD, MVT::i8, Custom);
  setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i8, Custom);
  setOperationAction(ISD::STORE, MVT::i8, Custom);
  setOperationAction(ISD::STORE, MVT::i32, Custom);
  setOperationAction(ISD::STORE, MVT::v2i32, Custom);
  setOperationAction(ISD::STORE, MVT::v4i32, Custom);

  setOperationAction(ISD::LOAD, MVT::i32, Custom);
  setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
  setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
  setOperationAction(ISD::UNDEF, MVT::f32, Expand);

  setTargetDAGCombine(ISD::FP_ROUND);
  setTargetDAGCombine(ISD::FP_TO_SINT);
  setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
  setTargetDAGCombine(ISD::SELECT_CC);

  setSchedulingPreference(Sched::VLIW);
}

MachineBasicBlock * R600TargetLowering::EmitInstrWithCustomInserter(
    MachineInstr * MI, MachineBasicBlock * BB) const {
  MachineFunction * MF = BB->getParent();
  MachineRegisterInfo &MRI = MF->getRegInfo();
  MachineBasicBlock::iterator I = *MI;

  switch (MI->getOpcode()) {
  default: return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
  case AMDGPU::SHADER_TYPE: break;
  case AMDGPU::CLAMP_R600: {
    MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
                                                   AMDGPU::MOV,
                                                   MI->getOperand(0).getReg(),
                                                   MI->getOperand(1).getReg());
    TII->addFlag(NewMI, 0, MO_FLAG_CLAMP);
    break;
  }

  case AMDGPU::FABS_R600: {
    MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
                                                    AMDGPU::MOV,
                                                    MI->getOperand(0).getReg(),
                                                    MI->getOperand(1).getReg());
    TII->addFlag(NewMI, 0, MO_FLAG_ABS);
    break;
  }

  case AMDGPU::FNEG_R600: {
    MachineInstr *NewMI = TII->buildDefaultInstruction(*BB, I,
                                                    AMDGPU::MOV,
                                                    MI->getOperand(0).getReg(),
                                                    MI->getOperand(1).getReg());
    TII->addFlag(NewMI, 0, MO_FLAG_NEG);
    break;
  }

  case AMDGPU::R600_ZEXT: {
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::COPY))
            .addOperand(MI->getOperand(0))
            .addOperand(MI->getOperand(1));
    break;
  }

  case AMDGPU::MASK_WRITE: {
    unsigned maskedRegister = MI->getOperand(0).getReg();
    assert(TargetRegisterInfo::isVirtualRegister(maskedRegister));
    MachineInstr * defInstr = MRI.getVRegDef(maskedRegister);
    TII->addFlag(defInstr, 0, MO_FLAG_MASK);
    break;
  }

  case AMDGPU::MOV_IMM_F32:
    TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
                     MI->getOperand(1).getFPImm()->getValueAPF()
                         .bitcastToAPInt().getZExtValue());
    break;
  case AMDGPU::MOV_IMM_I32:
    TII->buildMovImm(*BB, I, MI->getOperand(0).getReg(),
                     MI->getOperand(1).getImm());
    break;
  case AMDGPU::PRED_SET: {
    // Find the correct insertion point -  Occasionally the instruction
    // selector will insert instructions between the PRED_SET instruction
    // and the control flow instruction.  This usually happens when
    // compiling code like this:
    //
    // int a = 0
    // if (cond) {
    //   a = 1;
    // }
    //
    // and the resulting MachineInstr's look something like this:
    //
    // Pred0 = PRED_SET
    // a = MOV ZERO
    // R600_IF Pred0
    // a = MOV ONE
    // R600_ENDIF Pred0
    //

    unsigned DstReg = MI->getOperand(0).getReg();
    unsigned NumUses = 0;
    for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(DstReg),
                                           UE = MachineRegisterInfo::use_end();
                                           UI != UE; ++UI, ++NumUses) {
      MachineInstr *Use = &(*UI);
      MachineBasicBlock::iterator InsertPoint = Use;
      MachineInstr *PredSet;

      if (NumUses < 1) {
        MI->removeFromParent();
        PredSet = MI;
      } else {
        // PRED_SET can only have one use, so if there is more than one use, we
        // need to clone the instruction.
        PredSet = MF->CloneMachineInstr(MI);
        const TargetRegisterClass *DstRegClass =
                                    MRI.getRegClass(MI->getOperand(0).getReg());
        unsigned NewDst = MRI.createVirtualRegister(DstRegClass);
        PredSet->getOperand(0).setReg(NewDst);
        UI.getOperand().setReg(NewDst);
      }
      BB->insert(InsertPoint, PredSet);
    }

    return BB;
  }

  case AMDGPU::R600_IF: {
    // Remove all copies that have been inserted between the R600_IF and BRANCH
    // instructions.

    MachineBasicBlock::iterator PredSetI = --I;
    assert(PredSetI->getOpcode() == AMDGPU::PRED_SET);

    ++I; // Points to the IF instruction
    ++I; // Points to instruction after IF
    while (!I->isTerminator()) {
      MachineInstr &Copy = *I;
      ++I;
      // Don't move copies that copy the output of R600_IF
      if (Copy.getOpcode() == AMDGPU::COPY &&
          Copy.getOperand(1).getReg() == MI->getOperand(0).getReg()) {
        continue;
      }
      Copy.removeFromParent();
      BB->insert(PredSetI, &Copy);
    }
    return BB;
  }

  case AMDGPU::RAT_WRITE_CACHELESS_32_eg:
  case AMDGPU::RAT_WRITE_CACHELESS_128_eg: {
    unsigned EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN) ? 1 : 0;

    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
            .addOperand(MI->getOperand(0))
            .addOperand(MI->getOperand(1))
            .addImm(EOP); // Set End of program bit
    break;
  }

  case AMDGPU::TXD: {
    unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
    unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);

    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
            .addOperand(MI->getOperand(3))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6));
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
            .addOperand(MI->getOperand(2))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6));
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_G))
            .addOperand(MI->getOperand(0))
            .addOperand(MI->getOperand(1))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6))
            .addReg(T0, RegState::Implicit)
            .addReg(T1, RegState::Implicit);
    break;
  }

  case AMDGPU::TXD_SHADOW: {
    unsigned T0 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
    unsigned T1 = MRI.createVirtualRegister(&AMDGPU::R600_Reg128RegClass);

    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_H), T0)
            .addOperand(MI->getOperand(3))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6));
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SET_GRADIENTS_V), T1)
            .addOperand(MI->getOperand(2))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6));
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::TEX_SAMPLE_C_G))
            .addOperand(MI->getOperand(0))
            .addOperand(MI->getOperand(1))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6))
            .addReg(T0, RegState::Implicit)
            .addReg(T1, RegState::Implicit);
    break;
  }

  case AMDGPU::BRANCH:
      BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
              .addOperand(MI->getOperand(0));
//              .addReg(0);
      break;

  case AMDGPU::BRANCH_COND_f32: {
    MachineInstr *NewMI =
      BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
              AMDGPU::PREDICATE_BIT)
              .addOperand(MI->getOperand(1))
              .addImm(OPCODE_IS_NOT_ZERO)
              .addImm(0); // Flags
    TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
            .addOperand(MI->getOperand(0))
            .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
    break;
  }

  case AMDGPU::BRANCH_COND_i32: {
    MachineInstr *NewMI =
      BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::PRED_X),
            AMDGPU::PREDICATE_BIT)
            .addOperand(MI->getOperand(1))
            .addImm(OPCODE_IS_NOT_ZERO_INT)
            .addImm(0); // Flags
    TII->addFlag(NewMI, 0, MO_FLAG_PUSH);
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(AMDGPU::JUMP))
           .addOperand(MI->getOperand(0))
            .addReg(AMDGPU::PREDICATE_BIT, RegState::Kill);
    break;
  }

  case AMDGPU::EG_ExportSwz:
  case AMDGPU::R600_ExportSwz: {
    // Instruction is left unmodified if its not the last one of its type
    bool isLastInstructionOfItsType = true;
    unsigned InstExportType = MI->getOperand(1).getImm();
    for (MachineBasicBlock::iterator NextExportInst = llvm::next(I),
         EndBlock = BB->end(); NextExportInst != EndBlock;
         NextExportInst = llvm::next(NextExportInst)) {
      if (NextExportInst->getOpcode() == AMDGPU::EG_ExportSwz ||
          NextExportInst->getOpcode() == AMDGPU::R600_ExportSwz) {
        unsigned CurrentInstExportType = NextExportInst->getOperand(1)
            .getImm();
        if (CurrentInstExportType == InstExportType) {
          isLastInstructionOfItsType = false;
          break;
        }
      }
    }
    bool EOP = (llvm::next(I)->getOpcode() == AMDGPU::RETURN)? 1 : 0;
    if (!EOP && !isLastInstructionOfItsType)
      return BB;
    unsigned CfInst = (MI->getOpcode() == AMDGPU::EG_ExportSwz)? 84 : 40;
    BuildMI(*BB, I, BB->findDebugLoc(I), TII->get(MI->getOpcode()))
            .addOperand(MI->getOperand(0))
            .addOperand(MI->getOperand(1))
            .addOperand(MI->getOperand(2))
            .addOperand(MI->getOperand(3))
            .addOperand(MI->getOperand(4))
            .addOperand(MI->getOperand(5))
            .addOperand(MI->getOperand(6))
            .addImm(CfInst)
            .addImm(EOP);
    break;
  }
  }

  MI->eraseFromParent();
  return BB;
}

//===----------------------------------------------------------------------===//
// Custom DAG Lowering Operations
//===----------------------------------------------------------------------===//

using namespace llvm::Intrinsic;
using namespace llvm::AMDGPUIntrinsic;

static SDValue
InsertScalarToRegisterExport(SelectionDAG &DAG, DebugLoc DL, SDNode **ExportMap,
    unsigned Slot, unsigned Channel, unsigned Inst, unsigned Type,
    SDValue Scalar, SDValue Chain) {
  if (!ExportMap[Slot]) {
    SDValue Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT,
      DL, MVT::v4f32,
      DAG.getUNDEF(MVT::v4f32),
      Scalar,
      DAG.getConstant(Channel, MVT::i32));

    unsigned Mask = 1 << Channel;

    const SDValue Ops[] = {Chain, Vector, DAG.getConstant(Inst, MVT::i32),
        DAG.getConstant(Type, MVT::i32), DAG.getConstant(Slot, MVT::i32),
        DAG.getConstant(Mask, MVT::i32)};

    SDValue Res =  DAG.getNode(
        AMDGPUISD::EXPORT,
        DL,
        MVT::Other,
        Ops, 6);
     ExportMap[Slot] = Res.getNode();
     return Res;
  }

  SDNode *ExportInstruction = (SDNode *) ExportMap[Slot] ;
  SDValue PreviousVector = ExportInstruction->getOperand(1);
  SDValue Vector = DAG.getNode(ISD::INSERT_VECTOR_ELT,
      DL, MVT::v4f32,
      PreviousVector,
      Scalar,
      DAG.getConstant(Channel, MVT::i32));

  unsigned Mask = dyn_cast<ConstantSDNode>(ExportInstruction->getOperand(5))
      ->getZExtValue();
  Mask |= (1 << Channel);

  const SDValue Ops[] = {ExportInstruction->getOperand(0), Vector,
      DAG.getConstant(Inst, MVT::i32),
      DAG.getConstant(Type, MVT::i32),
      DAG.getConstant(Slot, MVT::i32),
      DAG.getConstant(Mask, MVT::i32)};

  DAG.UpdateNodeOperands(ExportInstruction,
      Ops, 6);

  return Chain;

}

SDValue R600TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  switch (Op.getOpcode()) {
  default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
  case ISD::BR_CC: return LowerBR_CC(Op, DAG);
  case ISD::BRCOND: return LowerBR_COND(Op, DAG);
  case ISD::CopyToReg: return LowerCopyToReg(Op, DAG);
  case ISD::ROTL: return LowerROTL(Op, DAG);
  case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
  case ISD::SELECT: return LowerSELECT(Op, DAG);
  case ISD::SETCC: return LowerSETCC(Op, DAG);
  case ISD::STORE: return LowerSTORE(Op, DAG);
  case ISD::LOAD: return LowerLOAD(Op, DAG);
  case ISD::FPOW: return LowerFPOW(Op, DAG);
  case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
  case ISD::INTRINSIC_VOID: {
    SDValue Chain = Op.getOperand(0);
    unsigned IntrinsicID =
                         cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
    switch (IntrinsicID) {
    case AMDGPUIntrinsic::AMDGPU_store_output: {
      MachineFunction &MF = DAG.getMachineFunction();
      MachineRegisterInfo &MRI = MF.getRegInfo();
      int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
      unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
      if (!MRI.isLiveOut(Reg)) {
        MRI.addLiveOut(Reg);
      }
      return DAG.getCopyToReg(Chain, Op.getDebugLoc(), Reg, Op.getOperand(2));
    }
    case AMDGPUIntrinsic::R600_store_pixel_color: {
      MachineFunction &MF = DAG.getMachineFunction();
      R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
      int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();

      SDNode **OutputsMap = MFI->Outputs;
      return InsertScalarToRegisterExport(DAG, Op.getDebugLoc(), OutputsMap,
          RegIndex / 4, RegIndex % 4, 0, 0, Op.getOperand(2),
          Chain);

    }

    case AMDGPUIntrinsic::R600_endcf: {
			return DAG.getNode(AMDGPUISD::ENDIF, Op.getDebugLoc(), MVT::Other, Chain);
    }

    // default for switch(IntrinsicID)
    default: break;
    }
    // break out of case ISD::INTRINSIC_VOID in switch(Op.getOpcode())
    break;
  }

  case ISD::INTRINSIC_W_CHAIN: {
    SDValue Chain = Op.getOperand(0);
    DebugLoc DL = Op.getDebugLoc();
    unsigned IntrinsicID =
      cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
    switch (IntrinsicID) {
    default: break;
    case AMDGPUIntrinsic::R600_ifbreak: {
      SDValue Cond = Op.getOperand(2);
      SDValue PredSet;
      if (Cond.getOpcode() == ISD::SETCC) {
        bool IsInteger = Cond.getOperand(0).getValueType().isInteger();
        unsigned CondCode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
        PredSet = DAG.getNode(AMDGPUISD::PRED_SET, DL, MVT::i1,
                                      DAG.getTargetConstant(CondCode, MVT::i32),
                                      DAG.getTargetConstant(IsInteger, MVT::i1),
                                      Cond.getOperand(0),
                                      Cond.getOperand(1));
      } else {
        ISD::CondCode CondCode = ISD::SETNE;
        if (Cond.getOpcode() == ISD::XOR) {
          ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
          if (C && C->isAllOnesValue()) {
            CondCode = ISD::getSetCCInverse(CondCode, true);
            Cond = Cond.getOperand(0);
          }
        }
        PredSet = DAG.getNode(AMDGPUISD::PRED_SET, DL, MVT::i1,
                              DAG.getTargetConstant(CondCode, MVT::i32),
                              DAG.getTargetConstant(-1, MVT::i1),
                              DAG.getZExtOrTrunc(Cond, DL, MVT::i32),
                              DAG.getConstant(0, MVT::i32));

      }

      SDValue Out[2];
      Out[0] = DAG.getNode(AMDGPUISD::IFBREAK, DL, MVT::i1, Chain, PredSet);
      Out[1] = Chain;
      return DAG.getMergeValues(Out, 2, DL);
    }
    case AMDGPUIntrinsic::R600_elsebreak: {
      SDValue Out[2];
      Out[0] = Op.getOperand(2);
      Out[1] = DAG.getNode(AMDGPUISD::ELSEBREAK, DL, MVT::Other, Chain);
      return DAG.getMergeValues(Out, 2, DL);
    }
		}
    break;
  }
  case ISD::INTRINSIC_WO_CHAIN: {
    unsigned IntrinsicID =
                         cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    EVT VT = Op.getValueType();
    DebugLoc DL = Op.getDebugLoc();
    switch(IntrinsicID) {
    default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
    case AMDGPUIntrinsic::R600_load_input: {
      int64_t RegIndex = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
      unsigned Reg = AMDGPU::R600_TReg32RegClass.getRegister(RegIndex);
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass, Reg, VT);
    }

    case AMDGPUIntrinsic::R600_interp_input: {
      int slot = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
      int ijb = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
      MachineSDNode *interp;
      if (ijb < 0) {
        interp = DAG.getMachineNode(AMDGPU::INTERP_VEC_LOAD, DL,
            MVT::v4f32, DAG.getTargetConstant(slot / 4 , MVT::i32));
        return DAG.getTargetExtractSubreg(
            TII->getRegisterInfo().getSubRegFromChannel(slot % 4),
            DL, MVT::f32, SDValue(interp, 0));
      }

      if (slot % 4 < 2)
        interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_XY, DL,
            MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
            CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
            CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));
      else
        interp = DAG.getMachineNode(AMDGPU::INTERP_PAIR_ZW, DL,
            MVT::f32, MVT::f32, DAG.getTargetConstant(slot / 4 , MVT::i32),
            CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb + 1), MVT::f32),
            CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                AMDGPU::R600_TReg32RegClass.getRegister(2 * ijb), MVT::f32));

      return SDValue(interp, slot % 2);
    }

    case r600_read_ngroups_x:
      return LowerImplicitParameter(DAG, VT, DL, 0);
    case r600_read_ngroups_y:
      return LowerImplicitParameter(DAG, VT, DL, 1);
    case r600_read_ngroups_z:
      return LowerImplicitParameter(DAG, VT, DL, 2);
    case r600_read_global_size_x:
      return LowerImplicitParameter(DAG, VT, DL, 3);
    case r600_read_global_size_y:
      return LowerImplicitParameter(DAG, VT, DL, 4);
    case r600_read_global_size_z:
      return LowerImplicitParameter(DAG, VT, DL, 5);
    case r600_read_local_size_x:
      return LowerImplicitParameter(DAG, VT, DL, 6);
    case r600_read_local_size_y:
      return LowerImplicitParameter(DAG, VT, DL, 7);
    case r600_read_local_size_z:
      return LowerImplicitParameter(DAG, VT, DL, 8);

    case r600_read_tgid_x:
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                                  AMDGPU::T1_X, VT);
    case r600_read_tgid_y:
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                                  AMDGPU::T1_Y, VT);
    case r600_read_tgid_z:
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                                  AMDGPU::T1_Z, VT);
    case r600_read_tidig_x:
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                                  AMDGPU::T0_X, VT);
    case r600_read_tidig_y:
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                                  AMDGPU::T0_Y, VT);
    case r600_read_tidig_z:
      return CreateLiveInRegister(DAG, &AMDGPU::R600_TReg32RegClass,
                                  AMDGPU::T0_Z, VT);
    }
    // break out of case ISD::INTRINSIC_WO_CHAIN in switch(Op.getOpcode())
    break;
  }
  } // end switch(Op.getOpcode())
  return SDValue();
}

void R600TargetLowering::ReplaceNodeResults(SDNode *N,
                                            SmallVectorImpl<SDValue> &Results,
                                            SelectionDAG &DAG) const {
  switch (N->getOpcode()) {
  default: return;
  case ISD::FP_TO_UINT: Results.push_back(LowerFPTOUINT(N->getOperand(0), DAG));
    return;
  case ISD::LOAD: {
    SDNode *Node = LowerLOAD(SDValue(N, 0), DAG).getNode();
    Results.push_back(SDValue(Node, 0));
    Results.push_back(SDValue(Node, 1));
    // XXX: LLVM seems not to replace Chain Value inside CustomWidenLowerNode
    // function
    DAG.ReplaceAllUsesOfValueWith(SDValue(N,1), SDValue(Node, 1));
    return;
  }
  case ISD::STORE:
    SDNode *Node = LowerSTORE(SDValue(N, 0), DAG).getNode();
    Results.push_back(SDValue(Node, 0));
    return;
  }
}

SDValue R600TargetLowering::LowerFPTOUINT(SDValue Op, SelectionDAG &DAG) const {
  return DAG.getNode(
      ISD::SETCC,
      Op.getDebugLoc(),
      MVT::i1,
      Op, DAG.getConstantFP(0.0f, MVT::f32),
      DAG.getCondCode(ISD::SETNE)
      );
}

SDValue R600TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
  SDValue Chain = Op.getOperand(0);
  SDValue CC = Op.getOperand(1);
  SDValue LHS   = Op.getOperand(2);
  SDValue RHS   = Op.getOperand(3);
  SDValue JumpT  = Op.getOperand(4);
  SDValue CmpValue;
  SDValue Result;

  if (LHS.getValueType() == MVT::i32) {
    CmpValue = DAG.getNode(
        ISD::SELECT_CC,
        Op.getDebugLoc(),
        MVT::i32,
        LHS, RHS,
        DAG.getConstant(-1, MVT::i32),
        DAG.getConstant(0, MVT::i32),
        CC);
  } else if (LHS.getValueType() == MVT::f32) {
    CmpValue = DAG.getNode(
        ISD::SELECT_CC,
        Op.getDebugLoc(),
        MVT::f32,
        LHS, RHS,
        DAG.getConstantFP(1.0f, MVT::f32),
        DAG.getConstantFP(0.0f, MVT::f32),
        CC);
  } else {
    assert(0 && "Not valid type for br_cc");
  }
  Result = DAG.getNode(
      AMDGPUISD::BRANCH_COND,
      CmpValue.getDebugLoc(),
      MVT::Other, Chain,
      JumpT, CmpValue);
  return Result;
}

SDValue R600TargetLowering::LowerBR_COND(SDValue Op, SelectionDAG &DAG) const {
  SDValue Chain = Op.getOperand(0);
  SDValue Cond = Op.getOperand(1);
  SDValue BB = Op.getOperand(2);
  DebugLoc DL = Op.getDebugLoc();
  SDValue CFIntrinsic;
  bool ReversePred = false;

  // If we have a SETCC opcode it means we are reversing the predicate
  // created by the control flow intrinsic.
  // XXX: We should double check to make sure this is always the case.
  if (Cond.getOpcode() == ISD::SETCC) {
    ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
    if (!C || !C->isAllOnesValue() || CCOpcode != ISD::SETNE) {
      assert("Cannot lower brcond (setcc)");
      return SDValue();
    }
    ReversePred = true;
    CFIntrinsic = Cond.getOperand(0);
  } else {
    CFIntrinsic = Cond;
  }

  if (CFIntrinsic.getOpcode() != ISD::INTRINSIC_W_CHAIN) {
    return SDValue();
  }

  unsigned IntrinsicID =
                cast<ConstantSDNode>(CFIntrinsic.getOperand(1))->getZExtValue();
  SDValue Ret;
  Cond = CFIntrinsic.getOperand(2);
  switch (IntrinsicID) {
  default: return SDValue();
  case AMDGPUIntrinsic::R600_if: {
    if (Cond.getOpcode() == ISD::SETCC) {
      SDValue CC = Cond.getOperand(2);
      ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
      bool IsInteger = Cond.getOperand(0).getValueType().isInteger();

      if (ReversePred) {
        CCOpcode = ISD::getSetCCInverse(CCOpcode, IsInteger);
      }

      unsigned CondCode = CCOpcode;

      Cond = DAG.getNode(AMDGPUISD::PRED_SET, DL, MVT::i1,
                           DAG.getTargetConstant(CCOpcode, MVT::i32),
                           DAG.getTargetConstant(IsInteger, MVT::i1),
                           Cond.getOperand(0),  // LHS
                           Cond.getOperand(1)); // RHS
    } else {
      ISD::CondCode CCOpcode = ISD::SETNE;
      if (ReversePred) {
        CCOpcode = ISD::getSetCCInverse(CCOpcode, true);
      }
      Cond = DAG.getNode(AMDGPUISD::PRED_SET, DL, MVT::i1,
                         DAG.getTargetConstant(CCOpcode, MVT::i32),
                         DAG.getTargetConstant(1, MVT::i1),
                         DAG.getZExtOrTrunc(Cond, DL, MVT::i32),
                         DAG.getConstant(0, MVT::i32));
    }

    Cond = DAG.getNode(AMDGPUISD::IF, DL, DAG.getVTList(MVT::i1, MVT::Other),
                       CFIntrinsic.getOperand(0), Cond, BB);
    DAG.ReplaceAllUsesWith(CFIntrinsic.getNode(), Cond.getNode());
    return Chain;
    break;
  }
  case AMDGPUIntrinsic::R600_else: {
    Ret = DAG.getNode(AMDGPUISD::ELSE, DL, MVT::Other, Chain, Cond, BB);
  DAG.ReplaceAllUsesOfValueWith(SDValue(CFIntrinsic.getNode(), 1),
                                  CFIntrinsic.getOperand(0));
  DAG.ReplaceAllUsesOfValueWith(SDValue(CFIntrinsic.getNode(), 0), Cond);
    break;
  }

  case AMDGPUIntrinsic::R600_loop: {
    Ret = DAG.getNode(AMDGPUISD::LOOP, DL, MVT::Other, Chain, BB);
  DAG.ReplaceAllUsesOfValueWith(SDValue(CFIntrinsic.getNode(), 1),
                                  CFIntrinsic.getOperand(0));
  DAG.ReplaceAllUsesOfValueWith(SDValue(CFIntrinsic.getNode(), 0), Cond);
    break;
  }

  }


  return Ret;
}

///
/// We need to do some lowering here to handle the cases where an i1 value
/// is used as a predicate for branching and also extended to an i32 value
/// and used by the ALU instructions.
SDValue R600TargetLowering::LowerCopyToReg(SDValue Op,
                                           SelectionDAG &DAG) const {
  SDValue Value = Op.getOperand(2);
  SDValue NewValue;
  DebugLoc DL = Op.getDebugLoc();

  if (Value.getValueType() != MVT::i1) {
    return SDValue();
  }

  switch (Value.getOpcode()) {
  default: return SDValue();
  case ISD::Constant: {
    ConstantSDNode *C = cast<ConstantSDNode>(Value);
    NewValue = DAG.getConstant(C->getZExtValue(), MVT::i32);
    break;
  }

  case ISD::SETCC: {
    NewValue = LowerSETCC(Value, DAG);

#if 0
    SDValue CC = SetCC.getOperand(2);
    ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();

    NewValue = DAG.getSelectCC(DL, SetCC.getOperand(0),
                                   SetCC.getOperand(1),
                                   DAG.getConstant(-1, MVT::i32),
                                   DAG.getConstant(0, MVT::i32),
                                   CCOpcode);
#endif
    break;
  }

  case AMDGPUISD::PRED_SET: {
    ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value.getOperand(0));
    ISD::CondCode CC = (ISD::CondCode)C->getZExtValue();
    SDValue SetCC = DAG.getSetCC(DL, MVT::i1, Value.getOperand(2),
                                              Value.getOperand(3),
                                              CC);
    if (SetCC.getOpcode() == ISD::SETCC) {
      NewValue = LowerSETCC(SetCC, DAG);
    } else {
      NewValue = SetCC;
    }

    break;
  }


  }
  MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  MRI.setRegClass(cast<RegisterSDNode>(Op.getOperand(1))->getReg(),
                  &AMDGPU::R600_TReg32RegClass);

  return DAG.getNode(ISD::CopyToReg, DL, Op.getValueType(),
                     Op.getOperand(0), Op.getOperand(1), NewValue);
}

SDValue R600TargetLowering::LowerImplicitParameter(SelectionDAG &DAG, EVT VT,
                                                   DebugLoc DL,
                                                   unsigned DwordOffset) const {
  unsigned ByteOffset = DwordOffset * 4;
  PointerType * PtrType = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
                                      AMDGPUAS::PARAM_I_ADDRESS);

  // We shouldn't be using an offset wider than 16-bits for implicit parameters.
  assert(isInt<16>(ByteOffset));

  return DAG.getLoad(VT, DL, DAG.getEntryNode(),
                     DAG.getConstant(ByteOffset, MVT::i32), // PTR
                     MachinePointerInfo(ConstantPointerNull::get(PtrType)),
                     false, false, false, 0);
}

SDValue R600TargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {

  MachineFunction &MF = DAG.getMachineFunction();
  const AMDGPUFrameLowering *TFL =
   static_cast<const AMDGPUFrameLowering*>(getTargetMachine().getFrameLowering());

  FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Op);
  assert(FIN);

  unsigned FrameIndex = FIN->getIndex();
  unsigned Offset = TFL->getFrameIndexOffset(MF, FrameIndex);
  return DAG.getConstant(Offset * 4 * TFL->getStackWidth(MF), MVT::i32);
}

SDValue R600TargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
  DebugLoc DL = Op.getDebugLoc();
  EVT VT = Op.getValueType();

  return DAG.getNode(AMDGPUISD::BITALIGN, DL, VT,
                     Op.getOperand(0),
                     Op.getOperand(0),
                     DAG.getNode(ISD::SUB, DL, VT,
                                 DAG.getConstant(32, MVT::i32),
                                 Op.getOperand(1)));
}

bool R600TargetLowering::isZero(SDValue Op) const {
  if(ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
    return Cst->isNullValue();
  } else if(ConstantFPSDNode *CstFP = dyn_cast<ConstantFPSDNode>(Op)){
    return CstFP->isZero();
  } else {
    return false;
  }
}

SDValue R600TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
  DebugLoc DL = Op.getDebugLoc();
  EVT VT = Op.getValueType();

  SDValue LHS = Op.getOperand(0);
  SDValue RHS = Op.getOperand(1);
  SDValue True = Op.getOperand(2);
  SDValue False = Op.getOperand(3);
  SDValue CC = Op.getOperand(4);
  SDValue Temp;

  // LHS and RHS are guaranteed to be the same value type
  EVT CompareVT = LHS.getValueType();

  // Check if we can lower this to a native operation.

  // Try to lower to a CND* instruction:
  // CND* instructions requires RHS to be zero.  Some SELECT_CC nodes that
  // can be lowered to CND* instructions can also be lowered to SET*
  // instructions.  CND* instructions are cheaper, because they dont't
  // require additional instructions to convert their result to the correct
  // value type, so this check should be first.
  if (isZero(LHS) || isZero(RHS)) {
    SDValue Cond = (isZero(LHS) ? RHS : LHS);
    SDValue Zero = (isZero(LHS) ? LHS : RHS);
    ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
    if (CompareVT != VT) {
      // Bitcast True / False to the correct types.  This will end up being
      // a nop, but it allows us to define only a single pattern in the
      // .TD files for each CND* instruction rather than having to have
      // one pattern for integer True/False and one for fp True/False
      True = DAG.getNode(ISD::BITCAST, DL, CompareVT, True);
      False = DAG.getNode(ISD::BITCAST, DL, CompareVT, False);
    }
    if (isZero(LHS)) {
      CCOpcode = ISD::getSetCCSwappedOperands(CCOpcode);
    }

    switch (CCOpcode) {
    case ISD::SETONE:
    case ISD::SETUNE:
    case ISD::SETNE:
    case ISD::SETULE:
    case ISD::SETULT:
    case ISD::SETOLE:
    case ISD::SETOLT:
    case ISD::SETLE:
    case ISD::SETLT:
      CCOpcode = ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32);
      Temp = True;
      True = False;
      False = Temp;
      break;
    default:
      break;
    }
    SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
        Cond, Zero,
        True, False,
        DAG.getCondCode(CCOpcode));
    return DAG.getNode(ISD::BITCAST, DL, VT, SelectNode);
  }

  // Try to lower to a SET* instruction:
  //
  // CompareVT == MVT::f32 and VT == MVT::i32 is supported by the hardware,
  // but for the other case where CompareVT != VT, all operands of
  // SELECT_CC to have the same value type, so we need to change True and False
  // to be the same type as LHS and RHS, and then convert the result of the
  // select_cc back to the correct type.

  // Move hardware True/False values to the correct operand.
  if (isHWTrueValue(False) && isHWFalseValue(True)) {
    ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
    std::swap(False, True);
    CC = DAG.getCondCode(ISD::getSetCCInverse(CCOpcode, CompareVT == MVT::i32));
  }

  if (isHWTrueValue(True) && isHWFalseValue(False)) {
    if (CompareVT !=  VT && VT == MVT::f32 && CompareVT == MVT::i32) {
      SDValue Boolean = DAG.getNode(ISD::SELECT_CC, DL, CompareVT,
          LHS, RHS,
          DAG.getConstant(-1, MVT::i32),
          DAG.getConstant(0, MVT::i32),
          CC);
      // Convert integer values of true (-1) and false (0) to fp values of
      // true (1.0f) and false (0.0f).
      SDValue LSB = DAG.getNode(ISD::AND, DL, MVT::i32, Boolean,
                                                DAG.getConstant(1, MVT::i32));
      return DAG.getNode(ISD::UINT_TO_FP, DL, VT, LSB);
    } else {
      // This SELECT_CC is already legal.
      return DAG.getNode(ISD::SELECT_CC, DL, VT, LHS, RHS, True, False, CC);
    }
  }

  // Possible Min/Max pattern
  SDValue MinMax = LowerMinMax(Op, DAG);
  if (MinMax.getNode()) {
    return MinMax;
  }

  // If we make it this for it means we have no native instructions to handle
  // this SELECT_CC, so we must lower it.
  SDValue HWTrue, HWFalse;

  if (CompareVT == MVT::f32) {
    HWTrue = DAG.getConstantFP(1.0f, CompareVT);
    HWFalse = DAG.getConstantFP(0.0f, CompareVT);
  } else if (CompareVT == MVT::i32) {
    HWTrue = DAG.getConstant(-1, CompareVT);
    HWFalse = DAG.getConstant(0, CompareVT);
  }
  else {
    assert(!"Unhandled value type in LowerSELECT_CC");
  }

  // Lower this unsupported SELECT_CC into a combination of two supported
  // SELECT_CC operations.
  SDValue Cond = DAG.getNode(ISD::SELECT_CC, DL, CompareVT, LHS, RHS, HWTrue, HWFalse, CC);

  return DAG.getNode(ISD::SELECT_CC, DL, VT,
      Cond, HWFalse,
      True, False,
      DAG.getCondCode(ISD::SETNE));
}

SDValue R600TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
  return DAG.getNode(ISD::SELECT_CC,
      Op.getDebugLoc(),
      Op.getValueType(),
      Op.getOperand(0),
      DAG.getConstant(0, MVT::i32),
      Op.getOperand(1),
      Op.getOperand(2),
      DAG.getCondCode(ISD::SETNE));
}

SDValue R600TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
  SDValue Cond;
  SDValue LHS = Op.getOperand(0);
  SDValue RHS = Op.getOperand(1);
  SDValue CC  = Op.getOperand(2);
  DebugLoc DL = Op.getDebugLoc();

#if 0
  if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
      cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
      AMDGPUIntrinsic::R600_if) {
    SDValue If = LHS;
    ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
    ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS);
    if (!C || !C->isAllOnesValue() || CCOpcode != ISD::SETNE) {
      return SDValue();
    }
    SDValue IfCond = If->getOperand(2);
    assert(IfCond.getOpcode() == ISD::SETCC);
    ISD::CondCode IfCondCC = cast<CondCodeSDNode>(IfCond.getOperand(2))->get();

    SDValue InverseIfCond = DAG.getSetCC(DL, MVT::i1, IfCond.getOperand(0),
                                         IfCond.getOperand(1),
                                         ISD::getSetCCInverse(IfCondCC, true));

    DAG.ReplaceAllUsesOfValueWith(IfCond, InverseIfCond);
    return If;

  }
#endif

  if (LHS.getValueType() == MVT::i32 ||
      LHS.getValueType() == MVT::i1) {
    Cond = DAG.getNode(
        ISD::SELECT_CC,
        Op.getDebugLoc(),
        LHS.getValueType(),
        LHS, RHS,
        DAG.getConstant(-1, LHS.getValueType()),
        DAG.getConstant(0, LHS.getValueType()),
        CC);
  } else if (LHS.getValueType() == MVT::f32) {
    Cond = DAG.getNode(
        ISD::SELECT_CC,
        Op.getDebugLoc(),
        MVT::f32,
        LHS, RHS,
        DAG.getConstantFP(1.0f, MVT::f32),
        DAG.getConstantFP(0.0f, MVT::f32),
        CC);
    Cond = DAG.getNode(
        ISD::FP_TO_SINT,
        DL,
        MVT::i32,
        Cond);
  } else {
    assert(0 && "Not valid type for set_cc");
  }
  Cond = DAG.getNode(
      ISD::TRUNCATE,
      DL,
      MVT::i1,
      Cond);
  return Cond;
}

/// LLVM generates byte-addresed pointers.  For indirect addressing, we need to
/// convert these pointers to a register index.  Each register holds
/// 16 bytes, (4 x 32bit sub-register), but we need to take into account the
/// \p StackWidth, which tells us how many of the 4 sub-registrers will be used
/// for indirect addressing.
SDValue R600TargetLowering::stackPtrToRegIndex(SDValue Ptr,
                                               unsigned StackWidth,
                                               SelectionDAG &DAG) const {
  unsigned SRLPad;
  switch(StackWidth) {
  case 1:
    SRLPad = 2;
    break;
  case 2:
    SRLPad = 3;
    break;
  case 4:
    SRLPad = 4;
    break;
  default: llvm_unreachable("Invalid stack width");
  }

  return DAG.getNode(ISD::SRL, Ptr.getDebugLoc(), Ptr.getValueType(), Ptr,
                     DAG.getConstant(SRLPad, MVT::i32));
}

void R600TargetLowering::getStackAddress(unsigned StackWidth,
                                         unsigned ElemIdx,
                                         unsigned &Channel,
                                         unsigned &PtrIncr) const {
  switch (StackWidth) {
  default:
  case 1:
    Channel = 0;
    if (ElemIdx > 0) {
      PtrIncr = 1;
    } else {
      PtrIncr = 0;
    }
    break;
  case 2:
    Channel = ElemIdx % 2;
    if (ElemIdx == 2) {
      PtrIncr = 1;
    } else {
      PtrIncr = 0;
    }
    break;
  case 4:
    Channel = ElemIdx;
    PtrIncr = 0;
    break;
  }
}

SDValue R600TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
  DebugLoc DL = Op.getDebugLoc();
  StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
  SDValue Chain = Op.getOperand(0);
  SDValue Value = Op.getOperand(1);
  SDValue Ptr = Op.getOperand(2);

  if (StoreNode->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS &&
      Ptr->getOpcode() != AMDGPUISD::DWORDADDR) {
    // Convert pointer from byte address to dword address.
    Ptr = DAG.getNode(AMDGPUISD::DWORDADDR, DL, Ptr.getValueType(),
                      DAG.getNode(ISD::SRL, DL, Ptr.getValueType(),
                                  Ptr, DAG.getConstant(2, MVT::i32)));

    if (StoreNode->isTruncatingStore() || StoreNode->isIndexed()) {
      assert(!"Truncated and indexed stores not supported yet");
    } else {
      Chain = DAG.getStore(Chain, DL, Value, Ptr, StoreNode->getMemOperand());
    }
    return Chain;
  }

  EVT ValueVT = Value.getValueType();

  if (StoreNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
    return SDValue();
  }

  // Lowering for indirect addressing

  const MachineFunction &MF = DAG.getMachineFunction();
  const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
                                         getTargetMachine().getFrameLowering());
  unsigned StackWidth = TFL->getStackWidth(MF);

  Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);

  if (ValueVT.isVector()) {
    unsigned NumElemVT = ValueVT.getVectorNumElements();
    EVT ElemVT = ValueVT.getVectorElementType();
    SDValue Stores[4];

    assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
                                      "vector width in load");

    for (unsigned i = 0; i < NumElemVT; ++i) {
      unsigned Channel, PtrIncr;
      getStackAddress(StackWidth, i, Channel, PtrIncr);
      Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
                        DAG.getConstant(PtrIncr, MVT::i32));
      SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ElemVT,
                                 Value, DAG.getConstant(i, MVT::i32));

      Stores[i] = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other,
                              Chain, Elem, Ptr,
                              DAG.getTargetConstant(Channel, MVT::i32));
    }
     Chain =  DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores, NumElemVT);
   } else {
    if (ValueVT == MVT::i8) {
      Value = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Value);
    }
    Chain = DAG.getNode(AMDGPUISD::REGISTER_STORE, DL, MVT::Other, Chain, Value, Ptr,
    DAG.getTargetConstant(0, MVT::i32)); // Channel 
  }

  return Chain;
}

// return (512 + (kc_bank << 12)
static int
ConstantAddressBlock(unsigned AddressSpace) {
  switch (AddressSpace) {
  case AMDGPUAS::CONSTANT_BUFFER_0:
    return 512;
  case AMDGPUAS::CONSTANT_BUFFER_1:
    return 512 + 4096;
  case AMDGPUAS::CONSTANT_BUFFER_2:
    return 512 + 4096 * 2;
  case AMDGPUAS::CONSTANT_BUFFER_3:
    return 512 + 4096 * 3;
  case AMDGPUAS::CONSTANT_BUFFER_4:
    return 512 + 4096 * 4;
  case AMDGPUAS::CONSTANT_BUFFER_5:
    return 512 + 4096 * 5;
  case AMDGPUAS::CONSTANT_BUFFER_6:
    return 512 + 4096 * 6;
  case AMDGPUAS::CONSTANT_BUFFER_7:
    return 512 + 4096 * 7;
  case AMDGPUAS::CONSTANT_BUFFER_8:
    return 512 + 4096 * 8;
  case AMDGPUAS::CONSTANT_BUFFER_9:
    return 512 + 4096 * 9;
  case AMDGPUAS::CONSTANT_BUFFER_10:
    return 512 + 4096 * 10;
  case AMDGPUAS::CONSTANT_BUFFER_11:
    return 512 + 4096 * 11;
  case AMDGPUAS::CONSTANT_BUFFER_12:
    return 512 + 4096 * 12;
  case AMDGPUAS::CONSTANT_BUFFER_13:
    return 512 + 4096 * 13;
  case AMDGPUAS::CONSTANT_BUFFER_14:
    return 512 + 4096 * 14;
  case AMDGPUAS::CONSTANT_BUFFER_15:
    return 512 + 4096 * 15;
  default:
    return -1;
  }
}

SDValue R600TargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const
{
  EVT VT = Op.getValueType();
  DebugLoc DL = Op.getDebugLoc();
  LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
  SDValue Chain = Op.getOperand(0);
  SDValue Ptr = Op.getOperand(1);
  SDValue LoweredLoad;

  int ConstantBlock = ConstantAddressBlock(LoadNode->getAddressSpace());
  if (ConstantBlock > -1) {
    SDValue Result;
    if (dyn_cast<ConstantExpr>(LoadNode->getSrcValue()) ||
        dyn_cast<Constant>(LoadNode->getSrcValue())) {
      SDValue Slots[4];
      for (unsigned i = 0; i < 4; i++) {
        // We want Const position encoded with the following formula :
        // (((512 + (kc_bank << 12) + const_index) << 2) + chan)
        // const_index is Ptr computed by llvm using an alignment of 16.
        // Thus we add (((512 + (kc_bank << 12)) + chan ) * 4 here and
        // then div by 4 at the ISel step
        SDValue NewPtr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
            DAG.getConstant(4 * i + ConstantBlock * 16, MVT::i32));
        Slots[i] = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::i32, NewPtr);
      }
      Result = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v4i32, Slots, 4);
    } else {
      // non constant ptr cant be folded, keeps it as a v4f32 load
      Result = DAG.getNode(AMDGPUISD::CONST_ADDRESS, DL, MVT::v4i32,
          DAG.getNode(ISD::SRL, DL, MVT::i32, Ptr, DAG.getConstant(4, MVT::i32))
          );
    }

    if (!VT.isVector()) {
      Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Result,
          DAG.getConstant(0, MVT::i32));
    }

    SDValue MergedValues[2] = {
        Result,
        Chain
    };
    return DAG.getMergeValues(MergedValues, 2, DL);
  }

  if (LoadNode->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS) {
    return SDValue();
  }

  // Lowering for indirect addressing
  const MachineFunction &MF = DAG.getMachineFunction();
  const AMDGPUFrameLowering *TFL = static_cast<const AMDGPUFrameLowering*>(
                                         getTargetMachine().getFrameLowering());
  unsigned StackWidth = TFL->getStackWidth(MF);

  Ptr = stackPtrToRegIndex(Ptr, StackWidth, DAG);

  if (VT.isVector()) {
    unsigned NumElemVT = VT.getVectorNumElements();
    EVT ElemVT = VT.getVectorElementType();
    SDValue Loads[4];

    assert(NumElemVT >= StackWidth && "Stack width cannot be greater than "
                                      "vector width in load");

    for (unsigned i = 0; i < NumElemVT; ++i) {
      unsigned Channel, PtrIncr;
      getStackAddress(StackWidth, i, Channel, PtrIncr);
      Ptr = DAG.getNode(ISD::ADD, DL, MVT::i32, Ptr,
                        DAG.getConstant(PtrIncr, MVT::i32));
      Loads[i] = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, ElemVT,
                             Chain, Ptr,
                             DAG.getTargetConstant(Channel, MVT::i32),
                             Op.getOperand(2));
    }
    for (unsigned i = NumElemVT; i < 4; ++i) {
      Loads[i] = DAG.getUNDEF(ElemVT);
    }
    EVT TargetVT = EVT::getVectorVT(*DAG.getContext(), ElemVT, 4);
    LoweredLoad = DAG.getNode(ISD::BUILD_VECTOR, DL, TargetVT, Loads, 4);
  } else {
    LoweredLoad = DAG.getNode(AMDGPUISD::REGISTER_LOAD, DL, VT,
                              Chain, Ptr,
                              DAG.getTargetConstant(0, MVT::i32), // Channel
                              Op.getOperand(2));
  }

  SDValue Ops[2];
  Ops[0] = LoweredLoad;
  Ops[1] = Chain;

  return DAG.getMergeValues(Ops, 2, DL);
}

SDValue R600TargetLowering::LowerFPOW(SDValue Op,
    SelectionDAG &DAG) const {
  DebugLoc DL = Op.getDebugLoc();
  EVT VT = Op.getValueType();
  SDValue LogBase = DAG.getNode(ISD::FLOG2, DL, VT, Op.getOperand(0));
  SDValue MulLogBase = DAG.getNode(ISD::FMUL, DL, VT, Op.getOperand(1), LogBase);
  return DAG.getNode(ISD::FEXP2, DL, VT, MulLogBase);
}

/// XXX Only kernel functions are supported, so we can assume for now that
/// every function is a kernel function, but in the future we should use
/// separate calling conventions for kernel and non-kernel functions.
SDValue R600TargetLowering::LowerFormalArguments(
                                      SDValue Chain,
                                      CallingConv::ID CallConv,
                                      bool isVarArg,
                                      const SmallVectorImpl<ISD::InputArg> &Ins,
                                      DebugLoc DL, SelectionDAG &DAG,
                                      SmallVectorImpl<SDValue> &InVals) const {
  unsigned ParamOffsetBytes = 36;
  Function::const_arg_iterator FuncArg =
                            DAG.getMachineFunction().getFunction()->arg_begin();
  for (unsigned i = 0, e = Ins.size(); i < e; ++i, ++FuncArg) {
    EVT VT = Ins[i].VT;
    Type *ArgType = FuncArg->getType();
    unsigned ArgSizeInBits = ArgType->isPointerTy() ?
                             32 : ArgType->getPrimitiveSizeInBits();
    unsigned ArgBytes = ArgSizeInBits >> 3;
    EVT ArgVT;
    if (ArgSizeInBits < VT.getSizeInBits()) {
      assert(!ArgType->isFloatTy() &&
             "Extending floating point arguments not supported yet");
      ArgVT = MVT::getIntegerVT(ArgSizeInBits);
    } else {
      ArgVT = VT;
    }
    PointerType *PtrTy = PointerType::get(VT.getTypeForEVT(*DAG.getContext()),
                                                    AMDGPUAS::PARAM_I_ADDRESS);
    SDValue Arg = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getRoot(),
                                DAG.getConstant(ParamOffsetBytes, MVT::i32),
                                       MachinePointerInfo(new Argument(PtrTy)),
                                       ArgVT, false, false, ArgBytes);
    InVals.push_back(Arg);
    ParamOffsetBytes += ArgBytes;
  }
  return Chain;
}

EVT R600TargetLowering::getSetCCResultType(EVT VT) const {
   if (!VT.isVector()) return MVT::i32;
   return VT.changeVectorElementTypeToInteger();
}

//===----------------------------------------------------------------------===//
// Custom DAG Optimizations
//===----------------------------------------------------------------------===//

SDValue R600TargetLowering::PerformDAGCombine(SDNode *N,
                                              DAGCombinerInfo &DCI) const {
  SelectionDAG &DAG = DCI.DAG;

  switch (N->getOpcode()) {
  // (f32 fp_round (f64 uint_to_fp a)) -> (f32 uint_to_fp a)
  case ISD::FP_ROUND: {
      SDValue Arg = N->getOperand(0);
      if (Arg.getOpcode() == ISD::UINT_TO_FP && Arg.getValueType() == MVT::f64) {
        return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), N->getValueType(0),
                           Arg.getOperand(0));
      }
      break;
    }

  // (i32 fp_to_sint (fneg (select_cc f32, f32, 1.0, 0.0 cc))) ->
  // (i32 select_cc f32, f32, -1, 0 cc)
  //
  // Mesa's GLSL frontend generates the above pattern a lot and we can lower
  // this to one of the SET*_DX10 instructions.
  case ISD::FP_TO_SINT: {
    SDValue FNeg = N->getOperand(0);
    if (FNeg.getOpcode() != ISD::FNEG) {
      return SDValue();
    }
    SDValue SelectCC = FNeg.getOperand(0);
    if (SelectCC.getOpcode() != ISD::SELECT_CC ||
        SelectCC.getOperand(0).getValueType() != MVT::f32 || // LHS
        SelectCC.getOperand(2).getValueType() != MVT::f32 || // True
        !isHWTrueValue(SelectCC.getOperand(2)) ||
        !isHWFalseValue(SelectCC.getOperand(3))) {
      return SDValue();
    }

    return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N->getValueType(0),
                           SelectCC.getOperand(0), // LHS
                           SelectCC.getOperand(1), // RHS
                           DAG.getConstant(-1, MVT::i32), // True
                           DAG.getConstant(0, MVT::i32),  // Flase
                           SelectCC.getOperand(4)); // CC

    break;
  }
  // Extract_vec (Build_vector) generated by custom lowering
  // also needs to be customly combined
  case ISD::EXTRACT_VECTOR_ELT: {
    SDValue Arg = N->getOperand(0);
    if (Arg.getOpcode() == ISD::BUILD_VECTOR) {
      if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
        unsigned Element = Const->getZExtValue();
        return Arg->getOperand(Element);
      }
    }
    if (Arg.getOpcode() == ISD::BITCAST &&
        Arg.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
      if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
        unsigned Element = Const->getZExtValue();
        return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getVTList(),
            Arg->getOperand(0).getOperand(Element));
      }
    }
  }

  case ISD::SELECT_CC: {
    // fold selectcc (selectcc x, y, a, b, cc), b, a, b, seteq ->
    //      selectcc x, y, a, b, inv(cc)
    SDValue LHS = N->getOperand(0);
    if (LHS.getOpcode() != ISD::SELECT_CC) {
      return SDValue();
    }

    SDValue RHS = N->getOperand(1);
    SDValue True = N->getOperand(2);
    SDValue False = N->getOperand(3);

    if (LHS.getOperand(2).getNode() != True.getNode() ||
        LHS.getOperand(3).getNode() != False.getNode() ||
        RHS.getNode() != False.getNode() ||
        cast<CondCodeSDNode>(N->getOperand(4))->get() != ISD::SETEQ) {
      return SDValue();
    }

    ISD::CondCode CCOpcode = cast<CondCodeSDNode>(LHS->getOperand(4))->get();
    CCOpcode = ISD::getSetCCInverse(
                        CCOpcode, LHS.getOperand(0).getValueType().isInteger());
    return DAG.getSelectCC(N->getDebugLoc(),
                           LHS.getOperand(0),
                           LHS.getOperand(1),
                           LHS.getOperand(2),
                           LHS.getOperand(3),
                           CCOpcode);

  }

  case AMDGPUISD::PRED_SET: {
    // (pred_set cc0 isint (selectcc lhs, rhs, -1, 0, cc1), 0) -> pred_set cc2, lhs rhs
    ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N->getOperand(3));
    SDValue SelectCC = N->getOperand(2);
    if (!C1 || !C1->isNullValue() ||
        SelectCC.getOpcode() != ISD::SELECT_CC ||
        SelectCC.getValueType() != MVT::i32 ||
        !isHWTrueValue(SelectCC.getOperand(2)) ||
        !isHWFalseValue(SelectCC.getOperand(3))) {
      return SDValue();
    }

    ISD::CondCode OldCondCode = (ISD::CondCode)
                   (dyn_cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
    ISD::CondCode NewCondCode =
                        cast<CondCodeSDNode>(SelectCC->getOperand(4))->get();

    if (OldCondCode == ISD::SETEQ) {
      NewCondCode = ISD::getSetCCInverse(NewCondCode,
                             SelectCC.getOperand(0).getValueType().isInteger());
    }

    assert(OldCondCode == ISD::SETEQ || OldCondCode == ISD::SETNE);

    return DAG.getNode(AMDGPUISD::PRED_SET, N->getDebugLoc(),
           N->getValueType(0),
           DAG.getTargetConstant(NewCondCode, MVT::i32),
           DAG.getTargetConstant(
                    SelectCC.getOperand(0).getValueType().isInteger(), MVT::i1),
           SelectCC.getOperand(0),
           SelectCC.getOperand(1));

  }

  }
  return SDValue();
}