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
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
|
//===- TranslateToCpp.cpp - Translating to C++ calls ----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/EmitC/IR/EmitC.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Dialect.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/Support/IndentedOstream.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Target/Cpp/CppEmitter.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormatVariadic.h"
#include <stack>
#define DEBUG_TYPE "translate-to-cpp"
using namespace mlir;
using namespace mlir::emitc;
using llvm::formatv;
/// Convenience functions to produce interleaved output with functions returning
/// a LogicalResult. This is different than those in STLExtras as functions used
/// on each element doesn't return a string.
template <typename ForwardIterator, typename UnaryFunctor,
typename NullaryFunctor>
inline LogicalResult
interleaveWithError(ForwardIterator begin, ForwardIterator end,
UnaryFunctor eachFn, NullaryFunctor betweenFn) {
if (begin == end)
return success();
if (failed(eachFn(*begin)))
return failure();
++begin;
for (; begin != end; ++begin) {
betweenFn();
if (failed(eachFn(*begin)))
return failure();
}
return success();
}
template <typename Container, typename UnaryFunctor, typename NullaryFunctor>
inline LogicalResult interleaveWithError(const Container &c,
UnaryFunctor eachFn,
NullaryFunctor betweenFn) {
return interleaveWithError(c.begin(), c.end(), eachFn, betweenFn);
}
template <typename Container, typename UnaryFunctor>
inline LogicalResult interleaveCommaWithError(const Container &c,
raw_ostream &os,
UnaryFunctor eachFn) {
return interleaveWithError(c.begin(), c.end(), eachFn, [&]() { os << ", "; });
}
/// Return the precedence of a operator as an integer, higher values
/// imply higher precedence.
static FailureOr<int> getOperatorPrecedence(Operation *operation) {
return llvm::TypeSwitch<Operation *, FailureOr<int>>(operation)
.Case<emitc::AddOp>([&](auto op) { return 12; })
.Case<emitc::ApplyOp>([&](auto op) { return 15; })
.Case<emitc::BitwiseAndOp>([&](auto op) { return 7; })
.Case<emitc::BitwiseLeftShiftOp>([&](auto op) { return 11; })
.Case<emitc::BitwiseNotOp>([&](auto op) { return 15; })
.Case<emitc::BitwiseOrOp>([&](auto op) { return 5; })
.Case<emitc::BitwiseRightShiftOp>([&](auto op) { return 11; })
.Case<emitc::BitwiseXorOp>([&](auto op) { return 6; })
.Case<emitc::CallOp>([&](auto op) { return 16; })
.Case<emitc::CallOpaqueOp>([&](auto op) { return 16; })
.Case<emitc::CastOp>([&](auto op) { return 15; })
.Case<emitc::CmpOp>([&](auto op) -> FailureOr<int> {
switch (op.getPredicate()) {
case emitc::CmpPredicate::eq:
case emitc::CmpPredicate::ne:
return 8;
case emitc::CmpPredicate::lt:
case emitc::CmpPredicate::le:
case emitc::CmpPredicate::gt:
case emitc::CmpPredicate::ge:
return 9;
case emitc::CmpPredicate::three_way:
return 10;
}
return op->emitError("unsupported cmp predicate");
})
.Case<emitc::ConditionalOp>([&](auto op) { return 2; })
.Case<emitc::DivOp>([&](auto op) { return 13; })
.Case<emitc::LoadOp>([&](auto op) { return 16; })
.Case<emitc::LogicalAndOp>([&](auto op) { return 4; })
.Case<emitc::LogicalNotOp>([&](auto op) { return 15; })
.Case<emitc::LogicalOrOp>([&](auto op) { return 3; })
.Case<emitc::MulOp>([&](auto op) { return 13; })
.Case<emitc::RemOp>([&](auto op) { return 13; })
.Case<emitc::SubOp>([&](auto op) { return 12; })
.Case<emitc::UnaryMinusOp>([&](auto op) { return 15; })
.Case<emitc::UnaryPlusOp>([&](auto op) { return 15; })
.Default([](auto op) { return op->emitError("unsupported operation"); });
}
namespace {
/// Emitter that uses dialect specific emitters to emit C++ code.
struct CppEmitter {
explicit CppEmitter(raw_ostream &os, bool declareVariablesAtTop,
StringRef fileId);
/// Emits attribute or returns failure.
LogicalResult emitAttribute(Location loc, Attribute attr);
/// Emits operation 'op' with/without training semicolon or returns failure.
///
/// For operations that should never be followed by a semicolon, like ForOp,
/// the `trailingSemicolon` argument is ignored and a semicolon is not
/// emitted.
LogicalResult emitOperation(Operation &op, bool trailingSemicolon);
/// Emits type 'type' or returns failure.
LogicalResult emitType(Location loc, Type type);
/// Emits array of types as a std::tuple of the emitted types.
/// - emits void for an empty array;
/// - emits the type of the only element for arrays of size one;
/// - emits a std::tuple otherwise;
LogicalResult emitTypes(Location loc, ArrayRef<Type> types);
/// Emits array of types as a std::tuple of the emitted types independently of
/// the array size.
LogicalResult emitTupleType(Location loc, ArrayRef<Type> types);
/// Emits an assignment for a variable which has been declared previously.
LogicalResult emitVariableAssignment(OpResult result);
/// Emits a variable declaration for a result of an operation.
LogicalResult emitVariableDeclaration(OpResult result,
bool trailingSemicolon);
/// Emits a declaration of a variable with the given type and name.
LogicalResult emitVariableDeclaration(Location loc, Type type,
StringRef name);
/// Emits the variable declaration and assignment prefix for 'op'.
/// - emits separate variable followed by std::tie for multi-valued operation;
/// - emits single type followed by variable for single result;
/// - emits nothing if no value produced by op;
/// Emits final '=' operator where a type is produced. Returns failure if
/// any result type could not be converted.
LogicalResult emitAssignPrefix(Operation &op);
/// Emits a global variable declaration or definition.
LogicalResult emitGlobalVariable(GlobalOp op);
/// Emits a label for the block.
LogicalResult emitLabel(Block &block);
/// Emits the operands and atttributes of the operation. All operands are
/// emitted first and then all attributes in alphabetical order.
LogicalResult emitOperandsAndAttributes(Operation &op,
ArrayRef<StringRef> exclude = {});
/// Emits the operands of the operation. All operands are emitted in order.
LogicalResult emitOperands(Operation &op);
/// Emits value as an operands of an operation
LogicalResult emitOperand(Value value);
/// Emit an expression as a C expression.
LogicalResult emitExpression(ExpressionOp expressionOp);
/// Insert the expression representing the operation into the value cache.
void cacheDeferredOpResult(Value value, StringRef str);
/// Return the existing or a new name for a Value.
StringRef getOrCreateName(Value val);
/// Return the existing or a new name for a loop induction variable of an
/// emitc::ForOp.
StringRef getOrCreateInductionVarName(Value val);
// Returns the textual representation of a subscript operation.
std::string getSubscriptName(emitc::SubscriptOp op);
// Returns the textual representation of a member (of object) operation.
std::string createMemberAccess(emitc::MemberOp op);
// Returns the textual representation of a member of pointer operation.
std::string createMemberAccess(emitc::MemberOfPtrOp op);
/// Return the existing or a new label of a Block.
StringRef getOrCreateName(Block &block);
/// Whether to map an mlir integer to a unsigned integer in C++.
bool shouldMapToUnsigned(IntegerType::SignednessSemantics val);
/// Abstract RAII helper function to manage entering/exiting C++ scopes.
struct Scope {
~Scope() { emitter.labelInScopeCount.pop(); }
private:
llvm::ScopedHashTableScope<Value, std::string> valueMapperScope;
llvm::ScopedHashTableScope<Block *, std::string> blockMapperScope;
protected:
Scope(CppEmitter &emitter)
: valueMapperScope(emitter.valueMapper),
blockMapperScope(emitter.blockMapper), emitter(emitter) {
emitter.labelInScopeCount.push(emitter.labelInScopeCount.top());
}
CppEmitter &emitter;
};
/// RAII helper function to manage entering/exiting functions, while re-using
/// value names.
struct FunctionScope : Scope {
FunctionScope(CppEmitter &emitter) : Scope(emitter) {
// Re-use value names.
emitter.resetValueCounter();
}
};
/// RAII helper function to manage entering/exiting emitc::forOp loops and
/// handle induction variable naming.
struct LoopScope : Scope {
LoopScope(CppEmitter &emitter) : Scope(emitter) {
emitter.increaseLoopNestingLevel();
}
~LoopScope() { emitter.decreaseLoopNestingLevel(); }
};
/// Returns wether the Value is assigned to a C++ variable in the scope.
bool hasValueInScope(Value val);
// Returns whether a label is assigned to the block.
bool hasBlockLabel(Block &block);
/// Returns the output stream.
raw_indented_ostream &ostream() { return os; };
/// Returns if all variables for op results and basic block arguments need to
/// be declared at the beginning of a function.
bool shouldDeclareVariablesAtTop() { return declareVariablesAtTop; };
/// Returns whether this file op should be emitted
bool shouldEmitFile(FileOp file) {
return !fileId.empty() && file.getId() == fileId;
}
/// Get expression currently being emitted.
ExpressionOp getEmittedExpression() { return emittedExpression; }
/// Determine whether given value is part of the expression potentially being
/// emitted.
bool isPartOfCurrentExpression(Value value) {
if (!emittedExpression)
return false;
Operation *def = value.getDefiningOp();
if (!def)
return false;
auto operandExpression = dyn_cast<ExpressionOp>(def->getParentOp());
return operandExpression == emittedExpression;
};
// Resets the value counter to 0.
void resetValueCounter();
// Increases the loop nesting level by 1.
void increaseLoopNestingLevel();
// Decreases the loop nesting level by 1.
void decreaseLoopNestingLevel();
private:
using ValueMapper = llvm::ScopedHashTable<Value, std::string>;
using BlockMapper = llvm::ScopedHashTable<Block *, std::string>;
/// Output stream to emit to.
raw_indented_ostream os;
/// Boolean to enforce that all variables for op results and block
/// arguments are declared at the beginning of the function. This also
/// includes results from ops located in nested regions.
bool declareVariablesAtTop;
/// Only emit file ops whos id matches this value.
std::string fileId;
/// Map from value to name of C++ variable that contain the name.
ValueMapper valueMapper;
/// Map from block to name of C++ label.
BlockMapper blockMapper;
/// Default values representing outermost scope.
llvm::ScopedHashTableScope<Value, std::string> defaultValueMapperScope;
llvm::ScopedHashTableScope<Block *, std::string> defaultBlockMapperScope;
std::stack<int64_t> labelInScopeCount;
/// Keeps track of the amount of nested loops the emitter currently operates
/// in.
uint64_t loopNestingLevel{0};
/// Emitter-level count of created values to enable unique identifiers.
unsigned int valueCount{0};
/// State of the current expression being emitted.
ExpressionOp emittedExpression;
SmallVector<int> emittedExpressionPrecedence;
void pushExpressionPrecedence(int precedence) {
emittedExpressionPrecedence.push_back(precedence);
}
void popExpressionPrecedence() { emittedExpressionPrecedence.pop_back(); }
static int lowestPrecedence() { return 0; }
int getExpressionPrecedence() {
if (emittedExpressionPrecedence.empty())
return lowestPrecedence();
return emittedExpressionPrecedence.back();
}
};
} // namespace
/// Determine whether expression \p op should be emitted in a deferred way.
static bool hasDeferredEmission(Operation *op) {
return isa_and_nonnull<emitc::GetGlobalOp, emitc::LiteralOp, emitc::MemberOp,
emitc::MemberOfPtrOp, emitc::SubscriptOp>(op);
}
/// Determine whether expression \p expressionOp should be emitted inline, i.e.
/// as part of its user. This function recommends inlining of any expressions
/// that can be inlined unless it is used by another expression, under the
/// assumption that any expression fusion/re-materialization was taken care of
/// by transformations run by the backend.
static bool shouldBeInlined(ExpressionOp expressionOp) {
// Do not inline if expression is marked as such.
if (expressionOp.getDoNotInline())
return false;
// Do not inline expressions with side effects to prevent side-effect
// reordering.
if (expressionOp.hasSideEffects())
return false;
// Do not inline expressions with multiple uses.
Value result = expressionOp.getResult();
if (!result.hasOneUse())
return false;
Operation *user = *result.getUsers().begin();
// Do not inline expressions used by operations with deferred emission, since
// their translation requires the materialization of variables.
if (hasDeferredEmission(user))
return false;
// Do not inline expressions used by ops with the CExpressionInterface. If
// this was intended, the user could have been merged into the expression op.
return !isa<emitc::CExpressionInterface>(*user);
}
static LogicalResult printConstantOp(CppEmitter &emitter, Operation *operation,
Attribute value) {
OpResult result = operation->getResult(0);
// Only emit an assignment as the variable was already declared when printing
// the FuncOp.
if (emitter.shouldDeclareVariablesAtTop()) {
// Skip the assignment if the emitc.constant has no value.
if (auto oAttr = dyn_cast<emitc::OpaqueAttr>(value)) {
if (oAttr.getValue().empty())
return success();
}
if (failed(emitter.emitVariableAssignment(result)))
return failure();
return emitter.emitAttribute(operation->getLoc(), value);
}
// Emit a variable declaration for an emitc.constant op without value.
if (auto oAttr = dyn_cast<emitc::OpaqueAttr>(value)) {
if (oAttr.getValue().empty())
// The semicolon gets printed by the emitOperation function.
return emitter.emitVariableDeclaration(result,
/*trailingSemicolon=*/false);
}
// Emit a variable declaration.
if (failed(emitter.emitAssignPrefix(*operation)))
return failure();
return emitter.emitAttribute(operation->getLoc(), value);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::ConstantOp constantOp) {
Operation *operation = constantOp.getOperation();
Attribute value = constantOp.getValue();
return printConstantOp(emitter, operation, value);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::VariableOp variableOp) {
Operation *operation = variableOp.getOperation();
Attribute value = variableOp.getValue();
return printConstantOp(emitter, operation, value);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::GlobalOp globalOp) {
return emitter.emitGlobalVariable(globalOp);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::AssignOp assignOp) {
OpResult result = assignOp.getVar().getDefiningOp()->getResult(0);
if (failed(emitter.emitVariableAssignment(result)))
return failure();
return emitter.emitOperand(assignOp.getValue());
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::LoadOp loadOp) {
if (failed(emitter.emitAssignPrefix(*loadOp)))
return failure();
return emitter.emitOperand(loadOp.getOperand());
}
static LogicalResult printBinaryOperation(CppEmitter &emitter,
Operation *operation,
StringRef binaryOperator) {
raw_ostream &os = emitter.ostream();
if (failed(emitter.emitAssignPrefix(*operation)))
return failure();
if (failed(emitter.emitOperand(operation->getOperand(0))))
return failure();
os << " " << binaryOperator << " ";
if (failed(emitter.emitOperand(operation->getOperand(1))))
return failure();
return success();
}
static LogicalResult printUnaryOperation(CppEmitter &emitter,
Operation *operation,
StringRef unaryOperator) {
raw_ostream &os = emitter.ostream();
if (failed(emitter.emitAssignPrefix(*operation)))
return failure();
os << unaryOperator;
if (failed(emitter.emitOperand(operation->getOperand(0))))
return failure();
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::AddOp addOp) {
Operation *operation = addOp.getOperation();
return printBinaryOperation(emitter, operation, "+");
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::DivOp divOp) {
Operation *operation = divOp.getOperation();
return printBinaryOperation(emitter, operation, "/");
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::MulOp mulOp) {
Operation *operation = mulOp.getOperation();
return printBinaryOperation(emitter, operation, "*");
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::RemOp remOp) {
Operation *operation = remOp.getOperation();
return printBinaryOperation(emitter, operation, "%");
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::SubOp subOp) {
Operation *operation = subOp.getOperation();
return printBinaryOperation(emitter, operation, "-");
}
static LogicalResult emitSwitchCase(CppEmitter &emitter,
raw_indented_ostream &os, Region ®ion) {
for (Region::OpIterator iteratorOp = region.op_begin(), end = region.op_end();
std::next(iteratorOp) != end; ++iteratorOp) {
if (failed(emitter.emitOperation(*iteratorOp, /*trailingSemicolon=*/true)))
return failure();
}
os << "break;\n";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::SwitchOp switchOp) {
raw_indented_ostream &os = emitter.ostream();
os << "switch (";
if (failed(emitter.emitOperand(switchOp.getArg())))
return failure();
os << ") {";
for (auto pair : llvm::zip(switchOp.getCases(), switchOp.getCaseRegions())) {
os << "\ncase " << std::get<0>(pair) << ": {\n";
os.indent();
if (failed(emitSwitchCase(emitter, os, std::get<1>(pair))))
return failure();
os.unindent() << "}";
}
os << "\ndefault: {\n";
os.indent();
if (failed(emitSwitchCase(emitter, os, switchOp.getDefaultRegion())))
return failure();
os.unindent() << "}\n}";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::CmpOp cmpOp) {
Operation *operation = cmpOp.getOperation();
StringRef binaryOperator;
switch (cmpOp.getPredicate()) {
case emitc::CmpPredicate::eq:
binaryOperator = "==";
break;
case emitc::CmpPredicate::ne:
binaryOperator = "!=";
break;
case emitc::CmpPredicate::lt:
binaryOperator = "<";
break;
case emitc::CmpPredicate::le:
binaryOperator = "<=";
break;
case emitc::CmpPredicate::gt:
binaryOperator = ">";
break;
case emitc::CmpPredicate::ge:
binaryOperator = ">=";
break;
case emitc::CmpPredicate::three_way:
binaryOperator = "<=>";
break;
}
return printBinaryOperation(emitter, operation, binaryOperator);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::ConditionalOp conditionalOp) {
raw_ostream &os = emitter.ostream();
if (failed(emitter.emitAssignPrefix(*conditionalOp)))
return failure();
if (failed(emitter.emitOperand(conditionalOp.getCondition())))
return failure();
os << " ? ";
if (failed(emitter.emitOperand(conditionalOp.getTrueValue())))
return failure();
os << " : ";
if (failed(emitter.emitOperand(conditionalOp.getFalseValue())))
return failure();
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::VerbatimOp verbatimOp) {
raw_ostream &os = emitter.ostream();
FailureOr<SmallVector<ReplacementItem>> items =
verbatimOp.parseFormatString();
if (failed(items))
return failure();
auto fmtArg = verbatimOp.getFmtArgs().begin();
for (ReplacementItem &item : *items) {
if (auto *str = std::get_if<StringRef>(&item)) {
os << *str;
} else {
if (failed(emitter.emitOperand(*fmtArg++)))
return failure();
}
}
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
cf::BranchOp branchOp) {
raw_ostream &os = emitter.ostream();
Block &successor = *branchOp.getSuccessor();
for (auto pair :
llvm::zip(branchOp.getOperands(), successor.getArguments())) {
Value &operand = std::get<0>(pair);
BlockArgument &argument = std::get<1>(pair);
os << emitter.getOrCreateName(argument) << " = "
<< emitter.getOrCreateName(operand) << ";\n";
}
os << "goto ";
if (!(emitter.hasBlockLabel(successor)))
return branchOp.emitOpError("unable to find label for successor block");
os << emitter.getOrCreateName(successor);
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
cf::CondBranchOp condBranchOp) {
raw_indented_ostream &os = emitter.ostream();
Block &trueSuccessor = *condBranchOp.getTrueDest();
Block &falseSuccessor = *condBranchOp.getFalseDest();
os << "if (";
if (failed(emitter.emitOperand(condBranchOp.getCondition())))
return failure();
os << ") {\n";
os.indent();
// If condition is true.
for (auto pair : llvm::zip(condBranchOp.getTrueOperands(),
trueSuccessor.getArguments())) {
Value &operand = std::get<0>(pair);
BlockArgument &argument = std::get<1>(pair);
os << emitter.getOrCreateName(argument) << " = "
<< emitter.getOrCreateName(operand) << ";\n";
}
os << "goto ";
if (!(emitter.hasBlockLabel(trueSuccessor))) {
return condBranchOp.emitOpError("unable to find label for successor block");
}
os << emitter.getOrCreateName(trueSuccessor) << ";\n";
os.unindent() << "} else {\n";
os.indent();
// If condition is false.
for (auto pair : llvm::zip(condBranchOp.getFalseOperands(),
falseSuccessor.getArguments())) {
Value &operand = std::get<0>(pair);
BlockArgument &argument = std::get<1>(pair);
os << emitter.getOrCreateName(argument) << " = "
<< emitter.getOrCreateName(operand) << ";\n";
}
os << "goto ";
if (!(emitter.hasBlockLabel(falseSuccessor))) {
return condBranchOp.emitOpError()
<< "unable to find label for successor block";
}
os << emitter.getOrCreateName(falseSuccessor) << ";\n";
os.unindent() << "}";
return success();
}
static LogicalResult printCallOperation(CppEmitter &emitter, Operation *callOp,
StringRef callee) {
if (failed(emitter.emitAssignPrefix(*callOp)))
return failure();
raw_ostream &os = emitter.ostream();
os << callee << "(";
if (failed(emitter.emitOperands(*callOp)))
return failure();
os << ")";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, func::CallOp callOp) {
Operation *operation = callOp.getOperation();
StringRef callee = callOp.getCallee();
return printCallOperation(emitter, operation, callee);
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::CallOp callOp) {
Operation *operation = callOp.getOperation();
StringRef callee = callOp.getCallee();
return printCallOperation(emitter, operation, callee);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::CallOpaqueOp callOpaqueOp) {
raw_ostream &os = emitter.ostream();
Operation &op = *callOpaqueOp.getOperation();
if (failed(emitter.emitAssignPrefix(op)))
return failure();
os << callOpaqueOp.getCallee();
// Template arguments can't refer to SSA values and as such the template
// arguments which are supplied in form of attributes can be emitted as is. We
// don't need to handle integer attributes specially like we do for arguments
// - see below.
auto emitTemplateArgs = [&](Attribute attr) -> LogicalResult {
return emitter.emitAttribute(op.getLoc(), attr);
};
if (callOpaqueOp.getTemplateArgs()) {
os << "<";
if (failed(interleaveCommaWithError(*callOpaqueOp.getTemplateArgs(), os,
emitTemplateArgs)))
return failure();
os << ">";
}
auto emitArgs = [&](Attribute attr) -> LogicalResult {
if (auto t = dyn_cast<IntegerAttr>(attr)) {
// Index attributes are treated specially as operand index.
if (t.getType().isIndex()) {
int64_t idx = t.getInt();
Value operand = op.getOperand(idx);
if (!emitter.hasValueInScope(operand))
return op.emitOpError("operand ")
<< idx << "'s value not defined in scope";
os << emitter.getOrCreateName(operand);
return success();
}
}
if (failed(emitter.emitAttribute(op.getLoc(), attr)))
return failure();
return success();
};
os << "(";
LogicalResult emittedArgs =
callOpaqueOp.getArgs()
? interleaveCommaWithError(*callOpaqueOp.getArgs(), os, emitArgs)
: emitter.emitOperands(op);
if (failed(emittedArgs))
return failure();
os << ")";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::ApplyOp applyOp) {
raw_ostream &os = emitter.ostream();
Operation &op = *applyOp.getOperation();
if (failed(emitter.emitAssignPrefix(op)))
return failure();
os << applyOp.getApplicableOperator();
os << emitter.getOrCreateName(applyOp.getOperand());
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::BitwiseAndOp bitwiseAndOp) {
Operation *operation = bitwiseAndOp.getOperation();
return printBinaryOperation(emitter, operation, "&");
}
static LogicalResult
printOperation(CppEmitter &emitter,
emitc::BitwiseLeftShiftOp bitwiseLeftShiftOp) {
Operation *operation = bitwiseLeftShiftOp.getOperation();
return printBinaryOperation(emitter, operation, "<<");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::BitwiseNotOp bitwiseNotOp) {
Operation *operation = bitwiseNotOp.getOperation();
return printUnaryOperation(emitter, operation, "~");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::BitwiseOrOp bitwiseOrOp) {
Operation *operation = bitwiseOrOp.getOperation();
return printBinaryOperation(emitter, operation, "|");
}
static LogicalResult
printOperation(CppEmitter &emitter,
emitc::BitwiseRightShiftOp bitwiseRightShiftOp) {
Operation *operation = bitwiseRightShiftOp.getOperation();
return printBinaryOperation(emitter, operation, ">>");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::BitwiseXorOp bitwiseXorOp) {
Operation *operation = bitwiseXorOp.getOperation();
return printBinaryOperation(emitter, operation, "^");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::UnaryPlusOp unaryPlusOp) {
Operation *operation = unaryPlusOp.getOperation();
return printUnaryOperation(emitter, operation, "+");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::UnaryMinusOp unaryMinusOp) {
Operation *operation = unaryMinusOp.getOperation();
return printUnaryOperation(emitter, operation, "-");
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::CastOp castOp) {
raw_ostream &os = emitter.ostream();
Operation &op = *castOp.getOperation();
if (failed(emitter.emitAssignPrefix(op)))
return failure();
os << "(";
if (failed(emitter.emitType(op.getLoc(), op.getResult(0).getType())))
return failure();
os << ") ";
return emitter.emitOperand(castOp.getOperand());
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::ExpressionOp expressionOp) {
if (shouldBeInlined(expressionOp))
return success();
Operation &op = *expressionOp.getOperation();
if (failed(emitter.emitAssignPrefix(op)))
return failure();
return emitter.emitExpression(expressionOp);
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::IncludeOp includeOp) {
raw_ostream &os = emitter.ostream();
os << "#include ";
if (includeOp.getIsStandardInclude())
os << "<" << includeOp.getInclude() << ">";
else
os << "\"" << includeOp.getInclude() << "\"";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::LogicalAndOp logicalAndOp) {
Operation *operation = logicalAndOp.getOperation();
return printBinaryOperation(emitter, operation, "&&");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::LogicalNotOp logicalNotOp) {
Operation *operation = logicalNotOp.getOperation();
return printUnaryOperation(emitter, operation, "!");
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::LogicalOrOp logicalOrOp) {
Operation *operation = logicalOrOp.getOperation();
return printBinaryOperation(emitter, operation, "||");
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::ForOp forOp) {
raw_indented_ostream &os = emitter.ostream();
// Utility function to determine whether a value is an expression that will be
// inlined, and as such should be wrapped in parentheses in order to guarantee
// its precedence and associativity.
auto requiresParentheses = [&](Value value) {
auto expressionOp = value.getDefiningOp<ExpressionOp>();
if (!expressionOp)
return false;
return shouldBeInlined(expressionOp);
};
os << "for (";
if (failed(
emitter.emitType(forOp.getLoc(), forOp.getInductionVar().getType())))
return failure();
os << " ";
os << emitter.getOrCreateInductionVarName(forOp.getInductionVar());
os << " = ";
if (failed(emitter.emitOperand(forOp.getLowerBound())))
return failure();
os << "; ";
os << emitter.getOrCreateInductionVarName(forOp.getInductionVar());
os << " < ";
Value upperBound = forOp.getUpperBound();
bool upperBoundRequiresParentheses = requiresParentheses(upperBound);
if (upperBoundRequiresParentheses)
os << "(";
if (failed(emitter.emitOperand(upperBound)))
return failure();
if (upperBoundRequiresParentheses)
os << ")";
os << "; ";
os << emitter.getOrCreateInductionVarName(forOp.getInductionVar());
os << " += ";
if (failed(emitter.emitOperand(forOp.getStep())))
return failure();
os << ") {\n";
os.indent();
CppEmitter::LoopScope lScope(emitter);
Region &forRegion = forOp.getRegion();
auto regionOps = forRegion.getOps();
// We skip the trailing yield op.
for (auto it = regionOps.begin(); std::next(it) != regionOps.end(); ++it) {
if (failed(emitter.emitOperation(*it, /*trailingSemicolon=*/true)))
return failure();
}
os.unindent() << "}";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, emitc::IfOp ifOp) {
raw_indented_ostream &os = emitter.ostream();
// Helper function to emit all ops except the last one, expected to be
// emitc::yield.
auto emitAllExceptLast = [&emitter](Region ®ion) {
Region::OpIterator it = region.op_begin(), end = region.op_end();
for (; std::next(it) != end; ++it) {
if (failed(emitter.emitOperation(*it, /*trailingSemicolon=*/true)))
return failure();
}
assert(isa<emitc::YieldOp>(*it) &&
"Expected last operation in the region to be emitc::yield");
return success();
};
os << "if (";
if (failed(emitter.emitOperand(ifOp.getCondition())))
return failure();
os << ") {\n";
os.indent();
if (failed(emitAllExceptLast(ifOp.getThenRegion())))
return failure();
os.unindent() << "}";
Region &elseRegion = ifOp.getElseRegion();
if (!elseRegion.empty()) {
os << " else {\n";
os.indent();
if (failed(emitAllExceptLast(elseRegion)))
return failure();
os.unindent() << "}";
}
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
func::ReturnOp returnOp) {
raw_ostream &os = emitter.ostream();
os << "return";
switch (returnOp.getNumOperands()) {
case 0:
return success();
case 1:
os << " ";
if (failed(emitter.emitOperand(returnOp.getOperand(0))))
return failure();
return success();
default:
os << " std::make_tuple(";
if (failed(emitter.emitOperandsAndAttributes(*returnOp.getOperation())))
return failure();
os << ")";
return success();
}
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::ReturnOp returnOp) {
raw_ostream &os = emitter.ostream();
os << "return";
if (returnOp.getNumOperands() == 0)
return success();
os << " ";
if (failed(emitter.emitOperand(returnOp.getOperand())))
return failure();
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, ModuleOp moduleOp) {
for (Operation &op : moduleOp) {
if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/false)))
return failure();
}
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, ClassOp classOp) {
raw_indented_ostream &os = emitter.ostream();
os << "class " << classOp.getSymName();
if (classOp.getFinalSpecifier())
os << " final";
os << " {\n public:\n";
os.indent();
for (Operation &op : classOp) {
if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/false)))
return failure();
}
os.unindent();
os << "};";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, FieldOp fieldOp) {
raw_ostream &os = emitter.ostream();
if (failed(emitter.emitType(fieldOp->getLoc(), fieldOp.getType())))
return failure();
os << " " << fieldOp.getSymName() << ";";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
GetFieldOp getFieldOp) {
raw_indented_ostream &os = emitter.ostream();
Value result = getFieldOp.getResult();
if (failed(emitter.emitType(getFieldOp->getLoc(), result.getType())))
return failure();
os << " ";
if (failed(emitter.emitOperand(result)))
return failure();
os << " = ";
os << getFieldOp.getFieldName().str();
return success();
}
static LogicalResult printOperation(CppEmitter &emitter, FileOp file) {
if (!emitter.shouldEmitFile(file))
return success();
for (Operation &op : file) {
if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/false)))
return failure();
}
return success();
}
static LogicalResult printFunctionArgs(CppEmitter &emitter,
Operation *functionOp,
ArrayRef<Type> arguments) {
raw_indented_ostream &os = emitter.ostream();
return (
interleaveCommaWithError(arguments, os, [&](Type arg) -> LogicalResult {
return emitter.emitType(functionOp->getLoc(), arg);
}));
}
static LogicalResult printFunctionArgs(CppEmitter &emitter,
Operation *functionOp,
Region::BlockArgListType arguments) {
raw_indented_ostream &os = emitter.ostream();
return (interleaveCommaWithError(
arguments, os, [&](BlockArgument arg) -> LogicalResult {
return emitter.emitVariableDeclaration(
functionOp->getLoc(), arg.getType(), emitter.getOrCreateName(arg));
}));
}
static LogicalResult printFunctionBody(CppEmitter &emitter,
Operation *functionOp,
Region::BlockListType &blocks) {
raw_indented_ostream &os = emitter.ostream();
os.indent();
if (emitter.shouldDeclareVariablesAtTop()) {
// Declare all variables that hold op results including those from nested
// regions.
WalkResult result =
functionOp->walk<WalkOrder::PreOrder>([&](Operation *op) -> WalkResult {
if (isa<emitc::ExpressionOp>(op->getParentOp()) ||
(isa<emitc::ExpressionOp>(op) &&
shouldBeInlined(cast<emitc::ExpressionOp>(op))))
return WalkResult::skip();
for (OpResult result : op->getResults()) {
if (failed(emitter.emitVariableDeclaration(
result, /*trailingSemicolon=*/true))) {
return WalkResult(
op->emitError("unable to declare result variable for op"));
}
}
return WalkResult::advance();
});
if (result.wasInterrupted())
return failure();
}
// Create label names for basic blocks.
for (Block &block : blocks) {
emitter.getOrCreateName(block);
}
// Declare variables for basic block arguments.
for (Block &block : llvm::drop_begin(blocks)) {
for (BlockArgument &arg : block.getArguments()) {
if (emitter.hasValueInScope(arg))
return functionOp->emitOpError(" block argument #")
<< arg.getArgNumber() << " is out of scope";
if (isa<ArrayType, LValueType>(arg.getType()))
return functionOp->emitOpError("cannot emit block argument #")
<< arg.getArgNumber() << " with type " << arg.getType();
if (failed(
emitter.emitType(block.getParentOp()->getLoc(), arg.getType()))) {
return failure();
}
os << " " << emitter.getOrCreateName(arg) << ";\n";
}
}
for (Block &block : blocks) {
// Only print a label if the block has predecessors.
if (!block.hasNoPredecessors()) {
if (failed(emitter.emitLabel(block)))
return failure();
}
for (Operation &op : block.getOperations()) {
if (failed(emitter.emitOperation(op, /*trailingSemicolon=*/true)))
return failure();
}
}
os.unindent();
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
func::FuncOp functionOp) {
// We need to declare variables at top if the function has multiple blocks.
if (!emitter.shouldDeclareVariablesAtTop() &&
functionOp.getBlocks().size() > 1) {
return functionOp.emitOpError(
"with multiple blocks needs variables declared at top");
}
if (llvm::any_of(functionOp.getArgumentTypes(), llvm::IsaPred<LValueType>)) {
return functionOp.emitOpError()
<< "cannot emit lvalue type as argument type";
}
if (llvm::any_of(functionOp.getResultTypes(), llvm::IsaPred<ArrayType>)) {
return functionOp.emitOpError() << "cannot emit array type as result type";
}
CppEmitter::FunctionScope scope(emitter);
raw_indented_ostream &os = emitter.ostream();
if (failed(emitter.emitTypes(functionOp.getLoc(),
functionOp.getFunctionType().getResults())))
return failure();
os << " " << functionOp.getName();
os << "(";
Operation *operation = functionOp.getOperation();
if (failed(printFunctionArgs(emitter, operation, functionOp.getArguments())))
return failure();
os << ") {\n";
if (failed(printFunctionBody(emitter, operation, functionOp.getBlocks())))
return failure();
os << "}\n";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
emitc::FuncOp functionOp) {
// We need to declare variables at top if the function has multiple blocks.
if (!emitter.shouldDeclareVariablesAtTop() &&
functionOp.getBlocks().size() > 1) {
return functionOp.emitOpError(
"with multiple blocks needs variables declared at top");
}
CppEmitter::FunctionScope scope(emitter);
raw_indented_ostream &os = emitter.ostream();
if (functionOp.getSpecifiers()) {
for (Attribute specifier : functionOp.getSpecifiersAttr()) {
os << cast<StringAttr>(specifier).str() << " ";
}
}
if (failed(emitter.emitTypes(functionOp.getLoc(),
functionOp.getFunctionType().getResults())))
return failure();
os << " " << functionOp.getName();
os << "(";
Operation *operation = functionOp.getOperation();
if (functionOp.isExternal()) {
if (failed(printFunctionArgs(emitter, operation,
functionOp.getArgumentTypes())))
return failure();
os << ");";
return success();
}
if (failed(printFunctionArgs(emitter, operation, functionOp.getArguments())))
return failure();
os << ") {\n";
if (failed(printFunctionBody(emitter, operation, functionOp.getBlocks())))
return failure();
os << "}\n";
return success();
}
static LogicalResult printOperation(CppEmitter &emitter,
DeclareFuncOp declareFuncOp) {
raw_indented_ostream &os = emitter.ostream();
CppEmitter::FunctionScope scope(emitter);
auto functionOp = SymbolTable::lookupNearestSymbolFrom<emitc::FuncOp>(
declareFuncOp, declareFuncOp.getSymNameAttr());
if (!functionOp)
return failure();
if (functionOp.getSpecifiers()) {
for (Attribute specifier : functionOp.getSpecifiersAttr()) {
os << cast<StringAttr>(specifier).str() << " ";
}
}
if (failed(emitter.emitTypes(functionOp.getLoc(),
functionOp.getFunctionType().getResults())))
return failure();
os << " " << functionOp.getName();
os << "(";
Operation *operation = functionOp.getOperation();
if (failed(printFunctionArgs(emitter, operation, functionOp.getArguments())))
return failure();
os << ");";
return success();
}
CppEmitter::CppEmitter(raw_ostream &os, bool declareVariablesAtTop,
StringRef fileId)
: os(os), declareVariablesAtTop(declareVariablesAtTop),
fileId(fileId.str()), defaultValueMapperScope(valueMapper),
defaultBlockMapperScope(blockMapper) {
labelInScopeCount.push(0);
}
std::string CppEmitter::getSubscriptName(emitc::SubscriptOp op) {
std::string out;
llvm::raw_string_ostream ss(out);
ss << getOrCreateName(op.getValue());
for (auto index : op.getIndices()) {
ss << "[" << getOrCreateName(index) << "]";
}
return out;
}
std::string CppEmitter::createMemberAccess(emitc::MemberOp op) {
std::string out;
llvm::raw_string_ostream ss(out);
ss << getOrCreateName(op.getOperand());
ss << "." << op.getMember();
return out;
}
std::string CppEmitter::createMemberAccess(emitc::MemberOfPtrOp op) {
std::string out;
llvm::raw_string_ostream ss(out);
ss << getOrCreateName(op.getOperand());
ss << "->" << op.getMember();
return out;
}
void CppEmitter::cacheDeferredOpResult(Value value, StringRef str) {
if (!valueMapper.count(value))
valueMapper.insert(value, str.str());
}
/// Return the existing or a new name for a Value.
StringRef CppEmitter::getOrCreateName(Value val) {
if (!valueMapper.count(val)) {
assert(!hasDeferredEmission(val.getDefiningOp()) &&
"cacheDeferredOpResult should have been called on this value, "
"update the emitOperation function.");
valueMapper.insert(val, formatv("v{0}", ++valueCount));
}
return *valueMapper.begin(val);
}
/// Return the existing or a new name for a loop induction variable Value.
/// Loop induction variables follow natural naming: i, j, k, ..., t, uX.
StringRef CppEmitter::getOrCreateInductionVarName(Value val) {
if (!valueMapper.count(val)) {
int64_t identifier = 'i' + loopNestingLevel;
if (identifier >= 'i' && identifier <= 't') {
valueMapper.insert(val,
formatv("{0}{1}", (char)identifier, ++valueCount));
} else {
// If running out of letters, continue with uX.
valueMapper.insert(val, formatv("u{0}", ++valueCount));
}
}
return *valueMapper.begin(val);
}
/// Return the existing or a new label for a Block.
StringRef CppEmitter::getOrCreateName(Block &block) {
if (!blockMapper.count(&block))
blockMapper.insert(&block, formatv("label{0}", ++labelInScopeCount.top()));
return *blockMapper.begin(&block);
}
bool CppEmitter::shouldMapToUnsigned(IntegerType::SignednessSemantics val) {
switch (val) {
case IntegerType::Signless:
return false;
case IntegerType::Signed:
return false;
case IntegerType::Unsigned:
return true;
}
llvm_unreachable("Unexpected IntegerType::SignednessSemantics");
}
bool CppEmitter::hasValueInScope(Value val) { return valueMapper.count(val); }
bool CppEmitter::hasBlockLabel(Block &block) {
return blockMapper.count(&block);
}
LogicalResult CppEmitter::emitAttribute(Location loc, Attribute attr) {
auto printInt = [&](const APInt &val, bool isUnsigned) {
if (val.getBitWidth() == 1) {
if (val.getBoolValue())
os << "true";
else
os << "false";
} else {
SmallString<128> strValue;
val.toString(strValue, 10, !isUnsigned, false);
os << strValue;
}
};
auto printFloat = [&](const APFloat &val) {
if (val.isFinite()) {
SmallString<128> strValue;
// Use default values of toString except don't truncate zeros.
val.toString(strValue, 0, 0, false);
os << strValue;
switch (llvm::APFloatBase::SemanticsToEnum(val.getSemantics())) {
case llvm::APFloatBase::S_IEEEhalf:
os << "f16";
break;
case llvm::APFloatBase::S_BFloat:
os << "bf16";
break;
case llvm::APFloatBase::S_IEEEsingle:
os << "f";
break;
case llvm::APFloatBase::S_IEEEdouble:
break;
default:
llvm_unreachable("unsupported floating point type");
};
} else if (val.isNaN()) {
os << "NAN";
} else if (val.isInfinity()) {
if (val.isNegative())
os << "-";
os << "INFINITY";
}
};
// Print floating point attributes.
if (auto fAttr = dyn_cast<FloatAttr>(attr)) {
if (!isa<Float16Type, BFloat16Type, Float32Type, Float64Type>(
fAttr.getType())) {
return emitError(
loc, "expected floating point attribute to be f16, bf16, f32 or f64");
}
printFloat(fAttr.getValue());
return success();
}
if (auto dense = dyn_cast<DenseFPElementsAttr>(attr)) {
if (!isa<Float16Type, BFloat16Type, Float32Type, Float64Type>(
dense.getElementType())) {
return emitError(
loc, "expected floating point attribute to be f16, bf16, f32 or f64");
}
os << '{';
interleaveComma(dense, os, [&](const APFloat &val) { printFloat(val); });
os << '}';
return success();
}
// Print integer attributes.
if (auto iAttr = dyn_cast<IntegerAttr>(attr)) {
if (auto iType = dyn_cast<IntegerType>(iAttr.getType())) {
printInt(iAttr.getValue(), shouldMapToUnsigned(iType.getSignedness()));
return success();
}
if (auto iType = dyn_cast<IndexType>(iAttr.getType())) {
printInt(iAttr.getValue(), false);
return success();
}
}
if (auto dense = dyn_cast<DenseIntElementsAttr>(attr)) {
if (auto iType = dyn_cast<IntegerType>(
cast<TensorType>(dense.getType()).getElementType())) {
os << '{';
interleaveComma(dense, os, [&](const APInt &val) {
printInt(val, shouldMapToUnsigned(iType.getSignedness()));
});
os << '}';
return success();
}
if (auto iType = dyn_cast<IndexType>(
cast<TensorType>(dense.getType()).getElementType())) {
os << '{';
interleaveComma(dense, os,
[&](const APInt &val) { printInt(val, false); });
os << '}';
return success();
}
}
// Print opaque attributes.
if (auto oAttr = dyn_cast<emitc::OpaqueAttr>(attr)) {
os << oAttr.getValue();
return success();
}
// Print symbolic reference attributes.
if (auto sAttr = dyn_cast<SymbolRefAttr>(attr)) {
if (sAttr.getNestedReferences().size() > 1)
return emitError(loc, "attribute has more than 1 nested reference");
os << sAttr.getRootReference().getValue();
return success();
}
// Print type attributes.
if (auto type = dyn_cast<TypeAttr>(attr))
return emitType(loc, type.getValue());
return emitError(loc, "cannot emit attribute: ") << attr;
}
LogicalResult CppEmitter::emitExpression(ExpressionOp expressionOp) {
assert(emittedExpressionPrecedence.empty() &&
"Expected precedence stack to be empty");
Operation *rootOp = expressionOp.getRootOp();
emittedExpression = expressionOp;
FailureOr<int> precedence = getOperatorPrecedence(rootOp);
if (failed(precedence))
return failure();
pushExpressionPrecedence(precedence.value());
if (failed(emitOperation(*rootOp, /*trailingSemicolon=*/false)))
return failure();
popExpressionPrecedence();
assert(emittedExpressionPrecedence.empty() &&
"Expected precedence stack to be empty");
emittedExpression = nullptr;
return success();
}
LogicalResult CppEmitter::emitOperand(Value value) {
if (isPartOfCurrentExpression(value)) {
Operation *def = value.getDefiningOp();
assert(def && "Expected operand to be defined by an operation");
FailureOr<int> precedence = getOperatorPrecedence(def);
if (failed(precedence))
return failure();
// Sub-expressions with equal or lower precedence need to be parenthesized,
// as they might be evaluated in the wrong order depending on the shape of
// the expression tree.
bool encloseInParenthesis = precedence.value() <= getExpressionPrecedence();
if (encloseInParenthesis)
os << "(";
pushExpressionPrecedence(precedence.value());
if (failed(emitOperation(*def, /*trailingSemicolon=*/false)))
return failure();
if (encloseInParenthesis)
os << ")";
popExpressionPrecedence();
return success();
}
auto expressionOp = value.getDefiningOp<ExpressionOp>();
if (expressionOp && shouldBeInlined(expressionOp))
return emitExpression(expressionOp);
os << getOrCreateName(value);
return success();
}
LogicalResult CppEmitter::emitOperands(Operation &op) {
return interleaveCommaWithError(op.getOperands(), os, [&](Value operand) {
// If an expression is being emitted, push lowest precedence as these
// operands are either wrapped by parenthesis.
if (getEmittedExpression())
pushExpressionPrecedence(lowestPrecedence());
if (failed(emitOperand(operand)))
return failure();
if (getEmittedExpression())
popExpressionPrecedence();
return success();
});
}
LogicalResult
CppEmitter::emitOperandsAndAttributes(Operation &op,
ArrayRef<StringRef> exclude) {
if (failed(emitOperands(op)))
return failure();
// Insert comma in between operands and non-filtered attributes if needed.
if (op.getNumOperands() > 0) {
for (NamedAttribute attr : op.getAttrs()) {
if (!llvm::is_contained(exclude, attr.getName().strref())) {
os << ", ";
break;
}
}
}
// Emit attributes.
auto emitNamedAttribute = [&](NamedAttribute attr) -> LogicalResult {
if (llvm::is_contained(exclude, attr.getName().strref()))
return success();
os << "/* " << attr.getName().getValue() << " */";
if (failed(emitAttribute(op.getLoc(), attr.getValue())))
return failure();
return success();
};
return interleaveCommaWithError(op.getAttrs(), os, emitNamedAttribute);
}
LogicalResult CppEmitter::emitVariableAssignment(OpResult result) {
if (!hasValueInScope(result)) {
return result.getDefiningOp()->emitOpError(
"result variable for the operation has not been declared");
}
os << getOrCreateName(result) << " = ";
return success();
}
LogicalResult CppEmitter::emitVariableDeclaration(OpResult result,
bool trailingSemicolon) {
if (hasDeferredEmission(result.getDefiningOp()))
return success();
if (hasValueInScope(result)) {
return result.getDefiningOp()->emitError(
"result variable for the operation already declared");
}
if (failed(emitVariableDeclaration(result.getOwner()->getLoc(),
result.getType(),
getOrCreateName(result))))
return failure();
if (trailingSemicolon)
os << ";\n";
return success();
}
LogicalResult CppEmitter::emitGlobalVariable(GlobalOp op) {
if (op.getExternSpecifier())
os << "extern ";
else if (op.getStaticSpecifier())
os << "static ";
if (op.getConstSpecifier())
os << "const ";
if (failed(emitVariableDeclaration(op->getLoc(), op.getType(),
op.getSymName()))) {
return failure();
}
std::optional<Attribute> initialValue = op.getInitialValue();
if (initialValue) {
os << " = ";
if (failed(emitAttribute(op->getLoc(), *initialValue)))
return failure();
}
os << ";";
return success();
}
LogicalResult CppEmitter::emitAssignPrefix(Operation &op) {
// If op is being emitted as part of an expression, bail out.
if (getEmittedExpression())
return success();
switch (op.getNumResults()) {
case 0:
break;
case 1: {
OpResult result = op.getResult(0);
if (shouldDeclareVariablesAtTop()) {
if (failed(emitVariableAssignment(result)))
return failure();
} else {
if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/false)))
return failure();
os << " = ";
}
break;
}
default:
if (!shouldDeclareVariablesAtTop()) {
for (OpResult result : op.getResults()) {
if (failed(emitVariableDeclaration(result, /*trailingSemicolon=*/true)))
return failure();
}
}
os << "std::tie(";
interleaveComma(op.getResults(), os,
[&](Value result) { os << getOrCreateName(result); });
os << ") = ";
}
return success();
}
LogicalResult CppEmitter::emitLabel(Block &block) {
if (!hasBlockLabel(block))
return block.getParentOp()->emitError("label for block not found");
// FIXME: Add feature in `raw_indented_ostream` to ignore indent for block
// label instead of using `getOStream`.
os.getOStream() << getOrCreateName(block) << ":\n";
return success();
}
LogicalResult CppEmitter::emitOperation(Operation &op, bool trailingSemicolon) {
LogicalResult status =
llvm::TypeSwitch<Operation *, LogicalResult>(&op)
// Builtin ops.
.Case<ModuleOp>([&](auto op) { return printOperation(*this, op); })
// CF ops.
.Case<cf::BranchOp, cf::CondBranchOp>(
[&](auto op) { return printOperation(*this, op); })
// EmitC ops.
.Case<emitc::AddOp, emitc::ApplyOp, emitc::AssignOp,
emitc::BitwiseAndOp, emitc::BitwiseLeftShiftOp,
emitc::BitwiseNotOp, emitc::BitwiseOrOp,
emitc::BitwiseRightShiftOp, emitc::BitwiseXorOp, emitc::CallOp,
emitc::CallOpaqueOp, emitc::CastOp, emitc::ClassOp,
emitc::CmpOp, emitc::ConditionalOp, emitc::ConstantOp,
emitc::DeclareFuncOp, emitc::DivOp, emitc::ExpressionOp,
emitc::FieldOp, emitc::FileOp, emitc::ForOp, emitc::FuncOp,
emitc::GetFieldOp, emitc::GlobalOp, emitc::IfOp,
emitc::IncludeOp, emitc::LoadOp, emitc::LogicalAndOp,
emitc::LogicalNotOp, emitc::LogicalOrOp, emitc::MulOp,
emitc::RemOp, emitc::ReturnOp, emitc::SubOp, emitc::SwitchOp,
emitc::UnaryMinusOp, emitc::UnaryPlusOp, emitc::VariableOp,
emitc::VerbatimOp>(
[&](auto op) { return printOperation(*this, op); })
// Func ops.
.Case<func::CallOp, func::FuncOp, func::ReturnOp>(
[&](auto op) { return printOperation(*this, op); })
.Case<emitc::GetGlobalOp>([&](auto op) {
cacheDeferredOpResult(op.getResult(), op.getName());
return success();
})
.Case<emitc::LiteralOp>([&](auto op) {
cacheDeferredOpResult(op.getResult(), op.getValue());
return success();
})
.Case<emitc::MemberOp>([&](auto op) {
cacheDeferredOpResult(op.getResult(), createMemberAccess(op));
return success();
})
.Case<emitc::MemberOfPtrOp>([&](auto op) {
cacheDeferredOpResult(op.getResult(), createMemberAccess(op));
return success();
})
.Case<emitc::SubscriptOp>([&](auto op) {
cacheDeferredOpResult(op.getResult(), getSubscriptName(op));
return success();
})
.Default([&](Operation *) {
return op.emitOpError("unable to find printer for op");
});
if (failed(status))
return failure();
if (hasDeferredEmission(&op))
return success();
if (getEmittedExpression() ||
(isa<emitc::ExpressionOp>(op) &&
shouldBeInlined(cast<emitc::ExpressionOp>(op))))
return success();
// Never emit a semicolon for some operations, especially if endening with
// `}`.
trailingSemicolon &=
!isa<cf::CondBranchOp, emitc::DeclareFuncOp, emitc::FileOp, emitc::ForOp,
emitc::IfOp, emitc::IncludeOp, emitc::SwitchOp, emitc::VerbatimOp>(
op);
os << (trailingSemicolon ? ";\n" : "\n");
return success();
}
LogicalResult CppEmitter::emitVariableDeclaration(Location loc, Type type,
StringRef name) {
if (auto arrType = dyn_cast<emitc::ArrayType>(type)) {
if (failed(emitType(loc, arrType.getElementType())))
return failure();
os << " " << name;
for (auto dim : arrType.getShape()) {
os << "[" << dim << "]";
}
return success();
}
if (failed(emitType(loc, type)))
return failure();
os << " " << name;
return success();
}
LogicalResult CppEmitter::emitType(Location loc, Type type) {
if (auto iType = dyn_cast<IntegerType>(type)) {
switch (iType.getWidth()) {
case 1:
return (os << "bool"), success();
case 8:
case 16:
case 32:
case 64:
if (shouldMapToUnsigned(iType.getSignedness()))
return (os << "uint" << iType.getWidth() << "_t"), success();
else
return (os << "int" << iType.getWidth() << "_t"), success();
default:
return emitError(loc, "cannot emit integer type ") << type;
}
}
if (auto fType = dyn_cast<FloatType>(type)) {
switch (fType.getWidth()) {
case 16: {
if (llvm::isa<Float16Type>(type))
return (os << "_Float16"), success();
else if (llvm::isa<BFloat16Type>(type))
return (os << "__bf16"), success();
else
return emitError(loc, "cannot emit float type ") << type;
}
case 32:
return (os << "float"), success();
case 64:
return (os << "double"), success();
default:
return emitError(loc, "cannot emit float type ") << type;
}
}
if (auto iType = dyn_cast<IndexType>(type))
return (os << "size_t"), success();
if (auto sType = dyn_cast<emitc::SizeTType>(type))
return (os << "size_t"), success();
if (auto sType = dyn_cast<emitc::SignedSizeTType>(type))
return (os << "ssize_t"), success();
if (auto pType = dyn_cast<emitc::PtrDiffTType>(type))
return (os << "ptrdiff_t"), success();
if (auto tType = dyn_cast<TensorType>(type)) {
if (!tType.hasRank())
return emitError(loc, "cannot emit unranked tensor type");
if (!tType.hasStaticShape())
return emitError(loc, "cannot emit tensor type with non static shape");
os << "Tensor<";
if (isa<ArrayType>(tType.getElementType()))
return emitError(loc, "cannot emit tensor of array type ") << type;
if (failed(emitType(loc, tType.getElementType())))
return failure();
auto shape = tType.getShape();
for (auto dimSize : shape) {
os << ", ";
os << dimSize;
}
os << ">";
return success();
}
if (auto tType = dyn_cast<TupleType>(type))
return emitTupleType(loc, tType.getTypes());
if (auto oType = dyn_cast<emitc::OpaqueType>(type)) {
os << oType.getValue();
return success();
}
if (auto aType = dyn_cast<emitc::ArrayType>(type)) {
if (failed(emitType(loc, aType.getElementType())))
return failure();
for (auto dim : aType.getShape())
os << "[" << dim << "]";
return success();
}
if (auto lType = dyn_cast<emitc::LValueType>(type))
return emitType(loc, lType.getValueType());
if (auto pType = dyn_cast<emitc::PointerType>(type)) {
if (isa<ArrayType>(pType.getPointee()))
return emitError(loc, "cannot emit pointer to array type ") << type;
if (failed(emitType(loc, pType.getPointee())))
return failure();
os << "*";
return success();
}
return emitError(loc, "cannot emit type ") << type;
}
LogicalResult CppEmitter::emitTypes(Location loc, ArrayRef<Type> types) {
switch (types.size()) {
case 0:
os << "void";
return success();
case 1:
return emitType(loc, types.front());
default:
return emitTupleType(loc, types);
}
}
LogicalResult CppEmitter::emitTupleType(Location loc, ArrayRef<Type> types) {
if (llvm::any_of(types, llvm::IsaPred<ArrayType>)) {
return emitError(loc, "cannot emit tuple of array type");
}
os << "std::tuple<";
if (failed(interleaveCommaWithError(
types, os, [&](Type type) { return emitType(loc, type); })))
return failure();
os << ">";
return success();
}
void CppEmitter::resetValueCounter() { valueCount = 0; }
void CppEmitter::increaseLoopNestingLevel() { loopNestingLevel++; }
void CppEmitter::decreaseLoopNestingLevel() { loopNestingLevel--; }
LogicalResult emitc::translateToCpp(Operation *op, raw_ostream &os,
bool declareVariablesAtTop,
StringRef fileId) {
CppEmitter emitter(os, declareVariablesAtTop, fileId);
return emitter.emitOperation(*op, /*trailingSemicolon=*/false);
}
|