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
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
/*
Notes:
- Any variadic macro requires a corresponding meta data entry in ::types.
e.g. a variadic struct requires a VARIADIC_TYPES entry.
This is required to enable desugared type inference at macro expansion time.
- Parameter names should not be changed without careful refactoring.
They are sometimes used to generate corresponding Rust functions for cuda_tile operations.
*/
/// Core GPU kernel programming types and operations.
///
/// This module provides the foundational types and operations for writing GPU kernels
/// in Rust. It defines a domain-specific language (DSL) that compiles to MLIR and then
/// to optimized CUDA code.
///
/// ## Overview
///
/// The core module provides:
///
/// - **Element types**: Scalar types that can be stored in tensors (`f32`, `f16`, `i32`, etc.)
/// - **Tiles**: Register/shared memory arrays that represent data being processed
/// - **Tensors**: GPU memory views with shape and stride information
/// - **Partitions**: Views that divide tensors into tiles for block-level processing
/// - **Operations**: Element-wise arithmetic, broadcasting, reshaping, matrix operations
///
/// ## Writing GPU Kernels
///
/// GPU kernels are written as regular Rust functions with special attributes:
///
/// ```rust,ignore
/// #[cutile::module]
/// mod my_kernels {
/// use cutile::core::*;
///
/// #[cutile::entry]
/// fn vector_add<T: ElementType, const N: i32>(
/// z: &mut Tensor<T, {[N]}>,
/// x: &Tensor<T, {[-1]}>,
/// y: &Tensor<T, {[-1]}>,
/// ) {
/// // Load tiles from input tensors based on block position
/// let tile_x = load_tile_like_1d(x, z);
/// let tile_y = load_tile_like_1d(y, z);
///
/// // Perform computation on tiles (in registers/shared memory)
/// let result = tile_x + tile_y;
///
/// // Store result back to global memory
/// z.store(result);
/// }
/// }
/// ```
///
/// ## Type System
///
/// ### Element Types
///
/// [`ElementType`] is the trait for scalar types that can be stored in tensors:
/// - Floating point: `f16`, `f32`, `f64`, `tf32`
/// - Integer: `i32`, `i64`, `u32`, `u64`
/// - Boolean: `bool` (maps to `i1`)
///
/// ### Tiles vs Tensors
///
/// - **[`Tile`]**: Data in registers or shared memory. Fast to access, supports element-wise operations.
/// - **[`Tensor`]**: View of data in global GPU memory. Must be loaded to tiles for processing.
///
/// ### Shapes
///
/// Shapes are compile-time constants represented as `const [i32; N]`:
/// - `{[128]}` - 1D with 128 elements
/// - `{[64, 64]}` - 2D with 64×64 elements
/// - `{[-1]}` - Dynamic size (inferred at runtime)
///
/// ## Common Operations
///
/// ### Loading and Storing
///
/// ```rust,ignore
/// // Load entire tensor to a tile
/// let tile = load_tile_mut(&mut tensor);
///
/// // Load from a specific position
/// let tile = load_tile_like_1d(&input_tensor, &output_tensor);
///
/// // Store tile back to tensor
/// tensor.store(tile);
/// ```
///
/// ### Arithmetic
///
/// Tiles support standard arithmetic operators that work element-wise:
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
///
/// let sum = a + b;
/// let product = a * b;
/// let diff = a - b;
/// let quot = a / b;
/// ```
///
/// ### Broadcasting
///
/// ```rust,ignore
/// // Broadcast a scalar to a tile
/// let scalar = 3.14f32;
/// let tile = scalar.broadcast(const_shape![128]);
///
/// // Reshape a tile
/// let reshaped = tile.reshape(const_shape![8, 16]);
/// ```
///
/// ### Matrix Operations
///
/// ```rust,ignore
/// // Matrix multiplication using hardware accelerated MMA
/// let c = mma(a, b, acc); // c = a * b + acc
/// ```
///
/// ## Partitions
///
/// [`Partition`] views divide tensors into tiles for parallel processing:
///
/// ```rust,ignore
/// let tensor_shape = tensor.shape();
/// let partition = tensor.partition(const_shape![64, 64]);
///
/// // Each thread block loads its partition based on block ID
/// let pid = get_tile_block_id();
/// let tile = partition.load([pid.0, pid.1]);
/// ```
///
/// ## Block Operations
///
/// Get information about the current thread block:
///
/// ```rust,ignore
/// let (x, y, z) = get_tile_block_id(); // Current block position
/// let (gx, gy, gz) = get_num_tile_blocks(); // Total number of blocks
/// ```
///
/// ## Debugging
///
/// Print from GPU kernels (for debugging):
///
/// ```rust,ignore
/// cuda_tile_print!("Block ID: {}, Value: {}\n", pid.0, value);
/// cuda_tile_assert!(value > 0, "Value must be positive");
/// ```
///
/// ## Advanced: Type Conversions
///
/// ```rust,ignore
/// // Convert between element types
/// let f32_tile: Tile<f32, {[128]}> = convert_tile(i32_tile);
///
/// // Convert scalar to tile and back
/// let tile = scalar_to_tile(3.14f32);
/// let scalar: f32 = tile_to_scalar(tile);
/// ```
///
/// ## Safety and Correctness
///
/// - Bounds checking can be enabled with `check_partition_access()`
/// - Type system ensures shape compatibility at compile time
/// - Undefined behavior if tensor shapes don't match partition shapes at runtime
///
/// ## See Also
///
/// - [`tile_async`](crate::tile_async) - Async execution and kernel compilation
/// - [`kernels`](crate::kernels) - Pre-built kernel examples
// ---------------------------------------------------------------
// Static operation parameter modules
//
// Defined outside the proc-macro-processed `core` module because the
// module macro doesn't support nested `mod` items. Re-exported from
// `core` via `pub use`.
//
// Each module defines a trait (`Mode`) and zero-sized marker structs.
// Binary switches use Enabled/Disabled. Multi-valued parameters use
// descriptive names.
// ---------------------------------------------------------------
/// Flush-to-zero modifier. Flushes denormal inputs and results to
/// sign-preserving zero. Only supported for f32.
/// Rounding mode for floating-point operations.
/// NaN propagation for maxf/minf operations.
>
/// Converts a 0-dimensional tile back to a scalar value.
///
/// This is the inverse of `scalar_to_tile`.
/// Converts a scalar from one type to another.
///
/// ## Examples
///
/// ```rust,ignore
/// let i: i32 = 42;
/// let f: f32 = convert_scalar(i); // 42.0
/// ```
/// Converts all elements of a tile from one type to another.
///
/// Performs element-wise type conversion, preserving the shape of the tile.
///
/// ## Examples
///
/// ```rust,ignore
/// let int_tile: Tile<i32, {[128]}> = ...;
/// let float_tile: Tile<f32, {[128]}> = convert_tile(int_tile);
/// ```
/// Checks that a partition access is within bounds.
///
/// This function can be used to add runtime bounds checking to partition loads.
/// If the compiler can prove the access is safe, no code is emitted. Otherwise,
/// an assertion is generated.
///
/// ## Examples
///
/// ```rust,ignore
/// let partition = tensor.partition(const_shape![64, 64]);
/// let index = [pid.0, pid.1];
/// check_partition_access(&partition, index);
/// let tile = partition.load(index);
/// ```
/// Trait for broadcasting scalar element types to tiles.
///
/// This trait provides the `broadcast` method that converts a scalar value
/// into a tile filled with that value. Automatically implemented for all
/// [`ElementType`]s.
///
/// ## Examples
///
/// ```rust,ignore
/// let scalar = 3.14f32;
/// let tile = scalar.broadcast(const_shape![128]); // Tile of 128 copies of 3.14
/// ```
// This generates the trait impl N times, varying the trait and method name.
// This implements the trait impl N times, varying the trait and method name.
/// Marker trait for GPU pointer types.
///
/// Implemented for mutable raw pointers to element types. Used for low-level
/// pointer operations within kernels.
// impl<E: ElementType> Pointer for *const E {}
/// Converts a raw pointer to a pointer tile.
///
/// This is used internally for pointer arithmetic and indexing operations.
}>
/// Converts a pointer tile back to a raw pointer.
///
/// This is the inverse of `pointer_to_tile`.
/// Prints formatted output from within a GPU kernel.
///
/// This macro provides printf-style debugging from GPU code. It's similar to Rust's
/// `print!` macro but works inside CUDA kernels.
///
/// ## Format String
///
/// The format string uses C-style format specifiers:
/// - `{}` is automatically converted to `%` by the compiler
/// - Use `\n` for newlines
///
/// ## Examples
///
/// ```rust,ignore
/// #[cutile::entry]
/// fn debug_kernel() {
/// let pid = get_tile_block_id();
/// cuda_tile_print!("Block ID: {}, {}, {}\n", pid.0, pid.1, pid.2);
///
/// let value = 42;
/// cuda_tile_print!("Value: {}\n", value);
/// }
/// ```
///
/// ## Note
///
/// Printing from GPU kernels can significantly impact performance and should be used
/// for debugging only.
// {} is converted to % by the compiler.
pub use cuda_tile_print;
/// Asserts a condition is true within a GPU kernel.
///
/// If the assertion fails, the kernel will terminate with the specified error message.
/// This is useful for runtime validation of assumptions in kernel code.
///
/// ## Parameters
///
/// - First argument: The condition to check (must evaluate to `bool`)
/// - Second argument: Error message string literal
///
/// ## Examples
///
/// ```rust,ignore
/// #[cutile::entry]
/// fn safe_kernel(x: &Tensor<f32, {[128]}>) {
/// let value = compute_something();
/// cuda_tile_assert!(value > 0, "Value must be positive");
///
/// let idx = get_index();
/// cuda_tile_assert!(idx < 128, "Index out of bounds");
/// }
/// ```
///
/// ## Note
///
/// Like CPU assertions, these have a runtime cost and should be used judiciously
/// in performance-critical code.
pub use cuda_tile_assert;
/// Returns the total number of thread blocks in the grid.
///
/// This returns the grid dimensions `(gridDim.x, gridDim.y, gridDim.z)` in CUDA terms.
///
/// ## Examples
///
/// ```rust,ignore
/// let (gx, gy, gz) = get_num_tile_blocks();
/// cuda_tile_print!("Grid size: {} x {} x {}\n", gx, gy, gz);
/// ```
/// Returns the current thread block's position in the grid.
///
/// This returns `(blockIdx.x, blockIdx.y, blockIdx.z)` in CUDA terms. Each block
/// processes a different partition of the data.
///
/// ## Examples
///
/// ```rust,ignore
/// let (bx, by, bz) = get_tile_block_id();
/// // Use block ID to determine which partition to process
/// let tile = partition.load([bx, by]);
/// ```
/* Shape */
/// A compile-time shape descriptor for tensors and tiles.
///
/// `Shape` represents the dimensions of a multi-dimensional array. The shape can
/// contain compile-time constants or runtime values.
///
/// ## Examples
///
/// ```rust,ignore
/// // Create constant shapes using the const_shape! macro
/// let shape = const_shape![128, 64];
///
/// // Get shape from a tensor
/// let tensor_shape = tensor.shape();
/// ```
/// Creates a compile-time constant shape.
///
/// This macro constructs a [`Shape`] with compile-time known dimensions. The shape
/// can be 0D to 4D.
///
/// ## Examples
///
/// ```rust,ignore
/// // Scalar (0D)
/// let scalar_shape = const_shape![];
///
/// // 1D shape
/// let vec_shape = const_shape![128];
///
/// // 2D shape
/// let matrix_shape = const_shape![64, 128];
///
/// // 3D shape
/// let volume_shape = const_shape![32, 64, 128];
///
/// // Use in kernel code
/// let partition = tensor.partition(const_shape![64, 64]);
/// ```
pub use const_shape;
/* Array */
/// A compile-time array descriptor for indexing and other metadata.
///
/// Similar to [`Shape`] but used for permutation indices and other array-valued metadata.
///
/// ## Examples
///
/// ```rust,ignore
/// // Create constant arrays using the const_array! macro
/// let arr = const_array![0, 2, 1]; // For permutation [0, 2, 1]
/// ```
/// Creates a compile-time constant array.
///
/// This macro constructs an [`Array`] with compile-time known values. Arrays are
/// typically used for permutation indices and other metadata.
///
/// ## Examples
///
/// ```rust,ignore
/// // Empty array (0D)
/// let empty = const_array![];
///
/// // 1D array
/// let idx = const_array![0];
///
/// // 2D permutation: transpose (swap dimensions 0 and 1)
/// let transpose = const_array![1, 0];
///
/// // 3D permutation: move last dimension to front
/// let perm = const_array![2, 0, 1];
///
/// // Use with permute operation
/// let transposed = permute(tile, const_array![1, 0]);
/// ```
pub use const_array;
/* PointerTile */
/// A tile of pointers for advanced memory operations.
///
/// `PointerTile` represents a multi-dimensional array of pointers, enabling
/// gather/scatter operations and indirect memory access patterns. This is a
/// low-level primitive rarely used directly in typical kernels.
///
/// ## Type Parameters
///
/// - `P`: Pointer type (must implement [`Pointer`])
/// - `D`: Shape of the pointer tile
/// Adds a scalar offset to all pointers in a pointer tile.
///
/// This is pointer arithmetic: `result[i] = ptr[i] + offset`.
/// Adds element-wise offsets to a pointer tile.
///
/// Each pointer is offset by the corresponding value in the offset tile:
/// `result[i] = ptr[i] + offset[i]`.
/// Broadcasts a pointer tile to a new shape.
///
/// Dimensions of size 1 in the source can be broadcast to any size in the result.
/// Reshapes a pointer tile to a new shape without moving data.
///
/// The total number of elements must remain the same.
/* Token */
/// A token representing memory operation ordering constraints.
///
/// Tokens are used internally to track dependencies between memory operations
/// and ensure correct ordering of loads and stores. The tile DSL automatically
/// manages tokens to maintain memory consistency.
///
/// ## Note
///
/// Users typically don't need to manipulate tokens directly; they're handled
/// automatically by the load/store operations and partition views.
/// Creates a new unordered token.
///
/// This is used internally to initialize token state. Most users won't need
/// to call this directly.
/// Joins multiple synchronization tokens into a single token.
///
/// This operation combines multiple tokens that represent independent async operations
/// into a single token that represents the completion of all of them. This is useful
/// when you have parallel loads or operations that need to complete before proceeding.
///
/// ## Parameters
///
/// - `tokens`: Array/slice of tokens to join
///
/// ## Returns
///
/// A new token that depends on all input tokens
///
/// ## Examples
///
/// ### Parallel loads with join
///
/// ```rust,ignore
/// let token = new_token_unordered();
///
/// // Load two tiles in parallel
/// let (tile_a, token_a) = load_from_view_mut(&partition_a, [0], token);
/// let (tile_b, token_b) = load_from_view_mut(&partition_b, [0], token);
///
/// // Wait for both loads to complete
/// let combined = join_tokens(&[token_a, token_b]);
///
/// // Now safe to proceed with both tiles
/// let result = tile_a + tile_b;
/// store_to_view_mut(&partition_out, result, [0], combined);
/// ```
// ============================================================================
// ATOMIC OPERATIONS
// ============================================================================
// The following functions provide atomic read-modify-write (RMW) and compare-and-swap
// (CAS) operations on global memory with token ordering semantics.
//
// DESIGN:
// - Generic atomic_rmw_tko() handles all RMW modes (hidden from users)
// - Wrapper functions (atomic_add_tko, atomic_and_tko, etc.) provide type-safe APIs
// - Mode, memory_ordering, and memory_scope passed as string literals
// - Compiler converts string literals to integer MLIR attributes (not symbol refs)
// - Optional mask and token parameters use Option<T> (not blank strings)
//
// MEMORY ORDERING:
// - "relaxed": No synchronization, concurrent access allowed
// - "acquire": Synchronizes with release, establishes happens-before for reads
// - "release": Synchronizes with acquire, establishes happens-before for writes
// - "acq_rel": Combined acquire+release semantics
//
// MEMORY SCOPE:
// - "tl_blk": Tile block scope (same CTA)
// - "device": GPU device scope (all CTAs on same GPU)
// - "sys": System scope (all devices including CPU)
//
// SUPPORTED TYPES:
// - Integer operations (and, or, xor, add, max, min, umax, umin): i32, i64
// - Float operations (addf): f16, f32, f64
// - Exchange (xchg): i32, i64, f32, f64
// - Compare-and-swap (CAS): i32, i64, f32, f64
// ============================================================================
/// Internal generic implementation for atomic read-modify-write operations with token ordering.
///
/// Performs element-wise atomic read-modify-write operations on global memory.
/// This function is not directly exposed - use the mode-specific wrapper functions instead
/// (e.g., `atomic_and_tko`, `atomic_add_tko`, `atomic_max_tko`, etc.).
///
/// ## Parameters
///
/// **Operands (values passed to MLIR operation):**
/// - `pointers`: Tile of memory addresses to operate on (required)
/// - `arg`: Tile of values to use in the atomic operation (required)
/// - `mask`: Optional mask tile (`Tile<bool, S>`) to selectively perform operations
/// - `token`: Optional input token for ordering
///
/// **Attributes (metadata/configuration):**
/// - `mode`: Atomic operation mode (string literal)
/// - `"and"`: Bitwise AND (integer types: i32, i64)
/// - `"or"`: Bitwise OR (integer types: i32, i64)
/// - `"xor"`: Bitwise XOR (integer types: i32, i64)
/// - `"add"`: Integer addition (integer types: i32, i64)
/// - `"addf"`: Floating-point addition (float types: f16, f32, f64)
/// - `"max"`: Signed maximum (integer types: i32, i64)
/// - `"min"`: Signed minimum (integer types: i32, i64)
/// - `"umax"`: Unsigned maximum (integer types: i32, i64)
/// - `"umin"`: Unsigned minimum (integer types: i32, i64)
/// - `"xchg"`: Exchange/swap (integer types: i32, i64; float types: f32, f64)
/// - `memory_ordering`: Memory ordering semantics (string literal)
/// - `"relaxed"`: Concurrent access allowed, no synchronization
/// - `"acquire"`: Read establishes happens-before if observing a release
/// - `"release"`: Write establishes happens-before for observers with acquire
/// - `"acq_rel"`: Combined acquire and release semantics
/// - `memory_scope`: Memory scope for synchronization (string literal)
/// - `"tl_blk"`: Tile block scope (same CTA)
/// - `"device"`: GPU device scope (all CTAs on same GPU)
/// - `"sys"`: System scope (all devices including CPU)
///
/// **Note:** `mode`, `memory_ordering`, and `memory_scope` are passed as function parameters in the
/// Rust API, but are compiled to MLIR attributes (not operands) by the compiler.
///
/// **Design Note:** This function can be called from wrapper functions (e.g., `atomic_and_tko`)
/// which pass variables instead of string literals. The compiler automatically resolves these
/// variables back to their original string literal AST expressions using a parameter-to-AST mapping.
///
/// ## Mode and Element Type Compatibility
///
/// The `mode` parameter must be compatible with the element type `E`:
/// - Integer modes (`and`, `or`, `xor`, `add`, `max`, `min`, `umax`, `umin`) require integer types
/// - Floating-point mode (`addf`) requires floating-point types
/// - Exchange mode (`xchg`) works with both integer and floating-point types
///
/// The compiler validates this at compile-time and will panic with a descriptive error if
/// an incompatible mode is used with a given element type.
///
/// ## Memory Semantics
///
/// The `memory_ordering` parameter controls visibility and synchronization:
/// - `relaxed`: Allows concurrent access but provides no ordering guarantees
/// - `acquire`: Synchronizes with release operations, establishing happens-before for reads
/// - `release`: Synchronizes with acquire operations, establishing happens-before for writes
/// - `acq_rel`: Combined acquire and release semantics (for read-modify-write operations)
///
/// The `memory_scope` parameter defines the range of threads that may observe the operation.
///
/// ## Examples
///
/// This function is typically called indirectly through wrapper functions:
/// ```rust,ignore
/// // Use atomic_and_tko instead of calling atomic_rmw_tko directly
/// let (old_values, token) = atomic_and_tko(
/// ptrs,
/// values,
/// "relaxed",
/// "device",
/// None,
/// None
/// );
/// ```
///
/// ## Returns
///
/// Returns a tuple of (old_values, result_token) where:
/// - `old_values`: Tile containing the values that were in memory before the atomic operation
/// - `result_token`: Token representing completion of the atomic operation
/// Atomic compare-and-swap operation with token ordering.
///
/// Atomically compares the value at each memory location with a comparison value.
/// If they match, replaces the memory value with a new value. This is the fundamental
/// building block for lock-free algorithms.
///
/// ## Parameters
///
/// **Operands:**
/// - `pointers`: Tile of memory addresses to operate on (required)
/// - `cmp`: Tile of comparison values (expected old values) (required)
/// - `val`: Tile of new values to write if comparison succeeds (required)
/// - `mask`: Optional mask tile (`Tile<bool, S>`) to selectively perform operations
/// - `token`: Optional input token for ordering
///
/// **Attributes:**
/// - `memory_ordering`: Memory ordering semantics (`"relaxed"`, `"acquire"`, `"release"`, `"acq_rel"`)
/// - `memory_scope`: Memory scope (`"tl_blk"`, `"device"`, `"sys"`)
///
/// ## Semantics
///
/// For each element i:
/// ```text
/// old = *pointers[i]
/// if (old == cmp[i]) {
/// *pointers[i] = val[i]
/// }
/// return old
/// ```
///
/// Masked-out elements return `cmp[i]` value instead of performing the atomic operation.
///
/// ## Memory Semantics
///
/// The `memory_ordering` parameter controls visibility and synchronization:
/// - `relaxed`: Allows concurrent access but provides no ordering guarantees
/// - `acquire`: Synchronizes with release operations, establishing happens-before for reads
/// - `release`: Synchronizes with acquire operations, establishing happens-before for writes
/// - `acq_rel`: Combined acquire and release semantics (for read-modify-write operations)
///
/// The `memory_scope` parameter defines the range of threads that may observe the operation.
///
/// ## Supported Types
///
/// - Integer types: i32, i64
/// - Floating-point types: f32, f64
///
/// For floating-point types, the comparison uses bitwise equality rather than IEEE-754 semantics.
/// This means different NaN bit patterns are treated as distinct values, and +0.0 and -0.0
/// are considered different if their bit patterns differ.
///
/// ## Examples
///
/// ### Lock-free update
///
/// ```rust,ignore
/// // Try to update value from expected to new
/// let (old_values, new_token) = atomic_cas_tko(
/// ptr_tile,
/// expected_values,
/// new_values,
/// "relaxed",
/// "device",
/// None,
/// None
/// );
/// // Check old_values to see if CAS succeeded
/// ```
///
/// ## Returns
///
/// Returns a tuple of (old_values, result_token) where old_values contains the
/// values that were in memory before the operation (regardless of success/failure).
/// Load from pointer tile with token ordering and full memory semantics control.
///
/// Performs a gather operation by loading a tile of data from global memory into
/// a result tile based on a tile of pointers.
///
/// ## Parameters
///
/// **Operands (values passed to MLIR operation):**
/// - `source`: Tile of pointers to load from (required)
/// - `mask`: Optional mask tile (`Tile<bool, S>`) to selectively load elements
/// - `padding_value`: Optional scalar value (`E`) to use for masked-out elements
/// - `token`: Optional input token for ordering
///
/// **Attributes (metadata/configuration):**
/// - `memory_ordering`: Memory ordering semantics (string literal)
/// - `"weak"`: No concurrent accesses (compiler can assume exclusive access)
/// - `"relaxed"`: Concurrent access allowed, no synchronization
/// - `"acquire"`: Load establishes happens-before if observing a release
/// - `memory_scope`: Memory scope for synchronization (string literal)
/// - `"tl_blk"`: Tile block scope (same CTA)
/// - `"device"`: GPU device scope (all CTAs on same GPU)
/// - `"sys"`: System scope (all devices including CPU)
/// - `latency`: Optional latency hint for the compiler
///
/// **Note:** When `memory_ordering` is `"weak"`, `memory_scope` is not included as an attribute
/// (per TileIR spec).
///
/// **Design Note:** `memory_ordering` and `memory_scope` are passed as function parameters in the
/// Rust API, but are compiled to MLIR attributes (not operands) by the compiler.
///
/// ## Scalar-to-Tile Promotion
///
/// The `padding_value` parameter accepts a scalar type (`E`, e.g., `0.0f32`). The compiler
/// automatically promotes it to a tile matching the result shape:
/// 1. Scalar value → Reshape to `tile<1xT>`
/// 2. `tile<1xT>` → Broadcast to `tile<NxT>` (matching result shape)
///
/// This allows using simple scalar values like `0.0f32` instead of creating a full tile.
///
/// ## Memory Semantics
///
/// The `memory_ordering` parameter controls visibility and synchronization:
/// - `weak`: Assumes no concurrent access (fastest, but unsafe if concurrent access exists)
/// - `relaxed`: Allows concurrent access but provides no ordering guarantees
/// - `acquire`: Synchronizes with release operations, establishing happens-before
///
/// The `memory_scope` parameter defines the range of threads that may observe the operation.
///
/// ## Examples
///
/// Basic load with default semantics:
/// ```rust,ignore
/// let ptrs: PointerTile<*mut f32, {[128]}> = ...;
/// let (values, token) = load_ptr_tko(ptrs, "relaxed", "device", None, None, None, None);
/// ```
///
/// Load with acquire semantics and input token:
/// ```rust,ignore
/// let (values, token) = load_ptr_tko(ptrs, "acquire", "device", None, None, Some(input_token), None);
/// ```
///
/// Load with mask and padding value (scalar automatically promoted to tile):
/// ```rust,ignore
/// let mask: Tile<bool, {[128]}> = ...;
/// let padding = 0.0f32; // Scalar - compiler promotes to tile<128xf32>
/// let (values, token) = load_ptr_tko(ptrs, "relaxed", "device", Some(mask), Some(padding), None, None);
/// ```
///
/// ## Returns
///
/// Returns a tuple of (loaded_values, result_token) where:
/// - `loaded_values`: Tile containing the loaded data
/// - `result_token`: Token representing completion of the load operation
/// Store to pointer tile with token ordering and full memory semantics control.
///
/// Performs a scatter operation by storing a tile of data to global memory addresses
/// specified by a tile of pointers.
///
/// ## Parameters
///
/// **Operands (values passed to MLIR operation):**
/// - `destination`: Tile of pointers to store to (required)
/// - `value`: Tile of values to store (required)
/// - `mask`: Optional mask tile (`Tile<bool, S>`) to selectively store elements
/// - `token`: Optional input token for ordering
///
/// **Attributes (metadata/configuration):**
/// - `memory_ordering`: Memory ordering semantics (string literal)
/// - `"weak"`: No concurrent accesses (compiler can assume exclusive access)
/// - `"relaxed"`: Concurrent access allowed, no synchronization
/// - `"release"`: Store establishes happens-before for observers with acquire
/// - `memory_scope`: Memory scope for synchronization (string literal)
/// - `"tl_blk"`: Tile block scope (same CTA)
/// - `"device"`: GPU device scope (all CTAs on same GPU)
/// - `"sys"`: System scope (all devices including CPU)
/// - `latency`: Optional latency hint for the compiler
///
/// **Note:** When `memory_ordering` is `"weak"`, `memory_scope` is not included as an attribute
/// (per TileIR spec).
///
/// **Design Note:** `memory_ordering` and `memory_scope` are passed as function parameters in the
/// Rust API, but are compiled to MLIR attributes (not operands) by the compiler.
///
/// ## Memory Semantics
///
/// The `memory_ordering` parameter controls visibility and synchronization:
/// - `weak`: Assumes no concurrent access (fastest, but unsafe if concurrent access exists)
/// - `relaxed`: Allows concurrent access but provides no ordering guarantees
/// - `release`: Synchronizes with acquire operations, establishing happens-before
///
/// The `memory_scope` parameter defines the range of threads that may observe the operation.
///
/// ## Examples
///
/// Basic store with default semantics:
/// ```rust,ignore
/// let ptrs: PointerTile<*mut f32, {[128]}> = ...;
/// let values: Tile<f32, {[128]}> = ...;
/// let token = store_ptr_tko(ptrs, values, "relaxed", "device", None, None, None);
/// ```
///
/// Store with release semantics and input token:
/// ```rust,ignore
/// let token = store_ptr_tko(ptrs, values, "release", "device", None, Some(input_token), None);
/// ```
///
/// Store with mask to selectively store elements:
/// ```rust,ignore
/// let mask: Tile<bool, {[128]}> = ...;
/// let token = store_ptr_tko(ptrs, values, "relaxed", "device", Some(mask), None, None);
/// ```
///
/// ## Returns
///
/// Returns the result token representing completion of the store operation.
/// Gets a reference to a global variable.
///
/// Returns a pointer to a global variable declared with the `global` operation.
/// Global variables are shared across all thread blocks and persist for the
/// lifetime of the module.
///
/// ## Parameters
///
/// The global variable is identified by name through a compiler attribute.
///
/// ## Examples
///
/// ```rust,ignore
/// // Assuming a global variable "shared_counter" was declared
/// let counter_ptr: PointerTile<*mut i32, {[]}> = get_global();
/// ```
///
/// Note: This operation requires the global to be declared first using `global`.
/// Currently this is an advanced operation with limited Rust API support.
}>
/// Generic reduce operation with custom closure.
///
/// Reduces a tile along a dimension using a user-provided binary operation.
/// This is the generic version that accepts any reduction operation via a closure.
///
/// ## Parameters
///
/// - `operand`: Tile to reduce
/// - `dim`: Dimension to reduce along (becomes scalar)
/// - `identity`: Identity value for the reduction
/// - `f`: Binary operation closure `|acc, x| -> result`
///
/// ## Examples
///
/// ```rust,ignore
/// // Sum reduction
/// let sum = reduce(tile, 0, 0.0f32, |acc, x| acc + x);
///
/// // Product reduction
/// let product = reduce(tile, 0, 1.0f32, |acc, x| acc * x);
///
/// // Min reduction
/// let min = reduce(tile, 0, f32::MAX, |acc, x| minf(acc, x));
///
/// // Max reduction
/// let max = reduce(tile, 0, f32::MIN, |acc, x| maxf(acc, x));
///
/// // Custom reduction
/// let result = reduce(tile, 0, 0.0f32, |acc, x| maxf(acc * 0.9, x));
/// ```
///
/// Note: The closure body is compiled into an MLIR region at compile-time.
/// Scan sum operation - parallel prefix sum along a dimension.
///
/// Computes cumulative sums along the specified dimension, preserving all
/// intermediate results.
///
/// ## Parameters
///
/// - `operand`: Tile to scan
/// - `dim`: Dimension to scan along
/// - `reverse`: Whether to scan in reverse direction
/// - `identity`: Identity value for sum (typically 0.0 or 0)
///
/// ## Example
///
/// ```rust,ignore
/// let data: Tile<f32, {[128]}> = ...; // [1, 2, 3, 4, ...]
/// let prefix_sums: Tile<f32, {[128]}> = scan_sum(data, 0, false, 0.0);
/// // Result: [1, 3, 6, 10, ...] (cumulative sums)
/// ```
///
/// Note: Compiler builds MLIR region with addf/addi operation automatically.
/// Generic scan operation with custom closure.
///
/// Computes a prefix scan (cumulative operation) along a dimension using a
/// user-provided binary operation. Preserves all intermediate results.
///
/// ## Parameters
///
/// - `operand`: Tile to scan
/// - `dim`: Dimension to scan along
/// - `reverse`: Whether to scan in reverse direction
/// - `identity`: Identity value for the scan
/// - `f`: Binary operation closure `|acc, x| -> result`
///
/// ## Examples
///
/// ```rust,ignore
/// // Prefix sum (cumulative sum)
/// let prefix_sum = scan(tile, 0, false, 0.0f32, |acc, x| acc + x);
/// // Input: [1, 2, 3, 4]
/// // Output: [1, 3, 6, 10]
///
/// // Prefix product
/// let prefix_prod = scan(tile, 0, false, 1.0f32, |acc, x| acc * x);
/// // Input: [2, 3, 4, 5]
/// // Output: [2, 6, 24, 120]
///
/// // Running maximum
/// let running_max = scan(tile, 0, false, f32::MIN, |acc, x| maxf(acc, x));
/// // Input: [3, 1, 4, 2]
/// // Output: [3, 3, 4, 4]
///
/// // Reverse scan
/// let suffix_sum = scan(tile, 0, true, 0.0f32, |acc, x| acc + x);
/// // Input: [1, 2, 3, 4]
/// // Output: [10, 9, 7, 4] (scans from right to left)
/// ```
///
/// Note: The closure body is compiled into an MLIR region at compile-time.
/* Tensor */
/// A view into GPU global memory with shape and stride information.
///
/// `Tensor` represents a multi-dimensional array stored in GPU memory. Unlike the
/// host-side [`crate::tensor::Tensor`], this is used within GPU kernels to reference
/// input and output data.
///
/// ## Type Parameters
///
/// - `E`: Element type (must implement [`ElementType`])
/// - `D`: Shape as a compile-time constant array. Use `-1` for dynamic dimensions.
///
/// ## Shape Specifications
///
/// - `{[128]}` - 1D tensor with exactly 128 elements
/// - `{[64, 64]}` - 2D tensor with shape 64×64
/// - `{[-1]}` - 1D tensor with dynamic size
/// - `{[-1, 64]}` - 2D tensor with dynamic first dimension, fixed second dimension
///
/// ## Examples
///
/// ### Reading from a tensor
///
/// ```rust,ignore
/// #[cutile::entry]
/// fn my_kernel<const N: i32>(
/// output: &mut Tensor<f32, {[N]}>,
/// input: &Tensor<f32, {[-1]}>,
/// ) {
/// // Load the input tile corresponding to this block
/// let tile = load_tile_like_1d(input, output);
///
/// // Process and store
/// output.store(tile * 2.0);
/// }
/// ```
///
/// ### Using partitions for large tensors
///
/// ```rust,ignore
/// #[cutile::entry]
/// fn process_matrix<const BM: i32, const BN: i32>(
/// output: &mut Tensor<f32, {[BM, BN]}>,
/// input: &Tensor<f32, {[-1, -1]}>,
/// ) {
/// let pid = get_tile_block_id();
/// let partition = input.partition(const_shape![BM, BN]);
/// let tile = partition.load([pid.0, pid.1]);
/// output.store(tile);
/// }
/// ```
/// Extracts the shape metadata from a tensor.
///
/// This is a low-level function that retrieves the shape information stored in
/// the tensor's type metadata. Typically called internally; users should use
/// the `.shape()` method on tensors instead.
///
/// ## Examples
///
/// ```rust,ignore
/// let tensor: &Tensor<f32, {[128, 64]}> = ...;
/// let shape = get_tensor_shape(tensor);
/// // Equivalent to: let shape = tensor.shape();
/// ```
/// Extracts the memory ordering token from a tensor.
///
/// Tokens track memory operation ordering to ensure correct synchronization.
/// This is used internally by the partition and load/store operations to maintain
/// memory consistency.
///
/// ## Note
///
/// This is an internal function used by the tile DSL implementation. Direct use
/// is rarely needed in user code.
/// Updates the memory ordering token for a tensor.
///
/// After performing memory operations on a tensor, this function updates its
/// token to reflect the new memory state. This ensures subsequent operations
/// observe the correct ordering.
///
/// ## Note
///
/// This is an internal function used to maintain memory consistency. The token
/// mechanism is handled automatically by load/store operations.
/// Creates a tensor view from raw components.
///
/// Constructs a [`Tensor`] from a base pointer, shape, strides, and ordering token.
/// This is a low-level unsafe operation used internally by the tile DSL.
///
/// ## Parameters
///
/// - `base`: Pointer to the tensor's data in global memory
/// - `shape`: Dimensions of the tensor
/// - `strides`: Stride values for each dimension
/// - `token`: Memory ordering token
///
/// ## Safety
///
/// This function is unsafe because:
/// - The pointer must be valid and point to allocated GPU memory
/// - The shape and strides must correctly describe the memory layout
/// - The token must represent valid ordering constraints
///
/// Typically, users should not call this directly; tensors are created through
/// the API functions or passed as kernel parameters.
pub unsafe
/* Partition */
/// A read-only view that divides a tensor into tiles for parallel processing.
///
/// `Partition` provides indexed access to tiles within a tensor. Each thread block
/// typically processes one or more tiles from a partition.
///
/// ## Type Parameters
///
/// - `E`: Element type
/// - `D`: Tile shape (shape of each partition)
///
/// ## Examples
///
/// ### Basic partition loading
///
/// ```rust,ignore
/// fn kernel(input: &Tensor<f32, {[-1, -1]}>) {
/// let partition = input.partition(const_shape![64, 64]);
/// let pid = get_tile_block_id();
///
/// // Load the tile for this block
/// let tile = partition.load([pid.0, pid.1]);
/// // Process tile...
/// }
/// ```
///
/// ### Loop over multiple tiles
///
/// ```rust,ignore
/// let partition = input.partition(const_shape![64, 64]);
/// for i in 0..num_tiles {
/// let tile = partition.load([pid.0, i]);
/// // Accumulate results...
/// }
/// ```
/// Creates a read-only partition view from a tensor.
///
/// This is the internal function used by `Tensor::partition()`. It creates a
/// partition structure that divides the tensor into tiles of the specified shape.
///
/// ## Parameters
///
/// - `tensor_view`: The tensor to partition
/// - `tile`: Shape of each partition tile
/// - `token`: Memory ordering token
///
/// ## Note
///
/// Users should call `.partition()` on tensors rather than using this function directly.
// TODO (hme): Mark loads from shared refs as unsafe and add suffix _unchecked.
/* PartitionMut */
/// A mutable partition view that allows unordered loads and stores.
///
/// `PartitionMut` is similar to [`Partition`] but allows both loading and storing tiles.
/// Operations on `PartitionMut` use unordered memory operations for performance,
/// which is why they're marked unsafe.
///
/// ## Safety
///
/// The load and store methods are unsafe because they don't enforce memory ordering.
/// Prefer using the ordered `load()` and `store()` methods on [`Tensor`] directly
/// when possible.
///
/// ## Type Parameters
///
/// - `E`: Element type
/// - `D`: Tile shape
// TODO (hme): Look into consolidating into a single type.
/// Creates a mutable partition view from a tensor.
///
/// This is the internal function used by `Tensor::partition_mut()`. It creates a
/// mutable partition structure for unordered memory operations.
///
/// ## Safety
///
/// This is unsafe because:
/// - The lifetime `'a` is not tied to the tensor lifetime
/// - The resulting partition uses unordered memory operations
///
/// ## Note
///
/// Users should prefer the ordered `load()` and `store()` methods on [`Tensor`].
// This is unsafe because the lifetime 'a is not tied to tensor.
pub unsafe
pub unsafe
/// Loads a tile from a mutable partition view (unordered).
///
/// This is the internal implementation used by `PartitionMut::load()`.
///
/// ## Safety
///
/// This is unsafe because it doesn't use ordered memory operations.
// This is unsafe because it doesn't make use of ordered memory operations.
pub unsafe
/// Stores a tile to a mutable partition view (unordered).
///
/// This is the internal implementation used by `PartitionMut::store()`.
/// Returns a token representing the completion of the store.
///
/// ## Safety
///
/// This is unsafe because it doesn't use ordered memory operations.
// This is unsafe because it doesn't make use of ordered memory operations.
pub unsafe
/// Extracts the memory ordering token from a mutable partition view.
///
/// Used internally to maintain memory consistency.
/* Tile */
/// A multi-dimensional array stored in registers or shared memory.
///
/// `Tile` is the fundamental data structure for computation within GPU kernels.
/// Unlike [`Tensor`] which resides in slow global memory, tiles are stored in fast
/// registers or shared memory, making operations on them extremely efficient.
///
/// ## Type Parameters
///
/// - `E`: Element type (must implement [`ElementType`])
/// - `D`: Shape as a compile-time constant array
///
/// ## Usage Pattern
///
/// 1. Load data from global memory ([`Tensor`]) into a tile
/// 2. Perform computations on the tile using operators (+, *, etc.)
/// 3. Store the result back to global memory
///
/// ## Examples
///
/// ### Element-wise operations
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = partition_a.load([pid.0]);
/// let b: Tile<f32, {[128]}> = partition_b.load([pid.0]);
///
/// // All operations happen in registers/shared memory
/// let sum = a + b;
/// let product = a * b;
/// let result = sum * 2.0 + product;
/// ```
///
/// ### Broadcasting and reshaping
///
/// ```rust,ignore
/// // Broadcast a scalar
/// let scalar_tile = 3.14f32.broadcast(const_shape![128]);
///
/// // Reshape a tile
/// let matrix: Tile<f32, {[8, 16]}> = vector.reshape(const_shape![8, 16]);
/// ```
///
/// ### Matrix multiplication
///
/// ```rust,ignore
/// let a: Tile<f32, {[64, 32]}> = ...;
/// let b: Tile<f32, {[32, 64]}> = ...;
/// let c: Tile<f32, {[64, 64]}> = ...;
///
/// // Hardware-accelerated matrix multiply-accumulate
/// let result = mma(a, b, c); // c + a * b
/// ```
/// Element-wise addition of tiles.
///
/// Enables the `+` operator for tiles. Performs element-wise addition where
/// `result[i] = self[i] + rhs[i]`.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let sum = a + b; // Element-wise addition
/// ```
/// Element-wise subtraction of tiles.
///
/// Enables the `-` operator for tiles. Performs element-wise subtraction where
/// `result[i] = self[i] - rhs[i]`.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let diff = a - b; // Element-wise subtraction
/// ```
/// Element-wise multiplication of tiles.
///
/// Enables the `*` operator for tiles. Performs element-wise (Hadamard) multiplication
/// where `result[i] = self[i] * rhs[i]`.
///
/// ## Note
///
/// This is **not** matrix multiplication. For matrix multiplication, use [`mma()`].
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let product = a * b; // Element-wise multiplication
/// ```
/// Element-wise division of tiles.
///
/// Enables the `/` operator for tiles. Performs element-wise division where
/// `result[i] = self[i] / rhs[i]`.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let quotient = a / b; // Element-wise division
/// ```
/// Element-wise remainder (modulo) of tiles.
///
/// Enables the `%` operator for tiles. Performs element-wise remainder where
/// `result[i] = self[i] % rhs[i]`.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i32, {[128]}> = ...;
/// let b: Tile<i32, {[128]}> = ...;
/// let remainder = a % b; // Element-wise modulo
/// ```
// These aren't going to be possible in Rust.
// #[cuda_tile::variadic_impl(N=4)]
// impl<E: ElementType, const D: [i32; N]> cmp::PartialEq for Tile<E, D> {
// fn eq(&self, other: &Self) -> bool {
// unreachable!()
// }
// }
//
// #[cuda_tile::variadic_impl(N=4)]
// impl<E: ElementType, const D: [i32; N]> cmp::Eq for Tile<E, D> {}
//
// #[cuda_tile::variadic_impl(N=4)]
// impl<E: ElementType, const D: [i32; N]> cmp::PartialOrd for Tile<E, D> {
// fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
// unreachable!()
// }
// }
//
// #[cuda_tile::variadic_impl(N=4)]
// impl<E: ElementType, const D: [i32; N]> cmp::Ord for Tile<E, D> {
// fn cmp(&self, other: &Self) -> cmp::Ordering {
// unreachable!()
// }
// }
// The compiler expects these ops to end with _tile.
/// Element-wise equality comparison.
///
/// Compares two tiles element-wise, returning a boolean tile where each element
/// is `true` if the corresponding elements are equal, `false` otherwise.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let equal = eq_tile(a, b); // Tile<bool, {[128]}>
/// // Use with select for conditional operations
/// let result = select(equal, a, b); // Choose a where equal, else b
/// ```
/// Element-wise inequality comparison.
///
/// Compares two tiles element-wise, returning a boolean tile where each element
/// is `true` if the corresponding elements are not equal, `false` otherwise.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i32, {[64, 64]}> = ...;
/// let b: Tile<i32, {[64, 64]}> = ...;
/// let not_equal = ne_tile(a, b); // Tile<bool, {[64, 64]}>
/// ```
/// Element-wise greater-than comparison.
///
/// Compares two tiles element-wise, returning a boolean tile where each element
/// is `true` if `lhs[i] > rhs[i]`, `false` otherwise.
///
/// ## Examples
///
/// ```rust,ignore
/// let values: Tile<f32, {[128]}> = ...;
/// let threshold: Tile<f32, {[128]}> = ...;
/// let above = gt_tile(values, threshold); // values > threshold
/// ```
/// Element-wise greater-than-or-equal comparison.
///
/// Compares two tiles element-wise, returning a boolean tile where each element
/// is `true` if `lhs[i] >= rhs[i]`, `false` otherwise.
///
/// ## Examples
///
/// ```rust,ignore
/// let values: Tile<f32, {[128]}> = ...;
/// let min_value = 0.0f32.broadcast(const_shape![128]);
/// let valid = ge_tile(values, min_value); // values >= 0
/// ```
/// Element-wise less-than comparison.
///
/// Compares two tiles element-wise, returning a boolean tile where each element
/// is `true` if `lhs[i] < rhs[i]`, `false` otherwise.
///
/// ## Examples
///
/// ```rust,ignore
/// let predictions: Tile<f32, {[64]}> = ...;
/// let targets: Tile<f32, {[64]}> = ...;
/// let underestimated = lt_tile(predictions, targets);
/// ```
/// Element-wise less-than-or-equal comparison.
///
/// Compares two tiles element-wise, returning a boolean tile where each element
/// is `true` if `lhs[i] <= rhs[i]`, `false` otherwise.
///
/// ## Examples
///
/// ```rust,ignore
/// let values: Tile<i32, {[256]}> = ...;
/// let max_val = 255i32.broadcast(const_shape![256]);
/// let in_range = le_tile(values, max_val); // values <= 255
/// ```
/// Returns the minimum of two scalar values.
///
/// ## Examples
///
/// ```rust,ignore
/// let result = min(5, 3); // 3
/// ```
/// Returns the maximum of two values.
///
/// ## Examples
///
/// ```rust,ignore
/// let result = max(5, 3); // 5
/// let result = max(2.7, 8.1); // 8.1
/// ```
/// Element-wise minimum of two tiles.
///
/// Returns a tile where each element is the minimum of the corresponding elements
/// from the two input tiles.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let minimums = min_tile(a, b); // min(a[i], b[i]) for each i
///
/// // Clamp values to maximum
/// let max_limit = 100.0f32.broadcast(const_shape![128]);
/// let clamped = min_tile(values, max_limit); // values clamped to [0, 100]
/// ```
/// Element-wise maximum of two tiles.
///
/// Returns a tile where each element is the maximum of the corresponding elements
/// from the two input tiles.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let maximums = max_tile(a, b); // max(a[i], b[i]) for each i
///
/// // Clamp values to minimum (ReLU-like)
/// let zero = 0.0f32.broadcast(const_shape![128]);
/// let activated = max_tile(values, zero); // ReLU: max(values, 0)
/// ```
/// Ceiling division: `⌈a / b⌉` for scalars.
///
/// Returns the smallest integer greater than or equal to `a / b`.
/// Equivalent to `(a + b - 1) / b` for positive integers.
///
/// ## Examples
///
/// ```rust,ignore
/// let result = ceil_div(7, 3); // 3 (since 7/3 = 2.33...)
/// let result = ceil_div(6, 3); // 2 (since 6/3 = 2.0)
/// let result = ceil_div(10, 4); // 3 (since 10/4 = 2.5)
/// ```
///
/// ## Use Cases
///
/// - Computing number of blocks needed for tile computation
/// - Rounding up to next multiple
/// - Allocating resources in discrete units
/// Element-wise true division (floating-point division).
///
/// Performs element-wise division ensuring floating-point result even for integer inputs.
/// This differs from the `/` operator which may perform integer division.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...;
/// let b: Tile<f32, {[128]}> = ...;
/// let quotients = true_div(a, b); // Always floating-point division
/// ```
// Common Unary Operations
/// Computes element-wise ceiling (round up) of floating-point tiles.
///
/// Returns a tile where each element is rounded up to the nearest integer.
///
/// ## Parameters
///
/// - `x`: Input tile
/// - `rounding_mode`: Rounding mode string (e.g., "nearest_even", "positive_inf", "negative_inf", "nearest_int_to_zero", "approx")
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [1.2, 2.7, -1.5, ...]
/// let result = ceil(x, "nearest_even"); // [2.0, 3.0, -1.0, ...]
/// ```
/// Computes element-wise cosine of floating-point tiles.
///
/// Returns a tile where each element is the cosine of the corresponding
/// input element (in radians).
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, π/2, π, ...]
/// let result = cos(x); // [1.0, 0.0, -1.0, ...]
/// ```
/// Computes element-wise exponential of floating-point tiles.
///
/// Returns a tile where each element is e raised to the power of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, 1.0, 2.0, ...]
/// let result = exp(x); // [1.0, 2.718..., 7.389..., ...]
/// ```
/// Computes element-wise natural logarithm of floating-point tiles.
///
/// Returns a tile where each element is the natural logarithm of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [1.0, 2.718..., 7.389..., ...]
/// let result = log(x); // [0.0, 1.0, 2.0, ...]
/// ```
/// Computes element-wise reciprocal square root of floating-point tiles.
///
/// Returns a tile where each element is the reciprocal square root of the
/// corresponding input element. This is often faster than computing 1.0/sqrt(x).
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [4.0, 9.0, 16.0, ...]
/// let result = rsqrt(x); // [0.5, 0.333..., 0.25, ...]
/// ```
/// Computes element-wise sine of floating-point tiles.
///
/// Returns a tile where each element is the sine of the corresponding
/// input element (in radians).
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, π/2, π, ...]
/// let result = sin(x); // [0.0, 1.0, 0.0, ...]
/// ```
/// Computes element-wise square root of floating-point tiles.
///
/// Returns a tile where each element is the square root of the corresponding
/// input element.
///
/// ## Parameters
///
/// - `x`: Input tile
/// - `rounding_mode`: Rounding mode string (e.g., "nearest_even", "positive_inf", "negative_inf", "nearest_int_to_zero", "approx")
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [4.0, 9.0, 16.0, ...]
/// let result = sqrt(x, "negative_inf"); // [2.0, 3.0, 4.0, ...]
/// ```
/// Computes element-wise tangent of floating-point tiles.
///
/// Returns a tile where each element is the tangent of the corresponding
/// input element (in radians).
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, π/4, π, ...]
/// let result = tan(x); // [0.0, 1.0, 0.0, ...]
/// ```
// Reduce operations
/// Reduces a tile along a dimension by computing the minimum.
///
/// Computes the minimum value along the specified dimension, collapsing that
/// dimension to size 1. This is a specialized version of [`reduce`] for minimum.
///
/// ## Parameters
///
/// - `x`: The input tile to reduce
/// - `dim`: Which dimension to reduce (0-indexed)
///
/// ## Examples
///
/// ```rust,ignore
/// // Find minimum along dimension 0 (rows)
/// let matrix: Tile<f32, {[64, 128]}> = ...;
/// let col_mins = reduce_min(matrix, 0); // Shape: {[1, 128]}
///
/// // Find minimum along dimension 1 (columns)
/// let row_mins = reduce_min(matrix, 1); // Shape: {[64, 1]}
/// ```
///
/// ## Use Cases
///
/// - Finding minimum values per feature
/// - Clipping/normalization operations
/// - Statistical analysis
/// Reduces a tile along a dimension by computing the maximum.
///
/// Computes the maximum value along the specified dimension, collapsing that
/// dimension to size 1. This is a specialized version of [`reduce`] for maximum.
///
/// ## Parameters
///
/// - `x`: The input tile to reduce
/// - `dim`: Which dimension to reduce (0-indexed)
///
/// ## Examples
///
/// ```rust,ignore
/// // Find maximum along dimension 0
/// let matrix: Tile<f32, {[64, 128]}> = ...;
/// let col_maxs = reduce_max(matrix, 0); // Shape: {[1, 128]}
///
/// // Find global maximum (reduce all dimensions)
/// let row_max = reduce_max(matrix, 1); // Shape: {[64, 1]}
/// let global_max = reduce_max(row_max, 0); // Shape: {[1, 1]}
/// ```
///
/// ## Use Cases
///
/// - Finding peak values
/// - Computing log-sum-exp for numerical stability
/// - Max pooling in neural networks
/// Reduces a tile along a dimension by computing the sum.
///
/// Computes the sum of values along the specified dimension, collapsing that
/// dimension to size 1. This is a specialized version of [`reduce`] for summation.
///
/// ## Parameters
///
/// - `x`: The input tile to reduce
/// - `dim`: Which dimension to reduce (0-indexed)
///
/// ## Examples
///
/// ```rust,ignore
/// // Sum along dimension 0 (column sums)
/// let matrix: Tile<f32, {[64, 128]}> = ...;
/// let col_sums = reduce_sum(matrix, 0); // Shape: {[1, 128]}
///
/// // Sum along dimension 1 (row sums)
/// let row_sums = reduce_sum(matrix, 1); // Shape: {[64, 1]}
///
/// // Compute mean by dividing result
/// let mean = reduce_sum(matrix, 0) / 64.0;
/// ```
///
/// ## Use Cases
///
/// - Computing totals and aggregates
/// - Mean/variance calculations
/// - Matrix-vector products (with broadcasting)
/// - Softmax normalization
/// Reduces a tile along a dimension by computing the product.
///
/// Computes the product of values along the specified dimension, collapsing that
/// dimension to size 1. This is a specialized version of [`reduce`] for multiplication.
///
/// ## Parameters
///
/// - `x`: The input tile to reduce
/// - `dim`: Which dimension to reduce (0-indexed)
///
/// ## Examples
///
/// ```rust,ignore
/// // Product along dimension 0
/// let matrix: Tile<f32, {[64, 128]}> = ...;
/// let col_products = reduce_prod(matrix, 0); // Shape: {[1, 128]}
///
/// // Useful for computing factorials or combinations
/// let numbers: Tile<f32, {[10]}> = ...; // [1, 2, 3, ..., 10]
/// let factorial = reduce_prod(numbers, 0); // 10! = 3628800
/// ```
///
/// ## Use Cases
///
/// - Computing geometric means (with log/exp)
/// - Probability calculations (product of independent probabilities)
/// - Determinant computations
///
/// ## Note
///
/// Be careful of numeric overflow/underflow with products. Consider using
/// sum of logarithms for better numerical stability.
/// Reshapes a tile to a new shape without moving data.
///
/// Reinterprets the tile's data with a different shape. The total number of elements
/// must remain the same (product of dimensions). This is a view operation that doesn't
/// copy or rearrange data in memory.
///
/// ## Parameters
///
/// - `source`: The input tile to reshape
/// - `shape`: The desired output shape
///
/// ## Constraints
///
/// The product of the source dimensions must equal the product of the result dimensions:
/// `S[0] * S[1] * ... * S[N-1] == R[0] * R[1] * ... * R[M-1]`
///
/// ## Examples
///
/// ```rust,ignore
/// // Reshape 1D to 2D
/// let vec: Tile<f32, {[128]}> = ...;
/// let matrix = reshape(vec, const_shape![8, 16]); // 128 = 8 * 16
///
/// // Reshape 2D to 1D (flatten)
/// let matrix: Tile<f32, {[4, 32]}> = ...;
/// let flat = reshape(matrix, const_shape![128]); // 4 * 32 = 128
///
/// // Change dimensionality
/// let tile_2d: Tile<i32, {[64, 64]}> = ...;
/// let tile_3d = reshape(tile_2d, const_shape![16, 16, 16]); // 4096 elements
/// ```
///
/// ## Use Cases
///
/// - Flattening multi-dimensional data for linear operations
/// - Preparing data for matrix multiplication with specific shapes
/// - Converting between different tensor representations
/// - Batching/unbatching operations
///
/// ## Note
///
/// Unlike `permute`, this doesn't change the order of elements in memory,
/// only how they're indexed. For reordering dimensions, use `permute`.
/// Broadcasts a tile to a new shape.
///
/// Dimensions of size 1 in the source can be broadcast to any size in the result.
/// Non-unit dimensions must match between source and result.
///
/// ## Examples
///
/// ```rust,ignore
/// // Broadcast a column vector across columns
/// let col: Tile<f32, {[64, 1]}> = ...;
/// let matrix = broadcast(col, const_shape![64, 128]);
/// // Each column of matrix is a copy of col
/// ```
/// Permutes (reorders) the dimensions of a tile.
///
/// Transposes or rearranges dimensions according to the specified permutation.
/// This is a generalization of matrix transpose to arbitrary dimensions.
///
/// ## Parameters
///
/// - `source`: The input tile to permute
/// - `permutation`: Array specifying the new dimension order
///
/// ## Semantics
///
/// The permutation array maps output dimensions to input dimensions. For example,
/// `[1, 0]` swaps dimensions 0 and 1 (transpose), while `[2, 0, 1]` moves the
/// last dimension to the front.
///
/// ## Examples
///
/// ```rust,ignore
/// // Transpose a 2D matrix
/// let matrix: Tile<f32, {[64, 128]}> = ...;
/// let transposed = permute(matrix, const_array![1, 0]);
/// // Result shape: {[128, 64]}
///
/// // Rotate 3D tensor dimensions
/// let tensor: Tile<f32, {[32, 64, 16]}> = ...;
/// let rotated = permute(tensor, const_array![2, 0, 1]);
/// // Result shape: {[16, 32, 64]} - last dim moved to front
/// ```
///
/// ## Use Cases
///
/// - Matrix transposition for matrix multiplication
/// - Changing memory layout for optimal access patterns
/// - Implementing operations like `einsum` with dimension reordering
/// Creates a tile filled with a constant value.
///
/// Generates a tile of the specified shape where all elements have the same value.
/// This is more efficient than broadcasting for compile-time constants as the value
/// can be embedded directly in the generated code.
///
/// ## Parameters
///
/// - `value`: The constant value to fill the tile with
/// - `shape`: The shape of the resulting tile
///
/// ## Examples
///
/// ```rust,ignore
/// // Create a tile of zeros
/// let zeros: Tile<f32, {[128, 64]}> = constant(0.0f32, const_shape![128, 64]);
///
/// // Create a tile of ones
/// let ones: Tile<i32, {[256]}> = constant(1i32, const_shape![256]);
///
/// // Create a tile with a specific constant
/// let tile: Tile<f32, {[64, 64]}> = constant(3.14f32, const_shape![64, 64]);
/// ```
///
/// ## Use Cases
///
/// - Initializing accumulators (zeros)
/// - Creating masks (ones/zeros)
/// - Generating constant tensors for operations
///
/// ## Note
///
/// For scalar broadcast followed by operations, consider using `broadcast_scalar`
/// or the `.broadcast()` method on scalars instead.
/// Matrix multiply-accumulate using hardware-accelerated Tensor Cores.
///
/// Performs `result = lhs × rhs + acc` using GPU Tensor Core instructions for
/// maximum performance. This is the primary operation for deep learning and
/// dense linear algebra on modern GPUs.
///
/// ## Type Parameters
///
/// - `E1`: Element type for input matrices (typically `f16`, `f32`, or `tf32`)
/// - `E2`: Element type for accumulator and result (typically `f32`)
/// - `M`, `N`, `K`: Matrix dimensions (M×K) × (K×N) + (M×N) → (M×N)
///
/// ## Matrix Shapes
///
/// - `lhs`: M×K matrix (left operand)
/// - `rhs`: K×N matrix (right operand)
/// - `acc`: M×N matrix (accumulator, added to product)
/// - Returns: M×N matrix (result)
///
/// ## Examples
///
/// ```rust,ignore
/// // Basic matrix multiplication with accumulation
/// let a: Tile<f16, {[64, 32]}> = ...; // 64×32
/// let b: Tile<f16, {[32, 64]}> = ...; // 32×64
/// let c: Tile<f32, {[64, 64]}> = ...; // 64×64 accumulator
/// let result = mma(a, b, c); // result = a × b + c, shape {[64, 64]}
///
/// // Initialize accumulator to zero for pure multiplication
/// let zeros: Tile<f32, {[64, 64]}> = constant(0.0f32, const_shape![64, 64]);
/// let product = mma(a, b, zeros); // product = a × b
/// ```
///
/// ## Performance Notes
///
/// - **Tensor Cores**: On NVIDIA Ampere and later GPUs, this uses specialized
/// Tensor Core hardware for massive throughput (up to 312 TFLOPS on A100)
/// - **Mixed Precision**: Using `f16` inputs with `f32` accumulation balances
/// performance and numerical accuracy
/// - **Tile Sizes**: Optimal tile sizes are typically multiples of 16 or 32
/// depending on GPU architecture
///
/// ## Supported Type Combinations
///
/// - `f16 × f16 + f32 → f32` (most common for deep learning)
/// - `f32 × f32 + f32 → f32` (standard precision)
/// - `tf32 × tf32 + f32 → f32` (TensorFloat-32 on Ampere+)
///
/// ## Use Cases
///
/// - Neural network layers (fully connected, attention)
/// - GEMM operations in deep learning
/// - Dense linear algebra (BLAS-3 operations)
/// - Matrix factorizations
}>
/// Generates a 1D tile with sequential integer values.
///
/// Creates a tile containing the sequence `[0, 1, 2, ..., N-1]` where N is
/// the specified size. This is useful for generating indices, ranges, and
/// arithmetic sequences.
///
/// ## Parameters
///
/// - `shape`: The shape of the resulting 1D tile
///
/// ## Examples
///
/// ```rust,ignore
/// // Generate indices 0 to 127
/// let indices: Tile<i32, {[128]}> = iota(const_shape![128]);
/// // indices = [0, 1, 2, 3, ..., 127]
///
/// // Use for indexing operations
/// let offsets: Tile<i32, {[64]}> = iota(const_shape![64]);
/// let scaled = offsets * 4; // [0, 4, 8, 12, ..., 252]
///
/// // Generate a range for lookup table
/// let range: Tile<f32, {[256]}> = convert_tile(iota(const_shape![256]));
/// let normalized = range / 255.0; // [0.0, 1/255, 2/255, ..., 1.0]
/// ```
///
/// ## Use Cases
///
/// - Generating array indices for gather/scatter operations
/// - Creating coordinate grids for image processing
/// - Building lookup tables and sequences
/// - Index calculations for strided memory access
///
/// ## Note
///
/// Currently only supports 1D tiles. For multi-dimensional index grids,
/// use `iota` with `reshape` and `broadcast`.
/// Computes element-wise absolute value of integer tiles.
///
/// Returns a tile where each element is the absolute value of the corresponding
/// input element (for integer types).
///
/// **Note:** Only `i64` is supported for signed integers in cutile, not `i32`.
/// TileIR itself supports both types.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<i64, {[128]}> = ...; // [-1, 2, -3, ...]
/// let result = absi(x); // [1, 2, 3, ...]
/// ```
/// Computes element-wise absolute value of floating-point tiles.
///
/// Returns a tile where each element is the absolute value of the corresponding
/// input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [-1.5, 2.0, -3.5, ...]
/// let result = absf(x); // [1.5, 2.0, 3.5, ...]
/// ```
/// Computes element-wise negation of integer tiles.
///
/// **Note:** Only `i64` is supported for signed integers in cutile, not `i32`.
/// TileIR itself supports both types.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<i64, {[128]}> = ...; // [1, -2, 3, ...]
/// let result = negi(x); // [-1, 2, -3, ...]
/// ```
/// Computes element-wise negation of floating-point tiles.
///
/// Returns a tile where each element is the negation of the corresponding
/// input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [1.5, -2.0, 3.5, ...]
/// let result = negf(x); // [-1.5, 2.0, -3.5, ...]
/// ```
/// Computes element-wise floor of floating-point tiles.
///
/// Returns a tile where each element is rounded down to the nearest integer.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [1.2, 2.7, -1.5, ...]
/// let result = floor(x); // [1.0, 2.0, -2.0, ...]
/// ```
/// Computes element-wise hyperbolic sine of floating-point tiles.
///
/// Returns a tile where each element is the hyperbolic sine of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, 1.0, 2.0, ...]
/// let result = sinh(x); // [0.0, 1.175..., 3.626..., ...]
/// ```
/// Computes element-wise hyperbolic cosine of floating-point tiles.
///
/// Returns a tile where each element is the hyperbolic cosine of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, 1.0, 2.0, ...]
/// let result = cosh(x); // [1.0, 1.543..., 3.762..., ...]
/// ```
/// Computes element-wise hyperbolic tangent of floating-point tiles.
///
/// Returns a tile where each element is the hyperbolic tangent of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, 1.0, 2.0, ...]
/// let result = tanh(x); // [0.0, 0.761..., 0.964..., ...]
/// ```
/// Computes element-wise base-2 exponential (2^x) of floating-point tiles.
///
/// Returns a tile where each element is 2 raised to the power of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [0.0, 1.0, 2.0, ...]
/// let result = exp2(x, ftz::Disabled); // [1.0, 2.0, 4.0, ...]
/// ```
/// Computes element-wise base-2 logarithm of floating-point tiles.
///
/// Returns a tile where each element is the base-2 logarithm of the
/// corresponding input element.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [1.0, 2.0, 4.0, ...]
/// let result = log2(x); // [0.0, 1.0, 2.0, ...]
/// ```
/// Fused multiply-add operation: `result = lhs * rhs + acc`.
///
/// Computes the multiply-add as a single operation with no intermediate rounding,
/// which is more accurate and faster than separate multiply and add operations.
///
/// ## Parameters
///
/// - `lhs`: Left-hand side tile
/// - `rhs`: Right-hand side tile
/// - `acc`: Accumulator tile
/// - `rounding_mode`: Rounding mode string (e.g., "nearest_even", "positive_inf", "negative_inf", "nearest_int_to_zero", "approx")
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...; // [1.0, 2.0, 3.0, ...]
/// let b: Tile<f32, {[128]}> = ...; // [2.0, 3.0, 4.0, ...]
/// let c: Tile<f32, {[128]}> = ...; // [1.0, 1.0, 1.0, ...]
/// let result = fma_op(a, b, c, "nearest_even"); // [3.0, 7.0, 13.0, ...]
/// ```
/// Power operation: `result = source ^ exponent`.
///
/// Computes the element-wise power of the source raised to the exponent.
/// Both operands must have the same shape.
///
/// ## Examples
///
/// ```rust,ignore
/// let x: Tile<f32, {[128]}> = ...; // [2.0, 3.0, 4.0, ...]
/// let y: Tile<f32, {[128]}> = ...; // [2.0, 3.0, 2.0, ...]
/// let result = pow(x, y); // [4.0, 27.0, 16.0, ...]
/// ```
/// Element-wise floating-point maximum.
///
/// Computes the maximum of two floating-point tiles element-wise.
/// Returns the larger of the two values. `-0.0` is considered less than `+0.0`.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...; // [1.0, 5.0, 3.0, ...]
/// let b: Tile<f32, {[128]}> = ...; // [2.0, 4.0, 6.0, ...]
/// let result = maxf(a, b); // [2.0, 5.0, 6.0, ...]
/// ```
///
/// Element-wise floating-point minimum.
///
/// Computes the minimum of two floating-point tiles element-wise.
/// Returns the smaller of the two values. `-0.0` is considered less than `+0.0`.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<f32, {[128]}> = ...; // [1.0, 5.0, 3.0, ...]
/// let b: Tile<f32, {[128]}> = ...; // [2.0, 4.0, 6.0, ...]
/// let result = minf(a, b, nan::Disabled, ftz::Disabled); // [1.0, 4.0, 3.0, ...]
/// ```
/// Element-wise floating-point addition with explicit rounding and FTZ control.
/// Element-wise floating-point subtraction with explicit rounding and FTZ control.
/// Element-wise floating-point multiplication with explicit rounding and FTZ control.
/// Element-wise floating-point division with explicit rounding and FTZ control.
/// Conditional selection operation.
///
/// Returns `val_if_true` where `cond` is true, otherwise returns `val_if_false`.
/// This is equivalent to the ternary operator: `cond ? val_if_true : val_if_false`.
///
/// ## Examples
///
/// ```rust,ignore
/// let cond: Tile<bool, {[128]}> = ...; // [true, false, true, ...]
/// let a: Tile<f32, {[128]}> = ...; // [1.0, 2.0, 3.0, ...]
/// let b: Tile<f32, {[128]}> = ...; // [9.0, 8.0, 7.0, ...]
/// let result = select(cond, a, b); // [1.0, 8.0, 3.0, ...]
/// ```
/// Bitwise AND operation on integer tiles.
///
/// Computes the element-wise bitwise AND of two integer tiles.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i64, {[128]}> = ...; // [0b1010, 0b1100, ...]
/// let b: Tile<i64, {[128]}> = ...; // [0b1100, 0b1010, ...]
/// let result = andi(a, b); // [0b1000, 0b1000, ...]
/// ```
/// Bitwise OR operation on integer tiles.
///
/// Computes the element-wise bitwise OR of two integer tiles.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i64, {[128]}> = ...; // [0b1010, 0b1100, ...]
/// let b: Tile<i64, {[128]}> = ...; // [0b0101, 0b0011, ...]
/// let result = ori(a, b); // [0b1111, 0b1111, ...]
/// ```
/// Bitwise XOR operation on integer tiles.
///
/// Computes the element-wise bitwise XOR of two integer tiles.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i64, {[128]}> = ...; // [0b1010, 0b1100, ...]
/// let b: Tile<i64, {[128]}> = ...; // [0b1100, 0b1010, ...]
/// let result = xori(a, b); // [0b0110, 0b0110, ...]
/// ```
/// Left bit shift operation on integer tiles.
///
/// Shifts the bits of `lhs` left by `rhs` positions, filling with zeros.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i64, {[128]}> = ...; // [1, 2, 4, ...]
/// let b: Tile<i64, {[128]}> = ...; // [2, 3, 1, ...]
/// let result = shli(a, b); // [4, 16, 8, ...]
/// ```
/// Right bit shift operation on integer tiles.
///
/// Shifts the bits of `lhs` right by `rhs` positions.
/// For signed integers, performs arithmetic shift (sign extension).
/// For unsigned integers, performs logical shift (zero fill).
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i64, {[128]}> = ...; // [8, 16, 32, ...]
/// let b: Tile<i64, {[128]}> = ...; // [2, 3, 1, ...]
/// let result = shri(a, b); // [2, 2, 16, ...]
/// ```
///
/// Note: Signedness is automatically inferred from the Rust element type:
/// - u32/u64 → logical shift (zero fill)
/// - i32/i64 and others → arithmetic shift (sign extension)
/// Bitcast operation - reinterprets bits as a different type.
///
/// Reinterprets the bit representation of the source as the target type
/// without changing the underlying bits. The source and target types must
/// have the same total size in bits.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<u32, {[128]}> = ...; // bit pattern 0x40400000
/// let result: Tile<f32, {[128]}> = bitcast(a); // interprets as 3.0
/// ```
/// Element-wise integer maximum.
///
/// Returns the element-wise maximum of two integer tiles. The signedness
/// attribute determines whether the comparison is signed or unsigned.
///
/// ## Examples
///
/// ```rust,ignore
/// let a: Tile<i64, {[128]}> = ...; // [1, -5, 3, ...]
/// let b: Tile<i64, {[128]}> = ...; // [2, -3, 1, ...]
/// let result = maxi(a, b); // [2, -3, 3, ...]
/// ```
///
/// ## Notes
///
/// - For signed comparison: treats values as signed integers (e.g., -1 < 0)
/// - For unsigned comparison: treats values as unsigned integers (e.g., 0xFF > 0x01)
///
/// Note: Signedness is automatically inferred from the Rust element type (u32/u64 → unsigned, others → signed)
/// Multiply high - returns upper bits of integer multiplication.
///
/// Computes the element-wise product of two integer tiles and returns
/// the high bits of the result. This is useful for computing the upper
/// part of a double-width multiplication.
///
/// ## Semantics
///
/// For `N`-bit integers:
/// - Performs `2N`-bit multiplication: `x[i] * y[i]`
/// - Returns the upper `N` bits of the result
///
/// ## Examples
///
/// ```rust,ignore
/// // For 32-bit integers:
/// let a: Tile<i32, {[128]}> = ...; // [0x10000, 0x20000, ...]
/// let b: Tile<i32, {[128]}> = ...; // [0x10000, 0x10000, ...]
/// let result = mulhii(a, b);
/// // a[0] * b[0] = 0x100000000 (64-bit), upper 32 bits = 0x1
/// // a[1] * b[1] = 0x200000000 (64-bit), upper 32 bits = 0x2
/// ```
///
/// ## Use Cases
///
/// - Fixed-point arithmetic
/// - Computing 128-bit products from 64-bit inputs
/// - Efficient division approximations
/// Integer extension - widen integer type with sign/zero extension.
///
/// Converts integers from a narrower to a wider type. The signedness
/// attribute determines whether to perform sign extension or zero extension.
///
/// ## Semantics
///
/// - **Signed extension**: Preserves the sign by replicating the sign bit
/// - **Zero extension**: Fills upper bits with zeros
///
/// ## Examples
///
/// ```rust,ignore
/// // Sign extension: i32 -> i64
/// let a: Tile<i32, {[128]}> = ...; // [-1, 127, ...]
/// let result: Tile<i64, {[128]}> = exti(a);
/// // [-1i32 extends to -1i64 (0xFFFFFFFFFFFFFFFF)]
/// // [127i32 extends to 127i64 (0x000000000000007F)]
/// ```
///
/// ## Notes
///
/// - The target type must be wider than the source type
/// - Signedness is automatically inferred from the source Rust element type
/// - Shape remains the same, only element type changes
/// Integer truncation - narrow integer type by discarding upper bits.
///
/// Converts integers from a wider to a narrower type by discarding the
/// upper bits. This is the inverse operation of `exti`.
///
/// ## Semantics
///
/// - Discards upper bits that don't fit in the target type
/// - Preserves lower bits (modulo arithmetic behavior)
///
/// ## Examples
///
/// ```rust,ignore
/// // i64 -> i32 truncation
/// let a: Tile<i64, {[128]}> = ...; // [0x100000001, 0xFFFFFFFF, ...]
/// let result: Tile<i32, {[128]}> = trunci(a);
/// // [0x100000001 truncates to 0x00000001]
/// // [0xFFFFFFFF truncates to 0xFFFFFFFF]
/// ```
///
/// ## Notes
///
/// - The target type must be narrower than the source type
/// - Value may be lost if the source value doesn't fit in target type
/// - Shape remains the same, only element type changes
/// Convert integer to pointer.
///
/// Converts a tile of integer values to a tile of pointer values.
/// This is used for pointer arithmetic and address manipulation.
///
/// ## Examples
///
/// ```rust,ignore
/// let addresses: Tile<u64, {[128]}> = ...; // [0x1000, 0x1004, ...]
/// let pointers: PointerTile<*mut f32, {[128]}> = int_to_ptr(addresses);
/// ```
///
/// ## Notes
///
/// - Typically used with `u64` or `i64` integer types
/// - Result is a `PointerTile` that can be used with memory operations
/// - This operation is useful for computing dynamic memory addresses
/// Convert pointer to integer.
///
/// Converts a tile of pointer values to a tile of integer values.
/// This is used for pointer arithmetic and address comparison.
///
/// ## Examples
///
/// ```rust,ignore
/// let pointers: PointerTile<*mut f32, {[128]}> = ...;
/// let addresses: Tile<u64, {[128]}> = ptr_to_int(pointers);
/// // Now addresses can be used for arithmetic operations
/// ```
///
/// ## Notes
///
/// - Result is typically `u64` or `i64` integer type
/// - Useful for computing pointer offsets or alignments
/// - This operation preserves pointer provenance information for the compiler
/// Cast pointer type - reinterpret pointers as pointing to different type.
///
/// Converts a tile of pointers from one element type to another without
/// changing the address values. This is similar to a C-style pointer cast.
///
/// ## Examples
///
/// ```rust,ignore
/// let float_ptrs: PointerTile<*mut f32, {[128]}> = ...;
/// let int_ptrs: PointerTile<*mut i32, {[128]}> = ptr_to_ptr(float_ptrs);
/// // Same addresses, but now interpreted as pointing to i32
/// ```
///
/// ## Notes
///
/// - Only changes the pointed-to type, not the address
/// - Distinct from `int_to_ptr` and `ptr_to_int` for provenance tracking
/// - Use with caution: accessing memory through wrong pointer type is unsafe
/// Extract a subtile from a tile.
///
/// Extracts a subtile from a source tile at specified indices. The result
/// shape must evenly divide the source shape.
///
/// ## Semantics
///
/// The indices specify which slice to extract, not the offsets. Only full
/// slices can be extracted - the result shape must evenly divide the source.
///
/// ## Examples
///
/// ```rust,ignore
/// // Extract 4-element slices from an 8-element tile
/// let source: Tile<f32, {[8]}> = ...; // [1, 2, 3, 4, 5, 6, 7, 8]
/// let idx0: Tile<i32, {[]}> = scalar_to_tile(0i32);
/// let slice0: Tile<f32, {[4]}> = extract(source, [idx0]);
/// // slice0 = [1, 2, 3, 4]
///
/// let idx1: Tile<i32, {[]}> = scalar_to_tile(1i32);
/// let slice1: Tile<f32, {[4]}> = extract(source, [idx1]);
/// // slice1 = [5, 6, 7, 8]
/// ```
///
/// ## Notes
///
/// - Result shape must evenly divide source shape in each dimension
/// - Indices specify slice number, not element offset
/// - Out-of-bounds indices result in undefined behavior
/// - Extracted slices are non-overlapping for unique indices
/// Concatenate two tiles along a specified dimension.
///
/// Joins two tiles together along a specified dimension. The tiles must have
/// the same shape in all dimensions except the concatenation dimension.
///
/// ## Semantics
///
/// The `dim` parameter specifies which dimension to concatenate along (0-indexed).
/// The result dimension size equals the sum of the two input dimension sizes.
///
/// ## Examples
///
/// ```rust,ignore
/// // 1D concatenation
/// let a: Tile<f32, {[4]}> = ...; // [1, 2, 3, 4]
/// let b: Tile<f32, {[4]}> = ...; // [5, 6, 7, 8]
/// let result: Tile<f32, {[8]}> = cat(a, b, 0);
/// // result = [1, 2, 3, 4, 5, 6, 7, 8]
///
/// // 2D concatenation along rows (dim=0)
/// let a: Tile<f32, {[2, 3]}> = ...; // [[1, 2, 3],
/// // [4, 5, 6]]
/// let b: Tile<f32, {[2, 3]}> = ...; // [[7, 8, 9],
/// // [10, 11, 12]]
/// let result: Tile<f32, {[4, 3]}> = cat(a, b, 0);
/// // result = [[1, 2, 3],
/// // [4, 5, 6],
/// // [7, 8, 9],
/// // [10, 11, 12]]
/// ```
///
/// ## Notes
///
/// - All dimensions except `dim` must match between inputs
/// - `dim` must be a valid dimension index (0 ≤ dim < rank)
/// - Result shape is same as inputs except along concatenation dimension
/* High-level Functions */
/// Broadcasts a scalar value to a tile of the specified shape.
///
/// This is the underlying implementation for the [`BroadcastScalar`] trait.
///
/// ## Examples
///
/// ```rust,ignore
/// let tile = broadcast_scalar(3.14f32, const_shape![128]);
/// // tile contains 128 copies of 3.14
/// ```
> = }> ;
let tile_x: }> = scalar_to_tile;
tile_x.reshape.broadcast
}
/// Loads the entire tensor into a tile.
///
/// This is used when the tensor shape matches the processing tile size.
/// The tensor must fit entirely within a single thread block's processing capacity.
///
/// ## Examples
///
/// ```rust,ignore
/// let tensor: &mut Tensor<f32, {[128]}> = ...;
/// let tile = load_tile(tensor);
/// ```
/// Stores a tile back to a tensor.
///
/// Writes the tile data to global memory at the location of the tensor.
///
/// ## Examples
///
/// ```rust,ignore
/// let tensor: &mut Tensor<f32, {[128]}> = ...;
/// let tile: Tile<f32, {[128]}> = compute_result();
/// store_tile(tensor, tile);
/// ```
/// Loads a tile from a dynamically-sized 2D input tensor using the output tensor's shape.
///
/// This helper function loads a tile from `x` that corresponds to the current thread
/// block's position, using `y`'s static shape to determine tile size. Common pattern
/// for kernels where the output shape determines processing granularity.
///
/// ## Examples
///
/// ```rust,ignore
/// fn kernel(
/// output: &mut Tensor<f32, {[64, 64]}>,
/// input: &Tensor<f32, {[-1, -1]}>,
/// ) {
/// let tile = load_tile_like_2d(input, output);
/// // Process tile corresponding to this block
/// }
/// ```
/// Loads a tile from a dynamically-sized 1D input tensor using the output tensor's shape.
///
/// This is the 1D version of [`load_tile_like_2d`]. It loads a tile from `x` that
/// corresponds to the current thread block's position, using `y`'s static shape to
/// determine tile size.
///
/// ## Type Parameters
///
/// - `E1`: Element type of input tensor (can differ from output)
/// - `E2`: Element type of output tensor
///
/// ## Parameters
///
/// - `x`: Input tensor with dynamic shape `{[-1]}`
/// - `y`: Output tensor with static shape (used to determine tile size)
///
/// ## Examples
///
/// ```rust,ignore
/// fn vector_process(
/// output: &mut Tensor<f32, {[128]}>,
/// input: &Tensor<f32, {[-1]}>,
/// ) {
/// let tile = load_tile_like_1d(input, output);
/// // Process 128-element tile corresponding to this block
/// let result = tile * 2.0;
/// output.store(result);
/// }
/// ```
// TODO (hme): Need to add a way to specify individual instances of N for pid-dependent operations.
// pub fn load_tile_like<const S: [i32; 2]>(x: &Tensor<f32, {[-1; 2]}>, y: &mut Tensor<f32, S>) -> Tile<f32, S> {
// // Load a tile of x from a statically shaped mutable tensor like y.
// // Since y is a mutable ref, it is partitioned and mapped to pid.
// let pid: (i32, i32, i32) = get_tile_block_id();
// // TODO (hme): Need to add support for N in function block.
// // pid should be provided up to N somehow.
// let pids: [i32; 2] = [pid.0, pid.1];
// let tile_shape: Shape<S> = y.shape();
// let x_partition: Partition<f32, S> = make_partition_view(&x, tile_shape);
// let tile_x: Tile<f32, S> = load_from_view(&x_partition, pids);
// tile_x
// }
/// Assume that a value is divisible by a constant.
///
/// Tells the compiler that the input value (or all elements if a tile) is divisible
/// by `DIVISOR`. This enables optimizations like strength reduction (replacing division
/// with cheaper operations) and loop unrolling.
///
/// ## Type Parameters
///
/// - `T`: Can be a scalar integer (`i32`) or a tile of integers (`Tile<i32, S>`)
/// - `DIVISOR`: The divisor constant (compile-time)
///
/// ## Safety
///
/// Undefined behavior if the assumption is violated. The compiler may generate code
/// that produces incorrect results or crashes if any element is not divisible by `DIVISOR`.
///
/// ## Examples
///
/// ```rust,ignore
/// // Tell compiler that dimension is divisible by tile size
/// let dim = get_dimension();
/// let aligned_dim = unsafe { assume_div_by::<_, 64>(dim) };
/// // Compiler can now optimize loops with this knowledge
/// ```
///
/// ## Use Cases
///
/// - Asserting alignment properties (e.g., pointer offsets divisible by 8)
/// - Loop trip counts divisible by unroll factor
/// - Array dimensions divisible by tile size
pub unsafe
/// Assume complex divisibility pattern along specific dimensions.
///
/// Tells the compiler that every `every` elements along dimension `along` are
/// divisible by `divisor`. This is useful for asserting strided memory access patterns.
///
/// ## Type Parameters
///
/// - `T`: Typically a tile or shaped value
/// - `divisor`: The divisor constant
/// - `every`: Spacing between elements that satisfy the divisibility property
/// - `along`: Which dimension to apply the pattern to
///
/// ## Safety
///
/// Undefined behavior if the assumption is violated at runtime.
///
/// ## Example
///
/// ```rust,ignore
/// let tile: Tile<i32, {[128, 64]}> = ...;
/// // Every 8 elements along dimension 1 are divisible by 16
/// let tile = unsafe { assume_div_by_every_along::<_, 16, 8, 1>(tile) };
/// ```
pub unsafe
/// Assume that a value has a lower bound (inclusive).
///
/// Tells the compiler that the input value (or all elements if a tile) is greater than
/// or equal to `LOWER`. This enables optimizations like:
/// - Eliminating unnecessary bounds checks
/// - Simplifying comparison operations
/// - Enabling unsigned optimizations when LOWER >= 0
///
/// ## Type Parameters
///
/// - `T`: Can be a scalar integer or a tile of integers
/// - `LOWER`: The minimum value (inclusive, compile-time constant)
///
/// ## Safety
///
/// Undefined behavior if any element is less than `LOWER`. The compiler may generate
/// optimized code that produces incorrect results for out-of-range values.
///
/// ## Examples
///
/// ```rust,ignore
/// // Assert that array index is non-negative
/// let idx = compute_index();
/// let safe_idx = unsafe { assume_bounds_lower::<_, 0>(idx) };
/// // Compiler knows idx >= 0, can optimize accordingly
///
/// // Assert all tile elements are positive
/// let tile: Tile<i32, {[128]}> = ...;
/// let positive = unsafe { assume_bounds_lower::<_, 1>(tile) };
/// ```
///
/// ## Use Cases
///
/// - Asserting non-negativity (LOWER = 0) after validation
/// - Expressing value ranges after clamping
/// - Enabling vectorization of loops with known ranges
pub unsafe
/// Assume that a value has an upper bound (inclusive).
///
/// Tells the compiler that the input value (or all elements if a tile) is less than
/// or equal to `UPPER`. This enables optimizations like:
/// - Eliminating unnecessary bounds checks
/// - Using smaller integer types internally
/// - Better branch prediction
///
/// ## Type Parameters
///
/// - `T`: Can be a scalar integer or a tile of integers
/// - `UPPER`: The maximum value (inclusive, compile-time constant)
///
/// ## Safety
///
/// Undefined behavior if any element is greater than `UPPER`.
///
/// ## Example
///
/// ```rust,ignore
/// let idx = compute_bounded_index();
/// let bounded_idx = unsafe { assume_bounds_upper::<_, 255>(idx) };
/// // Compiler knows idx <= 255, can use 8-bit operations
/// ```
pub unsafe
/// Assume that a value is within a specific range (inclusive bounds).
///
/// Combines lower and upper bound assumptions. Tells the compiler that the input
/// value (or all elements if a tile) satisfies `LOWER <= value <= UPPER`.
///
/// ## Type Parameters
///
/// - `T`: Can be a scalar integer or a tile of integers
/// - `LOWER`: The minimum value (inclusive, compile-time constant)
/// - `UPPER`: The maximum value (inclusive, compile-time constant)
///
/// ## Safety
///
/// Undefined behavior if any element is outside the range `[LOWER, UPPER]`.
///
/// ## Examples
///
/// ```rust,ignore
/// // Assert value is in valid byte range
/// let byte_val = compute_value();
/// let clamped = unsafe { assume_bounds::<_, 0, 255>(byte_val) };
///
/// // Assert tile elements are in valid range
/// let tile: Tile<i32, {[128]}> = ...;
/// let bounded = unsafe { assume_bounds::<_, -100, 100>(tile) };
/// ```
///
/// ## Use Cases
///
/// - Asserting values after clamping/saturation
/// - Expressing valid ranges for lookup table indices
/// - Enabling optimizations based on value ranges
pub unsafe
/// Assume that elements are identical within groups along dimension 0 (1D).
///
/// Tells the compiler that within every consecutive group of `GROUP0` elements,
/// all elements have the same value. This enables optimizations like:
/// - Loading only one element per group (broadcast the rest)
/// - Eliminating redundant computations on identical values
/// - Better vectorization opportunities
///
/// ## Type Parameters
///
/// - `T`: Typically a 1D tile (`Tile<E, {[N]}>`)
/// - `GROUP0`: Size of groups with identical elements
///
/// ## Semantics
///
/// For a tile with elements `[a₀, a₁, a₂, ..., a_{N-1}]`, this asserts:
/// - Elements `[0..GROUP0)` are all equal
/// - Elements `[GROUP0..2*GROUP0)` are all equal
/// - And so on for each group
///
/// ## Safety
///
/// Undefined behavior if the assumption is violated. The compiler may generate code
/// that loads only one element per group, producing incorrect results if elements differ.
///
/// ## Examples
///
/// ```rust,ignore
/// // After broadcasting a value
/// let tile: Tile<i32, {[128]}> = scalar.broadcast(const_shape![128]);
/// // Tell compiler all elements are identical
/// let optimized = unsafe { assume_same_elements_1d::<_, 128>(tile) };
///
/// // After grouping by blocks of 4
/// let data: Tile<f32, {[64]}> = ...;
/// // Groups of 4 consecutive elements are identical
/// let grouped = unsafe { assume_same_elements_1d::<_, 4>(data) };
/// ```
///
/// ## Use Cases
///
/// - After broadcasting operations where all elements are the same
/// - When processing block-replicated data
/// - After computing values that are constant within groups
pub unsafe
/// Assume that elements are identical within groups along each dimension (2D).
///
/// Tells the compiler that within rectangular groups of size `GROUP0 × GROUP1`,
/// all elements have the same value. This is the 2D extension of `assume_same_elements_1d`.
///
/// ## Type Parameters
///
/// - `T`: Typically a 2D tile (`Tile<E, {[M, N]}>`)
/// - `GROUP0`: Group size along dimension 0 (rows)
/// - `GROUP1`: Group size along dimension 1 (columns)
///
/// ## Semantics
///
/// For a 2D tile, this asserts that within each `GROUP0 × GROUP1` rectangular block,
/// all elements are identical. The tile is partitioned into non-overlapping blocks.
///
/// ## Safety
///
/// Undefined behavior if any element within a group differs from others in that group.
///
/// ## Examples
///
/// ```rust,ignore
/// // After 2D broadcast
/// let tile: Tile<f32, {[8, 16]}> = ...;
/// // Groups of 2×4 have identical elements
/// let grouped = unsafe { assume_same_elements_2d::<_, 2, 4>(tile) };
///
/// // Matrix with block-constant structure
/// let matrix: Tile<i32, {[64, 64]}> = ...;
/// // Each 8×8 block is constant
/// let block_const = unsafe { assume_same_elements_2d::<_, 8, 8>(matrix) };
/// ```
///
/// ## Use Cases
///
/// - Block-diagonal matrices where blocks are constant
/// - After 2D broadcasting/replication
/// - Tiled convolution with constant kernels per region
pub unsafe
/// Assume that elements are identical within groups along each dimension (3D).
///
/// Tells the compiler that within cubic groups of size `GROUP0 × GROUP1 × GROUP2`,
/// all elements have the same value. This is the 3D extension of `assume_same_elements_2d`.
///
/// ## Type Parameters
///
/// - `T`: Typically a 3D tile (`Tile<E, {[D0, D1, D2]}>`)
/// - `GROUP0`: Group size along dimension 0
/// - `GROUP1`: Group size along dimension 1
/// - `GROUP2`: Group size along dimension 2
///
/// ## Safety
///
/// Undefined behavior if any element within a group differs from others in that group.
///
/// ## Example
///
/// ```rust,ignore
/// let volume: Tile<f32, {[32, 32, 32]}> = ...;
/// // Each 4×4×4 block has identical elements
/// let blocked = unsafe { assume_same_elements_3d::<_, 4, 4, 4>(volume) };
/// ```
///
/// ## Use Cases
///
/// - 3D volume processing with block-constant regions
/// - Batched 2D operations where each batch is constant
/// - Spatiotemporal data with temporal replication
pub unsafe
/// Assume that elements are identical within groups along each dimension (4D).
///
/// Tells the compiler that within 4D hypercubic groups of size
/// `GROUP0 × GROUP1 × GROUP2 × GROUP3`, all elements have the same value.
/// This is the 4D extension of `assume_same_elements_3d`.
///
/// ## Type Parameters
///
/// - `T`: Typically a 4D tile (`Tile<E, {[D0, D1, D2, D3]}>`)
/// - `GROUP0`: Group size along dimension 0
/// - `GROUP1`: Group size along dimension 1
/// - `GROUP2`: Group size along dimension 2
/// - `GROUP3`: Group size along dimension 3
///
/// ## Safety
///
/// Undefined behavior if any element within a group differs from others in that group.
///
/// ## Example
///
/// ```rust,ignore
/// let tensor: Tile<f32, {[16, 16, 16, 16]}> = ...;
/// // Each 2×2×2×2 hyperblock has identical elements
/// let blocked = unsafe { assume_same_elements_4d::<_, 2, 2, 2, 2>(tensor) };
/// ```
///
/// ## Use Cases
///
/// - High-dimensional tensor operations with block structure
/// - Batched 3D operations where batches are constant
/// - Neural network layers with structured sparsity
pub unsafe
/* TensorArray */
// TODO (hme): Add support for this sort of type.
// #[cuda_tile::variadic_struct(N = 6)]
// struct TensorArray<E: ElementType, const D: [i32; N]> {
// _type: PhantomData<E>,
// }
pub unsafe > = }> ;
let dst_part: }> = dst.partition;
let dst_ptr_int: }> = dst_part.load;
let dst_ptr_int: }> = dst_ptr_int.reshape;
let dst_ptr: }> = int_to_ptr;
let dst_tensor: =
unsafe ;
dst_tensor
}
// #[cuda_tile::op(name="cuda_tile.permute", params=["source"], attribute_params=["permutation:array"])]
// #[cuda_tile::variadic_op(N = 6)]
// pub fn permute<E: ElementType, const A: [i32; N], const I: [i32; N], const R: [i32; N]>(
// source: Tile<E, A>,
// permutation: Array<I>,
// ) -> Tile<E, R> {
// unreachable!()
// }
}