summaryrefslogtreecommitdiff
path: root/mlir/test/CAPI/ir.c
blob: 5d4d63c9cda263baa19505ab25e4bc9955a7f3f0 (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
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
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
//===- ir.c - Simple test of C APIs ---------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

/* RUN: mlir-capi-ir-test 2>&1 | FileCheck %s
 */

#include "mlir-c/IR.h"
#include "mlir-c/AffineExpr.h"
#include "mlir-c/AffineMap.h"
#include "mlir-c/BuiltinAttributes.h"
#include "mlir-c/BuiltinTypes.h"
#include "mlir-c/Diagnostics.h"
#include "mlir-c/Dialect/Func.h"
#include "mlir-c/IntegerSet.h"
#include "mlir-c/RegisterEverything.h"
#include "mlir-c/Support.h"

#include <assert.h>
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void registerAllUpstreamDialects(MlirContext ctx) {
  MlirDialectRegistry registry = mlirDialectRegistryCreate();
  mlirRegisterAllDialects(registry);
  mlirContextAppendDialectRegistry(ctx, registry);
  mlirDialectRegistryDestroy(registry);
}

void populateLoopBody(MlirContext ctx, MlirBlock loopBody,
                      MlirLocation location, MlirBlock funcBody) {
  MlirValue iv = mlirBlockGetArgument(loopBody, 0);
  MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
  MlirValue funcArg1 = mlirBlockGetArgument(funcBody, 1);
  MlirType f32Type =
      mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("f32"));

  MlirOperationState loadLHSState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("memref.load"), location);
  MlirValue loadLHSOperands[] = {funcArg0, iv};
  mlirOperationStateAddOperands(&loadLHSState, 2, loadLHSOperands);
  mlirOperationStateAddResults(&loadLHSState, 1, &f32Type);
  MlirOperation loadLHS = mlirOperationCreate(&loadLHSState);
  mlirBlockAppendOwnedOperation(loopBody, loadLHS);

  MlirOperationState loadRHSState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("memref.load"), location);
  MlirValue loadRHSOperands[] = {funcArg1, iv};
  mlirOperationStateAddOperands(&loadRHSState, 2, loadRHSOperands);
  mlirOperationStateAddResults(&loadRHSState, 1, &f32Type);
  MlirOperation loadRHS = mlirOperationCreate(&loadRHSState);
  mlirBlockAppendOwnedOperation(loopBody, loadRHS);

  MlirOperationState addState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.addf"), location);
  MlirValue addOperands[] = {mlirOperationGetResult(loadLHS, 0),
                             mlirOperationGetResult(loadRHS, 0)};
  mlirOperationStateAddOperands(&addState, 2, addOperands);
  mlirOperationStateAddResults(&addState, 1, &f32Type);
  MlirOperation add = mlirOperationCreate(&addState);
  mlirBlockAppendOwnedOperation(loopBody, add);

  MlirOperationState storeState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("memref.store"), location);
  MlirValue storeOperands[] = {mlirOperationGetResult(add, 0), funcArg0, iv};
  mlirOperationStateAddOperands(&storeState, 3, storeOperands);
  MlirOperation store = mlirOperationCreate(&storeState);
  mlirBlockAppendOwnedOperation(loopBody, store);

  MlirOperationState yieldState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("scf.yield"), location);
  MlirOperation yield = mlirOperationCreate(&yieldState);
  mlirBlockAppendOwnedOperation(loopBody, yield);
}

MlirModule makeAndDumpAdd(MlirContext ctx, MlirLocation location) {
  MlirModule moduleOp = mlirModuleCreateEmpty(location);
  MlirBlock moduleBody = mlirModuleGetBody(moduleOp);

  MlirType memrefType =
      mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("memref<?xf32>"));
  MlirType funcBodyArgTypes[] = {memrefType, memrefType};
  MlirLocation funcBodyArgLocs[] = {location, location};
  MlirRegion funcBodyRegion = mlirRegionCreate();
  MlirBlock funcBody =
      mlirBlockCreate(sizeof(funcBodyArgTypes) / sizeof(MlirType),
                      funcBodyArgTypes, funcBodyArgLocs);
  mlirRegionAppendOwnedBlock(funcBodyRegion, funcBody);

  MlirAttribute funcTypeAttr = mlirAttributeParseGet(
      ctx,
      mlirStringRefCreateFromCString("(memref<?xf32>, memref<?xf32>) -> ()"));
  MlirAttribute funcNameAttr =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("\"add\""));
  MlirNamedAttribute funcAttrs[] = {
      mlirNamedAttributeGet(
          mlirIdentifierGet(ctx,
                            mlirStringRefCreateFromCString("function_type")),
          funcTypeAttr),
      mlirNamedAttributeGet(
          mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("sym_name")),
          funcNameAttr)};
  MlirOperationState funcState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("func.func"), location);
  mlirOperationStateAddAttributes(&funcState, 2, funcAttrs);
  mlirOperationStateAddOwnedRegions(&funcState, 1, &funcBodyRegion);
  MlirOperation func = mlirOperationCreate(&funcState);
  mlirBlockInsertOwnedOperation(moduleBody, 0, func);

  MlirType indexType =
      mlirTypeParseGet(ctx, mlirStringRefCreateFromCString("index"));
  MlirAttribute indexZeroLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
  MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
      indexZeroLiteral);
  MlirOperationState constZeroState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), location);
  mlirOperationStateAddResults(&constZeroState, 1, &indexType);
  mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
  MlirOperation constZero = mlirOperationCreate(&constZeroState);
  mlirBlockAppendOwnedOperation(funcBody, constZero);

  MlirValue funcArg0 = mlirBlockGetArgument(funcBody, 0);
  MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);
  MlirValue dimOperands[] = {funcArg0, constZeroValue};
  MlirOperationState dimState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("memref.dim"), location);
  mlirOperationStateAddOperands(&dimState, 2, dimOperands);
  mlirOperationStateAddResults(&dimState, 1, &indexType);
  MlirOperation dim = mlirOperationCreate(&dimState);
  mlirBlockAppendOwnedOperation(funcBody, dim);

  MlirRegion loopBodyRegion = mlirRegionCreate();
  MlirBlock loopBody = mlirBlockCreate(0, NULL, NULL);
  mlirBlockAddArgument(loopBody, indexType, location);
  mlirRegionAppendOwnedBlock(loopBodyRegion, loopBody);

  MlirAttribute indexOneLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
  MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
      indexOneLiteral);
  MlirOperationState constOneState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), location);
  mlirOperationStateAddResults(&constOneState, 1, &indexType);
  mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
  MlirOperation constOne = mlirOperationCreate(&constOneState);
  mlirBlockAppendOwnedOperation(funcBody, constOne);

  MlirValue dimValue = mlirOperationGetResult(dim, 0);
  MlirValue constOneValue = mlirOperationGetResult(constOne, 0);
  MlirValue loopOperands[] = {constZeroValue, dimValue, constOneValue};
  MlirOperationState loopState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("scf.for"), location);
  mlirOperationStateAddOperands(&loopState, 3, loopOperands);
  mlirOperationStateAddOwnedRegions(&loopState, 1, &loopBodyRegion);
  MlirOperation loop = mlirOperationCreate(&loopState);
  mlirBlockAppendOwnedOperation(funcBody, loop);

  populateLoopBody(ctx, loopBody, location, funcBody);

  MlirOperationState retState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("func.return"), location);
  MlirOperation ret = mlirOperationCreate(&retState);
  mlirBlockAppendOwnedOperation(funcBody, ret);

  MlirOperation module = mlirModuleGetOperation(moduleOp);
  mlirOperationDump(module);
  // clang-format off
  // CHECK: module {
  // CHECK:   func @add(%[[ARG0:.*]]: memref<?xf32>, %[[ARG1:.*]]: memref<?xf32>) {
  // CHECK:     %[[C0:.*]] = arith.constant 0 : index
  // CHECK:     %[[DIM:.*]] = memref.dim %[[ARG0]], %[[C0]] : memref<?xf32>
  // CHECK:     %[[C1:.*]] = arith.constant 1 : index
  // CHECK:     scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
  // CHECK:       %[[LHS:.*]] = memref.load %[[ARG0]][%[[I]]] : memref<?xf32>
  // CHECK:       %[[RHS:.*]] = memref.load %[[ARG1]][%[[I]]] : memref<?xf32>
  // CHECK:       %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
  // CHECK:       memref.store %[[SUM]], %[[ARG0]][%[[I]]] : memref<?xf32>
  // CHECK:     }
  // CHECK:     return
  // CHECK:   }
  // CHECK: }
  // clang-format on

  return moduleOp;
}

struct OpListNode {
  MlirOperation op;
  struct OpListNode *next;
};
typedef struct OpListNode OpListNode;

struct ModuleStats {
  unsigned numOperations;
  unsigned numAttributes;
  unsigned numBlocks;
  unsigned numRegions;
  unsigned numValues;
  unsigned numBlockArguments;
  unsigned numOpResults;
};
typedef struct ModuleStats ModuleStats;

int collectStatsSingle(OpListNode *head, ModuleStats *stats) {
  MlirOperation operation = head->op;
  stats->numOperations += 1;
  stats->numValues += mlirOperationGetNumResults(operation);
  stats->numAttributes += mlirOperationGetNumAttributes(operation);

  unsigned numRegions = mlirOperationGetNumRegions(operation);

  stats->numRegions += numRegions;

  intptr_t numResults = mlirOperationGetNumResults(operation);
  for (intptr_t i = 0; i < numResults; ++i) {
    MlirValue result = mlirOperationGetResult(operation, i);
    if (!mlirValueIsAOpResult(result))
      return 1;
    if (mlirValueIsABlockArgument(result))
      return 2;
    if (!mlirOperationEqual(operation, mlirOpResultGetOwner(result)))
      return 3;
    if (i != mlirOpResultGetResultNumber(result))
      return 4;
    ++stats->numOpResults;
  }

  MlirRegion region = mlirOperationGetFirstRegion(operation);
  while (!mlirRegionIsNull(region)) {
    for (MlirBlock block = mlirRegionGetFirstBlock(region);
         !mlirBlockIsNull(block); block = mlirBlockGetNextInRegion(block)) {
      ++stats->numBlocks;
      intptr_t numArgs = mlirBlockGetNumArguments(block);
      stats->numValues += numArgs;
      for (intptr_t j = 0; j < numArgs; ++j) {
        MlirValue arg = mlirBlockGetArgument(block, j);
        if (!mlirValueIsABlockArgument(arg))
          return 5;
        if (mlirValueIsAOpResult(arg))
          return 6;
        if (!mlirBlockEqual(block, mlirBlockArgumentGetOwner(arg)))
          return 7;
        if (j != mlirBlockArgumentGetArgNumber(arg))
          return 8;
        ++stats->numBlockArguments;
      }

      for (MlirOperation child = mlirBlockGetFirstOperation(block);
           !mlirOperationIsNull(child);
           child = mlirOperationGetNextInBlock(child)) {
        OpListNode *node = malloc(sizeof(OpListNode));
        node->op = child;
        node->next = head->next;
        head->next = node;
      }
    }
    region = mlirRegionGetNextInOperation(region);
  }
  return 0;
}

int collectStats(MlirOperation operation) {
  OpListNode *head = malloc(sizeof(OpListNode));
  head->op = operation;
  head->next = NULL;

  ModuleStats stats;
  stats.numOperations = 0;
  stats.numAttributes = 0;
  stats.numBlocks = 0;
  stats.numRegions = 0;
  stats.numValues = 0;
  stats.numBlockArguments = 0;
  stats.numOpResults = 0;

  do {
    int retval = collectStatsSingle(head, &stats);
    if (retval) {
      free(head);
      return retval;
    }
    OpListNode *next = head->next;
    free(head);
    head = next;
  } while (head);

  if (stats.numValues != stats.numBlockArguments + stats.numOpResults)
    return 100;

  fprintf(stderr, "@stats\n");
  fprintf(stderr, "Number of operations: %u\n", stats.numOperations);
  fprintf(stderr, "Number of attributes: %u\n", stats.numAttributes);
  fprintf(stderr, "Number of blocks: %u\n", stats.numBlocks);
  fprintf(stderr, "Number of regions: %u\n", stats.numRegions);
  fprintf(stderr, "Number of values: %u\n", stats.numValues);
  fprintf(stderr, "Number of block arguments: %u\n", stats.numBlockArguments);
  fprintf(stderr, "Number of op results: %u\n", stats.numOpResults);
  // clang-format off
  // CHECK-LABEL: @stats
  // CHECK: Number of operations: 12
  // CHECK: Number of attributes: 5
  // CHECK: Number of blocks: 3
  // CHECK: Number of regions: 3
  // CHECK: Number of values: 9
  // CHECK: Number of block arguments: 3
  // CHECK: Number of op results: 6
  // clang-format on
  return 0;
}

static void printToStderr(MlirStringRef str, void *userData) {
  (void)userData;
  fwrite(str.data, 1, str.length, stderr);
}

static void printFirstOfEach(MlirContext ctx, MlirOperation operation) {
  // Assuming we are given a module, go to the first operation of the first
  // function.
  MlirRegion region = mlirOperationGetRegion(operation, 0);
  MlirBlock block = mlirRegionGetFirstBlock(region);
  operation = mlirBlockGetFirstOperation(block);
  region = mlirOperationGetRegion(operation, 0);
  MlirOperation parentOperation = operation;
  block = mlirRegionGetFirstBlock(region);
  operation = mlirBlockGetFirstOperation(block);
  assert(mlirModuleIsNull(mlirModuleFromOperation(operation)));

  // Verify that parent operation and block report correctly.
  // CHECK: Parent operation eq: 1
  fprintf(stderr, "Parent operation eq: %d\n",
          mlirOperationEqual(mlirOperationGetParentOperation(operation),
                             parentOperation));
  // CHECK: Block eq: 1
  fprintf(stderr, "Block eq: %d\n",
          mlirBlockEqual(mlirOperationGetBlock(operation), block));
  // CHECK: Block parent operation eq: 1
  fprintf(
      stderr, "Block parent operation eq: %d\n",
      mlirOperationEqual(mlirBlockGetParentOperation(block), parentOperation));
  // CHECK: Block parent region eq: 1
  fprintf(stderr, "Block parent region eq: %d\n",
          mlirRegionEqual(mlirBlockGetParentRegion(block), region));

  // In the module we created, the first operation of the first function is
  // an "memref.dim", which has an attribute and a single result that we can
  // use to test the printing mechanism.
  mlirBlockPrint(block, printToStderr, NULL);
  fprintf(stderr, "\n");
  fprintf(stderr, "First operation: ");
  mlirOperationPrint(operation, printToStderr, NULL);
  fprintf(stderr, "\n");
  // clang-format off
  // CHECK:   %[[C0:.*]] = arith.constant 0 : index
  // CHECK:   %[[DIM:.*]] = memref.dim %{{.*}}, %[[C0]] : memref<?xf32>
  // CHECK:   %[[C1:.*]] = arith.constant 1 : index
  // CHECK:   scf.for %[[I:.*]] = %[[C0]] to %[[DIM]] step %[[C1]] {
  // CHECK:     %[[LHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
  // CHECK:     %[[RHS:.*]] = memref.load %{{.*}}[%[[I]]] : memref<?xf32>
  // CHECK:     %[[SUM:.*]] = arith.addf %[[LHS]], %[[RHS]] : f32
  // CHECK:     memref.store %[[SUM]], %{{.*}}[%[[I]]] : memref<?xf32>
  // CHECK:   }
  // CHECK: return
  // CHECK: First operation: {{.*}} = arith.constant 0 : index
  // clang-format on

  // Get the operation name and print it.
  MlirIdentifier ident = mlirOperationGetName(operation);
  MlirStringRef identStr = mlirIdentifierStr(ident);
  fprintf(stderr, "Operation name: '");
  for (size_t i = 0; i < identStr.length; ++i)
    fputc(identStr.data[i], stderr);
  fprintf(stderr, "'\n");
  // CHECK: Operation name: 'arith.constant'

  // Get the identifier again and verify equal.
  MlirIdentifier identAgain = mlirIdentifierGet(ctx, identStr);
  fprintf(stderr, "Identifier equal: %d\n",
          mlirIdentifierEqual(ident, identAgain));
  // CHECK: Identifier equal: 1

  // Get the block terminator and print it.
  MlirOperation terminator = mlirBlockGetTerminator(block);
  fprintf(stderr, "Terminator: ");
  mlirOperationPrint(terminator, printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Terminator: func.return

  // Get the attribute by index.
  MlirNamedAttribute namedAttr0 = mlirOperationGetAttribute(operation, 0);
  fprintf(stderr, "Get attr 0: ");
  mlirAttributePrint(namedAttr0.attribute, printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Get attr 0: 0 : index

  // Now re-get the attribute by name.
  MlirAttribute attr0ByName = mlirOperationGetAttributeByName(
      operation, mlirIdentifierStr(namedAttr0.name));
  fprintf(stderr, "Get attr 0 by name: ");
  mlirAttributePrint(attr0ByName, printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Get attr 0 by name: 0 : index

  // Get a non-existing attribute and assert that it is null (sanity).
  fprintf(stderr, "does_not_exist is null: %d\n",
          mlirAttributeIsNull(mlirOperationGetAttributeByName(
              operation, mlirStringRefCreateFromCString("does_not_exist"))));
  // CHECK: does_not_exist is null: 1

  // Get result 0 and its type.
  MlirValue value = mlirOperationGetResult(operation, 0);
  fprintf(stderr, "Result 0: ");
  mlirValuePrint(value, printToStderr, NULL);
  fprintf(stderr, "\n");
  fprintf(stderr, "Value is null: %d\n", mlirValueIsNull(value));
  // CHECK: Result 0: {{.*}} = arith.constant 0 : index
  // CHECK: Value is null: 0

  MlirType type = mlirValueGetType(value);
  fprintf(stderr, "Result 0 type: ");
  mlirTypePrint(type, printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Result 0 type: index

  // Set a custom attribute.
  mlirOperationSetAttributeByName(operation,
                                  mlirStringRefCreateFromCString("custom_attr"),
                                  mlirBoolAttrGet(ctx, 1));
  fprintf(stderr, "Op with set attr: ");
  mlirOperationPrint(operation, printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Op with set attr: {{.*}} {custom_attr = true}

  // Remove the attribute.
  fprintf(stderr, "Remove attr: %d\n",
          mlirOperationRemoveAttributeByName(
              operation, mlirStringRefCreateFromCString("custom_attr")));
  fprintf(stderr, "Remove attr again: %d\n",
          mlirOperationRemoveAttributeByName(
              operation, mlirStringRefCreateFromCString("custom_attr")));
  fprintf(stderr, "Removed attr is null: %d\n",
          mlirAttributeIsNull(mlirOperationGetAttributeByName(
              operation, mlirStringRefCreateFromCString("custom_attr"))));
  // CHECK: Remove attr: 1
  // CHECK: Remove attr again: 0
  // CHECK: Removed attr is null: 1

  // Add a large attribute to verify printing flags.
  int64_t eltsShape[] = {4};
  int32_t eltsData[] = {1, 2, 3, 4};
  mlirOperationSetAttributeByName(
      operation, mlirStringRefCreateFromCString("elts"),
      mlirDenseElementsAttrInt32Get(
          mlirRankedTensorTypeGet(1, eltsShape, mlirIntegerTypeGet(ctx, 32),
                                  mlirAttributeGetNull()),
          4, eltsData));
  MlirOpPrintingFlags flags = mlirOpPrintingFlagsCreate();
  mlirOpPrintingFlagsElideLargeElementsAttrs(flags, 2);
  mlirOpPrintingFlagsPrintGenericOpForm(flags);
  mlirOpPrintingFlagsEnableDebugInfo(flags, /*enable=*/1, /*prettyForm=*/0);
  mlirOpPrintingFlagsUseLocalScope(flags);
  fprintf(stderr, "Op print with all flags: ");
  mlirOperationPrintWithFlags(operation, flags, printToStderr, NULL);
  fprintf(stderr, "\n");
  // clang-format off
  // CHECK: Op print with all flags: %{{.*}} = "arith.constant"() <{value = 0 : index}> {elts = dense_resource<__elided__> : tensor<4xi32>} : () -> index loc(unknown)
  // clang-format on

  mlirOpPrintingFlagsDestroy(flags);
}

static int constructAndTraverseIr(MlirContext ctx) {
  MlirLocation location = mlirLocationUnknownGet(ctx);

  MlirModule moduleOp = makeAndDumpAdd(ctx, location);
  MlirOperation module = mlirModuleGetOperation(moduleOp);
  assert(!mlirModuleIsNull(mlirModuleFromOperation(module)));

  int errcode = collectStats(module);
  if (errcode)
    return errcode;

  printFirstOfEach(ctx, module);

  mlirModuleDestroy(moduleOp);
  return 0;
}

/// Creates an operation with a region containing multiple blocks with
/// operations and dumps it. The blocks and operations are inserted using
/// block/operation-relative API and their final order is checked.
static void buildWithInsertionsAndPrint(MlirContext ctx) {
  MlirLocation loc = mlirLocationUnknownGet(ctx);
  mlirContextSetAllowUnregisteredDialects(ctx, true);

  MlirRegion owningRegion = mlirRegionCreate();
  MlirBlock nullBlock = mlirRegionGetFirstBlock(owningRegion);
  MlirOperationState state = mlirOperationStateGet(
      mlirStringRefCreateFromCString("insertion.order.test"), loc);
  mlirOperationStateAddOwnedRegions(&state, 1, &owningRegion);
  MlirOperation op = mlirOperationCreate(&state);
  MlirRegion region = mlirOperationGetRegion(op, 0);

  // Use integer types of different bitwidth as block arguments in order to
  // differentiate blocks.
  MlirType i1 = mlirIntegerTypeGet(ctx, 1);
  MlirType i2 = mlirIntegerTypeGet(ctx, 2);
  MlirType i3 = mlirIntegerTypeGet(ctx, 3);
  MlirType i4 = mlirIntegerTypeGet(ctx, 4);
  MlirType i5 = mlirIntegerTypeGet(ctx, 5);
  MlirBlock block1 = mlirBlockCreate(1, &i1, &loc);
  MlirBlock block2 = mlirBlockCreate(1, &i2, &loc);
  MlirBlock block3 = mlirBlockCreate(1, &i3, &loc);
  MlirBlock block4 = mlirBlockCreate(1, &i4, &loc);
  MlirBlock block5 = mlirBlockCreate(1, &i5, &loc);
  // Insert blocks so as to obtain the 1-2-3-4 order,
  mlirRegionInsertOwnedBlockBefore(region, nullBlock, block3);
  mlirRegionInsertOwnedBlockBefore(region, block3, block2);
  mlirRegionInsertOwnedBlockAfter(region, nullBlock, block1);
  mlirRegionInsertOwnedBlockAfter(region, block3, block4);
  mlirRegionInsertOwnedBlockBefore(region, block3, block5);

  MlirOperationState op1State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op1"), loc);
  MlirOperationState op2State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc);
  MlirOperationState op3State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op3"), loc);
  MlirOperationState op4State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op4"), loc);
  MlirOperationState op5State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op5"), loc);
  MlirOperationState op6State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op6"), loc);
  MlirOperationState op7State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op7"), loc);
  MlirOperationState op8State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op8"), loc);
  MlirOperation op1 = mlirOperationCreate(&op1State);
  MlirOperation op2 = mlirOperationCreate(&op2State);
  MlirOperation op3 = mlirOperationCreate(&op3State);
  MlirOperation op4 = mlirOperationCreate(&op4State);
  MlirOperation op5 = mlirOperationCreate(&op5State);
  MlirOperation op6 = mlirOperationCreate(&op6State);
  MlirOperation op7 = mlirOperationCreate(&op7State);
  MlirOperation op8 = mlirOperationCreate(&op8State);

  // Insert operations in the first block so as to obtain the 1-2-3-4 order.
  MlirOperation nullOperation = mlirBlockGetFirstOperation(block1);
  assert(mlirOperationIsNull(nullOperation));
  mlirBlockInsertOwnedOperationBefore(block1, nullOperation, op3);
  mlirBlockInsertOwnedOperationBefore(block1, op3, op2);
  mlirBlockInsertOwnedOperationAfter(block1, nullOperation, op1);
  mlirBlockInsertOwnedOperationAfter(block1, op3, op4);

  // Append operations to the rest of blocks to make them non-empty and thus
  // printable.
  mlirBlockAppendOwnedOperation(block2, op5);
  mlirBlockAppendOwnedOperation(block3, op6);
  mlirBlockAppendOwnedOperation(block4, op7);
  mlirBlockAppendOwnedOperation(block5, op8);

  // Remove block5.
  mlirBlockDetach(block5);
  mlirBlockDestroy(block5);

  mlirOperationDump(op);
  mlirOperationDestroy(op);
  mlirContextSetAllowUnregisteredDialects(ctx, false);
  // clang-format off
  // CHECK-LABEL:  "insertion.order.test"
  // CHECK:      ^{{.*}}(%{{.*}}: i1
  // CHECK:        "dummy.op1"
  // CHECK-NEXT:   "dummy.op2"
  // CHECK-NEXT:   "dummy.op3"
  // CHECK-NEXT:   "dummy.op4"
  // CHECK:      ^{{.*}}(%{{.*}}: i2
  // CHECK:        "dummy.op5"
  // CHECK-NOT:  ^{{.*}}(%{{.*}}: i5
  // CHECK-NOT:    "dummy.op8"
  // CHECK:      ^{{.*}}(%{{.*}}: i3
  // CHECK:        "dummy.op6"
  // CHECK:      ^{{.*}}(%{{.*}}: i4
  // CHECK:        "dummy.op7"
  // clang-format on
}

/// Creates operations with type inference and tests various failure modes.
static int createOperationWithTypeInference(MlirContext ctx) {
  MlirLocation loc = mlirLocationUnknownGet(ctx);
  MlirAttribute iAttr = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 4);

  // The shape.const_size op implements result type inference and is only used
  // for that reason.
  MlirOperationState state = mlirOperationStateGet(
      mlirStringRefCreateFromCString("shape.const_size"), loc);
  MlirNamedAttribute valueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")), iAttr);
  mlirOperationStateAddAttributes(&state, 1, &valueAttr);
  mlirOperationStateEnableResultTypeInference(&state);

  // Expect result type inference to succeed.
  MlirOperation op = mlirOperationCreate(&state);
  if (mlirOperationIsNull(op)) {
    fprintf(stderr, "ERROR: Result type inference unexpectedly failed");
    return 1;
  }

  // CHECK: RESULT_TYPE_INFERENCE: !shape.size
  fprintf(stderr, "RESULT_TYPE_INFERENCE: ");
  mlirTypeDump(mlirValueGetType(mlirOperationGetResult(op, 0)));
  fprintf(stderr, "\n");
  mlirOperationDestroy(op);
  return 0;
}

/// Dumps instances of all builtin types to check that C API works correctly.
/// Additionally, performs simple identity checks that a builtin type
/// constructed with C API can be inspected and has the expected type. The
/// latter achieves full coverage of C API for builtin types. Returns 0 on
/// success and a non-zero error code on failure.
static int printBuiltinTypes(MlirContext ctx) {
  // Integer types.
  MlirType i32 = mlirIntegerTypeGet(ctx, 32);
  MlirType si32 = mlirIntegerTypeSignedGet(ctx, 32);
  MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
  if (!mlirTypeIsAInteger(i32) || mlirTypeIsAF32(i32))
    return 1;
  if (!mlirTypeIsAInteger(si32) || !mlirIntegerTypeIsSigned(si32))
    return 2;
  if (!mlirTypeIsAInteger(ui32) || !mlirIntegerTypeIsUnsigned(ui32))
    return 3;
  if (mlirTypeEqual(i32, ui32) || mlirTypeEqual(i32, si32))
    return 4;
  if (mlirIntegerTypeGetWidth(i32) != mlirIntegerTypeGetWidth(si32))
    return 5;
  fprintf(stderr, "@types\n");
  mlirTypeDump(i32);
  fprintf(stderr, "\n");
  mlirTypeDump(si32);
  fprintf(stderr, "\n");
  mlirTypeDump(ui32);
  fprintf(stderr, "\n");
  // CHECK-LABEL: @types
  // CHECK: i32
  // CHECK: si32
  // CHECK: ui32

  // Index type.
  MlirType index = mlirIndexTypeGet(ctx);
  if (!mlirTypeIsAIndex(index))
    return 6;
  mlirTypeDump(index);
  fprintf(stderr, "\n");
  // CHECK: index

  // Floating-point types.
  MlirType bf16 = mlirBF16TypeGet(ctx);
  MlirType f16 = mlirF16TypeGet(ctx);
  MlirType f32 = mlirF32TypeGet(ctx);
  MlirType f64 = mlirF64TypeGet(ctx);
  if (!mlirTypeIsABF16(bf16))
    return 7;
  if (!mlirTypeIsAF16(f16))
    return 9;
  if (!mlirTypeIsAF32(f32))
    return 10;
  if (!mlirTypeIsAF64(f64))
    return 11;
  mlirTypeDump(bf16);
  fprintf(stderr, "\n");
  mlirTypeDump(f16);
  fprintf(stderr, "\n");
  mlirTypeDump(f32);
  fprintf(stderr, "\n");
  mlirTypeDump(f64);
  fprintf(stderr, "\n");
  // CHECK: bf16
  // CHECK: f16
  // CHECK: f32
  // CHECK: f64

  // None type.
  MlirType none = mlirNoneTypeGet(ctx);
  if (!mlirTypeIsANone(none))
    return 12;
  mlirTypeDump(none);
  fprintf(stderr, "\n");
  // CHECK: none

  // Complex type.
  MlirType cplx = mlirComplexTypeGet(f32);
  if (!mlirTypeIsAComplex(cplx) ||
      !mlirTypeEqual(mlirComplexTypeGetElementType(cplx), f32))
    return 13;
  mlirTypeDump(cplx);
  fprintf(stderr, "\n");
  // CHECK: complex<f32>

  // Vector (and Shaped) type. ShapedType is a common base class for vectors,
  // memrefs and tensors, one cannot create instances of this class so it is
  // tested on an instance of vector type.
  int64_t shape[] = {2, 3};
  MlirType vector =
      mlirVectorTypeGet(sizeof(shape) / sizeof(int64_t), shape, f32);
  if (!mlirTypeIsAVector(vector) || !mlirTypeIsAShaped(vector))
    return 14;
  if (!mlirTypeEqual(mlirShapedTypeGetElementType(vector), f32) ||
      !mlirShapedTypeHasRank(vector) || mlirShapedTypeGetRank(vector) != 2 ||
      mlirShapedTypeGetDimSize(vector, 0) != 2 ||
      mlirShapedTypeIsDynamicDim(vector, 0) ||
      mlirShapedTypeGetDimSize(vector, 1) != 3 ||
      !mlirShapedTypeHasStaticShape(vector))
    return 15;
  mlirTypeDump(vector);
  fprintf(stderr, "\n");
  // CHECK: vector<2x3xf32>

  // Ranked tensor type.
  MlirType rankedTensor = mlirRankedTensorTypeGet(
      sizeof(shape) / sizeof(int64_t), shape, f32, mlirAttributeGetNull());
  if (!mlirTypeIsATensor(rankedTensor) ||
      !mlirTypeIsARankedTensor(rankedTensor) ||
      !mlirAttributeIsNull(mlirRankedTensorTypeGetEncoding(rankedTensor)))
    return 16;
  mlirTypeDump(rankedTensor);
  fprintf(stderr, "\n");
  // CHECK: tensor<2x3xf32>

  // Unranked tensor type.
  MlirType unrankedTensor = mlirUnrankedTensorTypeGet(f32);
  if (!mlirTypeIsATensor(unrankedTensor) ||
      !mlirTypeIsAUnrankedTensor(unrankedTensor) ||
      mlirShapedTypeHasRank(unrankedTensor))
    return 17;
  mlirTypeDump(unrankedTensor);
  fprintf(stderr, "\n");
  // CHECK: tensor<*xf32>

  // MemRef type.
  MlirAttribute memSpace2 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 2);
  MlirType memRef = mlirMemRefTypeContiguousGet(
      f32, sizeof(shape) / sizeof(int64_t), shape, memSpace2);
  if (!mlirTypeIsAMemRef(memRef) ||
      !mlirAttributeEqual(mlirMemRefTypeGetMemorySpace(memRef), memSpace2))
    return 18;
  mlirTypeDump(memRef);
  fprintf(stderr, "\n");
  // CHECK: memref<2x3xf32, 2>

  // Unranked MemRef type.
  MlirAttribute memSpace4 = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 64), 4);
  MlirType unrankedMemRef = mlirUnrankedMemRefTypeGet(f32, memSpace4);
  if (!mlirTypeIsAUnrankedMemRef(unrankedMemRef) ||
      mlirTypeIsAMemRef(unrankedMemRef) ||
      !mlirAttributeEqual(mlirUnrankedMemrefGetMemorySpace(unrankedMemRef),
                          memSpace4))
    return 19;
  mlirTypeDump(unrankedMemRef);
  fprintf(stderr, "\n");
  // CHECK: memref<*xf32, 4>

  // Tuple type.
  MlirType types[] = {unrankedMemRef, f32};
  MlirType tuple = mlirTupleTypeGet(ctx, 2, types);
  if (!mlirTypeIsATuple(tuple) || mlirTupleTypeGetNumTypes(tuple) != 2 ||
      !mlirTypeEqual(mlirTupleTypeGetType(tuple, 0), unrankedMemRef) ||
      !mlirTypeEqual(mlirTupleTypeGetType(tuple, 1), f32))
    return 20;
  mlirTypeDump(tuple);
  fprintf(stderr, "\n");
  // CHECK: tuple<memref<*xf32, 4>, f32>

  // Function type.
  MlirType funcInputs[2] = {mlirIndexTypeGet(ctx), mlirIntegerTypeGet(ctx, 1)};
  MlirType funcResults[3] = {mlirIntegerTypeGet(ctx, 16),
                             mlirIntegerTypeGet(ctx, 32),
                             mlirIntegerTypeGet(ctx, 64)};
  MlirType funcType = mlirFunctionTypeGet(ctx, 2, funcInputs, 3, funcResults);
  if (mlirFunctionTypeGetNumInputs(funcType) != 2)
    return 21;
  if (mlirFunctionTypeGetNumResults(funcType) != 3)
    return 22;
  if (!mlirTypeEqual(funcInputs[0], mlirFunctionTypeGetInput(funcType, 0)) ||
      !mlirTypeEqual(funcInputs[1], mlirFunctionTypeGetInput(funcType, 1)))
    return 23;
  if (!mlirTypeEqual(funcResults[0], mlirFunctionTypeGetResult(funcType, 0)) ||
      !mlirTypeEqual(funcResults[1], mlirFunctionTypeGetResult(funcType, 1)) ||
      !mlirTypeEqual(funcResults[2], mlirFunctionTypeGetResult(funcType, 2)))
    return 24;
  mlirTypeDump(funcType);
  fprintf(stderr, "\n");
  // CHECK: (index, i1) -> (i16, i32, i64)

  // Opaque type.
  MlirStringRef namespace = mlirStringRefCreate("dialect", 7);
  MlirStringRef data = mlirStringRefCreate("type", 4);
  mlirContextSetAllowUnregisteredDialects(ctx, true);
  MlirType opaque = mlirOpaqueTypeGet(ctx, namespace, data);
  mlirContextSetAllowUnregisteredDialects(ctx, false);
  if (!mlirTypeIsAOpaque(opaque) ||
      !mlirStringRefEqual(mlirOpaqueTypeGetDialectNamespace(opaque),
                          namespace) ||
      !mlirStringRefEqual(mlirOpaqueTypeGetData(opaque), data))
    return 25;
  mlirTypeDump(opaque);
  fprintf(stderr, "\n");
  // CHECK: !dialect.type

  return 0;
}

void callbackSetFixedLengthString(const char *data, intptr_t len,
                                  void *userData) {
  strncpy(userData, data, len);
}

bool stringIsEqual(const char *lhs, MlirStringRef rhs) {
  if (strlen(lhs) != rhs.length) {
    return false;
  }
  return !strncmp(lhs, rhs.data, rhs.length);
}

int printBuiltinAttributes(MlirContext ctx) {
  MlirAttribute floating =
      mlirFloatAttrDoubleGet(ctx, mlirF64TypeGet(ctx), 2.0);
  if (!mlirAttributeIsAFloat(floating) ||
      fabs(mlirFloatAttrGetValueDouble(floating) - 2.0) > 1E-6)
    return 1;
  fprintf(stderr, "@attrs\n");
  mlirAttributeDump(floating);
  // CHECK-LABEL: @attrs
  // CHECK: 2.000000e+00 : f64

  // Exercise mlirAttributeGetType() just for the first one.
  MlirType floatingType = mlirAttributeGetType(floating);
  mlirTypeDump(floatingType);
  // CHECK: f64

  MlirAttribute integer = mlirIntegerAttrGet(mlirIntegerTypeGet(ctx, 32), 42);
  MlirAttribute signedInteger =
      mlirIntegerAttrGet(mlirIntegerTypeSignedGet(ctx, 8), -1);
  MlirAttribute unsignedInteger =
      mlirIntegerAttrGet(mlirIntegerTypeUnsignedGet(ctx, 8), 255);
  if (!mlirAttributeIsAInteger(integer) ||
      mlirIntegerAttrGetValueInt(integer) != 42 ||
      mlirIntegerAttrGetValueSInt(signedInteger) != -1 ||
      mlirIntegerAttrGetValueUInt(unsignedInteger) != 255)
    return 2;
  mlirAttributeDump(integer);
  mlirAttributeDump(signedInteger);
  mlirAttributeDump(unsignedInteger);
  // CHECK: 42 : i32
  // CHECK: -1 : si8
  // CHECK: 255 : ui8

  MlirAttribute boolean = mlirBoolAttrGet(ctx, 1);
  if (!mlirAttributeIsABool(boolean) || !mlirBoolAttrGetValue(boolean))
    return 3;
  mlirAttributeDump(boolean);
  // CHECK: true

  const char data[] = "abcdefghijklmnopqestuvwxyz";
  MlirAttribute opaque =
      mlirOpaqueAttrGet(ctx, mlirStringRefCreateFromCString("func"), 3, data,
                        mlirNoneTypeGet(ctx));
  if (!mlirAttributeIsAOpaque(opaque) ||
      !stringIsEqual("func", mlirOpaqueAttrGetDialectNamespace(opaque)))
    return 4;

  MlirStringRef opaqueData = mlirOpaqueAttrGetData(opaque);
  if (opaqueData.length != 3 ||
      strncmp(data, opaqueData.data, opaqueData.length))
    return 5;
  mlirAttributeDump(opaque);
  // CHECK: #func.abc

  MlirAttribute string =
      mlirStringAttrGet(ctx, mlirStringRefCreate(data + 3, 2));
  if (!mlirAttributeIsAString(string))
    return 6;

  MlirStringRef stringValue = mlirStringAttrGetValue(string);
  if (stringValue.length != 2 ||
      strncmp(data + 3, stringValue.data, stringValue.length))
    return 7;
  mlirAttributeDump(string);
  // CHECK: "de"

  MlirAttribute flatSymbolRef =
      mlirFlatSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 5, 3));
  if (!mlirAttributeIsAFlatSymbolRef(flatSymbolRef))
    return 8;

  MlirStringRef flatSymbolRefValue =
      mlirFlatSymbolRefAttrGetValue(flatSymbolRef);
  if (flatSymbolRefValue.length != 3 ||
      strncmp(data + 5, flatSymbolRefValue.data, flatSymbolRefValue.length))
    return 9;
  mlirAttributeDump(flatSymbolRef);
  // CHECK: @fgh

  MlirAttribute symbols[] = {flatSymbolRef, flatSymbolRef};
  MlirAttribute symbolRef =
      mlirSymbolRefAttrGet(ctx, mlirStringRefCreate(data + 8, 2), 2, symbols);
  if (!mlirAttributeIsASymbolRef(symbolRef) ||
      mlirSymbolRefAttrGetNumNestedReferences(symbolRef) != 2 ||
      !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 0),
                          flatSymbolRef) ||
      !mlirAttributeEqual(mlirSymbolRefAttrGetNestedReference(symbolRef, 1),
                          flatSymbolRef))
    return 10;

  MlirStringRef symbolRefLeaf = mlirSymbolRefAttrGetLeafReference(symbolRef);
  MlirStringRef symbolRefRoot = mlirSymbolRefAttrGetRootReference(symbolRef);
  if (symbolRefLeaf.length != 3 ||
      strncmp(data + 5, symbolRefLeaf.data, symbolRefLeaf.length) ||
      symbolRefRoot.length != 2 ||
      strncmp(data + 8, symbolRefRoot.data, symbolRefRoot.length))
    return 11;
  mlirAttributeDump(symbolRef);
  // CHECK: @ij::@fgh::@fgh

  MlirAttribute type = mlirTypeAttrGet(mlirF32TypeGet(ctx));
  if (!mlirAttributeIsAType(type) ||
      !mlirTypeEqual(mlirF32TypeGet(ctx), mlirTypeAttrGetValue(type)))
    return 12;
  mlirAttributeDump(type);
  // CHECK: f32

  MlirAttribute unit = mlirUnitAttrGet(ctx);
  if (!mlirAttributeIsAUnit(unit))
    return 13;
  mlirAttributeDump(unit);
  // CHECK: unit

  int64_t shape[] = {1, 2};

  int bools[] = {0, 1};
  uint8_t uints8[] = {0u, 1u};
  int8_t ints8[] = {0, 1};
  uint16_t uints16[] = {0u, 1u};
  int16_t ints16[] = {0, 1};
  uint32_t uints32[] = {0u, 1u};
  int32_t ints32[] = {0, 1};
  uint64_t uints64[] = {0u, 1u};
  int64_t ints64[] = {0, 1};
  float floats[] = {0.0f, 1.0f};
  double doubles[] = {0.0, 1.0};
  uint16_t bf16s[] = {0x0, 0x3f80};
  uint16_t f16s[] = {0x0, 0x3c00};
  MlirAttribute encoding = mlirAttributeGetNull();
  MlirAttribute boolElements = mlirDenseElementsAttrBoolGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
      2, bools);
  MlirAttribute uint8Elements = mlirDenseElementsAttrUInt8Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
                              encoding),
      2, uints8);
  MlirAttribute int8Elements = mlirDenseElementsAttrInt8Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
      2, ints8);
  MlirAttribute uint16Elements = mlirDenseElementsAttrUInt16Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 16),
                              encoding),
      2, uints16);
  MlirAttribute int16Elements = mlirDenseElementsAttrInt16Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 16), encoding),
      2, ints16);
  MlirAttribute uint32Elements = mlirDenseElementsAttrUInt32Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
                              encoding),
      2, uints32);
  MlirAttribute int32Elements = mlirDenseElementsAttrInt32Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
      2, ints32);
  MlirAttribute uint64Elements = mlirDenseElementsAttrUInt64Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
                              encoding),
      2, uints64);
  MlirAttribute int64Elements = mlirDenseElementsAttrInt64Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
      2, ints64);
  MlirAttribute floatElements = mlirDenseElementsAttrFloatGet(
      mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 2,
      floats);
  MlirAttribute doubleElements = mlirDenseElementsAttrDoubleGet(
      mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 2,
      doubles);
  MlirAttribute bf16Elements = mlirDenseElementsAttrBFloat16Get(
      mlirRankedTensorTypeGet(2, shape, mlirBF16TypeGet(ctx), encoding), 2,
      bf16s);
  MlirAttribute f16Elements = mlirDenseElementsAttrFloat16Get(
      mlirRankedTensorTypeGet(2, shape, mlirF16TypeGet(ctx), encoding), 2,
      f16s);

  if (!mlirAttributeIsADenseElements(boolElements) ||
      !mlirAttributeIsADenseElements(uint8Elements) ||
      !mlirAttributeIsADenseElements(int8Elements) ||
      !mlirAttributeIsADenseElements(uint32Elements) ||
      !mlirAttributeIsADenseElements(int32Elements) ||
      !mlirAttributeIsADenseElements(uint64Elements) ||
      !mlirAttributeIsADenseElements(int64Elements) ||
      !mlirAttributeIsADenseElements(floatElements) ||
      !mlirAttributeIsADenseElements(doubleElements) ||
      !mlirAttributeIsADenseElements(bf16Elements) ||
      !mlirAttributeIsADenseElements(f16Elements))
    return 14;

  if (mlirDenseElementsAttrGetBoolValue(boolElements, 1) != 1 ||
      mlirDenseElementsAttrGetUInt8Value(uint8Elements, 1) != 1 ||
      mlirDenseElementsAttrGetInt8Value(int8Elements, 1) != 1 ||
      mlirDenseElementsAttrGetUInt16Value(uint16Elements, 1) != 1 ||
      mlirDenseElementsAttrGetInt16Value(int16Elements, 1) != 1 ||
      mlirDenseElementsAttrGetUInt32Value(uint32Elements, 1) != 1 ||
      mlirDenseElementsAttrGetInt32Value(int32Elements, 1) != 1 ||
      mlirDenseElementsAttrGetUInt64Value(uint64Elements, 1) != 1 ||
      mlirDenseElementsAttrGetInt64Value(int64Elements, 1) != 1 ||
      fabsf(mlirDenseElementsAttrGetFloatValue(floatElements, 1) - 1.0f) >
          1E-6f ||
      fabs(mlirDenseElementsAttrGetDoubleValue(doubleElements, 1) - 1.0) > 1E-6)
    return 15;

  mlirAttributeDump(boolElements);
  mlirAttributeDump(uint8Elements);
  mlirAttributeDump(int8Elements);
  mlirAttributeDump(uint32Elements);
  mlirAttributeDump(int32Elements);
  mlirAttributeDump(uint64Elements);
  mlirAttributeDump(int64Elements);
  mlirAttributeDump(floatElements);
  mlirAttributeDump(doubleElements);
  mlirAttributeDump(bf16Elements);
  mlirAttributeDump(f16Elements);
  // CHECK: dense<{{\[}}[false, true]]> : tensor<1x2xi1>
  // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui8>
  // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi8>
  // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui32>
  // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi32>
  // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xui64>
  // CHECK: dense<{{\[}}[0, 1]]> : tensor<1x2xi64>
  // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf32>
  // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf64>
  // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xbf16>
  // CHECK: dense<{{\[}}[0.000000e+00, 1.000000e+00]]> : tensor<1x2xf16>

  MlirAttribute splatBool = mlirDenseElementsAttrBoolSplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 1), encoding),
      1);
  MlirAttribute splatUInt8 = mlirDenseElementsAttrUInt8SplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
                              encoding),
      1);
  MlirAttribute splatInt8 = mlirDenseElementsAttrInt8SplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
      1);
  MlirAttribute splatUInt32 = mlirDenseElementsAttrUInt32SplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
                              encoding),
      1);
  MlirAttribute splatInt32 = mlirDenseElementsAttrInt32SplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
      1);
  MlirAttribute splatUInt64 = mlirDenseElementsAttrUInt64SplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
                              encoding),
      1);
  MlirAttribute splatInt64 = mlirDenseElementsAttrInt64SplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
      1);
  MlirAttribute splatFloat = mlirDenseElementsAttrFloatSplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding), 1.0f);
  MlirAttribute splatDouble = mlirDenseElementsAttrDoubleSplatGet(
      mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding), 1.0);

  if (!mlirAttributeIsADenseElements(splatBool) ||
      !mlirDenseElementsAttrIsSplat(splatBool) ||
      !mlirAttributeIsADenseElements(splatUInt8) ||
      !mlirDenseElementsAttrIsSplat(splatUInt8) ||
      !mlirAttributeIsADenseElements(splatInt8) ||
      !mlirDenseElementsAttrIsSplat(splatInt8) ||
      !mlirAttributeIsADenseElements(splatUInt32) ||
      !mlirDenseElementsAttrIsSplat(splatUInt32) ||
      !mlirAttributeIsADenseElements(splatInt32) ||
      !mlirDenseElementsAttrIsSplat(splatInt32) ||
      !mlirAttributeIsADenseElements(splatUInt64) ||
      !mlirDenseElementsAttrIsSplat(splatUInt64) ||
      !mlirAttributeIsADenseElements(splatInt64) ||
      !mlirDenseElementsAttrIsSplat(splatInt64) ||
      !mlirAttributeIsADenseElements(splatFloat) ||
      !mlirDenseElementsAttrIsSplat(splatFloat) ||
      !mlirAttributeIsADenseElements(splatDouble) ||
      !mlirDenseElementsAttrIsSplat(splatDouble))
    return 16;

  if (mlirDenseElementsAttrGetBoolSplatValue(splatBool) != 1 ||
      mlirDenseElementsAttrGetUInt8SplatValue(splatUInt8) != 1 ||
      mlirDenseElementsAttrGetInt8SplatValue(splatInt8) != 1 ||
      mlirDenseElementsAttrGetUInt32SplatValue(splatUInt32) != 1 ||
      mlirDenseElementsAttrGetInt32SplatValue(splatInt32) != 1 ||
      mlirDenseElementsAttrGetUInt64SplatValue(splatUInt64) != 1 ||
      mlirDenseElementsAttrGetInt64SplatValue(splatInt64) != 1 ||
      fabsf(mlirDenseElementsAttrGetFloatSplatValue(splatFloat) - 1.0f) >
          1E-6f ||
      fabs(mlirDenseElementsAttrGetDoubleSplatValue(splatDouble) - 1.0) > 1E-6)
    return 17;

  uint8_t *uint8RawData =
      (uint8_t *)mlirDenseElementsAttrGetRawData(uint8Elements);
  int8_t *int8RawData = (int8_t *)mlirDenseElementsAttrGetRawData(int8Elements);
  uint32_t *uint32RawData =
      (uint32_t *)mlirDenseElementsAttrGetRawData(uint32Elements);
  int32_t *int32RawData =
      (int32_t *)mlirDenseElementsAttrGetRawData(int32Elements);
  uint64_t *uint64RawData =
      (uint64_t *)mlirDenseElementsAttrGetRawData(uint64Elements);
  int64_t *int64RawData =
      (int64_t *)mlirDenseElementsAttrGetRawData(int64Elements);
  float *floatRawData = (float *)mlirDenseElementsAttrGetRawData(floatElements);
  double *doubleRawData =
      (double *)mlirDenseElementsAttrGetRawData(doubleElements);
  uint16_t *bf16RawData =
      (uint16_t *)mlirDenseElementsAttrGetRawData(bf16Elements);
  uint16_t *f16RawData =
      (uint16_t *)mlirDenseElementsAttrGetRawData(f16Elements);
  if (uint8RawData[0] != 0u || uint8RawData[1] != 1u || int8RawData[0] != 0 ||
      int8RawData[1] != 1 || uint32RawData[0] != 0u || uint32RawData[1] != 1u ||
      int32RawData[0] != 0 || int32RawData[1] != 1 || uint64RawData[0] != 0u ||
      uint64RawData[1] != 1u || int64RawData[0] != 0 || int64RawData[1] != 1 ||
      floatRawData[0] != 0.0f || floatRawData[1] != 1.0f ||
      doubleRawData[0] != 0.0 || doubleRawData[1] != 1.0 ||
      bf16RawData[0] != 0 || bf16RawData[1] != 0x3f80 || f16RawData[0] != 0 ||
      f16RawData[1] != 0x3c00)
    return 18;

  mlirAttributeDump(splatBool);
  mlirAttributeDump(splatUInt8);
  mlirAttributeDump(splatInt8);
  mlirAttributeDump(splatUInt32);
  mlirAttributeDump(splatInt32);
  mlirAttributeDump(splatUInt64);
  mlirAttributeDump(splatInt64);
  mlirAttributeDump(splatFloat);
  mlirAttributeDump(splatDouble);
  // CHECK: dense<true> : tensor<1x2xi1>
  // CHECK: dense<1> : tensor<1x2xui8>
  // CHECK: dense<1> : tensor<1x2xi8>
  // CHECK: dense<1> : tensor<1x2xui32>
  // CHECK: dense<1> : tensor<1x2xi32>
  // CHECK: dense<1> : tensor<1x2xui64>
  // CHECK: dense<1> : tensor<1x2xi64>
  // CHECK: dense<1.000000e+00> : tensor<1x2xf32>
  // CHECK: dense<1.000000e+00> : tensor<1x2xf64>

  mlirAttributeDump(mlirElementsAttrGetValue(floatElements, 2, uints64));
  mlirAttributeDump(mlirElementsAttrGetValue(doubleElements, 2, uints64));
  mlirAttributeDump(mlirElementsAttrGetValue(bf16Elements, 2, uints64));
  mlirAttributeDump(mlirElementsAttrGetValue(f16Elements, 2, uints64));
  // CHECK: 1.000000e+00 : f32
  // CHECK: 1.000000e+00 : f64
  // CHECK: 1.000000e+00 : bf16
  // CHECK: 1.000000e+00 : f16

  int64_t indices[] = {0, 1};
  int64_t one = 1;
  MlirAttribute indicesAttr = mlirDenseElementsAttrInt64Get(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
      2, indices);
  MlirAttribute valuesAttr = mlirDenseElementsAttrFloatGet(
      mlirRankedTensorTypeGet(1, &one, mlirF32TypeGet(ctx), encoding), 1,
      floats);
  MlirAttribute sparseAttr = mlirSparseElementsAttribute(
      mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding),
      indicesAttr, valuesAttr);
  mlirAttributeDump(sparseAttr);
  // CHECK: sparse<{{\[}}[0, 1]], 0.000000e+00> : tensor<1x2xf32>

  MlirAttribute boolArray = mlirDenseBoolArrayGet(ctx, 2, bools);
  MlirAttribute int8Array = mlirDenseI8ArrayGet(ctx, 2, ints8);
  MlirAttribute int16Array = mlirDenseI16ArrayGet(ctx, 2, ints16);
  MlirAttribute int32Array = mlirDenseI32ArrayGet(ctx, 2, ints32);
  MlirAttribute int64Array = mlirDenseI64ArrayGet(ctx, 2, ints64);
  MlirAttribute floatArray = mlirDenseF32ArrayGet(ctx, 2, floats);
  MlirAttribute doubleArray = mlirDenseF64ArrayGet(ctx, 2, doubles);
  if (!mlirAttributeIsADenseBoolArray(boolArray) ||
      !mlirAttributeIsADenseI8Array(int8Array) ||
      !mlirAttributeIsADenseI16Array(int16Array) ||
      !mlirAttributeIsADenseI32Array(int32Array) ||
      !mlirAttributeIsADenseI64Array(int64Array) ||
      !mlirAttributeIsADenseF32Array(floatArray) ||
      !mlirAttributeIsADenseF64Array(doubleArray))
    return 19;

  if (mlirDenseArrayGetNumElements(boolArray) != 2 ||
      mlirDenseArrayGetNumElements(int8Array) != 2 ||
      mlirDenseArrayGetNumElements(int16Array) != 2 ||
      mlirDenseArrayGetNumElements(int32Array) != 2 ||
      mlirDenseArrayGetNumElements(int64Array) != 2 ||
      mlirDenseArrayGetNumElements(floatArray) != 2 ||
      mlirDenseArrayGetNumElements(doubleArray) != 2)
    return 20;

  if (mlirDenseBoolArrayGetElement(boolArray, 1) != 1 ||
      mlirDenseI8ArrayGetElement(int8Array, 1) != 1 ||
      mlirDenseI16ArrayGetElement(int16Array, 1) != 1 ||
      mlirDenseI32ArrayGetElement(int32Array, 1) != 1 ||
      mlirDenseI64ArrayGetElement(int64Array, 1) != 1 ||
      fabsf(mlirDenseF32ArrayGetElement(floatArray, 1) - 1.0f) > 1E-6f ||
      fabs(mlirDenseF64ArrayGetElement(doubleArray, 1) - 1.0) > 1E-6)
    return 21;

  int64_t layoutStrides[3] = {5, 7, 13};
  MlirAttribute stridedLayoutAttr =
      mlirStridedLayoutAttrGet(ctx, 42, 3, &layoutStrides[0]);

  // CHECK: strided<[5, 7, 13], offset: 42>
  mlirAttributeDump(stridedLayoutAttr);

  if (mlirStridedLayoutAttrGetOffset(stridedLayoutAttr) != 42 ||
      mlirStridedLayoutAttrGetNumStrides(stridedLayoutAttr) != 3 ||
      mlirStridedLayoutAttrGetStride(stridedLayoutAttr, 0) != 5 ||
      mlirStridedLayoutAttrGetStride(stridedLayoutAttr, 1) != 7 ||
      mlirStridedLayoutAttrGetStride(stridedLayoutAttr, 2) != 13)
    return 22;

  MlirAttribute uint8Blob = mlirUnmanagedDenseUInt8ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 8),
                              encoding),
      mlirStringRefCreateFromCString("resource_ui8"), 2, uints8);
  MlirAttribute uint16Blob = mlirUnmanagedDenseUInt16ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 16),
                              encoding),
      mlirStringRefCreateFromCString("resource_ui16"), 2, uints16);
  MlirAttribute uint32Blob = mlirUnmanagedDenseUInt32ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 32),
                              encoding),
      mlirStringRefCreateFromCString("resource_ui32"), 2, uints32);
  MlirAttribute uint64Blob = mlirUnmanagedDenseUInt64ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeUnsignedGet(ctx, 64),
                              encoding),
      mlirStringRefCreateFromCString("resource_ui64"), 2, uints64);
  MlirAttribute int8Blob = mlirUnmanagedDenseInt8ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 8), encoding),
      mlirStringRefCreateFromCString("resource_i8"), 2, ints8);
  MlirAttribute int16Blob = mlirUnmanagedDenseInt16ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 16), encoding),
      mlirStringRefCreateFromCString("resource_i16"), 2, ints16);
  MlirAttribute int32Blob = mlirUnmanagedDenseInt32ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 32), encoding),
      mlirStringRefCreateFromCString("resource_i32"), 2, ints32);
  MlirAttribute int64Blob = mlirUnmanagedDenseInt64ResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirIntegerTypeGet(ctx, 64), encoding),
      mlirStringRefCreateFromCString("resource_i64"), 2, ints64);
  MlirAttribute floatsBlob = mlirUnmanagedDenseFloatResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirF32TypeGet(ctx), encoding),
      mlirStringRefCreateFromCString("resource_f32"), 2, floats);
  MlirAttribute doublesBlob = mlirUnmanagedDenseDoubleResourceElementsAttrGet(
      mlirRankedTensorTypeGet(2, shape, mlirF64TypeGet(ctx), encoding),
      mlirStringRefCreateFromCString("resource_f64"), 2, doubles);

  mlirAttributeDump(uint8Blob);
  mlirAttributeDump(uint16Blob);
  mlirAttributeDump(uint32Blob);
  mlirAttributeDump(uint64Blob);
  mlirAttributeDump(int8Blob);
  mlirAttributeDump(int16Blob);
  mlirAttributeDump(int32Blob);
  mlirAttributeDump(int64Blob);
  mlirAttributeDump(floatsBlob);
  mlirAttributeDump(doublesBlob);
  // CHECK: dense_resource<resource_ui8> : tensor<1x2xui8>
  // CHECK: dense_resource<resource_ui16> : tensor<1x2xui16>
  // CHECK: dense_resource<resource_ui32> : tensor<1x2xui32>
  // CHECK: dense_resource<resource_ui64> : tensor<1x2xui64>
  // CHECK: dense_resource<resource_i8> : tensor<1x2xi8>
  // CHECK: dense_resource<resource_i16> : tensor<1x2xi16>
  // CHECK: dense_resource<resource_i32> : tensor<1x2xi32>
  // CHECK: dense_resource<resource_i64> : tensor<1x2xi64>
  // CHECK: dense_resource<resource_f32> : tensor<1x2xf32>
  // CHECK: dense_resource<resource_f64> : tensor<1x2xf64>

  if (mlirDenseUInt8ResourceElementsAttrGetValue(uint8Blob, 1) != 1 ||
      mlirDenseUInt16ResourceElementsAttrGetValue(uint16Blob, 1) != 1 ||
      mlirDenseUInt32ResourceElementsAttrGetValue(uint32Blob, 1) != 1 ||
      mlirDenseUInt64ResourceElementsAttrGetValue(uint64Blob, 1) != 1 ||
      mlirDenseInt8ResourceElementsAttrGetValue(int8Blob, 1) != 1 ||
      mlirDenseInt16ResourceElementsAttrGetValue(int16Blob, 1) != 1 ||
      mlirDenseInt32ResourceElementsAttrGetValue(int32Blob, 1) != 1 ||
      mlirDenseInt64ResourceElementsAttrGetValue(int64Blob, 1) != 1 ||
      fabsf(mlirDenseF32ArrayGetElement(floatArray, 1) - 1.0f) > 1E-6f ||
      fabsf(mlirDenseFloatResourceElementsAttrGetValue(floatsBlob, 1) - 1.0f) >
          1e-6 ||
      fabs(mlirDenseDoubleResourceElementsAttrGetValue(doublesBlob, 1) - 1.0f) >
          1e-6)
    return 23;

  MlirLocation loc = mlirLocationUnknownGet(ctx);
  MlirAttribute locAttr = mlirLocationGetAttribute(loc);
  if (!mlirAttributeIsALocation(locAttr))
    return 24;

  return 0;
}

int printAffineMap(MlirContext ctx) {
  MlirAffineMap emptyAffineMap = mlirAffineMapEmptyGet(ctx);
  MlirAffineMap affineMap = mlirAffineMapZeroResultGet(ctx, 3, 2);
  MlirAffineMap constAffineMap = mlirAffineMapConstantGet(ctx, 2);
  MlirAffineMap multiDimIdentityAffineMap =
      mlirAffineMapMultiDimIdentityGet(ctx, 3);
  MlirAffineMap minorIdentityAffineMap =
      mlirAffineMapMinorIdentityGet(ctx, 3, 2);
  unsigned permutation[] = {1, 2, 0};
  MlirAffineMap permutationAffineMap = mlirAffineMapPermutationGet(
      ctx, sizeof(permutation) / sizeof(unsigned), permutation);

  fprintf(stderr, "@affineMap\n");
  mlirAffineMapDump(emptyAffineMap);
  mlirAffineMapDump(affineMap);
  mlirAffineMapDump(constAffineMap);
  mlirAffineMapDump(multiDimIdentityAffineMap);
  mlirAffineMapDump(minorIdentityAffineMap);
  mlirAffineMapDump(permutationAffineMap);
  // CHECK-LABEL: @affineMap
  // CHECK: () -> ()
  // CHECK: (d0, d1, d2)[s0, s1] -> ()
  // CHECK: () -> (2)
  // CHECK: (d0, d1, d2) -> (d0, d1, d2)
  // CHECK: (d0, d1, d2) -> (d1, d2)
  // CHECK: (d0, d1, d2) -> (d1, d2, d0)

  if (!mlirAffineMapIsIdentity(emptyAffineMap) ||
      mlirAffineMapIsIdentity(affineMap) ||
      mlirAffineMapIsIdentity(constAffineMap) ||
      !mlirAffineMapIsIdentity(multiDimIdentityAffineMap) ||
      mlirAffineMapIsIdentity(minorIdentityAffineMap) ||
      mlirAffineMapIsIdentity(permutationAffineMap))
    return 1;

  if (!mlirAffineMapIsMinorIdentity(emptyAffineMap) ||
      mlirAffineMapIsMinorIdentity(affineMap) ||
      !mlirAffineMapIsMinorIdentity(multiDimIdentityAffineMap) ||
      !mlirAffineMapIsMinorIdentity(minorIdentityAffineMap) ||
      mlirAffineMapIsMinorIdentity(permutationAffineMap))
    return 2;

  if (!mlirAffineMapIsEmpty(emptyAffineMap) ||
      mlirAffineMapIsEmpty(affineMap) || mlirAffineMapIsEmpty(constAffineMap) ||
      mlirAffineMapIsEmpty(multiDimIdentityAffineMap) ||
      mlirAffineMapIsEmpty(minorIdentityAffineMap) ||
      mlirAffineMapIsEmpty(permutationAffineMap))
    return 3;

  if (mlirAffineMapIsSingleConstant(emptyAffineMap) ||
      mlirAffineMapIsSingleConstant(affineMap) ||
      !mlirAffineMapIsSingleConstant(constAffineMap) ||
      mlirAffineMapIsSingleConstant(multiDimIdentityAffineMap) ||
      mlirAffineMapIsSingleConstant(minorIdentityAffineMap) ||
      mlirAffineMapIsSingleConstant(permutationAffineMap))
    return 4;

  if (mlirAffineMapGetSingleConstantResult(constAffineMap) != 2)
    return 5;

  if (mlirAffineMapGetNumDims(emptyAffineMap) != 0 ||
      mlirAffineMapGetNumDims(affineMap) != 3 ||
      mlirAffineMapGetNumDims(constAffineMap) != 0 ||
      mlirAffineMapGetNumDims(multiDimIdentityAffineMap) != 3 ||
      mlirAffineMapGetNumDims(minorIdentityAffineMap) != 3 ||
      mlirAffineMapGetNumDims(permutationAffineMap) != 3)
    return 6;

  if (mlirAffineMapGetNumSymbols(emptyAffineMap) != 0 ||
      mlirAffineMapGetNumSymbols(affineMap) != 2 ||
      mlirAffineMapGetNumSymbols(constAffineMap) != 0 ||
      mlirAffineMapGetNumSymbols(multiDimIdentityAffineMap) != 0 ||
      mlirAffineMapGetNumSymbols(minorIdentityAffineMap) != 0 ||
      mlirAffineMapGetNumSymbols(permutationAffineMap) != 0)
    return 7;

  if (mlirAffineMapGetNumResults(emptyAffineMap) != 0 ||
      mlirAffineMapGetNumResults(affineMap) != 0 ||
      mlirAffineMapGetNumResults(constAffineMap) != 1 ||
      mlirAffineMapGetNumResults(multiDimIdentityAffineMap) != 3 ||
      mlirAffineMapGetNumResults(minorIdentityAffineMap) != 2 ||
      mlirAffineMapGetNumResults(permutationAffineMap) != 3)
    return 8;

  if (mlirAffineMapGetNumInputs(emptyAffineMap) != 0 ||
      mlirAffineMapGetNumInputs(affineMap) != 5 ||
      mlirAffineMapGetNumInputs(constAffineMap) != 0 ||
      mlirAffineMapGetNumInputs(multiDimIdentityAffineMap) != 3 ||
      mlirAffineMapGetNumInputs(minorIdentityAffineMap) != 3 ||
      mlirAffineMapGetNumInputs(permutationAffineMap) != 3)
    return 9;

  if (!mlirAffineMapIsProjectedPermutation(emptyAffineMap) ||
      !mlirAffineMapIsPermutation(emptyAffineMap) ||
      mlirAffineMapIsProjectedPermutation(affineMap) ||
      mlirAffineMapIsPermutation(affineMap) ||
      mlirAffineMapIsProjectedPermutation(constAffineMap) ||
      mlirAffineMapIsPermutation(constAffineMap) ||
      !mlirAffineMapIsProjectedPermutation(multiDimIdentityAffineMap) ||
      !mlirAffineMapIsPermutation(multiDimIdentityAffineMap) ||
      !mlirAffineMapIsProjectedPermutation(minorIdentityAffineMap) ||
      mlirAffineMapIsPermutation(minorIdentityAffineMap) ||
      !mlirAffineMapIsProjectedPermutation(permutationAffineMap) ||
      !mlirAffineMapIsPermutation(permutationAffineMap))
    return 10;

  intptr_t sub[] = {1};

  MlirAffineMap subMap = mlirAffineMapGetSubMap(
      multiDimIdentityAffineMap, sizeof(sub) / sizeof(intptr_t), sub);
  MlirAffineMap majorSubMap =
      mlirAffineMapGetMajorSubMap(multiDimIdentityAffineMap, 1);
  MlirAffineMap minorSubMap =
      mlirAffineMapGetMinorSubMap(multiDimIdentityAffineMap, 1);

  mlirAffineMapDump(subMap);
  mlirAffineMapDump(majorSubMap);
  mlirAffineMapDump(minorSubMap);
  // CHECK: (d0, d1, d2) -> (d1)
  // CHECK: (d0, d1, d2) -> (d0)
  // CHECK: (d0, d1, d2) -> (d2)

  return 0;
}

int printAffineExpr(MlirContext ctx) {
  MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 5);
  MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 5);
  MlirAffineExpr affineConstantExpr = mlirAffineConstantExprGet(ctx, 5);
  MlirAffineExpr affineAddExpr =
      mlirAffineAddExprGet(affineDimExpr, affineSymbolExpr);
  MlirAffineExpr affineMulExpr =
      mlirAffineMulExprGet(affineDimExpr, affineSymbolExpr);
  MlirAffineExpr affineModExpr =
      mlirAffineModExprGet(affineDimExpr, affineSymbolExpr);
  MlirAffineExpr affineFloorDivExpr =
      mlirAffineFloorDivExprGet(affineDimExpr, affineSymbolExpr);
  MlirAffineExpr affineCeilDivExpr =
      mlirAffineCeilDivExprGet(affineDimExpr, affineSymbolExpr);

  // Tests mlirAffineExprDump.
  fprintf(stderr, "@affineExpr\n");
  mlirAffineExprDump(affineDimExpr);
  mlirAffineExprDump(affineSymbolExpr);
  mlirAffineExprDump(affineConstantExpr);
  mlirAffineExprDump(affineAddExpr);
  mlirAffineExprDump(affineMulExpr);
  mlirAffineExprDump(affineModExpr);
  mlirAffineExprDump(affineFloorDivExpr);
  mlirAffineExprDump(affineCeilDivExpr);
  // CHECK-LABEL: @affineExpr
  // CHECK: d5
  // CHECK: s5
  // CHECK: 5
  // CHECK: d5 + s5
  // CHECK: d5 * s5
  // CHECK: d5 mod s5
  // CHECK: d5 floordiv s5
  // CHECK: d5 ceildiv s5

  // Tests methods of affine binary operation expression, takes add expression
  // as an example.
  mlirAffineExprDump(mlirAffineBinaryOpExprGetLHS(affineAddExpr));
  mlirAffineExprDump(mlirAffineBinaryOpExprGetRHS(affineAddExpr));
  // CHECK: d5
  // CHECK: s5

  // Tests methods of affine dimension expression.
  if (mlirAffineDimExprGetPosition(affineDimExpr) != 5)
    return 1;

  // Tests methods of affine symbol expression.
  if (mlirAffineSymbolExprGetPosition(affineSymbolExpr) != 5)
    return 2;

  // Tests methods of affine constant expression.
  if (mlirAffineConstantExprGetValue(affineConstantExpr) != 5)
    return 3;

  // Tests methods of affine expression.
  if (mlirAffineExprIsSymbolicOrConstant(affineDimExpr) ||
      !mlirAffineExprIsSymbolicOrConstant(affineSymbolExpr) ||
      !mlirAffineExprIsSymbolicOrConstant(affineConstantExpr) ||
      mlirAffineExprIsSymbolicOrConstant(affineAddExpr) ||
      mlirAffineExprIsSymbolicOrConstant(affineMulExpr) ||
      mlirAffineExprIsSymbolicOrConstant(affineModExpr) ||
      mlirAffineExprIsSymbolicOrConstant(affineFloorDivExpr) ||
      mlirAffineExprIsSymbolicOrConstant(affineCeilDivExpr))
    return 4;

  if (!mlirAffineExprIsPureAffine(affineDimExpr) ||
      !mlirAffineExprIsPureAffine(affineSymbolExpr) ||
      !mlirAffineExprIsPureAffine(affineConstantExpr) ||
      !mlirAffineExprIsPureAffine(affineAddExpr) ||
      mlirAffineExprIsPureAffine(affineMulExpr) ||
      mlirAffineExprIsPureAffine(affineModExpr) ||
      mlirAffineExprIsPureAffine(affineFloorDivExpr) ||
      mlirAffineExprIsPureAffine(affineCeilDivExpr))
    return 5;

  if (mlirAffineExprGetLargestKnownDivisor(affineDimExpr) != 1 ||
      mlirAffineExprGetLargestKnownDivisor(affineSymbolExpr) != 1 ||
      mlirAffineExprGetLargestKnownDivisor(affineConstantExpr) != 5 ||
      mlirAffineExprGetLargestKnownDivisor(affineAddExpr) != 1 ||
      mlirAffineExprGetLargestKnownDivisor(affineMulExpr) != 1 ||
      mlirAffineExprGetLargestKnownDivisor(affineModExpr) != 1 ||
      mlirAffineExprGetLargestKnownDivisor(affineFloorDivExpr) != 1 ||
      mlirAffineExprGetLargestKnownDivisor(affineCeilDivExpr) != 1)
    return 6;

  if (!mlirAffineExprIsMultipleOf(affineDimExpr, 1) ||
      !mlirAffineExprIsMultipleOf(affineSymbolExpr, 1) ||
      !mlirAffineExprIsMultipleOf(affineConstantExpr, 5) ||
      !mlirAffineExprIsMultipleOf(affineAddExpr, 1) ||
      !mlirAffineExprIsMultipleOf(affineMulExpr, 1) ||
      !mlirAffineExprIsMultipleOf(affineModExpr, 1) ||
      !mlirAffineExprIsMultipleOf(affineFloorDivExpr, 1) ||
      !mlirAffineExprIsMultipleOf(affineCeilDivExpr, 1))
    return 7;

  if (!mlirAffineExprIsFunctionOfDim(affineDimExpr, 5) ||
      mlirAffineExprIsFunctionOfDim(affineSymbolExpr, 5) ||
      mlirAffineExprIsFunctionOfDim(affineConstantExpr, 5) ||
      !mlirAffineExprIsFunctionOfDim(affineAddExpr, 5) ||
      !mlirAffineExprIsFunctionOfDim(affineMulExpr, 5) ||
      !mlirAffineExprIsFunctionOfDim(affineModExpr, 5) ||
      !mlirAffineExprIsFunctionOfDim(affineFloorDivExpr, 5) ||
      !mlirAffineExprIsFunctionOfDim(affineCeilDivExpr, 5))
    return 8;

  // Tests 'IsA' methods of affine binary operation expression.
  if (!mlirAffineExprIsAAdd(affineAddExpr))
    return 9;

  if (!mlirAffineExprIsAMul(affineMulExpr))
    return 10;

  if (!mlirAffineExprIsAMod(affineModExpr))
    return 11;

  if (!mlirAffineExprIsAFloorDiv(affineFloorDivExpr))
    return 12;

  if (!mlirAffineExprIsACeilDiv(affineCeilDivExpr))
    return 13;

  if (!mlirAffineExprIsABinary(affineAddExpr))
    return 14;

  // Test other 'IsA' method on affine expressions.
  if (!mlirAffineExprIsAConstant(affineConstantExpr))
    return 15;

  if (!mlirAffineExprIsADim(affineDimExpr))
    return 16;

  if (!mlirAffineExprIsASymbol(affineSymbolExpr))
    return 17;

  // Test equality and nullity.
  MlirAffineExpr otherDimExpr = mlirAffineDimExprGet(ctx, 5);
  if (!mlirAffineExprEqual(affineDimExpr, otherDimExpr))
    return 18;

  if (mlirAffineExprIsNull(affineDimExpr))
    return 19;

  return 0;
}

int affineMapFromExprs(MlirContext ctx) {
  MlirAffineExpr affineDimExpr = mlirAffineDimExprGet(ctx, 0);
  MlirAffineExpr affineSymbolExpr = mlirAffineSymbolExprGet(ctx, 1);
  MlirAffineExpr exprs[] = {affineDimExpr, affineSymbolExpr};
  MlirAffineMap map = mlirAffineMapGet(ctx, 3, 3, 2, exprs);

  // CHECK-LABEL: @affineMapFromExprs
  fprintf(stderr, "@affineMapFromExprs");
  // CHECK: (d0, d1, d2)[s0, s1, s2] -> (d0, s1)
  mlirAffineMapDump(map);

  if (mlirAffineMapGetNumResults(map) != 2)
    return 1;

  if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 0), affineDimExpr))
    return 2;

  if (!mlirAffineExprEqual(mlirAffineMapGetResult(map, 1), affineSymbolExpr))
    return 3;

  MlirAffineExpr affineDim2Expr = mlirAffineDimExprGet(ctx, 1);
  MlirAffineExpr composed = mlirAffineExprCompose(affineDim2Expr, map);
  // CHECK: s1
  mlirAffineExprDump(composed);
  if (!mlirAffineExprEqual(composed, affineSymbolExpr))
    return 4;

  return 0;
}

int printIntegerSet(MlirContext ctx) {
  MlirIntegerSet emptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);

  // CHECK-LABEL: @printIntegerSet
  fprintf(stderr, "@printIntegerSet");

  // CHECK: (d0, d1)[s0] : (1 == 0)
  mlirIntegerSetDump(emptySet);

  if (!mlirIntegerSetIsCanonicalEmpty(emptySet))
    return 1;

  MlirIntegerSet anotherEmptySet = mlirIntegerSetEmptyGet(ctx, 2, 1);
  if (!mlirIntegerSetEqual(emptySet, anotherEmptySet))
    return 2;

  // Construct a set constrained by:
  //   d0 - s0 == 0,
  //   d1 - 42 >= 0.
  MlirAffineExpr negOne = mlirAffineConstantExprGet(ctx, -1);
  MlirAffineExpr negFortyTwo = mlirAffineConstantExprGet(ctx, -42);
  MlirAffineExpr d0 = mlirAffineDimExprGet(ctx, 0);
  MlirAffineExpr d1 = mlirAffineDimExprGet(ctx, 1);
  MlirAffineExpr s0 = mlirAffineSymbolExprGet(ctx, 0);
  MlirAffineExpr negS0 = mlirAffineMulExprGet(negOne, s0);
  MlirAffineExpr d0minusS0 = mlirAffineAddExprGet(d0, negS0);
  MlirAffineExpr d1minus42 = mlirAffineAddExprGet(d1, negFortyTwo);
  MlirAffineExpr constraints[] = {d0minusS0, d1minus42};
  bool flags[] = {true, false};

  MlirIntegerSet set = mlirIntegerSetGet(ctx, 2, 1, 2, constraints, flags);
  // CHECK: (d0, d1)[s0] : (
  // CHECK-DAG: d0 - s0 == 0
  // CHECK-DAG: d1 - 42 >= 0
  mlirIntegerSetDump(set);

  // Transform d1 into s0.
  MlirAffineExpr s1 = mlirAffineSymbolExprGet(ctx, 1);
  MlirAffineExpr repl[] = {d0, s1};
  MlirIntegerSet replaced = mlirIntegerSetReplaceGet(set, repl, &s0, 1, 2);
  // CHECK: (d0)[s0, s1] : (
  // CHECK-DAG: d0 - s0 == 0
  // CHECK-DAG: s1 - 42 >= 0
  mlirIntegerSetDump(replaced);

  if (mlirIntegerSetGetNumDims(set) != 2)
    return 3;
  if (mlirIntegerSetGetNumDims(replaced) != 1)
    return 4;

  if (mlirIntegerSetGetNumSymbols(set) != 1)
    return 5;
  if (mlirIntegerSetGetNumSymbols(replaced) != 2)
    return 6;

  if (mlirIntegerSetGetNumInputs(set) != 3)
    return 7;

  if (mlirIntegerSetGetNumConstraints(set) != 2)
    return 8;

  if (mlirIntegerSetGetNumEqualities(set) != 1)
    return 9;

  if (mlirIntegerSetGetNumInequalities(set) != 1)
    return 10;

  MlirAffineExpr cstr1 = mlirIntegerSetGetConstraint(set, 0);
  MlirAffineExpr cstr2 = mlirIntegerSetGetConstraint(set, 1);
  bool isEq1 = mlirIntegerSetIsConstraintEq(set, 0);
  bool isEq2 = mlirIntegerSetIsConstraintEq(set, 1);
  if (!mlirAffineExprEqual(cstr1, isEq1 ? d0minusS0 : d1minus42))
    return 11;
  if (!mlirAffineExprEqual(cstr2, isEq2 ? d0minusS0 : d1minus42))
    return 12;

  return 0;
}

int registerOnlyStd(void) {
  MlirContext ctx = mlirContextCreate();
  // The built-in dialect is always loaded.
  if (mlirContextGetNumLoadedDialects(ctx) != 1)
    return 1;

  MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();

  MlirDialect std = mlirContextGetOrLoadDialect(
      ctx, mlirDialectHandleGetNamespace(stdHandle));
  if (!mlirDialectIsNull(std))
    return 2;

  mlirDialectHandleRegisterDialect(stdHandle, ctx);

  std = mlirContextGetOrLoadDialect(ctx,
                                    mlirDialectHandleGetNamespace(stdHandle));
  if (mlirDialectIsNull(std))
    return 3;

  MlirDialect alsoStd = mlirDialectHandleLoadDialect(stdHandle, ctx);
  if (!mlirDialectEqual(std, alsoStd))
    return 4;

  MlirStringRef stdNs = mlirDialectGetNamespace(std);
  MlirStringRef alsoStdNs = mlirDialectHandleGetNamespace(stdHandle);
  if (stdNs.length != alsoStdNs.length ||
      strncmp(stdNs.data, alsoStdNs.data, stdNs.length))
    return 5;

  fprintf(stderr, "@registration\n");
  // CHECK-LABEL: @registration

  // CHECK: cf.cond_br is_registered: 1
  fprintf(stderr, "cf.cond_br is_registered: %d\n",
          mlirContextIsRegisteredOperation(
              ctx, mlirStringRefCreateFromCString("cf.cond_br")));

  // CHECK: func.not_existing_op is_registered: 0
  fprintf(stderr, "func.not_existing_op is_registered: %d\n",
          mlirContextIsRegisteredOperation(
              ctx, mlirStringRefCreateFromCString("func.not_existing_op")));

  // CHECK: not_existing_dialect.not_existing_op is_registered: 0
  fprintf(stderr, "not_existing_dialect.not_existing_op is_registered: %d\n",
          mlirContextIsRegisteredOperation(
              ctx, mlirStringRefCreateFromCString(
                       "not_existing_dialect.not_existing_op")));

  mlirContextDestroy(ctx);
  return 0;
}

/// Tests backreference APIs
static int testBackreferences(void) {
  fprintf(stderr, "@test_backreferences\n");

  MlirContext ctx = mlirContextCreate();
  mlirContextSetAllowUnregisteredDialects(ctx, true);
  MlirLocation loc = mlirLocationUnknownGet(ctx);

  MlirOperationState opState =
      mlirOperationStateGet(mlirStringRefCreateFromCString("invalid.op"), loc);
  MlirRegion region = mlirRegionCreate();
  MlirBlock block = mlirBlockCreate(0, NULL, NULL);
  mlirRegionAppendOwnedBlock(region, block);
  mlirOperationStateAddOwnedRegions(&opState, 1, &region);
  MlirOperation op = mlirOperationCreate(&opState);
  MlirIdentifier ident =
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("identifier"));

  if (!mlirContextEqual(ctx, mlirOperationGetContext(op))) {
    fprintf(stderr, "ERROR: Getting context from operation failed\n");
    return 1;
  }
  if (!mlirOperationEqual(op, mlirBlockGetParentOperation(block))) {
    fprintf(stderr, "ERROR: Getting parent operation from block failed\n");
    return 2;
  }
  if (!mlirContextEqual(ctx, mlirIdentifierGetContext(ident))) {
    fprintf(stderr, "ERROR: Getting context from identifier failed\n");
    return 3;
  }

  mlirOperationDestroy(op);
  mlirContextDestroy(ctx);

  // CHECK-LABEL: @test_backreferences
  return 0;
}

/// Tests operand APIs.
int testOperands(void) {
  fprintf(stderr, "@testOperands\n");
  // CHECK-LABEL: @testOperands

  MlirContext ctx = mlirContextCreate();
  registerAllUpstreamDialects(ctx);

  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("arith"));
  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("test"));
  MlirLocation loc = mlirLocationUnknownGet(ctx);
  MlirType indexType = mlirIndexTypeGet(ctx);

  // Create some constants to use as operands.
  MlirAttribute indexZeroLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
  MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
      indexZeroLiteral);
  MlirOperationState constZeroState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), loc);
  mlirOperationStateAddResults(&constZeroState, 1, &indexType);
  mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
  MlirOperation constZero = mlirOperationCreate(&constZeroState);
  MlirValue constZeroValue = mlirOperationGetResult(constZero, 0);

  MlirAttribute indexOneLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
  MlirNamedAttribute indexOneValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
      indexOneLiteral);
  MlirOperationState constOneState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), loc);
  mlirOperationStateAddResults(&constOneState, 1, &indexType);
  mlirOperationStateAddAttributes(&constOneState, 1, &indexOneValueAttr);
  MlirOperation constOne = mlirOperationCreate(&constOneState);
  MlirValue constOneValue = mlirOperationGetResult(constOne, 0);

  // Create the operation under test.
  mlirContextSetAllowUnregisteredDialects(ctx, true);
  MlirOperationState opState =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
  MlirValue initialOperands[] = {constZeroValue};
  mlirOperationStateAddOperands(&opState, 1, initialOperands);
  MlirOperation op = mlirOperationCreate(&opState);

  // Test operand APIs.
  intptr_t numOperands = mlirOperationGetNumOperands(op);
  fprintf(stderr, "Num Operands: %" PRIdPTR "\n", numOperands);
  // CHECK: Num Operands: 1

  MlirValue opOperand1 = mlirOperationGetOperand(op, 0);
  fprintf(stderr, "Original operand: ");
  mlirValuePrint(opOperand1, printToStderr, NULL);
  // CHECK: Original operand: {{.+}} arith.constant 0 : index

  mlirOperationSetOperand(op, 0, constOneValue);
  MlirValue opOperand2 = mlirOperationGetOperand(op, 0);
  fprintf(stderr, "Updated operand: ");
  mlirValuePrint(opOperand2, printToStderr, NULL);
  // CHECK: Updated operand: {{.+}} arith.constant 1 : index

  // Test op operand APIs.
  MlirOpOperand use1 = mlirValueGetFirstUse(opOperand1);
  if (!mlirOpOperandIsNull(use1)) {
    fprintf(stderr, "ERROR: Use should be null\n");
    return 1;
  }

  MlirOpOperand use2 = mlirValueGetFirstUse(opOperand2);
  if (mlirOpOperandIsNull(use2)) {
    fprintf(stderr, "ERROR: Use should not be null\n");
    return 2;
  }

  fprintf(stderr, "Use owner: ");
  mlirOperationPrint(mlirOpOperandGetOwner(use2), printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Use owner: "dummy.op"

  fprintf(stderr, "Use operandNumber: %d\n",
          mlirOpOperandGetOperandNumber(use2));
  // CHECK: Use operandNumber: 0

  use2 = mlirOpOperandGetNextUse(use2);
  if (!mlirOpOperandIsNull(use2)) {
    fprintf(stderr, "ERROR: Next use should be null\n");
    return 3;
  }

  MlirOperationState op2State =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op2"), loc);
  MlirValue initialOperands2[] = {constOneValue};
  mlirOperationStateAddOperands(&op2State, 1, initialOperands2);
  MlirOperation op2 = mlirOperationCreate(&op2State);

  MlirOpOperand use3 = mlirValueGetFirstUse(constOneValue);
  fprintf(stderr, "First use owner: ");
  mlirOperationPrint(mlirOpOperandGetOwner(use3), printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: First use owner: "dummy.op2"

  use3 = mlirOpOperandGetNextUse(mlirValueGetFirstUse(constOneValue));
  fprintf(stderr, "Second use owner: ");
  mlirOperationPrint(mlirOpOperandGetOwner(use3), printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Second use owner: "dummy.op"

  MlirAttribute indexTwoLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("2 : index"));
  MlirNamedAttribute indexTwoValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, mlirStringRefCreateFromCString("value")),
      indexTwoLiteral);
  MlirOperationState constTwoState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), loc);
  mlirOperationStateAddResults(&constTwoState, 1, &indexType);
  mlirOperationStateAddAttributes(&constTwoState, 1, &indexTwoValueAttr);
  MlirOperation constTwo = mlirOperationCreate(&constTwoState);
  MlirValue constTwoValue = mlirOperationGetResult(constTwo, 0);

  mlirValueReplaceAllUsesOfWith(constOneValue, constTwoValue);

  use3 = mlirValueGetFirstUse(constOneValue);
  if (!mlirOpOperandIsNull(use3)) {
    fprintf(stderr, "ERROR: Use should be null\n");
    return 4;
  }

  MlirOpOperand use4 = mlirValueGetFirstUse(constTwoValue);
  fprintf(stderr, "First replacement use owner: ");
  mlirOperationPrint(mlirOpOperandGetOwner(use4), printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: First replacement use owner: "dummy.op"

  use4 = mlirOpOperandGetNextUse(mlirValueGetFirstUse(constTwoValue));
  fprintf(stderr, "Second replacement use owner: ");
  mlirOperationPrint(mlirOpOperandGetOwner(use4), printToStderr, NULL);
  fprintf(stderr, "\n");
  // CHECK: Second replacement use owner: "dummy.op2"

  mlirOperationDestroy(op);
  mlirOperationDestroy(op2);
  mlirOperationDestroy(constZero);
  mlirOperationDestroy(constOne);
  mlirOperationDestroy(constTwo);
  mlirContextDestroy(ctx);

  return 0;
}

/// Tests clone APIs.
int testClone(void) {
  fprintf(stderr, "@testClone\n");
  // CHECK-LABEL: @testClone

  MlirContext ctx = mlirContextCreate();
  registerAllUpstreamDialects(ctx);

  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
  MlirLocation loc = mlirLocationUnknownGet(ctx);
  MlirType indexType = mlirIndexTypeGet(ctx);
  MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");

  MlirAttribute indexZeroLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
  MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
  MlirOperationState constZeroState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), loc);
  mlirOperationStateAddResults(&constZeroState, 1, &indexType);
  mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
  MlirOperation constZero = mlirOperationCreate(&constZeroState);

  MlirAttribute indexOneLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("1 : index"));
  MlirOperation constOne = mlirOperationClone(constZero);
  mlirOperationSetAttributeByName(constOne, valueStringRef, indexOneLiteral);

  mlirOperationPrint(constZero, printToStderr, NULL);
  mlirOperationPrint(constOne, printToStderr, NULL);
  // CHECK: arith.constant 0 : index
  // CHECK: arith.constant 1 : index

  mlirOperationDestroy(constZero);
  mlirOperationDestroy(constOne);
  mlirContextDestroy(ctx);
  return 0;
}

// Wraps a diagnostic into additional text we can match against.
MlirLogicalResult errorHandler(MlirDiagnostic diagnostic, void *userData) {
  fprintf(stderr, "processing diagnostic (userData: %" PRIdPTR ") <<\n",
          (intptr_t)userData);
  mlirDiagnosticPrint(diagnostic, printToStderr, NULL);
  fprintf(stderr, "\n");
  MlirLocation loc = mlirDiagnosticGetLocation(diagnostic);
  mlirLocationPrint(loc, printToStderr, NULL);
  assert(mlirDiagnosticGetNumNotes(diagnostic) == 0);
  fprintf(stderr, "\n>> end of diagnostic (userData: %" PRIdPTR ")\n",
          (intptr_t)userData);
  return mlirLogicalResultSuccess();
}

// Logs when the delete user data callback is called
static void deleteUserData(void *userData) {
  fprintf(stderr, "deleting user data (userData: %" PRIdPTR ")\n",
          (intptr_t)userData);
}

int testTypeID(MlirContext ctx) {
  fprintf(stderr, "@testTypeID\n");

  // Test getting and comparing type and attribute type ids.
  MlirType i32 = mlirIntegerTypeGet(ctx, 32);
  MlirTypeID i32ID = mlirTypeGetTypeID(i32);
  MlirType ui32 = mlirIntegerTypeUnsignedGet(ctx, 32);
  MlirTypeID ui32ID = mlirTypeGetTypeID(ui32);
  MlirType f32 = mlirF32TypeGet(ctx);
  MlirTypeID f32ID = mlirTypeGetTypeID(f32);
  MlirAttribute i32Attr = mlirIntegerAttrGet(i32, 1);
  MlirTypeID i32AttrID = mlirAttributeGetTypeID(i32Attr);

  if (mlirTypeIDIsNull(i32ID) || mlirTypeIDIsNull(ui32ID) ||
      mlirTypeIDIsNull(f32ID) || mlirTypeIDIsNull(i32AttrID)) {
    fprintf(stderr, "ERROR: Expected type ids to be present\n");
    return 1;
  }

  if (!mlirTypeIDEqual(i32ID, ui32ID) ||
      mlirTypeIDHashValue(i32ID) != mlirTypeIDHashValue(ui32ID)) {
    fprintf(
        stderr,
        "ERROR: Expected different integer types to have the same type id\n");
    return 2;
  }

  if (mlirTypeIDEqual(i32ID, f32ID)) {
    fprintf(stderr,
            "ERROR: Expected integer type id to not equal float type id\n");
    return 3;
  }

  if (mlirTypeIDEqual(i32ID, i32AttrID)) {
    fprintf(stderr, "ERROR: Expected integer type id to not equal integer "
                    "attribute type id\n");
    return 4;
  }

  MlirLocation loc = mlirLocationUnknownGet(ctx);
  MlirType indexType = mlirIndexTypeGet(ctx);
  MlirStringRef valueStringRef = mlirStringRefCreateFromCString("value");

  // Create a registered operation, which should have a type id.
  MlirAttribute indexZeroLiteral =
      mlirAttributeParseGet(ctx, mlirStringRefCreateFromCString("0 : index"));
  MlirNamedAttribute indexZeroValueAttr = mlirNamedAttributeGet(
      mlirIdentifierGet(ctx, valueStringRef), indexZeroLiteral);
  MlirOperationState constZeroState = mlirOperationStateGet(
      mlirStringRefCreateFromCString("arith.constant"), loc);
  mlirOperationStateAddResults(&constZeroState, 1, &indexType);
  mlirOperationStateAddAttributes(&constZeroState, 1, &indexZeroValueAttr);
  MlirOperation constZero = mlirOperationCreate(&constZeroState);

  if (!mlirOperationVerify(constZero)) {
    fprintf(stderr, "ERROR: Expected operation to verify correctly\n");
    return 5;
  }

  if (mlirOperationIsNull(constZero)) {
    fprintf(stderr, "ERROR: Expected registered operation to be present\n");
    return 6;
  }

  MlirTypeID registeredOpID = mlirOperationGetTypeID(constZero);

  if (mlirTypeIDIsNull(registeredOpID)) {
    fprintf(stderr,
            "ERROR: Expected registered operation type id to be present\n");
    return 7;
  }

  // Create an unregistered operation, which should not have a type id.
  mlirContextSetAllowUnregisteredDialects(ctx, true);
  MlirOperationState opState =
      mlirOperationStateGet(mlirStringRefCreateFromCString("dummy.op"), loc);
  MlirOperation unregisteredOp = mlirOperationCreate(&opState);
  if (mlirOperationIsNull(unregisteredOp)) {
    fprintf(stderr, "ERROR: Expected unregistered operation to be present\n");
    return 8;
  }

  MlirTypeID unregisteredOpID = mlirOperationGetTypeID(unregisteredOp);

  if (!mlirTypeIDIsNull(unregisteredOpID)) {
    fprintf(stderr,
            "ERROR: Expected unregistered operation type id to be null\n");
    return 9;
  }

  mlirOperationDestroy(constZero);
  mlirOperationDestroy(unregisteredOp);

  return 0;
}

int testSymbolTable(MlirContext ctx) {
  fprintf(stderr, "@testSymbolTable\n");

  const char *moduleString = "func.func private @foo()"
                             "func.func private @bar()";
  const char *otherModuleString = "func.func private @qux()"
                                  "func.func private @foo()";

  MlirModule module =
      mlirModuleCreateParse(ctx, mlirStringRefCreateFromCString(moduleString));
  MlirModule otherModule = mlirModuleCreateParse(
      ctx, mlirStringRefCreateFromCString(otherModuleString));

  MlirSymbolTable symbolTable =
      mlirSymbolTableCreate(mlirModuleGetOperation(module));

  MlirOperation funcFoo =
      mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("foo"));
  if (mlirOperationIsNull(funcFoo))
    return 1;

  MlirOperation funcBar =
      mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
  if (mlirOperationEqual(funcFoo, funcBar))
    return 2;

  MlirOperation missing =
      mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
  if (!mlirOperationIsNull(missing))
    return 3;

  MlirBlock moduleBody = mlirModuleGetBody(module);
  MlirBlock otherModuleBody = mlirModuleGetBody(otherModule);
  MlirOperation operation = mlirBlockGetFirstOperation(otherModuleBody);
  mlirOperationRemoveFromParent(operation);
  mlirBlockAppendOwnedOperation(moduleBody, operation);

  // At this moment, the operation is still missing from the symbol table.
  MlirOperation stillMissing =
      mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
  if (!mlirOperationIsNull(stillMissing))
    return 4;

  // After it is added to the symbol table, and not only the operation with
  // which the table is associated, it can be looked up.
  mlirSymbolTableInsert(symbolTable, operation);
  MlirOperation funcQux =
      mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("qux"));
  if (!mlirOperationEqual(operation, funcQux))
    return 5;

  // Erasing from the symbol table also removes the operation.
  mlirSymbolTableErase(symbolTable, funcBar);
  MlirOperation nowMissing =
      mlirSymbolTableLookup(symbolTable, mlirStringRefCreateFromCString("bar"));
  if (!mlirOperationIsNull(nowMissing))
    return 6;

  // Adding a symbol with the same name to the table should rename.
  MlirOperation duplicateNameOp = mlirBlockGetFirstOperation(otherModuleBody);
  mlirOperationRemoveFromParent(duplicateNameOp);
  mlirBlockAppendOwnedOperation(moduleBody, duplicateNameOp);
  MlirAttribute newName = mlirSymbolTableInsert(symbolTable, duplicateNameOp);
  MlirStringRef newNameStr = mlirStringAttrGetValue(newName);
  if (mlirStringRefEqual(newNameStr, mlirStringRefCreateFromCString("foo")))
    return 7;
  MlirAttribute updatedName = mlirOperationGetAttributeByName(
      duplicateNameOp, mlirSymbolTableGetSymbolAttributeName());
  if (!mlirAttributeEqual(updatedName, newName))
    return 8;

  mlirOperationDump(mlirModuleGetOperation(module));
  mlirOperationDump(mlirModuleGetOperation(otherModule));
  // clang-format off
  // CHECK-LABEL: @testSymbolTable
  // CHECK: module
  // CHECK:   func private @foo
  // CHECK:   func private @qux
  // CHECK:   func private @foo{{.+}}
  // CHECK: module
  // CHECK-NOT: @qux
  // CHECK-NOT: @foo
  // clang-format on

  mlirSymbolTableDestroy(symbolTable);
  mlirModuleDestroy(module);
  mlirModuleDestroy(otherModule);

  return 0;
}

int testDialectRegistry(void) {
  fprintf(stderr, "@testDialectRegistry\n");

  MlirDialectRegistry registry = mlirDialectRegistryCreate();
  if (mlirDialectRegistryIsNull(registry)) {
    fprintf(stderr, "ERROR: Expected registry to be present\n");
    return 1;
  }

  MlirDialectHandle stdHandle = mlirGetDialectHandle__func__();
  mlirDialectHandleInsertDialect(stdHandle, registry);

  MlirContext ctx = mlirContextCreate();
  if (mlirContextGetNumRegisteredDialects(ctx) != 0) {
    fprintf(stderr,
            "ERROR: Expected no dialects to be registered to new context\n");
  }

  mlirContextAppendDialectRegistry(ctx, registry);
  if (mlirContextGetNumRegisteredDialects(ctx) != 1) {
    fprintf(stderr, "ERROR: Expected the dialect in the registry to be "
                    "registered to the context\n");
  }

  mlirContextDestroy(ctx);
  mlirDialectRegistryDestroy(registry);

  return 0;
}

void testDiagnostics(void) {
  MlirContext ctx = mlirContextCreate();
  MlirDiagnosticHandlerID id = mlirContextAttachDiagnosticHandler(
      ctx, errorHandler, (void *)42, deleteUserData);
  fprintf(stderr, "@test_diagnostics\n");
  MlirLocation unknownLoc = mlirLocationUnknownGet(ctx);
  mlirEmitError(unknownLoc, "test diagnostics");
  MlirAttribute unknownAttr = mlirLocationGetAttribute(unknownLoc);
  MlirLocation unknownClone = mlirLocationFromAttribute(unknownAttr);
  mlirEmitError(unknownClone, "test clone");
  MlirLocation fileLineColLoc = mlirLocationFileLineColGet(
      ctx, mlirStringRefCreateFromCString("file.c"), 1, 2);
  mlirEmitError(fileLineColLoc, "test diagnostics");
  MlirLocation callSiteLoc = mlirLocationCallSiteGet(
      mlirLocationFileLineColGet(
          ctx, mlirStringRefCreateFromCString("other-file.c"), 2, 3),
      fileLineColLoc);
  mlirEmitError(callSiteLoc, "test diagnostics");
  MlirLocation null = {0};
  MlirLocation nameLoc =
      mlirLocationNameGet(ctx, mlirStringRefCreateFromCString("named"), null);
  mlirEmitError(nameLoc, "test diagnostics");
  MlirLocation locs[2] = {nameLoc, callSiteLoc};
  MlirAttribute nullAttr = {0};
  MlirLocation fusedLoc = mlirLocationFusedGet(ctx, 2, locs, nullAttr);
  mlirEmitError(fusedLoc, "test diagnostics");
  mlirContextDetachDiagnosticHandler(ctx, id);
  mlirEmitError(unknownLoc, "more test diagnostics");
  // CHECK-LABEL: @test_diagnostics
  // CHECK: processing diagnostic (userData: 42) <<
  // CHECK:   test diagnostics
  // CHECK:   loc(unknown)
  // CHECK: processing diagnostic (userData: 42) <<
  // CHECK:   test clone
  // CHECK:   loc(unknown)
  // CHECK: >> end of diagnostic (userData: 42)
  // CHECK: processing diagnostic (userData: 42) <<
  // CHECK:   test diagnostics
  // CHECK:   loc("file.c":1:2)
  // CHECK: >> end of diagnostic (userData: 42)
  // CHECK: processing diagnostic (userData: 42) <<
  // CHECK:   test diagnostics
  // CHECK:   loc(callsite("other-file.c":2:3 at "file.c":1:2))
  // CHECK: >> end of diagnostic (userData: 42)
  // CHECK: processing diagnostic (userData: 42) <<
  // CHECK:   test diagnostics
  // CHECK:   loc("named")
  // CHECK: >> end of diagnostic (userData: 42)
  // CHECK: processing diagnostic (userData: 42) <<
  // CHECK:   test diagnostics
  // CHECK:   loc(fused["named", callsite("other-file.c":2:3 at "file.c":1:2)])
  // CHECK: deleting user data (userData: 42)
  // CHECK-NOT: processing diagnostic
  // CHECK:     more test diagnostics
  mlirContextDestroy(ctx);
}

int main(void) {
  MlirContext ctx = mlirContextCreate();
  registerAllUpstreamDialects(ctx);
  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("func"));
  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("memref"));
  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("shape"));
  mlirContextGetOrLoadDialect(ctx, mlirStringRefCreateFromCString("scf"));

  if (constructAndTraverseIr(ctx))
    return 1;
  buildWithInsertionsAndPrint(ctx);
  if (createOperationWithTypeInference(ctx))
    return 2;

  if (printBuiltinTypes(ctx))
    return 3;
  if (printBuiltinAttributes(ctx))
    return 4;
  if (printAffineMap(ctx))
    return 5;
  if (printAffineExpr(ctx))
    return 6;
  if (affineMapFromExprs(ctx))
    return 7;
  if (printIntegerSet(ctx))
    return 8;
  if (registerOnlyStd())
    return 9;
  if (testBackreferences())
    return 10;
  if (testOperands())
    return 11;
  if (testClone())
    return 12;
  if (testTypeID(ctx))
    return 13;
  if (testSymbolTable(ctx))
    return 14;
  if (testDialectRegistry())
    return 15;

  mlirContextDestroy(ctx);

  testDiagnostics();
  return 0;
}