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
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
|
//===- OpenMPToLLVMIRTranslation.cpp - Translate OpenMP dialect to LLVM IR-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements a translation between the MLIR OpenMP dialect and LLVM
// IR.
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.h"
#include "mlir/Analysis/TopologicalSortUtils.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/LLVMIR/LLVMTypes.h"
#include "mlir/Dialect/OpenMP/OpenMPDialect.h"
#include "mlir/Dialect/OpenMP/OpenMPInterfaces.h"
#include "mlir/IR/Operation.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Target/LLVMIR/Dialect/OpenMPCommon.h"
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/ReplaceConstant.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/TargetParser/Triple.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include <cstdint>
#include <iterator>
#include <numeric>
#include <optional>
#include <utility>
using namespace mlir;
namespace {
static llvm::omp::ScheduleKind
convertToScheduleKind(std::optional<omp::ClauseScheduleKind> schedKind) {
if (!schedKind.has_value())
return llvm::omp::OMP_SCHEDULE_Default;
switch (schedKind.value()) {
case omp::ClauseScheduleKind::Static:
return llvm::omp::OMP_SCHEDULE_Static;
case omp::ClauseScheduleKind::Dynamic:
return llvm::omp::OMP_SCHEDULE_Dynamic;
case omp::ClauseScheduleKind::Guided:
return llvm::omp::OMP_SCHEDULE_Guided;
case omp::ClauseScheduleKind::Auto:
return llvm::omp::OMP_SCHEDULE_Auto;
case omp::ClauseScheduleKind::Runtime:
return llvm::omp::OMP_SCHEDULE_Runtime;
case omp::ClauseScheduleKind::Distribute:
return llvm::omp::OMP_SCHEDULE_Distribute;
}
llvm_unreachable("unhandled schedule clause argument");
}
/// ModuleTranslation stack frame for OpenMP operations. This keeps track of the
/// insertion points for allocas.
class OpenMPAllocaStackFrame
: public StateStackFrameBase<OpenMPAllocaStackFrame> {
public:
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OpenMPAllocaStackFrame)
explicit OpenMPAllocaStackFrame(llvm::OpenMPIRBuilder::InsertPointTy allocaIP)
: allocaInsertPoint(allocaIP) {}
llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint;
};
/// Stack frame to hold a \see llvm::CanonicalLoopInfo representing the
/// collapsed canonical loop information corresponding to an \c omp.loop_nest
/// operation.
class OpenMPLoopInfoStackFrame
: public StateStackFrameBase<OpenMPLoopInfoStackFrame> {
public:
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(OpenMPLoopInfoStackFrame)
llvm::CanonicalLoopInfo *loopInfo = nullptr;
};
/// Custom error class to signal translation errors that don't need reporting,
/// since encountering them will have already triggered relevant error messages.
///
/// Its purpose is to serve as the glue between MLIR failures represented as
/// \see LogicalResult instances and \see llvm::Error instances used to
/// propagate errors through the \see llvm::OpenMPIRBuilder. Generally, when an
/// error of the first type is raised, a message is emitted directly (the \see
/// LogicalResult itself does not hold any information). If we need to forward
/// this error condition as an \see llvm::Error while avoiding triggering some
/// redundant error reporting later on, we need a custom \see llvm::ErrorInfo
/// class to just signal this situation has happened.
///
/// For example, this class should be used to trigger errors from within
/// callbacks passed to the \see OpenMPIRBuilder when they were triggered by the
/// translation of their own regions. This unclutters the error log from
/// redundant messages.
class PreviouslyReportedError
: public llvm::ErrorInfo<PreviouslyReportedError> {
public:
void log(raw_ostream &) const override {
// Do not log anything.
}
std::error_code convertToErrorCode() const override {
llvm_unreachable(
"PreviouslyReportedError doesn't support ECError conversion");
}
// Used by ErrorInfo::classID.
static char ID;
};
char PreviouslyReportedError::ID = 0;
/*
* Custom class for processing linear clause for omp.wsloop
* and omp.simd. Linear clause translation requires setup,
* initialization, update, and finalization at varying
* basic blocks in the IR. This class helps maintain
* internal state to allow consistent translation in
* each of these stages.
*/
class LinearClauseProcessor {
private:
SmallVector<llvm::Value *> linearPreconditionVars;
SmallVector<llvm::Value *> linearLoopBodyTemps;
SmallVector<llvm::Value *> linearOrigVal;
SmallVector<llvm::Value *> linearSteps;
SmallVector<llvm::Type *> linearVarTypes;
llvm::BasicBlock *linearFinalizationBB;
llvm::BasicBlock *linearExitBB;
llvm::BasicBlock *linearLastIterExitBB;
public:
// Register type for the linear variables
void registerType(LLVM::ModuleTranslation &moduleTranslation,
mlir::Attribute &ty) {
linearVarTypes.push_back(moduleTranslation.convertType(
mlir::cast<mlir::TypeAttr>(ty).getValue()));
}
// Allocate space for linear variabes
void createLinearVar(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::Value *linearVar, int idx) {
linearPreconditionVars.push_back(
builder.CreateAlloca(linearVarTypes[idx], nullptr, ".linear_var"));
llvm::Value *linearLoopBodyTemp =
builder.CreateAlloca(linearVarTypes[idx], nullptr, ".linear_result");
linearOrigVal.push_back(linearVar);
linearLoopBodyTemps.push_back(linearLoopBodyTemp);
}
// Initialize linear step
inline void initLinearStep(LLVM::ModuleTranslation &moduleTranslation,
mlir::Value &linearStep) {
linearSteps.push_back(moduleTranslation.lookupValue(linearStep));
}
// Emit IR for initialization of linear variables
void initLinearVar(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::BasicBlock *loopPreHeader) {
builder.SetInsertPoint(loopPreHeader->getTerminator());
for (size_t index = 0; index < linearOrigVal.size(); index++) {
llvm::LoadInst *linearVarLoad =
builder.CreateLoad(linearVarTypes[index], linearOrigVal[index]);
builder.CreateStore(linearVarLoad, linearPreconditionVars[index]);
}
}
// Emit IR for updating Linear variables
void updateLinearVar(llvm::IRBuilderBase &builder, llvm::BasicBlock *loopBody,
llvm::Value *loopInductionVar) {
builder.SetInsertPoint(loopBody->getTerminator());
for (size_t index = 0; index < linearPreconditionVars.size(); index++) {
llvm::Type *linearVarType = linearVarTypes[index];
llvm::Value *iv = loopInductionVar;
llvm::Value *step = linearSteps[index];
if (!iv->getType()->isIntegerTy())
llvm_unreachable("OpenMP loop induction variable must be an integer "
"type");
if (linearVarType->isIntegerTy()) {
// Integer path: normalize all arithmetic to linearVarType
iv = builder.CreateSExtOrTrunc(iv, linearVarType);
step = builder.CreateSExtOrTrunc(step, linearVarType);
llvm::LoadInst *linearVarStart =
builder.CreateLoad(linearVarType, linearPreconditionVars[index]);
llvm::Value *mulInst = builder.CreateMul(iv, step);
llvm::Value *addInst = builder.CreateAdd(linearVarStart, mulInst);
builder.CreateStore(addInst, linearLoopBodyTemps[index]);
} else if (linearVarType->isFloatingPointTy()) {
// Float path: perform multiply in integer, then convert to float
step = builder.CreateSExtOrTrunc(step, iv->getType());
llvm::Value *mulInst = builder.CreateMul(iv, step);
llvm::LoadInst *linearVarStart =
builder.CreateLoad(linearVarType, linearPreconditionVars[index]);
llvm::Value *mulFp = builder.CreateSIToFP(mulInst, linearVarType);
llvm::Value *addInst = builder.CreateFAdd(linearVarStart, mulFp);
builder.CreateStore(addInst, linearLoopBodyTemps[index]);
} else {
llvm_unreachable(
"Linear variable must be of integer or floating-point type");
}
}
}
// Linear variable finalization is conditional on the last logical iteration.
// Create BB splits to manage the same.
void splitLinearFiniBB(llvm::IRBuilderBase &builder,
llvm::BasicBlock *loopExit) {
linearFinalizationBB = loopExit->splitBasicBlock(
loopExit->getTerminator(), "omp_loop.linear_finalization");
linearExitBB = linearFinalizationBB->splitBasicBlock(
linearFinalizationBB->getTerminator(), "omp_loop.linear_exit");
linearLastIterExitBB = linearFinalizationBB->splitBasicBlock(
linearFinalizationBB->getTerminator(), "omp_loop.linear_lastiter_exit");
}
// Finalize the linear vars
llvm::OpenMPIRBuilder::InsertPointOrErrorTy
finalizeLinearVar(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::Value *lastIter) {
// Emit condition to check whether last logical iteration is being executed
builder.SetInsertPoint(linearFinalizationBB->getTerminator());
llvm::Value *loopLastIterLoad = builder.CreateLoad(
llvm::Type::getInt32Ty(builder.getContext()), lastIter);
llvm::Value *isLast =
builder.CreateCmp(llvm::CmpInst::ICMP_NE, loopLastIterLoad,
llvm::ConstantInt::get(
llvm::Type::getInt32Ty(builder.getContext()), 0));
// Store the linear variable values to original variables.
builder.SetInsertPoint(linearLastIterExitBB->getTerminator());
for (size_t index = 0; index < linearOrigVal.size(); index++) {
llvm::LoadInst *linearVarTemp =
builder.CreateLoad(linearVarTypes[index], linearLoopBodyTemps[index]);
builder.CreateStore(linearVarTemp, linearOrigVal[index]);
}
// Create conditional branch such that the linear variable
// values are stored to original variables only at the
// last logical iteration
builder.SetInsertPoint(linearFinalizationBB->getTerminator());
builder.CreateCondBr(isLast, linearLastIterExitBB, linearExitBB);
linearFinalizationBB->getTerminator()->eraseFromParent();
// Emit barrier
builder.SetInsertPoint(linearExitBB->getTerminator());
return moduleTranslation.getOpenMPBuilder()->createBarrier(
builder.saveIP(), llvm::omp::OMPD_barrier);
}
// Emit stores for linear variables. Useful in case of SIMD
// construct.
void emitStoresForLinearVar(llvm::IRBuilderBase &builder) {
for (size_t index = 0; index < linearOrigVal.size(); index++) {
llvm::LoadInst *linearVarTemp =
builder.CreateLoad(linearVarTypes[index], linearLoopBodyTemps[index]);
builder.CreateStore(linearVarTemp, linearOrigVal[index]);
}
}
// Rewrite all uses of the original variable in `BBName`
// with the linear variable in-place
void rewriteInPlace(llvm::IRBuilderBase &builder, const std::string &BBName,
size_t varIndex) {
llvm::SmallVector<llvm::User *> users;
for (llvm::User *user : linearOrigVal[varIndex]->users())
users.push_back(user);
for (auto *user : users) {
if (auto *userInst = dyn_cast<llvm::Instruction>(user)) {
if (userInst->getParent()->getName().str().find(BBName) !=
std::string::npos)
user->replaceUsesOfWith(linearOrigVal[varIndex],
linearLoopBodyTemps[varIndex]);
}
}
}
};
} // namespace
/// Looks up from the operation from and returns the PrivateClauseOp with
/// name symbolName
static omp::PrivateClauseOp findPrivatizer(Operation *from,
SymbolRefAttr symbolName) {
omp::PrivateClauseOp privatizer =
SymbolTable::lookupNearestSymbolFrom<omp::PrivateClauseOp>(from,
symbolName);
assert(privatizer && "privatizer not found in the symbol table");
return privatizer;
}
/// Check whether translation to LLVM IR for the given operation is currently
/// supported. If not, descriptive diagnostics will be emitted to let users know
/// this is a not-yet-implemented feature.
///
/// \returns success if no unimplemented features are needed to translate the
/// given operation.
static LogicalResult checkImplementationStatus(Operation &op) {
auto todo = [&op](StringRef clauseName) {
return op.emitError() << "not yet implemented: Unhandled clause "
<< clauseName << " in " << op.getName()
<< " operation";
};
auto checkAffinity = [&todo](auto op, LogicalResult &result) {
if (!op.getAffinityVars().empty())
result = todo("affinity");
};
auto checkAllocate = [&todo](auto op, LogicalResult &result) {
if (!op.getAllocateVars().empty() || !op.getAllocatorVars().empty())
result = todo("allocate");
};
auto checkBare = [&todo](auto op, LogicalResult &result) {
if (op.getBare())
result = todo("ompx_bare");
};
auto checkDepend = [&todo](auto op, LogicalResult &result) {
if (!op.getDependVars().empty() || op.getDependKinds())
result = todo("depend");
};
auto checkHint = [](auto op, LogicalResult &) {
if (op.getHint())
op.emitWarning("hint clause discarded");
};
auto checkInReduction = [&todo](auto op, LogicalResult &result) {
if (!op.getInReductionVars().empty() || op.getInReductionByref() ||
op.getInReductionSyms())
result = todo("in_reduction");
};
auto checkNowait = [&todo](auto op, LogicalResult &result) {
if (op.getNowait())
result = todo("nowait");
};
auto checkOrder = [&todo](auto op, LogicalResult &result) {
if (op.getOrder() || op.getOrderMod())
result = todo("order");
};
auto checkParLevelSimd = [&todo](auto op, LogicalResult &result) {
if (op.getParLevelSimd())
result = todo("parallelization-level");
};
auto checkPrivate = [&todo](auto op, LogicalResult &result) {
if (!op.getPrivateVars().empty() || op.getPrivateSyms())
result = todo("privatization");
};
auto checkReduction = [&todo](auto op, LogicalResult &result) {
if (isa<omp::TeamsOp>(op) || isa<omp::TaskloopOp>(op))
if (!op.getReductionVars().empty() || op.getReductionByref() ||
op.getReductionSyms())
result = todo("reduction");
if (op.getReductionMod() &&
op.getReductionMod().value() != omp::ReductionModifier::defaultmod)
result = todo("reduction with modifier");
};
auto checkTaskReduction = [&todo](auto op, LogicalResult &result) {
if (!op.getTaskReductionVars().empty() || op.getTaskReductionByref() ||
op.getTaskReductionSyms())
result = todo("task_reduction");
};
auto checkNumTeams = [&todo](auto op, LogicalResult &result) {
if (op.hasNumTeamsMultiDim())
result = todo("num_teams with multi-dimensional values");
};
auto checkNumThreads = [&todo](auto op, LogicalResult &result) {
if (op.hasNumThreadsMultiDim())
result = todo("num_threads with multi-dimensional values");
};
auto checkThreadLimit = [&todo](auto op, LogicalResult &result) {
if (op.hasThreadLimitMultiDim())
result = todo("thread_limit with multi-dimensional values");
};
LogicalResult result = success();
llvm::TypeSwitch<Operation &>(op)
.Case([&](omp::DistributeOp op) {
checkAllocate(op, result);
checkOrder(op, result);
})
.Case([&](omp::OrderedRegionOp op) { checkParLevelSimd(op, result); })
.Case([&](omp::SectionsOp op) {
checkAllocate(op, result);
checkPrivate(op, result);
checkReduction(op, result);
})
.Case([&](omp::SingleOp op) {
checkAllocate(op, result);
checkPrivate(op, result);
})
.Case([&](omp::TeamsOp op) {
checkAllocate(op, result);
checkPrivate(op, result);
checkNumTeams(op, result);
checkThreadLimit(op, result);
})
.Case([&](omp::TaskOp op) {
checkAffinity(op, result);
checkAllocate(op, result);
checkInReduction(op, result);
})
.Case([&](omp::TaskgroupOp op) {
checkAllocate(op, result);
checkTaskReduction(op, result);
})
.Case([&](omp::TaskwaitOp op) {
checkDepend(op, result);
checkNowait(op, result);
})
.Case([&](omp::TaskloopOp op) {
checkAllocate(op, result);
checkInReduction(op, result);
checkReduction(op, result);
})
.Case([&](omp::WsloopOp op) {
checkAllocate(op, result);
checkOrder(op, result);
checkReduction(op, result);
})
.Case([&](omp::ParallelOp op) {
checkAllocate(op, result);
checkReduction(op, result);
checkNumThreads(op, result);
})
.Case([&](omp::SimdOp op) { checkReduction(op, result); })
.Case<omp::AtomicReadOp, omp::AtomicWriteOp, omp::AtomicUpdateOp,
omp::AtomicCaptureOp>([&](auto op) { checkHint(op, result); })
.Case<omp::TargetEnterDataOp, omp::TargetExitDataOp>(
[&](auto op) { checkDepend(op, result); })
.Case([&](omp::TargetUpdateOp op) { checkDepend(op, result); })
.Case([&](omp::TargetOp op) {
checkAllocate(op, result);
checkBare(op, result);
checkInReduction(op, result);
checkThreadLimit(op, result);
})
.Default([](Operation &) {
// Assume all clauses for an operation can be translated unless they are
// checked above.
});
return result;
}
static LogicalResult handleError(llvm::Error error, Operation &op) {
LogicalResult result = success();
if (error) {
llvm::handleAllErrors(
std::move(error),
[&](const PreviouslyReportedError &) { result = failure(); },
[&](const llvm::ErrorInfoBase &err) {
result = op.emitError(err.message());
});
}
return result;
}
template <typename T>
static LogicalResult handleError(llvm::Expected<T> &result, Operation &op) {
if (!result)
return handleError(result.takeError(), op);
return success();
}
/// Find the insertion point for allocas given the current insertion point for
/// normal operations in the builder.
static llvm::OpenMPIRBuilder::InsertPointTy
findAllocaInsertPoint(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
// If there is an alloca insertion point on stack, i.e. we are in a nested
// operation and a specific point was provided by some surrounding operation,
// use it.
llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint;
WalkResult walkResult = moduleTranslation.stackWalk<OpenMPAllocaStackFrame>(
[&](OpenMPAllocaStackFrame &frame) {
allocaInsertPoint = frame.allocaInsertPoint;
return WalkResult::interrupt();
});
// In cases with multiple levels of outlining, the tree walk might find an
// alloca insertion point that is inside the original function while the
// builder insertion point is inside the outlined function. We need to make
// sure that we do not use it in those cases.
if (walkResult.wasInterrupted() &&
allocaInsertPoint.getBlock()->getParent() ==
builder.GetInsertBlock()->getParent())
return allocaInsertPoint;
// Otherwise, insert to the entry block of the surrounding function.
// If the current IRBuilder InsertPoint is the function's entry, it cannot
// also be used for alloca insertion which would result in insertion order
// confusion. Create a new BasicBlock for the Builder and use the entry block
// for the allocs.
// TODO: Create a dedicated alloca BasicBlock at function creation such that
// we do not need to move the current InertPoint here.
if (builder.GetInsertBlock() ==
&builder.GetInsertBlock()->getParent()->getEntryBlock()) {
assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end() &&
"Assuming end of basic block");
llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(
builder.getContext(), "entry", builder.GetInsertBlock()->getParent(),
builder.GetInsertBlock()->getNextNode());
builder.CreateBr(entryBB);
builder.SetInsertPoint(entryBB);
}
llvm::BasicBlock &funcEntryBlock =
builder.GetInsertBlock()->getParent()->getEntryBlock();
return llvm::OpenMPIRBuilder::InsertPointTy(
&funcEntryBlock, funcEntryBlock.getFirstInsertionPt());
}
/// Find the loop information structure for the loop nest being translated. It
/// will return a `null` value unless called from the translation function for
/// a loop wrapper operation after successfully translating its body.
static llvm::CanonicalLoopInfo *
findCurrentLoopInfo(LLVM::ModuleTranslation &moduleTranslation) {
llvm::CanonicalLoopInfo *loopInfo = nullptr;
moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
[&](OpenMPLoopInfoStackFrame &frame) {
loopInfo = frame.loopInfo;
return WalkResult::interrupt();
});
return loopInfo;
}
/// Converts the given region that appears within an OpenMP dialect operation to
/// LLVM IR, creating a branch from the `sourceBlock` to the entry block of the
/// region, and a branch from any block with an successor-less OpenMP terminator
/// to `continuationBlock`. Populates `continuationBlockPHIs` with the PHI nodes
/// of the continuation block if provided.
static llvm::Expected<llvm::BasicBlock *> convertOmpOpRegions(
Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
SmallVectorImpl<llvm::PHINode *> *continuationBlockPHIs = nullptr) {
bool isLoopWrapper = isa<omp::LoopWrapperInterface>(region.getParentOp());
llvm::BasicBlock *continuationBlock =
splitBB(builder, true, "omp.region.cont");
llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();
llvm::LLVMContext &llvmContext = builder.getContext();
for (Block &bb : region) {
llvm::BasicBlock *llvmBB = llvm::BasicBlock::Create(
llvmContext, blockName, builder.GetInsertBlock()->getParent(),
builder.GetInsertBlock()->getNextNode());
moduleTranslation.mapBlock(&bb, llvmBB);
}
llvm::Instruction *sourceTerminator = sourceBlock->getTerminator();
// Terminators (namely YieldOp) may be forwarding values to the region that
// need to be available in the continuation block. Collect the types of these
// operands in preparation of creating PHI nodes. This is skipped for loop
// wrapper operations, for which we know in advance they have no terminators.
SmallVector<llvm::Type *> continuationBlockPHITypes;
unsigned numYields = 0;
if (!isLoopWrapper) {
bool operandsProcessed = false;
for (Block &bb : region.getBlocks()) {
if (omp::YieldOp yield = dyn_cast<omp::YieldOp>(bb.getTerminator())) {
if (!operandsProcessed) {
for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) {
continuationBlockPHITypes.push_back(
moduleTranslation.convertType(yield->getOperand(i).getType()));
}
operandsProcessed = true;
} else {
assert(continuationBlockPHITypes.size() == yield->getNumOperands() &&
"mismatching number of values yielded from the region");
for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) {
llvm::Type *operandType =
moduleTranslation.convertType(yield->getOperand(i).getType());
(void)operandType;
assert(continuationBlockPHITypes[i] == operandType &&
"values of mismatching types yielded from the region");
}
}
numYields++;
}
}
}
// Insert PHI nodes in the continuation block for any values forwarded by the
// terminators in this region.
if (!continuationBlockPHITypes.empty())
assert(
continuationBlockPHIs &&
"expected continuation block PHIs if converted regions yield values");
if (continuationBlockPHIs) {
llvm::IRBuilderBase::InsertPointGuard guard(builder);
continuationBlockPHIs->reserve(continuationBlockPHITypes.size());
builder.SetInsertPoint(continuationBlock, continuationBlock->begin());
for (llvm::Type *ty : continuationBlockPHITypes)
continuationBlockPHIs->push_back(builder.CreatePHI(ty, numYields));
}
// Convert blocks one by one in topological order to ensure
// defs are converted before uses.
SetVector<Block *> blocks = getBlocksSortedByDominance(region);
for (Block *bb : blocks) {
llvm::BasicBlock *llvmBB = moduleTranslation.lookupBlock(bb);
// Retarget the branch of the entry block to the entry block of the
// converted region (regions are single-entry).
if (bb->isEntryBlock()) {
assert(sourceTerminator->getNumSuccessors() == 1 &&
"provided entry block has multiple successors");
assert(sourceTerminator->getSuccessor(0) == continuationBlock &&
"ContinuationBlock is not the successor of the entry block");
sourceTerminator->setSuccessor(0, llvmBB);
}
llvm::IRBuilderBase::InsertPointGuard guard(builder);
if (failed(
moduleTranslation.convertBlock(*bb, bb->isEntryBlock(), builder)))
return llvm::make_error<PreviouslyReportedError>();
// Create a direct branch here for loop wrappers to prevent their lack of a
// terminator from causing a crash below.
if (isLoopWrapper) {
builder.CreateBr(continuationBlock);
continue;
}
// Special handling for `omp.yield` and `omp.terminator` (we may have more
// than one): they return the control to the parent OpenMP dialect operation
// so replace them with the branch to the continuation block. We handle this
// here to avoid relying inter-function communication through the
// ModuleTranslation class to set up the correct insertion point. This is
// also consistent with MLIR's idiom of handling special region terminators
// in the same code that handles the region-owning operation.
Operation *terminator = bb->getTerminator();
if (isa<omp::TerminatorOp, omp::YieldOp>(terminator)) {
builder.CreateBr(continuationBlock);
for (unsigned i = 0, e = terminator->getNumOperands(); i < e; ++i)
(*continuationBlockPHIs)[i]->addIncoming(
moduleTranslation.lookupValue(terminator->getOperand(i)), llvmBB);
}
}
// After all blocks have been traversed and values mapped, connect the PHI
// nodes to the results of preceding blocks.
LLVM::detail::connectPHINodes(region, moduleTranslation);
// Remove the blocks and values defined in this region from the mapping since
// they are not visible outside of this region. This allows the same region to
// be converted several times, that is cloned, without clashes, and slightly
// speeds up the lookups.
moduleTranslation.forgetMapping(region);
return continuationBlock;
}
/// Convert ProcBindKind from MLIR-generated enum to LLVM enum.
static llvm::omp::ProcBindKind getProcBindKind(omp::ClauseProcBindKind kind) {
switch (kind) {
case omp::ClauseProcBindKind::Close:
return llvm::omp::ProcBindKind::OMP_PROC_BIND_close;
case omp::ClauseProcBindKind::Master:
return llvm::omp::ProcBindKind::OMP_PROC_BIND_master;
case omp::ClauseProcBindKind::Primary:
return llvm::omp::ProcBindKind::OMP_PROC_BIND_primary;
case omp::ClauseProcBindKind::Spread:
return llvm::omp::ProcBindKind::OMP_PROC_BIND_spread;
}
llvm_unreachable("Unknown ClauseProcBindKind kind");
}
/// Converts an OpenMP 'masked' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpMasked(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto maskedOp = cast<omp::MaskedOp>(opInst);
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
if (failed(checkImplementationStatus(opInst)))
return failure();
auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP) {
// MaskedOp has only one region associated with it.
auto ®ion = maskedOp.getRegion();
builder.restoreIP(codeGenIP);
return convertOmpOpRegions(region, "omp.masked.region", builder,
moduleTranslation)
.takeError();
};
// TODO: Perform finalization actions for variables. This has to be
// called for variables which have destructors/finalizers.
auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
llvm::Value *filterVal = nullptr;
if (auto filterVar = maskedOp.getFilteredThreadId()) {
filterVal = moduleTranslation.lookupValue(filterVar);
} else {
llvm::LLVMContext &llvmContext = builder.getContext();
filterVal =
llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext), /*V=*/0);
}
assert(filterVal != nullptr);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createMasked(ompLoc, bodyGenCB,
finiCB, filterVal);
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
/// Converts an OpenMP 'master' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpMaster(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
auto masterOp = cast<omp::MasterOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP) {
// MasterOp has only one region associated with it.
auto ®ion = masterOp.getRegion();
builder.restoreIP(codeGenIP);
return convertOmpOpRegions(region, "omp.master.region", builder,
moduleTranslation)
.takeError();
};
// TODO: Perform finalization actions for variables. This has to be
// called for variables which have destructors/finalizers.
auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createMaster(ompLoc, bodyGenCB,
finiCB);
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
/// Converts an OpenMP 'critical' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpCritical(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
auto criticalOp = cast<omp::CriticalOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP) {
// CriticalOp has only one region associated with it.
auto ®ion = cast<omp::CriticalOp>(opInst).getRegion();
builder.restoreIP(codeGenIP);
return convertOmpOpRegions(region, "omp.critical.region", builder,
moduleTranslation)
.takeError();
};
// TODO: Perform finalization actions for variables. This has to be
// called for variables which have destructors/finalizers.
auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::LLVMContext &llvmContext = moduleTranslation.getLLVMContext();
llvm::Constant *hint = nullptr;
// If it has a name, it probably has a hint too.
if (criticalOp.getNameAttr()) {
// The verifiers in OpenMP Dialect guarentee that all the pointers are
// non-null
auto symbolRef = cast<SymbolRefAttr>(criticalOp.getNameAttr());
auto criticalDeclareOp =
SymbolTable::lookupNearestSymbolFrom<omp::CriticalDeclareOp>(criticalOp,
symbolRef);
hint =
llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext),
static_cast<int>(criticalDeclareOp.getHint()));
}
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createCritical(
ompLoc, bodyGenCB, finiCB, criticalOp.getName().value_or(""), hint);
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
/// A util to collect info needed to convert delayed privatizers from MLIR to
/// LLVM.
struct PrivateVarsInfo {
template <typename OP>
PrivateVarsInfo(OP op)
: blockArgs(
cast<omp::BlockArgOpenMPOpInterface>(*op).getPrivateBlockArgs()) {
mlirVars.reserve(blockArgs.size());
llvmVars.reserve(blockArgs.size());
collectPrivatizationDecls<OP>(op);
for (mlir::Value privateVar : op.getPrivateVars())
mlirVars.push_back(privateVar);
}
MutableArrayRef<BlockArgument> blockArgs;
SmallVector<mlir::Value> mlirVars;
SmallVector<llvm::Value *> llvmVars;
SmallVector<omp::PrivateClauseOp> privatizers;
private:
/// Populates `privatizations` with privatization declarations used for the
/// given op.
template <class OP>
void collectPrivatizationDecls(OP op) {
std::optional<ArrayAttr> attr = op.getPrivateSyms();
if (!attr)
return;
privatizers.reserve(privatizers.size() + attr->size());
for (auto symbolRef : attr->getAsRange<SymbolRefAttr>()) {
privatizers.push_back(findPrivatizer(op, symbolRef));
}
}
};
/// Populates `reductions` with reduction declarations used in the given op.
template <typename T>
static void
collectReductionDecls(T op,
SmallVectorImpl<omp::DeclareReductionOp> &reductions) {
std::optional<ArrayAttr> attr = op.getReductionSyms();
if (!attr)
return;
reductions.reserve(reductions.size() + op.getNumReductionVars());
for (auto symbolRef : attr->getAsRange<SymbolRefAttr>()) {
reductions.push_back(
SymbolTable::lookupNearestSymbolFrom<omp::DeclareReductionOp>(
op, symbolRef));
}
}
/// Translates the blocks contained in the given region and appends them to at
/// the current insertion point of `builder`. The operations of the entry block
/// are appended to the current insertion block. If set, `continuationBlockArgs`
/// is populated with translated values that correspond to the values
/// omp.yield'ed from the region.
static LogicalResult inlineConvertOmpRegions(
Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
SmallVectorImpl<llvm::Value *> *continuationBlockArgs = nullptr) {
if (region.empty())
return success();
// Special case for single-block regions that don't create additional blocks:
// insert operations without creating additional blocks.
if (region.hasOneBlock()) {
llvm::Instruction *potentialTerminator =
builder.GetInsertBlock()->empty() ? nullptr
: &builder.GetInsertBlock()->back();
if (potentialTerminator && potentialTerminator->isTerminator())
potentialTerminator->removeFromParent();
moduleTranslation.mapBlock(®ion.front(), builder.GetInsertBlock());
if (failed(moduleTranslation.convertBlock(
region.front(), /*ignoreArguments=*/true, builder)))
return failure();
// The continuation arguments are simply the translated terminator operands.
if (continuationBlockArgs)
llvm::append_range(
*continuationBlockArgs,
moduleTranslation.lookupValues(region.front().back().getOperands()));
// Drop the mapping that is no longer necessary so that the same region can
// be processed multiple times.
moduleTranslation.forgetMapping(region);
if (potentialTerminator && potentialTerminator->isTerminator()) {
llvm::BasicBlock *block = builder.GetInsertBlock();
if (block->empty()) {
// this can happen for really simple reduction init regions e.g.
// %0 = llvm.mlir.constant(0 : i32) : i32
// omp.yield(%0 : i32)
// because the llvm.mlir.constant (MLIR op) isn't converted into any
// llvm op
potentialTerminator->insertInto(block, block->begin());
} else {
potentialTerminator->insertAfter(&block->back());
}
}
return success();
}
SmallVector<llvm::PHINode *> phis;
llvm::Expected<llvm::BasicBlock *> continuationBlock =
convertOmpOpRegions(region, blockName, builder, moduleTranslation, &phis);
if (failed(handleError(continuationBlock, *region.getParentOp())))
return failure();
if (continuationBlockArgs)
llvm::append_range(*continuationBlockArgs, phis);
builder.SetInsertPoint(*continuationBlock,
(*continuationBlock)->getFirstInsertionPt());
return success();
}
namespace {
/// Owning equivalents of OpenMPIRBuilder::(Atomic)ReductionGen that are used to
/// store lambdas with capture.
using OwningReductionGen =
std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *,
llvm::Value *&)>;
using OwningAtomicReductionGen =
std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
llvm::OpenMPIRBuilder::InsertPointTy, llvm::Type *, llvm::Value *,
llvm::Value *)>;
using OwningDataPtrPtrReductionGen =
std::function<llvm::OpenMPIRBuilder::InsertPointOrErrorTy(
llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *&)>;
} // namespace
/// Create an OpenMPIRBuilder-compatible reduction generator for the given
/// reduction declaration. The generator uses `builder` but ignores its
/// insertion point.
static OwningReductionGen
makeReductionGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
// The lambda is mutable because we need access to non-const methods of decl
// (which aren't actually mutating it), and we must capture decl by-value to
// avoid the dangling reference after the parent function returns.
OwningReductionGen gen =
[&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
llvm::Value *lhs, llvm::Value *rhs,
llvm::Value *&result) mutable
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
moduleTranslation.mapValue(decl.getReductionLhsArg(), lhs);
moduleTranslation.mapValue(decl.getReductionRhsArg(), rhs);
builder.restoreIP(insertPoint);
SmallVector<llvm::Value *> phis;
if (failed(inlineConvertOmpRegions(decl.getReductionRegion(),
"omp.reduction.nonatomic.body", builder,
moduleTranslation, &phis)))
return llvm::createStringError(
"failed to inline `combiner` region of `omp.declare_reduction`");
result = llvm::getSingleElement(phis);
return builder.saveIP();
};
return gen;
}
/// Create an OpenMPIRBuilder-compatible atomic reduction generator for the
/// given reduction declaration. The generator uses `builder` but ignores its
/// insertion point. Returns null if there is no atomic region available in the
/// reduction declaration.
static OwningAtomicReductionGen
makeAtomicReductionGen(omp::DeclareReductionOp decl,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
if (decl.getAtomicReductionRegion().empty())
return OwningAtomicReductionGen();
// The lambda is mutable because we need access to non-const methods of decl
// (which aren't actually mutating it), and we must capture decl by-value to
// avoid the dangling reference after the parent function returns.
OwningAtomicReductionGen atomicGen =
[&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, llvm::Type *,
llvm::Value *lhs, llvm::Value *rhs) mutable
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
moduleTranslation.mapValue(decl.getAtomicReductionLhsArg(), lhs);
moduleTranslation.mapValue(decl.getAtomicReductionRhsArg(), rhs);
builder.restoreIP(insertPoint);
SmallVector<llvm::Value *> phis;
if (failed(inlineConvertOmpRegions(decl.getAtomicReductionRegion(),
"omp.reduction.atomic.body", builder,
moduleTranslation, &phis)))
return llvm::createStringError(
"failed to inline `atomic` region of `omp.declare_reduction`");
assert(phis.empty());
return builder.saveIP();
};
return atomicGen;
}
/// Create an OpenMPIRBuilder-compatible `data_ptr_ptr` reduction generator for
/// the given reduction declaration. The generator uses `builder` but ignores
/// its insertion point. Returns null if there is no `data_ptr_ptr` region
/// available in the reduction declaration.
static OwningDataPtrPtrReductionGen
makeRefDataPtrGen(omp::DeclareReductionOp decl, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation, bool isByRef) {
if (!isByRef)
return OwningDataPtrPtrReductionGen();
OwningDataPtrPtrReductionGen refDataPtrGen =
[&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
llvm::Value *byRefVal, llvm::Value *&result) mutable
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
moduleTranslation.mapValue(decl.getDataPtrPtrRegionArg(), byRefVal);
builder.restoreIP(insertPoint);
SmallVector<llvm::Value *> phis;
if (failed(inlineConvertOmpRegions(decl.getDataPtrPtrRegion(),
"omp.data_ptr_ptr.body", builder,
moduleTranslation, &phis)))
return llvm::createStringError(
"failed to inline `data_ptr_ptr` region of `omp.declare_reduction`");
result = llvm::getSingleElement(phis);
return builder.saveIP();
};
return refDataPtrGen;
}
/// Converts an OpenMP 'ordered' operation into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpOrdered(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto orderedOp = cast<omp::OrderedOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
omp::ClauseDepend dependType = *orderedOp.getDoacrossDependType();
bool isDependSource = dependType == omp::ClauseDepend::dependsource;
unsigned numLoops = *orderedOp.getDoacrossNumLoops();
SmallVector<llvm::Value *> vecValues =
moduleTranslation.lookupValues(orderedOp.getDoacrossDependVars());
size_t indexVecValues = 0;
while (indexVecValues < vecValues.size()) {
SmallVector<llvm::Value *> storeValues;
storeValues.reserve(numLoops);
for (unsigned i = 0; i < numLoops; i++) {
storeValues.push_back(vecValues[indexVecValues]);
indexVecValues++;
}
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createOrderedDepend(
ompLoc, allocaIP, numLoops, storeValues, ".cnt.addr", isDependSource));
}
return success();
}
/// Converts an OpenMP 'ordered_region' operation into LLVM IR using
/// OpenMPIRBuilder.
static LogicalResult
convertOmpOrderedRegion(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
auto orderedRegionOp = cast<omp::OrderedRegionOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP) {
// OrderedOp has only one region associated with it.
auto ®ion = cast<omp::OrderedRegionOp>(opInst).getRegion();
builder.restoreIP(codeGenIP);
return convertOmpOpRegions(region, "omp.ordered.region", builder,
moduleTranslation)
.takeError();
};
// TODO: Perform finalization actions for variables. This has to be
// called for variables which have destructors/finalizers.
auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createOrderedThreadsSimd(
ompLoc, bodyGenCB, finiCB, !orderedRegionOp.getParLevelSimd());
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
namespace {
/// Contains the arguments for an LLVM store operation
struct DeferredStore {
DeferredStore(llvm::Value *value, llvm::Value *address)
: value(value), address(address) {}
llvm::Value *value;
llvm::Value *address;
};
} // namespace
/// Allocate space for privatized reduction variables.
/// `deferredStores` contains information to create store operations which needs
/// to be inserted after all allocas
template <typename T>
static LogicalResult
allocReductionVars(T loop, ArrayRef<BlockArgument> reductionArgs,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
SmallVectorImpl<omp::DeclareReductionOp> &reductionDecls,
SmallVectorImpl<llvm::Value *> &privateReductionVariables,
DenseMap<Value, llvm::Value *> &reductionVariableMap,
SmallVectorImpl<DeferredStore> &deferredStores,
llvm::ArrayRef<bool> isByRefs) {
llvm::IRBuilderBase::InsertPointGuard guard(builder);
builder.SetInsertPoint(allocaIP.getBlock()->getTerminator());
// delay creating stores until after all allocas
deferredStores.reserve(loop.getNumReductionVars());
for (std::size_t i = 0; i < loop.getNumReductionVars(); ++i) {
Region &allocRegion = reductionDecls[i].getAllocRegion();
if (isByRefs[i]) {
if (allocRegion.empty())
continue;
SmallVector<llvm::Value *, 1> phis;
if (failed(inlineConvertOmpRegions(allocRegion, "omp.reduction.alloc",
builder, moduleTranslation, &phis)))
return loop.emitError(
"failed to inline `alloc` region of `omp.declare_reduction`");
assert(phis.size() == 1 && "expected one allocation to be yielded");
builder.SetInsertPoint(allocaIP.getBlock()->getTerminator());
// Allocate reduction variable (which is a pointer to the real reduction
// variable allocated in the inlined region)
llvm::Value *var = builder.CreateAlloca(
moduleTranslation.convertType(reductionDecls[i].getType()));
llvm::Type *ptrTy = builder.getPtrTy();
llvm::Value *castVar =
builder.CreatePointerBitCastOrAddrSpaceCast(var, ptrTy);
llvm::Value *castPhi =
builder.CreatePointerBitCastOrAddrSpaceCast(phis[0], ptrTy);
deferredStores.emplace_back(castPhi, castVar);
privateReductionVariables[i] = castVar;
moduleTranslation.mapValue(reductionArgs[i], castPhi);
reductionVariableMap.try_emplace(loop.getReductionVars()[i], castPhi);
} else {
assert(allocRegion.empty() &&
"allocaction is implicit for by-val reduction");
llvm::Value *var = builder.CreateAlloca(
moduleTranslation.convertType(reductionDecls[i].getType()));
llvm::Type *ptrTy = builder.getPtrTy();
llvm::Value *castVar =
builder.CreatePointerBitCastOrAddrSpaceCast(var, ptrTy);
moduleTranslation.mapValue(reductionArgs[i], castVar);
privateReductionVariables[i] = castVar;
reductionVariableMap.try_emplace(loop.getReductionVars()[i], castVar);
}
}
return success();
}
/// Map input arguments to reduction initialization region
template <typename T>
static void
mapInitializationArgs(T loop, LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase &builder,
SmallVectorImpl<omp::DeclareReductionOp> &reductionDecls,
DenseMap<Value, llvm::Value *> &reductionVariableMap,
unsigned i) {
// map input argument to the initialization region
mlir::omp::DeclareReductionOp &reduction = reductionDecls[i];
Region &initializerRegion = reduction.getInitializerRegion();
Block &entry = initializerRegion.front();
mlir::Value mlirSource = loop.getReductionVars()[i];
llvm::Value *llvmSource = moduleTranslation.lookupValue(mlirSource);
llvm::Value *origVal = llvmSource;
// If a non-pointer value is expected, load the value from the source pointer.
if (!isa<LLVM::LLVMPointerType>(
reduction.getInitializerMoldArg().getType()) &&
isa<LLVM::LLVMPointerType>(mlirSource.getType())) {
origVal =
builder.CreateLoad(moduleTranslation.convertType(
reduction.getInitializerMoldArg().getType()),
llvmSource, "omp_orig");
}
moduleTranslation.mapValue(reduction.getInitializerMoldArg(), origVal);
if (entry.getNumArguments() > 1) {
llvm::Value *allocation =
reductionVariableMap.lookup(loop.getReductionVars()[i]);
moduleTranslation.mapValue(reduction.getInitializerAllocArg(), allocation);
}
}
static void
setInsertPointForPossiblyEmptyBlock(llvm::IRBuilderBase &builder,
llvm::BasicBlock *block = nullptr) {
if (block == nullptr)
block = builder.GetInsertBlock();
if (block->empty() || block->getTerminator() == nullptr)
builder.SetInsertPoint(block);
else
builder.SetInsertPoint(block->getTerminator());
}
/// Inline reductions' `init` regions. This functions assumes that the
/// `builder`'s insertion point is where the user wants the `init` regions to be
/// inlined; i.e. it does not try to find a proper insertion location for the
/// `init` regions. It also leaves the `builder's insertions point in a state
/// where the user can continue the code-gen directly afterwards.
template <typename OP>
static LogicalResult
initReductionVars(OP op, ArrayRef<BlockArgument> reductionArgs,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::BasicBlock *latestAllocaBlock,
SmallVectorImpl<omp::DeclareReductionOp> &reductionDecls,
SmallVectorImpl<llvm::Value *> &privateReductionVariables,
DenseMap<Value, llvm::Value *> &reductionVariableMap,
llvm::ArrayRef<bool> isByRef,
SmallVectorImpl<DeferredStore> &deferredStores) {
if (op.getNumReductionVars() == 0)
return success();
llvm::BasicBlock *initBlock = splitBB(builder, true, "omp.reduction.init");
auto allocaIP = llvm::IRBuilderBase::InsertPoint(
latestAllocaBlock, latestAllocaBlock->getTerminator()->getIterator());
builder.restoreIP(allocaIP);
SmallVector<llvm::Value *> byRefVars(op.getNumReductionVars());
for (unsigned i = 0; i < op.getNumReductionVars(); ++i) {
if (isByRef[i]) {
if (!reductionDecls[i].getAllocRegion().empty())
continue;
// TODO: remove after all users of by-ref are updated to use the alloc
// region: Allocate reduction variable (which is a pointer to the real
// reduciton variable allocated in the inlined region)
byRefVars[i] = builder.CreateAlloca(
moduleTranslation.convertType(reductionDecls[i].getType()));
}
}
setInsertPointForPossiblyEmptyBlock(builder, initBlock);
// store result of the alloc region to the allocated pointer to the real
// reduction variable
for (auto [data, addr] : deferredStores)
builder.CreateStore(data, addr);
// Before the loop, store the initial values of reductions into reduction
// variables. Although this could be done after allocas, we don't want to mess
// up with the alloca insertion point.
for (unsigned i = 0; i < op.getNumReductionVars(); ++i) {
SmallVector<llvm::Value *, 1> phis;
// map block argument to initializer region
mapInitializationArgs(op, moduleTranslation, builder, reductionDecls,
reductionVariableMap, i);
// TODO In some cases (specially on the GPU), the init regions may
// contains stack alloctaions. If the region is inlined in a loop, this is
// problematic. Instead of just inlining the region, handle allocations by
// hoisting fixed length allocations to the function entry and using
// stacksave and restore for variable length ones.
if (failed(inlineConvertOmpRegions(reductionDecls[i].getInitializerRegion(),
"omp.reduction.neutral", builder,
moduleTranslation, &phis)))
return failure();
assert(phis.size() == 1 && "expected one value to be yielded from the "
"reduction neutral element declaration region");
setInsertPointForPossiblyEmptyBlock(builder);
if (isByRef[i]) {
if (!reductionDecls[i].getAllocRegion().empty())
// done in allocReductionVars
continue;
// TODO: this path can be removed once all users of by-ref are updated to
// use an alloc region
// Store the result of the inlined region to the allocated reduction var
// ptr
builder.CreateStore(phis[0], byRefVars[i]);
privateReductionVariables[i] = byRefVars[i];
moduleTranslation.mapValue(reductionArgs[i], phis[0]);
reductionVariableMap.try_emplace(op.getReductionVars()[i], phis[0]);
} else {
// for by-ref case the store is inside of the reduction region
builder.CreateStore(phis[0], privateReductionVariables[i]);
// the rest was handled in allocByValReductionVars
}
// forget the mapping for the initializer region because we might need a
// different mapping if this reduction declaration is re-used for a
// different variable
moduleTranslation.forgetMapping(reductionDecls[i].getInitializerRegion());
}
return success();
}
/// Collect reduction info
template <typename T>
static void collectReductionInfo(
T loop, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
SmallVectorImpl<omp::DeclareReductionOp> &reductionDecls,
SmallVectorImpl<OwningReductionGen> &owningReductionGens,
SmallVectorImpl<OwningAtomicReductionGen> &owningAtomicReductionGens,
SmallVector<OwningDataPtrPtrReductionGen> &owningDataPtrPtrReductionGens,
const ArrayRef<llvm::Value *> privateReductionVariables,
SmallVectorImpl<llvm::OpenMPIRBuilder::ReductionInfo> &reductionInfos,
ArrayRef<bool> isByRef) {
unsigned numReductions = loop.getNumReductionVars();
for (unsigned i = 0; i < numReductions; ++i) {
owningReductionGens.push_back(
makeReductionGen(reductionDecls[i], builder, moduleTranslation));
owningAtomicReductionGens.push_back(
makeAtomicReductionGen(reductionDecls[i], builder, moduleTranslation));
owningDataPtrPtrReductionGens.push_back(makeRefDataPtrGen(
reductionDecls[i], builder, moduleTranslation, isByRef[i]));
}
// Collect the reduction information.
reductionInfos.reserve(numReductions);
for (unsigned i = 0; i < numReductions; ++i) {
llvm::OpenMPIRBuilder::ReductionGenAtomicCBTy atomicGen = nullptr;
if (owningAtomicReductionGens[i])
atomicGen = owningAtomicReductionGens[i];
llvm::Value *variable =
moduleTranslation.lookupValue(loop.getReductionVars()[i]);
mlir::Type allocatedType;
reductionDecls[i].getAllocRegion().walk([&](mlir::Operation *op) {
if (auto alloca = mlir::dyn_cast<LLVM::AllocaOp>(op)) {
allocatedType = alloca.getElemType();
return mlir::WalkResult::interrupt();
}
return mlir::WalkResult::advance();
});
reductionInfos.push_back(
{moduleTranslation.convertType(reductionDecls[i].getType()), variable,
privateReductionVariables[i],
/*EvaluationKind=*/llvm::OpenMPIRBuilder::EvalKind::Scalar,
owningReductionGens[i],
/*ReductionGenClang=*/nullptr, atomicGen,
owningDataPtrPtrReductionGens[i],
allocatedType ? moduleTranslation.convertType(allocatedType) : nullptr,
reductionDecls[i].getByrefElementType()
? moduleTranslation.convertType(
*reductionDecls[i].getByrefElementType())
: nullptr});
}
}
/// handling of DeclareReductionOp's cleanup region
static LogicalResult
inlineOmpRegionCleanup(llvm::SmallVectorImpl<Region *> &cleanupRegions,
llvm::ArrayRef<llvm::Value *> privateVariables,
LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase &builder, StringRef regionName,
bool shouldLoadCleanupRegionArg = true) {
for (auto [i, cleanupRegion] : llvm::enumerate(cleanupRegions)) {
if (cleanupRegion->empty())
continue;
// map the argument to the cleanup region
Block &entry = cleanupRegion->front();
llvm::Instruction *potentialTerminator =
builder.GetInsertBlock()->empty() ? nullptr
: &builder.GetInsertBlock()->back();
if (potentialTerminator && potentialTerminator->isTerminator())
builder.SetInsertPoint(potentialTerminator);
llvm::Value *privateVarValue =
shouldLoadCleanupRegionArg
? builder.CreateLoad(
moduleTranslation.convertType(entry.getArgument(0).getType()),
privateVariables[i])
: privateVariables[i];
moduleTranslation.mapValue(entry.getArgument(0), privateVarValue);
if (failed(inlineConvertOmpRegions(*cleanupRegion, regionName, builder,
moduleTranslation)))
return failure();
// clear block argument mapping in case it needs to be re-created with a
// different source for another use of the same reduction decl
moduleTranslation.forgetMapping(*cleanupRegion);
}
return success();
}
// TODO: not used by ParallelOp
template <class OP>
static LogicalResult createReductionsAndCleanup(
OP op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
SmallVectorImpl<omp::DeclareReductionOp> &reductionDecls,
ArrayRef<llvm::Value *> privateReductionVariables, ArrayRef<bool> isByRef,
bool isNowait = false, bool isTeamsReduction = false) {
// Process the reductions if required.
if (op.getNumReductionVars() == 0)
return success();
SmallVector<OwningReductionGen> owningReductionGens;
SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
SmallVector<OwningDataPtrPtrReductionGen> owningReductionGenRefDataPtrGens;
SmallVector<llvm::OpenMPIRBuilder::ReductionInfo, 2> reductionInfos;
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
// Create the reduction generators. We need to own them here because
// ReductionInfo only accepts references to the generators.
collectReductionInfo(op, builder, moduleTranslation, reductionDecls,
owningReductionGens, owningAtomicReductionGens,
owningReductionGenRefDataPtrGens,
privateReductionVariables, reductionInfos, isByRef);
// The call to createReductions below expects the block to have a
// terminator. Create an unreachable instruction to serve as terminator
// and remove it later.
llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
builder.SetInsertPoint(tempTerminator);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy contInsertPoint =
ompBuilder->createReductions(builder.saveIP(), allocaIP, reductionInfos,
isByRef, isNowait, isTeamsReduction);
if (failed(handleError(contInsertPoint, *op)))
return failure();
if (!contInsertPoint->getBlock())
return op->emitOpError() << "failed to convert reductions";
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createBarrier(*contInsertPoint, llvm::omp::OMPD_for);
if (failed(handleError(afterIP, *op)))
return failure();
tempTerminator->eraseFromParent();
builder.restoreIP(*afterIP);
// after the construct, deallocate private reduction variables
SmallVector<Region *> reductionRegions;
llvm::transform(reductionDecls, std::back_inserter(reductionRegions),
[](omp::DeclareReductionOp reductionDecl) {
return &reductionDecl.getCleanupRegion();
});
return inlineOmpRegionCleanup(reductionRegions, privateReductionVariables,
moduleTranslation, builder,
"omp.reduction.cleanup");
return success();
}
static ArrayRef<bool> getIsByRef(std::optional<ArrayRef<bool>> attr) {
if (!attr)
return {};
return *attr;
}
// TODO: not used by omp.parallel
template <typename OP>
static LogicalResult allocAndInitializeReductionVars(
OP op, ArrayRef<BlockArgument> reductionArgs, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
SmallVectorImpl<omp::DeclareReductionOp> &reductionDecls,
SmallVectorImpl<llvm::Value *> &privateReductionVariables,
DenseMap<Value, llvm::Value *> &reductionVariableMap,
llvm::ArrayRef<bool> isByRef) {
if (op.getNumReductionVars() == 0)
return success();
SmallVector<DeferredStore> deferredStores;
if (failed(allocReductionVars(op, reductionArgs, builder, moduleTranslation,
allocaIP, reductionDecls,
privateReductionVariables, reductionVariableMap,
deferredStores, isByRef)))
return failure();
return initReductionVars(op, reductionArgs, builder, moduleTranslation,
allocaIP.getBlock(), reductionDecls,
privateReductionVariables, reductionVariableMap,
isByRef, deferredStores);
}
/// Return the llvm::Value * corresponding to the `privateVar` that
/// is being privatized. It isn't always as simple as looking up
/// moduleTranslation with privateVar. For instance, in case of
/// an allocatable, the descriptor for the allocatable is privatized.
/// This descriptor is mapped using an MapInfoOp. So, this function
/// will return a pointer to the llvm::Value corresponding to the
/// block argument for the mapped descriptor.
static llvm::Value *
findAssociatedValue(Value privateVar, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
if (mappedPrivateVars == nullptr || !mappedPrivateVars->contains(privateVar))
return moduleTranslation.lookupValue(privateVar);
Value blockArg = (*mappedPrivateVars)[privateVar];
Type privVarType = privateVar.getType();
Type blockArgType = blockArg.getType();
assert(isa<LLVM::LLVMPointerType>(blockArgType) &&
"A block argument corresponding to a mapped var should have "
"!llvm.ptr type");
if (privVarType == blockArgType)
return moduleTranslation.lookupValue(blockArg);
// This typically happens when the privatized type is lowered from
// boxchar<KIND> and gets lowered to !llvm.struct<(ptr, i64)>. That is the
// struct/pair is passed by value. But, mapped values are passed only as
// pointers, so before we privatize, we must load the pointer.
if (!isa<LLVM::LLVMPointerType>(privVarType))
return builder.CreateLoad(moduleTranslation.convertType(privVarType),
moduleTranslation.lookupValue(blockArg));
return moduleTranslation.lookupValue(privateVar);
}
/// Initialize a single (first)private variable. You probably want to use
/// allocateAndInitPrivateVars instead of this.
/// This returns the private variable which has been initialized. This
/// variable should be mapped before constructing the body of the Op.
static llvm::Expected<llvm::Value *>
initPrivateVar(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
omp::PrivateClauseOp &privDecl, llvm::Value *nonPrivateVar,
BlockArgument &blockArg, llvm::Value *llvmPrivateVar,
llvm::BasicBlock *privInitBlock,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
Region &initRegion = privDecl.getInitRegion();
if (initRegion.empty())
return llvmPrivateVar;
assert(nonPrivateVar);
moduleTranslation.mapValue(privDecl.getInitMoldArg(), nonPrivateVar);
moduleTranslation.mapValue(privDecl.getInitPrivateArg(), llvmPrivateVar);
// in-place convert the private initialization region
SmallVector<llvm::Value *, 1> phis;
if (failed(inlineConvertOmpRegions(initRegion, "omp.private.init", builder,
moduleTranslation, &phis)))
return llvm::createStringError(
"failed to inline `init` region of `omp.private`");
assert(phis.size() == 1 && "expected one allocation to be yielded");
// clear init region block argument mapping in case it needs to be
// re-created with a different source for another use of the same
// reduction decl
moduleTranslation.forgetMapping(initRegion);
// Prefer the value yielded from the init region to the allocated private
// variable in case the region is operating on arguments by-value (e.g.
// Fortran character boxes).
return phis[0];
}
/// Version of initPrivateVar which looks up the nonPrivateVar from mlirPrivVar.
static llvm::Expected<llvm::Value *> initPrivateVar(
llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
omp::PrivateClauseOp &privDecl, Value mlirPrivVar, BlockArgument &blockArg,
llvm::Value *llvmPrivateVar, llvm::BasicBlock *privInitBlock,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
return initPrivateVar(
builder, moduleTranslation, privDecl,
findAssociatedValue(mlirPrivVar, builder, moduleTranslation,
mappedPrivateVars),
blockArg, llvmPrivateVar, privInitBlock, mappedPrivateVars);
}
static llvm::Error
initPrivateVars(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
PrivateVarsInfo &privateVarsInfo,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
if (privateVarsInfo.blockArgs.empty())
return llvm::Error::success();
llvm::BasicBlock *privInitBlock = splitBB(builder, true, "omp.private.init");
setInsertPointForPossiblyEmptyBlock(builder, privInitBlock);
for (auto [idx, zip] : llvm::enumerate(llvm::zip_equal(
privateVarsInfo.privatizers, privateVarsInfo.mlirVars,
privateVarsInfo.blockArgs, privateVarsInfo.llvmVars))) {
auto [privDecl, mlirPrivVar, blockArg, llvmPrivateVar] = zip;
llvm::Expected<llvm::Value *> privVarOrErr = initPrivateVar(
builder, moduleTranslation, privDecl, mlirPrivVar, blockArg,
llvmPrivateVar, privInitBlock, mappedPrivateVars);
if (!privVarOrErr)
return privVarOrErr.takeError();
llvmPrivateVar = privVarOrErr.get();
moduleTranslation.mapValue(blockArg, llvmPrivateVar);
setInsertPointForPossiblyEmptyBlock(builder);
}
return llvm::Error::success();
}
/// Allocate and initialize delayed private variables. Returns the basic block
/// which comes after all of these allocations. llvm::Value * for each of these
/// private variables are populated in llvmPrivateVars.
static llvm::Expected<llvm::BasicBlock *>
allocatePrivateVars(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
PrivateVarsInfo &privateVarsInfo,
const llvm::OpenMPIRBuilder::InsertPointTy &allocaIP,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
// Allocate private vars
llvm::Instruction *allocaTerminator = allocaIP.getBlock()->getTerminator();
splitBB(llvm::OpenMPIRBuilder::InsertPointTy(allocaIP.getBlock(),
allocaTerminator->getIterator()),
true, allocaTerminator->getStableDebugLoc(),
"omp.region.after_alloca");
llvm::IRBuilderBase::InsertPointGuard guard(builder);
// Update the allocaTerminator since the alloca block was split above.
allocaTerminator = allocaIP.getBlock()->getTerminator();
builder.SetInsertPoint(allocaTerminator);
// The new terminator is an uncondition branch created by the splitBB above.
assert(allocaTerminator->getNumSuccessors() == 1 &&
"This is an unconditional branch created by splitBB");
llvm::DataLayout dataLayout = builder.GetInsertBlock()->getDataLayout();
llvm::BasicBlock *afterAllocas = allocaTerminator->getSuccessor(0);
unsigned int allocaAS =
moduleTranslation.getLLVMModule()->getDataLayout().getAllocaAddrSpace();
unsigned int defaultAS = moduleTranslation.getLLVMModule()
->getDataLayout()
.getProgramAddressSpace();
for (auto [privDecl, mlirPrivVar, blockArg] :
llvm::zip_equal(privateVarsInfo.privatizers, privateVarsInfo.mlirVars,
privateVarsInfo.blockArgs)) {
llvm::Type *llvmAllocType =
moduleTranslation.convertType(privDecl.getType());
builder.SetInsertPoint(allocaIP.getBlock()->getTerminator());
llvm::Value *llvmPrivateVar = builder.CreateAlloca(
llvmAllocType, /*ArraySize=*/nullptr, "omp.private.alloc");
if (allocaAS != defaultAS)
llvmPrivateVar = builder.CreateAddrSpaceCast(llvmPrivateVar,
builder.getPtrTy(defaultAS));
privateVarsInfo.llvmVars.push_back(llvmPrivateVar);
}
return afterAllocas;
}
/// This can't always be determined statically, but when we can, it is good to
/// avoid generating compiler-added barriers which will deadlock the program.
static bool opIsInSingleThread(mlir::Operation *op) {
for (mlir::Operation *parent = op->getParentOp(); parent != nullptr;
parent = parent->getParentOp()) {
if (mlir::isa<omp::SingleOp, omp::CriticalOp>(parent))
return true;
// e.g.
// omp.single {
// omp.parallel {
// op
// }
// }
if (mlir::isa<omp::ParallelOp>(parent))
return false;
}
return false;
}
static LogicalResult copyFirstPrivateVars(
mlir::Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
SmallVectorImpl<llvm::Value *> &moldVars,
ArrayRef<llvm::Value *> llvmPrivateVars,
SmallVectorImpl<omp::PrivateClauseOp> &privateDecls, bool insertBarrier,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
// Apply copy region for firstprivate.
bool needsFirstprivate =
llvm::any_of(privateDecls, [](omp::PrivateClauseOp &privOp) {
return privOp.getDataSharingType() ==
omp::DataSharingClauseType::FirstPrivate;
});
if (!needsFirstprivate)
return success();
llvm::BasicBlock *copyBlock =
splitBB(builder, /*CreateBranch=*/true, "omp.private.copy");
setInsertPointForPossiblyEmptyBlock(builder, copyBlock);
for (auto [decl, moldVar, llvmVar] :
llvm::zip_equal(privateDecls, moldVars, llvmPrivateVars)) {
if (decl.getDataSharingType() != omp::DataSharingClauseType::FirstPrivate)
continue;
// copyRegion implements `lhs = rhs`
Region ©Region = decl.getCopyRegion();
moduleTranslation.mapValue(decl.getCopyMoldArg(), moldVar);
// map copyRegion lhs arg
moduleTranslation.mapValue(decl.getCopyPrivateArg(), llvmVar);
// in-place convert copy region
if (failed(inlineConvertOmpRegions(copyRegion, "omp.private.copy", builder,
moduleTranslation)))
return decl.emitError("failed to inline `copy` region of `omp.private`");
setInsertPointForPossiblyEmptyBlock(builder);
// ignore unused value yielded from copy region
// clear copy region block argument mapping in case it needs to be
// re-created with different sources for reuse of the same reduction
// decl
moduleTranslation.forgetMapping(copyRegion);
}
if (insertBarrier && !opIsInSingleThread(op)) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::InsertPointOrErrorTy res =
ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
if (failed(handleError(res, *op)))
return failure();
}
return success();
}
static LogicalResult copyFirstPrivateVars(
mlir::Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
SmallVectorImpl<mlir::Value> &mlirPrivateVars,
ArrayRef<llvm::Value *> llvmPrivateVars,
SmallVectorImpl<omp::PrivateClauseOp> &privateDecls, bool insertBarrier,
llvm::DenseMap<Value, Value> *mappedPrivateVars = nullptr) {
llvm::SmallVector<llvm::Value *> moldVars(mlirPrivateVars.size());
llvm::transform(mlirPrivateVars, moldVars.begin(), [&](mlir::Value mlirVar) {
// map copyRegion rhs arg
llvm::Value *moldVar = findAssociatedValue(
mlirVar, builder, moduleTranslation, mappedPrivateVars);
assert(moldVar);
return moldVar;
});
return copyFirstPrivateVars(op, builder, moduleTranslation, moldVars,
llvmPrivateVars, privateDecls, insertBarrier,
mappedPrivateVars);
}
static LogicalResult
cleanupPrivateVars(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation, Location loc,
SmallVectorImpl<llvm::Value *> &llvmPrivateVars,
SmallVectorImpl<omp::PrivateClauseOp> &privateDecls) {
// private variable deallocation
SmallVector<Region *> privateCleanupRegions;
llvm::transform(privateDecls, std::back_inserter(privateCleanupRegions),
[](omp::PrivateClauseOp privatizer) {
return &privatizer.getDeallocRegion();
});
if (failed(inlineOmpRegionCleanup(
privateCleanupRegions, llvmPrivateVars, moduleTranslation, builder,
"omp.private.dealloc", /*shouldLoadCleanupRegionArg=*/false)))
return mlir::emitError(loc, "failed to inline `dealloc` region of an "
"`omp.private` op in");
return success();
}
/// Returns true if the construct contains omp.cancel or omp.cancellation_point
static bool constructIsCancellable(Operation *op) {
// omp.cancel and omp.cancellation_point must be "closely nested" so they will
// be visible and not inside of function calls. This is enforced by the
// verifier.
return op
->walk([](Operation *child) {
if (mlir::isa<omp::CancelOp, omp::CancellationPointOp>(child))
return WalkResult::interrupt();
return WalkResult::advance();
})
.wasInterrupted();
}
static LogicalResult
convertOmpSections(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
using StorableBodyGenCallbackTy =
llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
auto sectionsOp = cast<omp::SectionsOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
llvm::ArrayRef<bool> isByRef = getIsByRef(sectionsOp.getReductionByref());
assert(isByRef.size() == sectionsOp.getNumReductionVars());
SmallVector<omp::DeclareReductionOp> reductionDecls;
collectReductionDecls(sectionsOp, reductionDecls);
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
SmallVector<llvm::Value *> privateReductionVariables(
sectionsOp.getNumReductionVars());
DenseMap<Value, llvm::Value *> reductionVariableMap;
MutableArrayRef<BlockArgument> reductionArgs =
cast<omp::BlockArgOpenMPOpInterface>(opInst).getReductionBlockArgs();
if (failed(allocAndInitializeReductionVars(
sectionsOp, reductionArgs, builder, moduleTranslation, allocaIP,
reductionDecls, privateReductionVariables, reductionVariableMap,
isByRef)))
return failure();
SmallVector<StorableBodyGenCallbackTy> sectionCBs;
for (Operation &op : *sectionsOp.getRegion().begin()) {
auto sectionOp = dyn_cast<omp::SectionOp>(op);
if (!sectionOp) // omp.terminator
continue;
Region ®ion = sectionOp.getRegion();
auto sectionCB = [§ionsOp, ®ion, &builder, &moduleTranslation](
InsertPointTy allocaIP, InsertPointTy codeGenIP) {
builder.restoreIP(codeGenIP);
// map the omp.section reduction block argument to the omp.sections block
// arguments
// TODO: this assumes that the only block arguments are reduction
// variables
assert(region.getNumArguments() ==
sectionsOp.getRegion().getNumArguments());
for (auto [sectionsArg, sectionArg] : llvm::zip_equal(
sectionsOp.getRegion().getArguments(), region.getArguments())) {
llvm::Value *llvmVal = moduleTranslation.lookupValue(sectionsArg);
assert(llvmVal);
moduleTranslation.mapValue(sectionArg, llvmVal);
}
return convertOmpOpRegions(region, "omp.section.region", builder,
moduleTranslation)
.takeError();
};
sectionCBs.push_back(sectionCB);
}
// No sections within omp.sections operation - skip generation. This situation
// is only possible if there is only a terminator operation inside the
// sections operation
if (sectionCBs.empty())
return success();
assert(isa<omp::SectionOp>(*sectionsOp.getRegion().op_begin()));
// TODO: Perform appropriate actions according to the data-sharing
// attribute (shared, private, firstprivate, ...) of variables.
// Currently defaults to shared.
auto privCB = [&](InsertPointTy, InsertPointTy codeGenIP, llvm::Value &,
llvm::Value &vPtr, llvm::Value *&replacementValue)
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
replacementValue = &vPtr;
return codeGenIP;
};
// TODO: Perform finalization actions for variables. This has to be
// called for variables which have destructors/finalizers.
auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
bool isCancellable = constructIsCancellable(sectionsOp);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createSections(
ompLoc, allocaIP, sectionCBs, privCB, finiCB, isCancellable,
sectionsOp.getNowait());
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
// Process the reductions if required.
return createReductionsAndCleanup(
sectionsOp, builder, moduleTranslation, allocaIP, reductionDecls,
privateReductionVariables, isByRef, sectionsOp.getNowait());
}
/// Converts an OpenMP single construct into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpSingle(omp::SingleOp &singleOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
if (failed(checkImplementationStatus(*singleOp)))
return failure();
auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
builder.restoreIP(codegenIP);
return convertOmpOpRegions(singleOp.getRegion(), "omp.single.region",
builder, moduleTranslation)
.takeError();
};
auto finiCB = [&](InsertPointTy codeGenIP) { return llvm::Error::success(); };
// Handle copyprivate
Operation::operand_range cpVars = singleOp.getCopyprivateVars();
std::optional<ArrayAttr> cpFuncs = singleOp.getCopyprivateSyms();
llvm::SmallVector<llvm::Value *> llvmCPVars;
llvm::SmallVector<llvm::Function *> llvmCPFuncs;
for (size_t i = 0, e = cpVars.size(); i < e; ++i) {
llvmCPVars.push_back(moduleTranslation.lookupValue(cpVars[i]));
auto llvmFuncOp = SymbolTable::lookupNearestSymbolFrom<LLVM::LLVMFuncOp>(
singleOp, cast<SymbolRefAttr>((*cpFuncs)[i]));
llvmCPFuncs.push_back(
moduleTranslation.lookupFunction(llvmFuncOp.getName()));
}
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createSingle(
ompLoc, bodyCB, finiCB, singleOp.getNowait(), llvmCPVars,
llvmCPFuncs);
if (failed(handleError(afterIP, *singleOp)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
static bool teamsReductionContainedInDistribute(omp::TeamsOp teamsOp) {
auto iface =
llvm::cast<mlir::omp::BlockArgOpenMPOpInterface>(teamsOp.getOperation());
// Check that all uses of the reduction block arg has the same distribute op
// parent.
llvm::SmallVector<mlir::Operation *> debugUses;
Operation *distOp = nullptr;
for (auto ra : iface.getReductionBlockArgs())
for (auto &use : ra.getUses()) {
auto *useOp = use.getOwner();
// Ignore debug uses.
if (mlir::isa<LLVM::DbgDeclareOp, LLVM::DbgValueOp>(useOp)) {
debugUses.push_back(useOp);
continue;
}
auto currentDistOp = useOp->getParentOfType<omp::DistributeOp>();
// Use is not inside a distribute op - return false
if (!currentDistOp)
return false;
// Multiple distribute operations - return false
Operation *currentOp = currentDistOp.getOperation();
if (distOp && (distOp != currentOp))
return false;
distOp = currentOp;
}
// If we are going to use distribute reduction then remove any debug uses of
// the reduction parameters in teamsOp. Otherwise they will be left without
// any mapped value in moduleTranslation and will eventually error out.
for (auto *use : debugUses)
use->erase();
return true;
}
// Convert an OpenMP Teams construct to LLVM IR using OpenMPIRBuilder
static LogicalResult
convertOmpTeams(omp::TeamsOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
if (failed(checkImplementationStatus(*op)))
return failure();
DenseMap<Value, llvm::Value *> reductionVariableMap;
unsigned numReductionVars = op.getNumReductionVars();
SmallVector<omp::DeclareReductionOp> reductionDecls;
SmallVector<llvm::Value *> privateReductionVariables(numReductionVars);
llvm::ArrayRef<bool> isByRef;
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
// Only do teams reduction if there is no distribute op that captures the
// reduction instead.
bool doTeamsReduction = !teamsReductionContainedInDistribute(op);
if (doTeamsReduction) {
isByRef = getIsByRef(op.getReductionByref());
assert(isByRef.size() == op.getNumReductionVars());
MutableArrayRef<BlockArgument> reductionArgs =
llvm::cast<omp::BlockArgOpenMPOpInterface>(*op).getReductionBlockArgs();
collectReductionDecls(op, reductionDecls);
if (failed(allocAndInitializeReductionVars(
op, reductionArgs, builder, moduleTranslation, allocaIP,
reductionDecls, privateReductionVariables, reductionVariableMap,
isByRef)))
return failure();
}
auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
builder.restoreIP(codegenIP);
return convertOmpOpRegions(op.getRegion(), "omp.teams.region", builder,
moduleTranslation)
.takeError();
};
llvm::Value *numTeamsLower = nullptr;
if (Value numTeamsLowerVar = op.getNumTeamsLower())
numTeamsLower = moduleTranslation.lookupValue(numTeamsLowerVar);
llvm::Value *numTeamsUpper = nullptr;
if (!op.getNumTeamsUpperVars().empty())
numTeamsUpper = moduleTranslation.lookupValue(op.getNumTeams(0));
llvm::Value *threadLimit = nullptr;
if (!op.getThreadLimitVars().empty())
threadLimit = moduleTranslation.lookupValue(op.getThreadLimit(0));
llvm::Value *ifExpr = nullptr;
if (Value ifVar = op.getIfExpr())
ifExpr = moduleTranslation.lookupValue(ifVar);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createTeams(
ompLoc, bodyCB, numTeamsLower, numTeamsUpper, threadLimit, ifExpr);
if (failed(handleError(afterIP, *op)))
return failure();
builder.restoreIP(*afterIP);
if (doTeamsReduction) {
// Process the reductions if required.
return createReductionsAndCleanup(
op, builder, moduleTranslation, allocaIP, reductionDecls,
privateReductionVariables, isByRef,
/*isNoWait*/ false, /*isTeamsReduction*/ true);
}
return success();
}
static void
buildDependData(std::optional<ArrayAttr> dependKinds, OperandRange dependVars,
LLVM::ModuleTranslation &moduleTranslation,
SmallVectorImpl<llvm::OpenMPIRBuilder::DependData> &dds) {
if (dependVars.empty())
return;
for (auto dep : llvm::zip(dependVars, dependKinds->getValue())) {
llvm::omp::RTLDependenceKindTy type;
switch (
cast<mlir::omp::ClauseTaskDependAttr>(std::get<1>(dep)).getValue()) {
case mlir::omp::ClauseTaskDepend::taskdependin:
type = llvm::omp::RTLDependenceKindTy::DepIn;
break;
// The OpenMP runtime requires that the codegen for 'depend' clause for
// 'out' dependency kind must be the same as codegen for 'depend' clause
// with 'inout' dependency.
case mlir::omp::ClauseTaskDepend::taskdependout:
case mlir::omp::ClauseTaskDepend::taskdependinout:
type = llvm::omp::RTLDependenceKindTy::DepInOut;
break;
case mlir::omp::ClauseTaskDepend::taskdependmutexinoutset:
type = llvm::omp::RTLDependenceKindTy::DepMutexInOutSet;
break;
case mlir::omp::ClauseTaskDepend::taskdependinoutset:
type = llvm::omp::RTLDependenceKindTy::DepInOutSet;
break;
};
llvm::Value *depVal = moduleTranslation.lookupValue(std::get<0>(dep));
llvm::OpenMPIRBuilder::DependData dd(type, depVal->getType(), depVal);
dds.emplace_back(dd);
}
}
/// Shared implementation of a callback which adds a termiator for the new block
/// created for the branch taken when an openmp construct is cancelled. The
/// terminator is saved in \p cancelTerminators. This callback is invoked only
/// if there is cancellation inside of the taskgroup body.
/// The terminator will need to be fixed to branch to the correct block to
/// cleanup the construct.
static void
pushCancelFinalizationCB(SmallVectorImpl<llvm::BranchInst *> &cancelTerminators,
llvm::IRBuilderBase &llvmBuilder,
llvm::OpenMPIRBuilder &ompBuilder, mlir::Operation *op,
llvm::omp::Directive cancelDirective) {
auto finiCB = [&](llvm::OpenMPIRBuilder::InsertPointTy ip) -> llvm::Error {
llvm::IRBuilderBase::InsertPointGuard guard(llvmBuilder);
// ip is currently in the block branched to if cancellation occurred.
// We need to create a branch to terminate that block.
llvmBuilder.restoreIP(ip);
// We must still clean up the construct after cancelling it, so we need to
// branch to the block that finalizes the taskgroup.
// That block has not been created yet so use this block as a dummy for now
// and fix this after creating the operation.
cancelTerminators.push_back(llvmBuilder.CreateBr(ip.getBlock()));
return llvm::Error::success();
};
// We have to add the cleanup to the OpenMPIRBuilder before the body gets
// created in case the body contains omp.cancel (which will then expect to be
// able to find this cleanup callback).
ompBuilder.pushFinalizationCB(
{finiCB, cancelDirective, constructIsCancellable(op)});
}
/// If we cancelled the construct, we should branch to the finalization block of
/// that construct. OMPIRBuilder structures the CFG such that the cleanup block
/// is immediately before the continuation block. Now this finalization has
/// been created we can fix the branch.
static void
popCancelFinalizationCB(const ArrayRef<llvm::BranchInst *> cancelTerminators,
llvm::OpenMPIRBuilder &ompBuilder,
const llvm::OpenMPIRBuilder::InsertPointTy &afterIP) {
ompBuilder.popFinalizationCB();
llvm::BasicBlock *constructFini = afterIP.getBlock()->getSinglePredecessor();
for (llvm::BranchInst *cancelBranch : cancelTerminators) {
assert(cancelBranch->getNumSuccessors() == 1 &&
"cancel branch should have one target");
cancelBranch->setSuccessor(0, constructFini);
}
}
namespace {
/// TaskContextStructManager takes care of creating and freeing a structure
/// containing information needed by the task body to execute.
class TaskContextStructManager {
public:
TaskContextStructManager(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
MutableArrayRef<omp::PrivateClauseOp> privateDecls)
: builder{builder}, moduleTranslation{moduleTranslation},
privateDecls{privateDecls} {}
/// Creates a heap allocated struct containing space for each private
/// variable. Invariant: privateVarTypes, privateDecls, and the elements of
/// the structure should all have the same order (although privateDecls which
/// do not read from the mold argument are skipped).
void generateTaskContextStruct();
/// Create GEPs to access each member of the structure representing a private
/// variable, adding them to llvmPrivateVars. Null values are added where
/// private decls were skipped so that the ordering continues to match the
/// private decls.
void createGEPsToPrivateVars();
/// Given the address of the structure, return a GEP for each private variable
/// in the structure. Null values are added where private decls were skipped
/// so that the ordering continues to match the private decls.
/// Must be called after generateTaskContextStruct().
SmallVector<llvm::Value *>
createGEPsToPrivateVars(llvm::Value *altStructPtr) const;
/// De-allocate the task context structure.
void freeStructPtr();
MutableArrayRef<llvm::Value *> getLLVMPrivateVarGEPs() {
return llvmPrivateVarGEPs;
}
llvm::Value *getStructPtr() { return structPtr; }
private:
llvm::IRBuilderBase &builder;
LLVM::ModuleTranslation &moduleTranslation;
MutableArrayRef<omp::PrivateClauseOp> privateDecls;
/// The type of each member of the structure, in order.
SmallVector<llvm::Type *> privateVarTypes;
/// LLVM values for each private variable, or null if that private variable is
/// not included in the task context structure
SmallVector<llvm::Value *> llvmPrivateVarGEPs;
/// A pointer to the structure containing context for this task.
llvm::Value *structPtr = nullptr;
/// The type of the structure
llvm::Type *structTy = nullptr;
};
} // namespace
void TaskContextStructManager::generateTaskContextStruct() {
if (privateDecls.empty())
return;
privateVarTypes.reserve(privateDecls.size());
for (omp::PrivateClauseOp &privOp : privateDecls) {
// Skip private variables which can safely be allocated and initialised
// inside of the task
if (!privOp.readsFromMold())
continue;
Type mlirType = privOp.getType();
privateVarTypes.push_back(moduleTranslation.convertType(mlirType));
}
if (privateVarTypes.empty())
return;
structTy = llvm::StructType::get(moduleTranslation.getLLVMContext(),
privateVarTypes);
llvm::DataLayout dataLayout =
builder.GetInsertBlock()->getModule()->getDataLayout();
llvm::Type *intPtrTy = builder.getIntPtrTy(dataLayout);
llvm::Constant *allocSize = llvm::ConstantExpr::getSizeOf(structTy);
// Heap allocate the structure
structPtr = builder.CreateMalloc(intPtrTy, structTy, allocSize,
/*ArraySize=*/nullptr, /*MallocF=*/nullptr,
"omp.task.context_ptr");
}
SmallVector<llvm::Value *> TaskContextStructManager::createGEPsToPrivateVars(
llvm::Value *altStructPtr) const {
SmallVector<llvm::Value *> ret;
// Create GEPs for each struct member
ret.reserve(privateDecls.size());
llvm::Value *zero = builder.getInt32(0);
unsigned i = 0;
for (auto privDecl : privateDecls) {
if (!privDecl.readsFromMold()) {
// Handle this inside of the task so we don't pass unnessecary vars in
ret.push_back(nullptr);
continue;
}
llvm::Value *iVal = builder.getInt32(i);
llvm::Value *gep = builder.CreateGEP(structTy, altStructPtr, {zero, iVal});
ret.push_back(gep);
i += 1;
}
return ret;
}
void TaskContextStructManager::createGEPsToPrivateVars() {
if (!structPtr)
assert(privateVarTypes.empty());
// Still need to run createGEPsToPrivateVars to populate llvmPrivateVarGEPs
// with null values for skipped private decls
llvmPrivateVarGEPs = createGEPsToPrivateVars(structPtr);
}
void TaskContextStructManager::freeStructPtr() {
if (!structPtr)
return;
llvm::IRBuilderBase::InsertPointGuard guard{builder};
// Ensure we don't put the call to free() after the terminator
builder.SetInsertPoint(builder.GetInsertBlock()->getTerminator());
builder.CreateFree(structPtr);
}
/// Converts an OpenMP task construct into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpTaskOp(omp::TaskOp taskOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
if (failed(checkImplementationStatus(*taskOp)))
return failure();
PrivateVarsInfo privateVarsInfo(taskOp);
TaskContextStructManager taskStructMgr{builder, moduleTranslation,
privateVarsInfo.privatizers};
// Allocate and copy private variables before creating the task. This avoids
// accessing invalid memory if (after this scope ends) the private variables
// are initialized from host variables or if the variables are copied into
// from host variables (firstprivate). The insertion point is just before
// where the code for creating and scheduling the task will go. That puts this
// code outside of the outlined task region, which is what we want because
// this way the initialization and copy regions are executed immediately while
// the host variable data are still live.
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
// Not using splitBB() because that requires the current block to have a
// terminator.
assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end());
llvm::BasicBlock *taskStartBlock = llvm::BasicBlock::Create(
builder.getContext(), "omp.task.start",
/*Parent=*/builder.GetInsertBlock()->getParent());
llvm::Instruction *branchToTaskStartBlock = builder.CreateBr(taskStartBlock);
builder.SetInsertPoint(branchToTaskStartBlock);
// Now do this again to make the initialization and copy blocks
llvm::BasicBlock *copyBlock =
splitBB(builder, /*CreateBranch=*/true, "omp.private.copy");
llvm::BasicBlock *initBlock =
splitBB(builder, /*CreateBranch=*/true, "omp.private.init");
// Now the control flow graph should look like
// starter_block:
// <---- where we started when convertOmpTaskOp was called
// br %omp.private.init
// omp.private.init:
// br %omp.private.copy
// omp.private.copy:
// br %omp.task.start
// omp.task.start:
// <---- where we want the insertion point to be when we call createTask()
// Save the alloca insertion point on ModuleTranslation stack for use in
// nested regions.
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
// Allocate and initialize private variables
builder.SetInsertPoint(initBlock->getTerminator());
// Create task variable structure
taskStructMgr.generateTaskContextStruct();
// GEPs so that we can initialize the variables. Don't use these GEPs inside
// of the body otherwise it will be the GEP not the struct which is fowarded
// to the outlined function. GEPs forwarded in this way are passed in a
// stack-allocated (by OpenMPIRBuilder) structure which is not safe for tasks
// which may not be executed until after the current stack frame goes out of
// scope.
taskStructMgr.createGEPsToPrivateVars();
for (auto [privDecl, mlirPrivVar, blockArg, llvmPrivateVarAlloc] :
llvm::zip_equal(privateVarsInfo.privatizers, privateVarsInfo.mlirVars,
privateVarsInfo.blockArgs,
taskStructMgr.getLLVMPrivateVarGEPs())) {
// To be handled inside the task.
if (!privDecl.readsFromMold())
continue;
assert(llvmPrivateVarAlloc &&
"reads from mold so shouldn't have been skipped");
llvm::Expected<llvm::Value *> privateVarOrErr =
initPrivateVar(builder, moduleTranslation, privDecl, mlirPrivVar,
blockArg, llvmPrivateVarAlloc, initBlock);
if (!privateVarOrErr)
return handleError(privateVarOrErr, *taskOp.getOperation());
setInsertPointForPossiblyEmptyBlock(builder);
// TODO: this is a bit of a hack for Fortran character boxes.
// Character boxes are passed by value into the init region and then the
// initialized character box is yielded by value. Here we need to store the
// yielded value into the private allocation, and load the private
// allocation to match the type expected by region block arguments.
if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
!mlir::isa<LLVM::LLVMPointerType>(blockArg.getType())) {
builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
// Load it so we have the value pointed to by the GEP
llvmPrivateVarAlloc = builder.CreateLoad(privateVarOrErr.get()->getType(),
llvmPrivateVarAlloc);
}
assert(llvmPrivateVarAlloc->getType() ==
moduleTranslation.convertType(blockArg.getType()));
// Mapping blockArg -> llvmPrivateVarAlloc is done inside the body callback
// so that OpenMPIRBuilder doesn't try to pass each GEP address through a
// stack allocated structure.
}
// firstprivate copy region
setInsertPointForPossiblyEmptyBlock(builder, copyBlock);
if (failed(copyFirstPrivateVars(
taskOp, builder, moduleTranslation, privateVarsInfo.mlirVars,
taskStructMgr.getLLVMPrivateVarGEPs(), privateVarsInfo.privatizers,
taskOp.getPrivateNeedsBarrier())))
return llvm::failure();
// Set up for call to createTask()
builder.SetInsertPoint(taskStartBlock);
auto bodyCB = [&](InsertPointTy allocaIP,
InsertPointTy codegenIP) -> llvm::Error {
// Save the alloca insertion point on ModuleTranslation stack for use in
// nested regions.
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
// translate the body of the task:
builder.restoreIP(codegenIP);
llvm::BasicBlock *privInitBlock = nullptr;
privateVarsInfo.llvmVars.resize(privateVarsInfo.blockArgs.size());
for (auto [i, zip] : llvm::enumerate(llvm::zip_equal(
privateVarsInfo.blockArgs, privateVarsInfo.privatizers,
privateVarsInfo.mlirVars))) {
auto [blockArg, privDecl, mlirPrivVar] = zip;
// This is handled before the task executes
if (privDecl.readsFromMold())
continue;
llvm::IRBuilderBase::InsertPointGuard guard(builder);
llvm::Type *llvmAllocType =
moduleTranslation.convertType(privDecl.getType());
builder.SetInsertPoint(allocaIP.getBlock()->getTerminator());
llvm::Value *llvmPrivateVar = builder.CreateAlloca(
llvmAllocType, /*ArraySize=*/nullptr, "omp.private.alloc");
llvm::Expected<llvm::Value *> privateVarOrError =
initPrivateVar(builder, moduleTranslation, privDecl, mlirPrivVar,
blockArg, llvmPrivateVar, privInitBlock);
if (!privateVarOrError)
return privateVarOrError.takeError();
moduleTranslation.mapValue(blockArg, privateVarOrError.get());
privateVarsInfo.llvmVars[i] = privateVarOrError.get();
}
taskStructMgr.createGEPsToPrivateVars();
for (auto [i, llvmPrivVar] :
llvm::enumerate(taskStructMgr.getLLVMPrivateVarGEPs())) {
if (!llvmPrivVar) {
assert(privateVarsInfo.llvmVars[i] &&
"This is added in the loop above");
continue;
}
privateVarsInfo.llvmVars[i] = llvmPrivVar;
}
// Find and map the addresses of each variable within the task context
// structure
for (auto [blockArg, llvmPrivateVar, privateDecl] :
llvm::zip_equal(privateVarsInfo.blockArgs, privateVarsInfo.llvmVars,
privateVarsInfo.privatizers)) {
// This was handled above.
if (!privateDecl.readsFromMold())
continue;
// Fix broken pass-by-value case for Fortran character boxes
if (!mlir::isa<LLVM::LLVMPointerType>(blockArg.getType())) {
llvmPrivateVar = builder.CreateLoad(
moduleTranslation.convertType(blockArg.getType()), llvmPrivateVar);
}
assert(llvmPrivateVar->getType() ==
moduleTranslation.convertType(blockArg.getType()));
moduleTranslation.mapValue(blockArg, llvmPrivateVar);
}
auto continuationBlockOrError = convertOmpOpRegions(
taskOp.getRegion(), "omp.task.region", builder, moduleTranslation);
if (failed(handleError(continuationBlockOrError, *taskOp)))
return llvm::make_error<PreviouslyReportedError>();
builder.SetInsertPoint(continuationBlockOrError.get()->getTerminator());
if (failed(cleanupPrivateVars(builder, moduleTranslation, taskOp.getLoc(),
privateVarsInfo.llvmVars,
privateVarsInfo.privatizers)))
return llvm::make_error<PreviouslyReportedError>();
// Free heap allocated task context structure at the end of the task.
taskStructMgr.freeStructPtr();
return llvm::Error::success();
};
llvm::OpenMPIRBuilder &ompBuilder = *moduleTranslation.getOpenMPBuilder();
SmallVector<llvm::BranchInst *> cancelTerminators;
// The directive to match here is OMPD_taskgroup because it is the taskgroup
// which is canceled. This is handled here because it is the task's cleanup
// block which should be branched to.
pushCancelFinalizationCB(cancelTerminators, builder, ompBuilder, taskOp,
llvm::omp::Directive::OMPD_taskgroup);
SmallVector<llvm::OpenMPIRBuilder::DependData> dds;
buildDependData(taskOp.getDependKinds(), taskOp.getDependVars(),
moduleTranslation, dds);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createTask(
ompLoc, allocaIP, bodyCB, !taskOp.getUntied(),
moduleTranslation.lookupValue(taskOp.getFinal()),
moduleTranslation.lookupValue(taskOp.getIfExpr()), dds,
taskOp.getMergeable(),
moduleTranslation.lookupValue(taskOp.getEventHandle()),
moduleTranslation.lookupValue(taskOp.getPriority()));
if (failed(handleError(afterIP, *taskOp)))
return failure();
// Set the correct branch target for task cancellation
popCancelFinalizationCB(cancelTerminators, ompBuilder, afterIP.get());
builder.restoreIP(*afterIP);
return success();
}
// Converts an OpenMP taskloop construct into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpTaskloopOp(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
auto taskloopOp = cast<omp::TaskloopOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
// It stores the pointer of allocated firstprivate copies,
// which can be used later for freeing the allocated space.
SmallVector<llvm::Value *> llvmFirstPrivateVars;
PrivateVarsInfo privateVarsInfo(taskloopOp);
TaskContextStructManager taskStructMgr{builder, moduleTranslation,
privateVarsInfo.privatizers};
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
assert(builder.GetInsertPoint() == builder.GetInsertBlock()->end());
llvm::BasicBlock *taskloopStartBlock = llvm::BasicBlock::Create(
builder.getContext(), "omp.taskloop.start",
/*Parent=*/builder.GetInsertBlock()->getParent());
llvm::Instruction *branchToTaskloopStartBlock =
builder.CreateBr(taskloopStartBlock);
builder.SetInsertPoint(branchToTaskloopStartBlock);
llvm::BasicBlock *copyBlock =
splitBB(builder, /*CreateBranch=*/true, "omp.private.copy");
llvm::BasicBlock *initBlock =
splitBB(builder, /*CreateBranch=*/true, "omp.private.init");
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
// Allocate and initialize private variables
builder.SetInsertPoint(initBlock->getTerminator());
// TODO: don't allocate if the loop has zero iterations.
taskStructMgr.generateTaskContextStruct();
taskStructMgr.createGEPsToPrivateVars();
llvmFirstPrivateVars.resize(privateVarsInfo.blockArgs.size());
for (auto [i, zip] : llvm::enumerate(llvm::zip_equal(
privateVarsInfo.privatizers, privateVarsInfo.mlirVars,
privateVarsInfo.blockArgs, taskStructMgr.getLLVMPrivateVarGEPs()))) {
auto [privDecl, mlirPrivVar, blockArg, llvmPrivateVarAlloc] = zip;
// To be handled inside the taskloop.
if (!privDecl.readsFromMold())
continue;
assert(llvmPrivateVarAlloc &&
"reads from mold so shouldn't have been skipped");
llvm::Expected<llvm::Value *> privateVarOrErr =
initPrivateVar(builder, moduleTranslation, privDecl, mlirPrivVar,
blockArg, llvmPrivateVarAlloc, initBlock);
if (!privateVarOrErr)
return handleError(privateVarOrErr, *taskloopOp.getOperation());
llvmFirstPrivateVars[i] = privateVarOrErr.get();
llvm::IRBuilderBase::InsertPointGuard guard(builder);
builder.SetInsertPoint(builder.GetInsertBlock()->getTerminator());
if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
!mlir::isa<LLVM::LLVMPointerType>(blockArg.getType())) {
builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
// Load it so we have the value pointed to by the GEP
llvmPrivateVarAlloc = builder.CreateLoad(privateVarOrErr.get()->getType(),
llvmPrivateVarAlloc);
}
assert(llvmPrivateVarAlloc->getType() ==
moduleTranslation.convertType(blockArg.getType()));
}
// firstprivate copy region
setInsertPointForPossiblyEmptyBlock(builder, copyBlock);
if (failed(copyFirstPrivateVars(
taskloopOp, builder, moduleTranslation, privateVarsInfo.mlirVars,
taskStructMgr.getLLVMPrivateVarGEPs(), privateVarsInfo.privatizers,
taskloopOp.getPrivateNeedsBarrier())))
return llvm::failure();
// Set up inserttion point for call to createTaskloop()
builder.SetInsertPoint(taskloopStartBlock);
auto bodyCB = [&](InsertPointTy allocaIP,
InsertPointTy codegenIP) -> llvm::Error {
// Save the alloca insertion point on ModuleTranslation stack for use in
// nested regions.
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
// translate the body of the taskloop:
builder.restoreIP(codegenIP);
llvm::BasicBlock *privInitBlock = nullptr;
privateVarsInfo.llvmVars.resize(privateVarsInfo.blockArgs.size());
for (auto [i, zip] : llvm::enumerate(llvm::zip_equal(
privateVarsInfo.blockArgs, privateVarsInfo.privatizers,
privateVarsInfo.mlirVars))) {
auto [blockArg, privDecl, mlirPrivVar] = zip;
// This is handled before the task executes
if (privDecl.readsFromMold())
continue;
llvm::IRBuilderBase::InsertPointGuard guard(builder);
llvm::Type *llvmAllocType =
moduleTranslation.convertType(privDecl.getType());
builder.SetInsertPoint(allocaIP.getBlock()->getTerminator());
llvm::Value *llvmPrivateVar = builder.CreateAlloca(
llvmAllocType, /*ArraySize=*/nullptr, "omp.private.alloc");
llvm::Expected<llvm::Value *> privateVarOrError =
initPrivateVar(builder, moduleTranslation, privDecl, mlirPrivVar,
blockArg, llvmPrivateVar, privInitBlock);
if (!privateVarOrError)
return privateVarOrError.takeError();
moduleTranslation.mapValue(blockArg, privateVarOrError.get());
privateVarsInfo.llvmVars[i] = privateVarOrError.get();
}
taskStructMgr.createGEPsToPrivateVars();
for (auto [i, llvmPrivVar] :
llvm::enumerate(taskStructMgr.getLLVMPrivateVarGEPs())) {
if (!llvmPrivVar) {
assert(privateVarsInfo.llvmVars[i] &&
"This is added in the loop above");
continue;
}
privateVarsInfo.llvmVars[i] = llvmPrivVar;
}
// Find and map the addresses of each variable within the taskloop context
// structure
for (auto [blockArg, llvmPrivateVar, privateDecl] :
llvm::zip_equal(privateVarsInfo.blockArgs, privateVarsInfo.llvmVars,
privateVarsInfo.privatizers)) {
// This was handled above.
if (!privateDecl.readsFromMold())
continue;
// Fix broken pass-by-value case for Fortran character boxes
if (!mlir::isa<LLVM::LLVMPointerType>(blockArg.getType())) {
llvmPrivateVar = builder.CreateLoad(
moduleTranslation.convertType(blockArg.getType()), llvmPrivateVar);
}
assert(llvmPrivateVar->getType() ==
moduleTranslation.convertType(blockArg.getType()));
moduleTranslation.mapValue(blockArg, llvmPrivateVar);
}
auto continuationBlockOrError =
convertOmpOpRegions(taskloopOp.getRegion(), "omp.taskloop.region",
builder, moduleTranslation);
if (failed(handleError(continuationBlockOrError, opInst)))
return llvm::make_error<PreviouslyReportedError>();
builder.SetInsertPoint(continuationBlockOrError.get()->getTerminator());
// This is freeing the private variables as mapped inside of the task: these
// will be per-task private copies possibly after task duplication. This is
// handled transparently by how these are passed to the structure passed
// into the outlined function. When the task is duplicated, that structure
// is duplicated too.
if (failed(cleanupPrivateVars(builder, moduleTranslation,
taskloopOp.getLoc(), privateVarsInfo.llvmVars,
privateVarsInfo.privatizers)))
return llvm::make_error<PreviouslyReportedError>();
// Similarly, the task context structure freed inside the task is the
// per-task copy after task duplication.
taskStructMgr.freeStructPtr();
return llvm::Error::success();
};
// Taskloop divides into an appropriate number of tasks by repeatedly
// duplicating the original task. Each time this is done, the task context
// structure must be duplicated too.
auto taskDupCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
llvm::Value *destPtr, llvm::Value *srcPtr)
-> llvm::Expected<llvm::IRBuilderBase::InsertPoint> {
llvm::IRBuilderBase::InsertPointGuard guard(builder);
builder.restoreIP(codegenIP);
llvm::Type *ptrTy =
builder.getPtrTy(srcPtr->getType()->getPointerAddressSpace());
llvm::Value *src =
builder.CreateLoad(ptrTy, srcPtr, "omp.taskloop.context.src");
TaskContextStructManager &srcStructMgr = taskStructMgr;
TaskContextStructManager destStructMgr(builder, moduleTranslation,
privateVarsInfo.privatizers);
destStructMgr.generateTaskContextStruct();
llvm::Value *dest = destStructMgr.getStructPtr();
dest->setName("omp.taskloop.context.dest");
builder.CreateStore(dest, destPtr);
llvm::SmallVector<llvm::Value *> srcGEPs =
srcStructMgr.createGEPsToPrivateVars(src);
llvm::SmallVector<llvm::Value *> destGEPs =
destStructMgr.createGEPsToPrivateVars(dest);
// Inline init regions.
for (auto [privDecl, mold, blockArg, llvmPrivateVarAlloc] :
llvm::zip_equal(privateVarsInfo.privatizers, srcGEPs,
privateVarsInfo.blockArgs, destGEPs)) {
// To be handled inside task body.
if (!privDecl.readsFromMold())
continue;
assert(llvmPrivateVarAlloc &&
"reads from mold so shouldn't have been skipped");
llvm::Expected<llvm::Value *> privateVarOrErr =
initPrivateVar(builder, moduleTranslation, privDecl, mold, blockArg,
llvmPrivateVarAlloc, builder.GetInsertBlock());
if (!privateVarOrErr)
return privateVarOrErr.takeError();
setInsertPointForPossiblyEmptyBlock(builder);
// TODO: this is a bit of a hack for Fortran character boxes.
// Character boxes are passed by value into the init region and then the
// initialized character box is yielded by value. Here we need to store
// the yielded value into the private allocation, and load the private
// allocation to match the type expected by region block arguments.
if ((privateVarOrErr.get() != llvmPrivateVarAlloc) &&
!mlir::isa<LLVM::LLVMPointerType>(blockArg.getType())) {
builder.CreateStore(privateVarOrErr.get(), llvmPrivateVarAlloc);
// Load it so we have the value pointed to by the GEP
llvmPrivateVarAlloc = builder.CreateLoad(
privateVarOrErr.get()->getType(), llvmPrivateVarAlloc);
}
assert(llvmPrivateVarAlloc->getType() ==
moduleTranslation.convertType(blockArg.getType()));
// Mapping blockArg -> llvmPrivateVarAlloc is done inside the body
// callback so that OpenMPIRBuilder doesn't try to pass each GEP address
// through a stack allocated structure.
}
if (failed(copyFirstPrivateVars(
&opInst, builder, moduleTranslation, srcGEPs, destGEPs,
privateVarsInfo.privatizers, taskloopOp.getPrivateNeedsBarrier())))
return llvm::make_error<PreviouslyReportedError>();
return builder.saveIP();
};
auto loopOp = cast<omp::LoopNestOp>(taskloopOp.getWrappedLoop());
auto loopInfo = [&]() -> llvm::Expected<llvm::CanonicalLoopInfo *> {
llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
return loopInfo;
};
Operation::operand_range lowerBounds = loopOp.getLoopLowerBounds();
Operation::operand_range upperBounds = loopOp.getLoopUpperBounds();
Operation::operand_range steps = loopOp.getLoopSteps();
llvm::Type *boundType =
moduleTranslation.lookupValue(lowerBounds[0])->getType();
llvm::Value *lbVal = nullptr;
llvm::Value *ubVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
llvm::Value *stepVal = nullptr;
if (loopOp.getCollapseNumLoops() > 1) {
// In cases where Collapse is used with Taskloop, the upper bound of the
// iteration space needs to be recalculated to cater for the collapsed loop.
// The Collapsed Loop UpperBound is the product of all collapsed
// loop's tripcount.
// The LowerBound for collapsed loops is always 1. When the loops are
// collapsed, it will reset the bounds and introduce processing to ensure
// the index's are presented as expected. As this happens after creating
// Taskloop, these bounds need predicting. Example:
// !$omp taskloop collapse(2)
// do i = 1, 10
// do j = 1, 5
// ..
// end do
// end do
// This loop above has a total of 50 iterations, so the lb will be 1, and
// the ub will be 50. collapseLoops in OMPIRBuilder then handles ensuring
// that i and j are properly presented when used in the loop.
for (uint64_t i = 0; i < loopOp.getCollapseNumLoops(); i++) {
llvm::Value *loopLb = moduleTranslation.lookupValue(lowerBounds[i]);
llvm::Value *loopUb = moduleTranslation.lookupValue(upperBounds[i]);
llvm::Value *loopStep = moduleTranslation.lookupValue(steps[i]);
// In some cases, such as where the ub is less than the lb so the loop
// steps down, the calculation for the loopTripCount is swapped. To ensure
// the correct value is found, calculate both UB - LB and LB - UB then
// select which value to use depending on how the loop has been
// configured.
llvm::Value *loopLbMinusOne = builder.CreateSub(
loopLb, builder.getIntN(boundType->getIntegerBitWidth(), 1));
llvm::Value *loopUbMinusOne = builder.CreateSub(
loopUb, builder.getIntN(boundType->getIntegerBitWidth(), 1));
llvm::Value *boundsCmp = builder.CreateICmpSLT(loopLb, loopUb);
llvm::Value *ubMinusLb = builder.CreateSub(loopUb, loopLbMinusOne);
llvm::Value *lbMinusUb = builder.CreateSub(loopLb, loopUbMinusOne);
llvm::Value *loopTripCount =
builder.CreateSelect(boundsCmp, ubMinusLb, lbMinusUb);
loopTripCount = builder.CreateBinaryIntrinsic(
llvm::Intrinsic::abs, loopTripCount, builder.getFalse());
// For loops that have a step value not equal to 1, we need to adjust the
// trip count to ensure the correct number of iterations for the loop is
// captured.
llvm::Value *loopTripCountDivStep =
builder.CreateSDiv(loopTripCount, loopStep);
loopTripCountDivStep = builder.CreateBinaryIntrinsic(
llvm::Intrinsic::abs, loopTripCountDivStep, builder.getFalse());
llvm::Value *loopTripCountRem =
builder.CreateSRem(loopTripCount, loopStep);
loopTripCountRem = builder.CreateBinaryIntrinsic(
llvm::Intrinsic::abs, loopTripCountRem, builder.getFalse());
llvm::Value *needsRoundUp = builder.CreateICmpNE(
loopTripCountRem,
builder.getIntN(loopTripCountRem->getType()->getIntegerBitWidth(),
0));
loopTripCount =
builder.CreateAdd(loopTripCountDivStep,
builder.CreateZExtOrTrunc(
needsRoundUp, loopTripCountDivStep->getType()));
ubVal = builder.CreateMul(ubVal, loopTripCount);
}
lbVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
stepVal = builder.getIntN(boundType->getIntegerBitWidth(), 1);
} else {
lbVal = moduleTranslation.lookupValue(lowerBounds[0]);
ubVal = moduleTranslation.lookupValue(upperBounds[0]);
stepVal = moduleTranslation.lookupValue(steps[0]);
}
assert(lbVal != nullptr && "Expected value for lbVal");
assert(ubVal != nullptr && "Expected value for ubVal");
assert(stepVal != nullptr && "Expected value for stepVal");
llvm::Value *ifCond = nullptr;
llvm::Value *grainsize = nullptr;
int sched = 0; // default
mlir::Value grainsizeVal = taskloopOp.getGrainsize();
mlir::Value numTasksVal = taskloopOp.getNumTasks();
if (Value ifVar = taskloopOp.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
if (grainsizeVal) {
grainsize = moduleTranslation.lookupValue(grainsizeVal);
sched = 1; // grainsize
} else if (numTasksVal) {
grainsize = moduleTranslation.lookupValue(numTasksVal);
sched = 2; // num_tasks
}
llvm::OpenMPIRBuilder::TaskDupCallbackTy taskDupOrNull = nullptr;
if (taskStructMgr.getStructPtr())
taskDupOrNull = taskDupCB;
llvm::OpenMPIRBuilder &ompBuilder = *moduleTranslation.getOpenMPBuilder();
SmallVector<llvm::BranchInst *> cancelTerminators;
// The directive to match here is OMPD_taskgroup because it is the
// taskgroup which is canceled. This is handled here because it is the
// task's cleanup block which should be branched to. It doesn't depend upon
// nogroup because even in that case the taskloop might still be inside an
// explicit taskgroup.
pushCancelFinalizationCB(cancelTerminators, builder, ompBuilder, taskloopOp,
llvm::omp::Directive::OMPD_taskgroup);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createTaskloop(
ompLoc, allocaIP, bodyCB, loopInfo, lbVal, ubVal, stepVal,
taskloopOp.getUntied(), ifCond, grainsize, taskloopOp.getNogroup(),
sched, moduleTranslation.lookupValue(taskloopOp.getFinal()),
taskloopOp.getMergeable(),
moduleTranslation.lookupValue(taskloopOp.getPriority()),
loopOp.getCollapseNumLoops(), taskDupOrNull,
taskStructMgr.getStructPtr());
if (failed(handleError(afterIP, opInst)))
return failure();
popCancelFinalizationCB(cancelTerminators, ompBuilder, afterIP.get());
builder.restoreIP(*afterIP);
return success();
}
/// Converts an OpenMP taskgroup construct into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpTaskgroupOp(omp::TaskgroupOp tgOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
if (failed(checkImplementationStatus(*tgOp)))
return failure();
auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP) {
builder.restoreIP(codegenIP);
return convertOmpOpRegions(tgOp.getRegion(), "omp.taskgroup.region",
builder, moduleTranslation)
.takeError();
};
InsertPointTy allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createTaskgroup(ompLoc, allocaIP,
bodyCB);
if (failed(handleError(afterIP, *tgOp)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
static LogicalResult
convertOmpTaskwaitOp(omp::TaskwaitOp twOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
if (failed(checkImplementationStatus(*twOp)))
return failure();
moduleTranslation.getOpenMPBuilder()->createTaskwait(builder.saveIP());
return success();
}
/// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpWsloop(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
auto wsloopOp = cast<omp::WsloopOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
auto loopOp = cast<omp::LoopNestOp>(wsloopOp.getWrappedLoop());
llvm::ArrayRef<bool> isByRef = getIsByRef(wsloopOp.getReductionByref());
assert(isByRef.size() == wsloopOp.getNumReductionVars());
// Static is the default.
auto schedule =
wsloopOp.getScheduleKind().value_or(omp::ClauseScheduleKind::Static);
// Find the loop configuration.
llvm::Value *step = moduleTranslation.lookupValue(loopOp.getLoopSteps()[0]);
llvm::Type *ivType = step->getType();
llvm::Value *chunk = nullptr;
if (wsloopOp.getScheduleChunk()) {
llvm::Value *chunkVar =
moduleTranslation.lookupValue(wsloopOp.getScheduleChunk());
chunk = builder.CreateSExtOrTrunc(chunkVar, ivType);
}
omp::DistributeOp distributeOp = nullptr;
llvm::Value *distScheduleChunk = nullptr;
bool hasDistSchedule = false;
if (llvm::isa_and_present<omp::DistributeOp>(opInst.getParentOp())) {
distributeOp = cast<omp::DistributeOp>(opInst.getParentOp());
hasDistSchedule = distributeOp.getDistScheduleStatic();
if (distributeOp.getDistScheduleChunkSize()) {
llvm::Value *chunkVar = moduleTranslation.lookupValue(
distributeOp.getDistScheduleChunkSize());
distScheduleChunk = builder.CreateSExtOrTrunc(chunkVar, ivType);
}
}
PrivateVarsInfo privateVarsInfo(wsloopOp);
SmallVector<omp::DeclareReductionOp> reductionDecls;
collectReductionDecls(wsloopOp, reductionDecls);
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
SmallVector<llvm::Value *> privateReductionVariables(
wsloopOp.getNumReductionVars());
llvm::Expected<llvm::BasicBlock *> afterAllocas = allocatePrivateVars(
builder, moduleTranslation, privateVarsInfo, allocaIP);
if (handleError(afterAllocas, opInst).failed())
return failure();
DenseMap<Value, llvm::Value *> reductionVariableMap;
MutableArrayRef<BlockArgument> reductionArgs =
cast<omp::BlockArgOpenMPOpInterface>(opInst).getReductionBlockArgs();
SmallVector<DeferredStore> deferredStores;
if (failed(allocReductionVars(wsloopOp, reductionArgs, builder,
moduleTranslation, allocaIP, reductionDecls,
privateReductionVariables, reductionVariableMap,
deferredStores, isByRef)))
return failure();
if (handleError(initPrivateVars(builder, moduleTranslation, privateVarsInfo),
opInst)
.failed())
return failure();
if (failed(copyFirstPrivateVars(
wsloopOp, builder, moduleTranslation, privateVarsInfo.mlirVars,
privateVarsInfo.llvmVars, privateVarsInfo.privatizers,
wsloopOp.getPrivateNeedsBarrier())))
return failure();
assert(afterAllocas.get()->getSinglePredecessor());
if (failed(initReductionVars(wsloopOp, reductionArgs, builder,
moduleTranslation,
afterAllocas.get()->getSinglePredecessor(),
reductionDecls, privateReductionVariables,
reductionVariableMap, isByRef, deferredStores)))
return failure();
// TODO: Handle doacross loops when the ordered clause has a parameter.
bool isOrdered = wsloopOp.getOrdered().has_value();
std::optional<omp::ScheduleModifier> scheduleMod = wsloopOp.getScheduleMod();
bool isSimd = wsloopOp.getScheduleSimd();
bool loopNeedsBarrier = !wsloopOp.getNowait();
// The only legal way for the direct parent to be omp.distribute is that this
// represents 'distribute parallel do'. Otherwise, this is a regular
// worksharing loop.
llvm::omp::WorksharingLoopType workshareLoopType =
llvm::isa_and_present<omp::DistributeOp>(opInst.getParentOp())
? llvm::omp::WorksharingLoopType::DistributeForStaticLoop
: llvm::omp::WorksharingLoopType::ForStaticLoop;
SmallVector<llvm::BranchInst *> cancelTerminators;
pushCancelFinalizationCB(cancelTerminators, builder, *ompBuilder, wsloopOp,
llvm::omp::Directive::OMPD_for);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
// Initialize linear variables and linear step
LinearClauseProcessor linearClauseProcessor;
if (!wsloopOp.getLinearVars().empty()) {
auto linearVarTypes = wsloopOp.getLinearVarTypes().value();
for (mlir::Attribute linearVarType : linearVarTypes)
linearClauseProcessor.registerType(moduleTranslation, linearVarType);
for (auto [idx, linearVar] : llvm::enumerate(wsloopOp.getLinearVars()))
linearClauseProcessor.createLinearVar(
builder, moduleTranslation, moduleTranslation.lookupValue(linearVar),
idx);
for (mlir::Value linearStep : wsloopOp.getLinearStepVars())
linearClauseProcessor.initLinearStep(moduleTranslation, linearStep);
}
llvm::Expected<llvm::BasicBlock *> regionBlock = convertOmpOpRegions(
wsloopOp.getRegion(), "omp.wsloop.region", builder, moduleTranslation);
if (failed(handleError(regionBlock, opInst)))
return failure();
llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
// Emit Initialization and Update IR for linear variables
if (!wsloopOp.getLinearVars().empty()) {
linearClauseProcessor.initLinearVar(builder, moduleTranslation,
loopInfo->getPreheader());
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
moduleTranslation.getOpenMPBuilder()->createBarrier(
builder.saveIP(), llvm::omp::OMPD_barrier);
if (failed(handleError(afterBarrierIP, *loopOp)))
return failure();
builder.restoreIP(*afterBarrierIP);
linearClauseProcessor.updateLinearVar(builder, loopInfo->getBody(),
loopInfo->getIndVar());
linearClauseProcessor.splitLinearFiniBB(builder, loopInfo->getExit());
}
builder.SetInsertPoint(*regionBlock, (*regionBlock)->begin());
// Check if we can generate no-loop kernel
bool noLoopMode = false;
omp::TargetOp targetOp = wsloopOp->getParentOfType<mlir::omp::TargetOp>();
if (targetOp) {
Operation *targetCapturedOp = targetOp.getInnermostCapturedOmpOp();
// We need this check because, without it, noLoopMode would be set to true
// for every omp.wsloop nested inside a no-loop SPMD target region, even if
// that loop is not the top-level SPMD one.
if (loopOp == targetCapturedOp) {
omp::TargetRegionFlags kernelFlags =
targetOp.getKernelExecFlags(targetCapturedOp);
if (omp::bitEnumContainsAll(kernelFlags,
omp::TargetRegionFlags::spmd |
omp::TargetRegionFlags::no_loop) &&
!omp::bitEnumContainsAny(kernelFlags,
omp::TargetRegionFlags::generic))
noLoopMode = true;
}
}
llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
ompBuilder->applyWorkshareLoop(
ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
convertToScheduleKind(schedule), chunk, isSimd,
scheduleMod == omp::ScheduleModifier::monotonic,
scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
workshareLoopType, noLoopMode, hasDistSchedule, distScheduleChunk);
if (failed(handleError(wsloopIP, opInst)))
return failure();
// Emit finalization and in-place rewrites for linear vars.
if (!wsloopOp.getLinearVars().empty()) {
llvm::OpenMPIRBuilder::InsertPointTy oldIP = builder.saveIP();
assert(loopInfo->getLastIter() &&
"`lastiter` in CanonicalLoopInfo is nullptr");
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterBarrierIP =
linearClauseProcessor.finalizeLinearVar(builder, moduleTranslation,
loopInfo->getLastIter());
if (failed(handleError(afterBarrierIP, *loopOp)))
return failure();
for (size_t index = 0; index < wsloopOp.getLinearVars().size(); index++)
linearClauseProcessor.rewriteInPlace(builder, "omp.loop_nest.region",
index);
builder.restoreIP(oldIP);
}
// Set the correct branch target for task cancellation
popCancelFinalizationCB(cancelTerminators, *ompBuilder, wsloopIP.get());
// Process the reductions if required.
if (failed(createReductionsAndCleanup(
wsloopOp, builder, moduleTranslation, allocaIP, reductionDecls,
privateReductionVariables, isByRef, wsloopOp.getNowait(),
/*isTeamsReduction=*/false)))
return failure();
return cleanupPrivateVars(builder, moduleTranslation, wsloopOp.getLoc(),
privateVarsInfo.llvmVars,
privateVarsInfo.privatizers);
}
/// Converts the OpenMP parallel operation to LLVM IR.
static LogicalResult
convertOmpParallel(omp::ParallelOp opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
ArrayRef<bool> isByRef = getIsByRef(opInst.getReductionByref());
assert(isByRef.size() == opInst.getNumReductionVars());
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
bool isCancellable = constructIsCancellable(opInst);
if (failed(checkImplementationStatus(*opInst)))
return failure();
PrivateVarsInfo privateVarsInfo(opInst);
// Collect reduction declarations
SmallVector<omp::DeclareReductionOp> reductionDecls;
collectReductionDecls(opInst, reductionDecls);
SmallVector<llvm::Value *> privateReductionVariables(
opInst.getNumReductionVars());
SmallVector<DeferredStore> deferredStores;
auto bodyGenCB = [&](InsertPointTy allocaIP,
InsertPointTy codeGenIP) -> llvm::Error {
llvm::Expected<llvm::BasicBlock *> afterAllocas = allocatePrivateVars(
builder, moduleTranslation, privateVarsInfo, allocaIP);
if (handleError(afterAllocas, *opInst).failed())
return llvm::make_error<PreviouslyReportedError>();
// Allocate reduction vars
DenseMap<Value, llvm::Value *> reductionVariableMap;
MutableArrayRef<BlockArgument> reductionArgs =
cast<omp::BlockArgOpenMPOpInterface>(*opInst).getReductionBlockArgs();
allocaIP =
InsertPointTy(allocaIP.getBlock(),
allocaIP.getBlock()->getTerminator()->getIterator());
if (failed(allocReductionVars(
opInst, reductionArgs, builder, moduleTranslation, allocaIP,
reductionDecls, privateReductionVariables, reductionVariableMap,
deferredStores, isByRef)))
return llvm::make_error<PreviouslyReportedError>();
assert(afterAllocas.get()->getSinglePredecessor());
builder.restoreIP(codeGenIP);
if (handleError(
initPrivateVars(builder, moduleTranslation, privateVarsInfo),
*opInst)
.failed())
return llvm::make_error<PreviouslyReportedError>();
if (failed(copyFirstPrivateVars(
opInst, builder, moduleTranslation, privateVarsInfo.mlirVars,
privateVarsInfo.llvmVars, privateVarsInfo.privatizers,
opInst.getPrivateNeedsBarrier())))
return llvm::make_error<PreviouslyReportedError>();
if (failed(
initReductionVars(opInst, reductionArgs, builder, moduleTranslation,
afterAllocas.get()->getSinglePredecessor(),
reductionDecls, privateReductionVariables,
reductionVariableMap, isByRef, deferredStores)))
return llvm::make_error<PreviouslyReportedError>();
// Save the alloca insertion point on ModuleTranslation stack for use in
// nested regions.
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
// ParallelOp has only one region associated with it.
llvm::Expected<llvm::BasicBlock *> regionBlock = convertOmpOpRegions(
opInst.getRegion(), "omp.par.region", builder, moduleTranslation);
if (!regionBlock)
return regionBlock.takeError();
// Process the reductions if required.
if (opInst.getNumReductionVars() > 0) {
// Collect reduction info
SmallVector<OwningReductionGen> owningReductionGens;
SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
SmallVector<OwningDataPtrPtrReductionGen>
owningReductionGenRefDataPtrGens;
SmallVector<llvm::OpenMPIRBuilder::ReductionInfo, 2> reductionInfos;
collectReductionInfo(opInst, builder, moduleTranslation, reductionDecls,
owningReductionGens, owningAtomicReductionGens,
owningReductionGenRefDataPtrGens,
privateReductionVariables, reductionInfos, isByRef);
// Move to region cont block
builder.SetInsertPoint((*regionBlock)->getTerminator());
// Generate reductions from info
llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
builder.SetInsertPoint(tempTerminator);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy contInsertPoint =
ompBuilder->createReductions(
builder.saveIP(), allocaIP, reductionInfos, isByRef,
/*IsNoWait=*/false, /*IsTeamsReduction=*/false);
if (!contInsertPoint)
return contInsertPoint.takeError();
if (!contInsertPoint->getBlock())
return llvm::make_error<PreviouslyReportedError>();
tempTerminator->eraseFromParent();
builder.restoreIP(*contInsertPoint);
}
return llvm::Error::success();
};
auto privCB = [](InsertPointTy allocaIP, InsertPointTy codeGenIP,
llvm::Value &, llvm::Value &val, llvm::Value *&replVal) {
// tell OpenMPIRBuilder not to do anything. We handled Privatisation in
// bodyGenCB.
replVal = &val;
return codeGenIP;
};
// TODO: Perform finalization actions for variables. This has to be
// called for variables which have destructors/finalizers.
auto finiCB = [&](InsertPointTy codeGenIP) -> llvm::Error {
InsertPointTy oldIP = builder.saveIP();
builder.restoreIP(codeGenIP);
// if the reduction has a cleanup region, inline it here to finalize the
// reduction variables
SmallVector<Region *> reductionCleanupRegions;
llvm::transform(reductionDecls, std::back_inserter(reductionCleanupRegions),
[](omp::DeclareReductionOp reductionDecl) {
return &reductionDecl.getCleanupRegion();
});
if (failed(inlineOmpRegionCleanup(
reductionCleanupRegions, privateReductionVariables,
moduleTranslation, builder, "omp.reduction.cleanup")))
return llvm::createStringError(
"failed to inline `cleanup` region of `omp.declare_reduction`");
if (failed(cleanupPrivateVars(builder, moduleTranslation, opInst.getLoc(),
privateVarsInfo.llvmVars,
privateVarsInfo.privatizers)))
return llvm::make_error<PreviouslyReportedError>();
// If we could be performing cancellation, add the cancellation barrier on
// the way out of the outlined region.
if (isCancellable) {
auto IPOrErr = ompBuilder->createBarrier(
llvm::OpenMPIRBuilder::LocationDescription(builder),
llvm::omp::Directive::OMPD_unknown,
/* ForceSimpleCall */ false,
/* CheckCancelFlag */ false);
if (!IPOrErr)
return IPOrErr.takeError();
}
builder.restoreIP(oldIP);
return llvm::Error::success();
};
llvm::Value *ifCond = nullptr;
if (auto ifVar = opInst.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
llvm::Value *numThreads = nullptr;
if (!opInst.getNumThreadsVars().empty())
numThreads = moduleTranslation.lookupValue(opInst.getNumThreads(0));
auto pbKind = llvm::omp::OMP_PROC_BIND_default;
if (auto bind = opInst.getProcBindKind())
pbKind = getProcBindKind(*bind);
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createParallel(ompLoc, allocaIP, bodyGenCB, privCB, finiCB,
ifCond, numThreads, pbKind, isCancellable);
if (failed(handleError(afterIP, *opInst)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
/// Convert Order attribute to llvm::omp::OrderKind.
static llvm::omp::OrderKind
convertOrderKind(std::optional<omp::ClauseOrderKind> o) {
if (!o)
return llvm::omp::OrderKind::OMP_ORDER_unknown;
switch (*o) {
case omp::ClauseOrderKind::Concurrent:
return llvm::omp::OrderKind::OMP_ORDER_concurrent;
}
llvm_unreachable("Unknown ClauseOrderKind kind");
}
/// Converts an OpenMP simd loop into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpSimd(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
auto simdOp = cast<omp::SimdOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
PrivateVarsInfo privateVarsInfo(simdOp);
MutableArrayRef<BlockArgument> reductionArgs =
cast<omp::BlockArgOpenMPOpInterface>(opInst).getReductionBlockArgs();
DenseMap<Value, llvm::Value *> reductionVariableMap;
SmallVector<llvm::Value *> privateReductionVariables(
simdOp.getNumReductionVars());
SmallVector<DeferredStore> deferredStores;
SmallVector<omp::DeclareReductionOp> reductionDecls;
collectReductionDecls(simdOp, reductionDecls);
llvm::ArrayRef<bool> isByRef = getIsByRef(simdOp.getReductionByref());
assert(isByRef.size() == simdOp.getNumReductionVars());
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::Expected<llvm::BasicBlock *> afterAllocas = allocatePrivateVars(
builder, moduleTranslation, privateVarsInfo, allocaIP);
if (handleError(afterAllocas, opInst).failed())
return failure();
// Initialize linear variables and linear step
LinearClauseProcessor linearClauseProcessor;
if (!simdOp.getLinearVars().empty()) {
auto linearVarTypes = simdOp.getLinearVarTypes().value();
for (mlir::Attribute linearVarType : linearVarTypes)
linearClauseProcessor.registerType(moduleTranslation, linearVarType);
for (auto [idx, linearVar] : llvm::enumerate(simdOp.getLinearVars())) {
bool isImplicit = false;
for (auto [mlirPrivVar, llvmPrivateVar] : llvm::zip_equal(
privateVarsInfo.mlirVars, privateVarsInfo.llvmVars)) {
// If the linear variable is implicit, reuse the already
// existing llvm::Value
if (linearVar == mlirPrivVar) {
isImplicit = true;
linearClauseProcessor.createLinearVar(builder, moduleTranslation,
llvmPrivateVar, idx);
break;
}
}
if (!isImplicit)
linearClauseProcessor.createLinearVar(
builder, moduleTranslation,
moduleTranslation.lookupValue(linearVar), idx);
}
for (mlir::Value linearStep : simdOp.getLinearStepVars())
linearClauseProcessor.initLinearStep(moduleTranslation, linearStep);
}
if (failed(allocReductionVars(simdOp, reductionArgs, builder,
moduleTranslation, allocaIP, reductionDecls,
privateReductionVariables, reductionVariableMap,
deferredStores, isByRef)))
return failure();
if (handleError(initPrivateVars(builder, moduleTranslation, privateVarsInfo),
opInst)
.failed())
return failure();
// No call to copyFirstPrivateVars because FIRSTPRIVATE is not allowed for
// SIMD.
assert(afterAllocas.get()->getSinglePredecessor());
if (failed(initReductionVars(simdOp, reductionArgs, builder,
moduleTranslation,
afterAllocas.get()->getSinglePredecessor(),
reductionDecls, privateReductionVariables,
reductionVariableMap, isByRef, deferredStores)))
return failure();
llvm::ConstantInt *simdlen = nullptr;
if (std::optional<uint64_t> simdlenVar = simdOp.getSimdlen())
simdlen = builder.getInt64(simdlenVar.value());
llvm::ConstantInt *safelen = nullptr;
if (std::optional<uint64_t> safelenVar = simdOp.getSafelen())
safelen = builder.getInt64(safelenVar.value());
llvm::MapVector<llvm::Value *, llvm::Value *> alignedVars;
llvm::omp::OrderKind order = convertOrderKind(simdOp.getOrder());
llvm::BasicBlock *sourceBlock = builder.GetInsertBlock();
std::optional<ArrayAttr> alignmentValues = simdOp.getAlignments();
mlir::OperandRange operands = simdOp.getAlignedVars();
for (size_t i = 0; i < operands.size(); ++i) {
llvm::Value *alignment = nullptr;
llvm::Value *llvmVal = moduleTranslation.lookupValue(operands[i]);
llvm::Type *ty = llvmVal->getType();
auto intAttr = cast<IntegerAttr>((*alignmentValues)[i]);
alignment = builder.getInt64(intAttr.getInt());
assert(ty->isPointerTy() && "Invalid type for aligned variable");
assert(alignment && "Invalid alignment value");
// Check if the alignment value is not a power of 2. If so, skip emitting
// alignment.
if (!intAttr.getValue().isPowerOf2())
continue;
auto curInsert = builder.saveIP();
builder.SetInsertPoint(sourceBlock);
llvmVal = builder.CreateLoad(ty, llvmVal);
builder.restoreIP(curInsert);
alignedVars[llvmVal] = alignment;
}
llvm::Expected<llvm::BasicBlock *> regionBlock = convertOmpOpRegions(
simdOp.getRegion(), "omp.simd.region", builder, moduleTranslation);
if (failed(handleError(regionBlock, opInst)))
return failure();
llvm::CanonicalLoopInfo *loopInfo = findCurrentLoopInfo(moduleTranslation);
// Emit Initialization for linear variables
if (simdOp.getLinearVars().size()) {
linearClauseProcessor.initLinearVar(builder, moduleTranslation,
loopInfo->getPreheader());
linearClauseProcessor.updateLinearVar(builder, loopInfo->getBody(),
loopInfo->getIndVar());
}
builder.SetInsertPoint(*regionBlock, (*regionBlock)->begin());
ompBuilder->applySimd(loopInfo, alignedVars,
simdOp.getIfExpr()
? moduleTranslation.lookupValue(simdOp.getIfExpr())
: nullptr,
order, simdlen, safelen);
linearClauseProcessor.emitStoresForLinearVar(builder);
for (size_t index = 0; index < simdOp.getLinearVars().size(); index++)
linearClauseProcessor.rewriteInPlace(builder, "omp.loop_nest.region",
index);
// We now need to reduce the per-simd-lane reduction variable into the
// original variable. This works a bit differently to other reductions (e.g.
// wsloop) because we don't need to call into the OpenMP runtime to handle
// threads: everything happened in this one thread.
for (auto [i, tuple] : llvm::enumerate(
llvm::zip(reductionDecls, isByRef, simdOp.getReductionVars(),
privateReductionVariables))) {
auto [decl, byRef, reductionVar, privateReductionVar] = tuple;
OwningReductionGen gen = makeReductionGen(decl, builder, moduleTranslation);
llvm::Value *originalVariable = moduleTranslation.lookupValue(reductionVar);
llvm::Type *reductionType = moduleTranslation.convertType(decl.getType());
// We have one less load for by-ref case because that load is now inside of
// the reduction region.
llvm::Value *redValue = originalVariable;
if (!byRef)
redValue =
builder.CreateLoad(reductionType, redValue, "red.value." + Twine(i));
llvm::Value *privateRedValue = builder.CreateLoad(
reductionType, privateReductionVar, "red.private.value." + Twine(i));
llvm::Value *reduced;
auto res = gen(builder.saveIP(), redValue, privateRedValue, reduced);
if (failed(handleError(res, opInst)))
return failure();
builder.restoreIP(res.get());
// For by-ref case, the store is inside of the reduction region.
if (!byRef)
builder.CreateStore(reduced, originalVariable);
}
// After the construct, deallocate private reduction variables.
SmallVector<Region *> reductionRegions;
llvm::transform(reductionDecls, std::back_inserter(reductionRegions),
[](omp::DeclareReductionOp reductionDecl) {
return &reductionDecl.getCleanupRegion();
});
if (failed(inlineOmpRegionCleanup(reductionRegions, privateReductionVariables,
moduleTranslation, builder,
"omp.reduction.cleanup")))
return failure();
return cleanupPrivateVars(builder, moduleTranslation, simdOp.getLoc(),
privateVarsInfo.llvmVars,
privateVarsInfo.privatizers);
}
/// Converts an OpenMP loop nest into LLVM IR using OpenMPIRBuilder.
static LogicalResult
convertOmpLoopNest(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
auto loopOp = cast<omp::LoopNestOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
// Set up the source location value for OpenMP runtime.
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
// Generator of the canonical loop body.
SmallVector<llvm::CanonicalLoopInfo *> loopInfos;
SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints;
auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip,
llvm::Value *iv) -> llvm::Error {
// Make sure further conversions know about the induction variable.
moduleTranslation.mapValue(
loopOp.getRegion().front().getArgument(loopInfos.size()), iv);
// Capture the body insertion point for use in nested loops. BodyIP of the
// CanonicalLoopInfo always points to the beginning of the entry block of
// the body.
bodyInsertPoints.push_back(ip);
if (loopInfos.size() != loopOp.getNumLoops() - 1)
return llvm::Error::success();
// Convert the body of the loop.
builder.restoreIP(ip);
llvm::Expected<llvm::BasicBlock *> regionBlock = convertOmpOpRegions(
loopOp.getRegion(), "omp.loop_nest.region", builder, moduleTranslation);
if (!regionBlock)
return regionBlock.takeError();
builder.SetInsertPoint(*regionBlock, (*regionBlock)->begin());
return llvm::Error::success();
};
// Delegate actual loop construction to the OpenMP IRBuilder.
// TODO: this currently assumes omp.loop_nest is semantically similar to SCF
// loop, i.e. it has a positive step, uses signed integer semantics.
// Reconsider this code when the nested loop operation clearly supports more
// cases.
for (unsigned i = 0, e = loopOp.getNumLoops(); i < e; ++i) {
llvm::Value *lowerBound =
moduleTranslation.lookupValue(loopOp.getLoopLowerBounds()[i]);
llvm::Value *upperBound =
moduleTranslation.lookupValue(loopOp.getLoopUpperBounds()[i]);
llvm::Value *step = moduleTranslation.lookupValue(loopOp.getLoopSteps()[i]);
// Make sure loop trip count are emitted in the preheader of the outermost
// loop at the latest so that they are all available for the new collapsed
// loop will be created below.
llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
if (i != 0) {
loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back(),
ompLoc.DL);
computeIP = loopInfos.front()->getPreheaderIP();
}
llvm::Expected<llvm::CanonicalLoopInfo *> loopResult =
ompBuilder->createCanonicalLoop(
loc, bodyGen, lowerBound, upperBound, step,
/*IsSigned=*/true, loopOp.getLoopInclusive(), computeIP);
if (failed(handleError(loopResult, *loopOp)))
return failure();
loopInfos.push_back(*loopResult);
}
llvm::OpenMPIRBuilder::InsertPointTy afterIP =
loopInfos.front()->getAfterIP();
// Do tiling.
if (const auto &tiles = loopOp.getTileSizes()) {
llvm::Type *ivType = loopInfos.front()->getIndVarType();
SmallVector<llvm::Value *> tileSizes;
for (auto tile : tiles.value()) {
llvm::Value *tileVal = llvm::ConstantInt::get(ivType, tile);
tileSizes.push_back(tileVal);
}
std::vector<llvm::CanonicalLoopInfo *> newLoops =
ompBuilder->tileLoops(ompLoc.DL, loopInfos, tileSizes);
// Update afterIP to get the correct insertion point after
// tiling.
llvm::BasicBlock *afterBB = newLoops.front()->getAfter();
llvm::BasicBlock *afterAfterBB = afterBB->getSingleSuccessor();
afterIP = {afterAfterBB, afterAfterBB->begin()};
// Update the loop infos.
loopInfos.clear();
for (const auto &newLoop : newLoops)
loopInfos.push_back(newLoop);
} // Tiling done.
// Do collapse.
const auto &numCollapse = loopOp.getCollapseNumLoops();
SmallVector<llvm::CanonicalLoopInfo *> collapseLoopInfos(
loopInfos.begin(), loopInfos.begin() + (numCollapse));
auto newTopLoopInfo =
ompBuilder->collapseLoops(ompLoc.DL, collapseLoopInfos, {});
assert(newTopLoopInfo && "New top loop information is missing");
moduleTranslation.stackWalk<OpenMPLoopInfoStackFrame>(
[&](OpenMPLoopInfoStackFrame &frame) {
frame.loopInfo = newTopLoopInfo;
return WalkResult::interrupt();
});
// Continue building IR after the loop. Note that the LoopInfo returned by
// `collapseLoops` points inside the outermost loop and is intended for
// potential further loop transformations. Use the insertion point stored
// before collapsing loops instead.
builder.restoreIP(afterIP);
return success();
}
/// Convert an omp.canonical_loop to LLVM-IR
static LogicalResult
convertOmpCanonicalLoopOp(omp::CanonicalLoopOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::LocationDescription loopLoc(builder);
Value loopIV = op.getInductionVar();
Value loopTC = op.getTripCount();
llvm::Value *llvmTC = moduleTranslation.lookupValue(loopTC);
llvm::Expected<llvm::CanonicalLoopInfo *> llvmOrError =
ompBuilder->createCanonicalLoop(
loopLoc,
[&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *llvmIV) {
// Register the mapping of MLIR induction variable to LLVM-IR
// induction variable
moduleTranslation.mapValue(loopIV, llvmIV);
builder.restoreIP(ip);
llvm::Expected<llvm::BasicBlock *> bodyGenStatus =
convertOmpOpRegions(op.getRegion(), "omp.loop.region", builder,
moduleTranslation);
return bodyGenStatus.takeError();
},
llvmTC, "omp.loop");
if (!llvmOrError)
return op.emitError(llvm::toString(llvmOrError.takeError()));
llvm::CanonicalLoopInfo *llvmCLI = *llvmOrError;
llvm::IRBuilderBase::InsertPoint afterIP = llvmCLI->getAfterIP();
builder.restoreIP(afterIP);
// Register the mapping of MLIR loop to LLVM-IR OpenMPIRBuilder loop
if (Value cli = op.getCli())
moduleTranslation.mapOmpLoop(cli, llvmCLI);
return success();
}
/// Apply a `#pragma omp unroll` / "!$omp unroll" transformation using the
/// OpenMPIRBuilder.
static LogicalResult
applyUnrollHeuristic(omp::UnrollHeuristicOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
Value applyee = op.getApplyee();
assert(applyee && "Loop to apply unrolling on required");
llvm::CanonicalLoopInfo *consBuilderCLI =
moduleTranslation.lookupOMPLoop(applyee);
llvm::OpenMPIRBuilder::LocationDescription loc(builder);
ompBuilder->unrollLoopHeuristic(loc.DL, consBuilderCLI);
moduleTranslation.invalidateOmpLoop(applyee);
return success();
}
/// Apply a `#pragma omp tile` / `!$omp tile` transformation using the
/// OpenMPIRBuilder.
static LogicalResult applyTile(omp::TileOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::LocationDescription loc(builder);
SmallVector<llvm::CanonicalLoopInfo *> translatedLoops;
SmallVector<llvm::Value *> translatedSizes;
for (Value size : op.getSizes()) {
llvm::Value *translatedSize = moduleTranslation.lookupValue(size);
assert(translatedSize &&
"sizes clause arguments must already be translated");
translatedSizes.push_back(translatedSize);
}
for (Value applyee : op.getApplyees()) {
llvm::CanonicalLoopInfo *consBuilderCLI =
moduleTranslation.lookupOMPLoop(applyee);
assert(applyee && "Canonical loop must already been translated");
translatedLoops.push_back(consBuilderCLI);
}
auto generatedLoops =
ompBuilder->tileLoops(loc.DL, translatedLoops, translatedSizes);
if (!op.getGeneratees().empty()) {
for (auto [mlirLoop, genLoop] :
zip_equal(op.getGeneratees(), generatedLoops))
moduleTranslation.mapOmpLoop(mlirLoop, genLoop);
}
// CLIs can only be consumed once
for (Value applyee : op.getApplyees())
moduleTranslation.invalidateOmpLoop(applyee);
return success();
}
/// Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
static llvm::AtomicOrdering
convertAtomicOrdering(std::optional<omp::ClauseMemoryOrderKind> ao) {
if (!ao)
return llvm::AtomicOrdering::Monotonic; // Default Memory Ordering
switch (*ao) {
case omp::ClauseMemoryOrderKind::Seq_cst:
return llvm::AtomicOrdering::SequentiallyConsistent;
case omp::ClauseMemoryOrderKind::Acq_rel:
return llvm::AtomicOrdering::AcquireRelease;
case omp::ClauseMemoryOrderKind::Acquire:
return llvm::AtomicOrdering::Acquire;
case omp::ClauseMemoryOrderKind::Release:
return llvm::AtomicOrdering::Release;
case omp::ClauseMemoryOrderKind::Relaxed:
return llvm::AtomicOrdering::Monotonic;
}
llvm_unreachable("Unknown ClauseMemoryOrderKind kind");
}
/// Convert omp.atomic.read operation to LLVM IR.
static LogicalResult
convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto readOp = cast<omp::AtomicReadOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::AtomicOrdering AO = convertAtomicOrdering(readOp.getMemoryOrder());
llvm::Value *x = moduleTranslation.lookupValue(readOp.getX());
llvm::Value *v = moduleTranslation.lookupValue(readOp.getV());
llvm::Type *elementType =
moduleTranslation.convertType(readOp.getElementType());
llvm::OpenMPIRBuilder::AtomicOpValue V = {v, elementType, false, false};
llvm::OpenMPIRBuilder::AtomicOpValue X = {x, elementType, false, false};
builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO, allocaIP));
return success();
}
/// Converts an omp.atomic.write operation to LLVM IR.
static LogicalResult
convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto writeOp = cast<omp::AtomicWriteOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::AtomicOrdering ao = convertAtomicOrdering(writeOp.getMemoryOrder());
llvm::Value *expr = moduleTranslation.lookupValue(writeOp.getExpr());
llvm::Value *dest = moduleTranslation.lookupValue(writeOp.getX());
llvm::Type *ty = moduleTranslation.convertType(writeOp.getExpr().getType());
llvm::OpenMPIRBuilder::AtomicOpValue x = {dest, ty, /*isSigned=*/false,
/*isVolatile=*/false};
builder.restoreIP(
ompBuilder->createAtomicWrite(ompLoc, x, expr, ao, allocaIP));
return success();
}
/// Converts an LLVM dialect binary operation to the corresponding enum value
/// for `atomicrmw` supported binary operation.
static llvm::AtomicRMWInst::BinOp convertBinOpToAtomic(Operation &op) {
return llvm::TypeSwitch<Operation *, llvm::AtomicRMWInst::BinOp>(&op)
.Case([&](LLVM::AddOp) { return llvm::AtomicRMWInst::BinOp::Add; })
.Case([&](LLVM::SubOp) { return llvm::AtomicRMWInst::BinOp::Sub; })
.Case([&](LLVM::AndOp) { return llvm::AtomicRMWInst::BinOp::And; })
.Case([&](LLVM::OrOp) { return llvm::AtomicRMWInst::BinOp::Or; })
.Case([&](LLVM::XOrOp) { return llvm::AtomicRMWInst::BinOp::Xor; })
.Case([&](LLVM::UMaxOp) { return llvm::AtomicRMWInst::BinOp::UMax; })
.Case([&](LLVM::UMinOp) { return llvm::AtomicRMWInst::BinOp::UMin; })
.Case([&](LLVM::FAddOp) { return llvm::AtomicRMWInst::BinOp::FAdd; })
.Case([&](LLVM::FSubOp) { return llvm::AtomicRMWInst::BinOp::FSub; })
.Default(llvm::AtomicRMWInst::BinOp::BAD_BINOP);
}
static void extractAtomicControlFlags(omp::AtomicUpdateOp atomicUpdateOp,
bool &isIgnoreDenormalMode,
bool &isFineGrainedMemory,
bool &isRemoteMemory) {
isIgnoreDenormalMode = false;
isFineGrainedMemory = false;
isRemoteMemory = false;
if (atomicUpdateOp &&
atomicUpdateOp->hasAttr(atomicUpdateOp.getAtomicControlAttrName())) {
mlir::omp::AtomicControlAttr atomicControlAttr =
atomicUpdateOp.getAtomicControlAttr();
isIgnoreDenormalMode = atomicControlAttr.getIgnoreDenormalMode();
isFineGrainedMemory = atomicControlAttr.getFineGrainedMemory();
isRemoteMemory = atomicControlAttr.getRemoteMemory();
}
}
/// Converts an OpenMP atomic update operation using OpenMPIRBuilder.
static LogicalResult
convertOmpAtomicUpdate(omp::AtomicUpdateOp &opInst,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
if (failed(checkImplementationStatus(*opInst)))
return failure();
// Convert values and types.
auto &innerOpList = opInst.getRegion().front().getOperations();
bool isXBinopExpr{false};
llvm::AtomicRMWInst::BinOp binop;
mlir::Value mlirExpr;
llvm::Value *llvmExpr = nullptr;
llvm::Value *llvmX = nullptr;
llvm::Type *llvmXElementType = nullptr;
if (innerOpList.size() == 2) {
// The two operations here are the update and the terminator.
// Since we can identify the update operation, there is a possibility
// that we can generate the atomicrmw instruction.
mlir::Operation &innerOp = *opInst.getRegion().front().begin();
if (!llvm::is_contained(innerOp.getOperands(),
opInst.getRegion().getArgument(0))) {
return opInst.emitError("no atomic update operation with region argument"
" as operand found inside atomic.update region");
}
binop = convertBinOpToAtomic(innerOp);
isXBinopExpr = innerOp.getOperand(0) == opInst.getRegion().getArgument(0);
mlirExpr = (isXBinopExpr ? innerOp.getOperand(1) : innerOp.getOperand(0));
llvmExpr = moduleTranslation.lookupValue(mlirExpr);
} else {
// Since the update region includes more than one operation
// we will resort to generating a cmpxchg loop.
binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
}
llvmX = moduleTranslation.lookupValue(opInst.getX());
llvmXElementType = moduleTranslation.convertType(
opInst.getRegion().getArgument(0).getType());
llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
/*isSigned=*/false,
/*isVolatile=*/false};
llvm::AtomicOrdering atomicOrdering =
convertAtomicOrdering(opInst.getMemoryOrder());
// Generate update code.
auto updateFn =
[&opInst, &moduleTranslation](
llvm::Value *atomicx,
llvm::IRBuilder<> &builder) -> llvm::Expected<llvm::Value *> {
Block &bb = *opInst.getRegion().begin();
moduleTranslation.mapValue(*opInst.getRegion().args_begin(), atomicx);
moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
if (failed(moduleTranslation.convertBlock(bb, true, builder)))
return llvm::make_error<PreviouslyReportedError>();
omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
assert(yieldop && yieldop.getResults().size() == 1 &&
"terminator must be omp.yield op and it must have exactly one "
"argument");
return moduleTranslation.lookupValue(yieldop.getResults()[0]);
};
bool isIgnoreDenormalMode;
bool isFineGrainedMemory;
bool isRemoteMemory;
extractAtomicControlFlags(opInst, isIgnoreDenormalMode, isFineGrainedMemory,
isRemoteMemory);
// Handle ambiguous alloca, if any.
auto allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createAtomicUpdate(ompLoc, allocaIP, llvmAtomicX, llvmExpr,
atomicOrdering, binop, updateFn,
isXBinopExpr, isIgnoreDenormalMode,
isFineGrainedMemory, isRemoteMemory);
if (failed(handleError(afterIP, *opInst)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
static LogicalResult
convertOmpAtomicCapture(omp::AtomicCaptureOp atomicCaptureOp,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
if (failed(checkImplementationStatus(*atomicCaptureOp)))
return failure();
mlir::Value mlirExpr;
bool isXBinopExpr = false, isPostfixUpdate = false;
llvm::AtomicRMWInst::BinOp binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
omp::AtomicUpdateOp atomicUpdateOp = atomicCaptureOp.getAtomicUpdateOp();
omp::AtomicWriteOp atomicWriteOp = atomicCaptureOp.getAtomicWriteOp();
assert((atomicUpdateOp || atomicWriteOp) &&
"internal op must be an atomic.update or atomic.write op");
if (atomicWriteOp) {
isPostfixUpdate = true;
mlirExpr = atomicWriteOp.getExpr();
} else {
isPostfixUpdate = atomicCaptureOp.getSecondOp() ==
atomicCaptureOp.getAtomicUpdateOp().getOperation();
auto &innerOpList = atomicUpdateOp.getRegion().front().getOperations();
// Find the binary update operation that uses the region argument
// and get the expression to update
if (innerOpList.size() == 2) {
mlir::Operation &innerOp = *atomicUpdateOp.getRegion().front().begin();
if (!llvm::is_contained(innerOp.getOperands(),
atomicUpdateOp.getRegion().getArgument(0))) {
return atomicUpdateOp.emitError(
"no atomic update operation with region argument"
" as operand found inside atomic.update region");
}
binop = convertBinOpToAtomic(innerOp);
isXBinopExpr =
innerOp.getOperand(0) == atomicUpdateOp.getRegion().getArgument(0);
mlirExpr = (isXBinopExpr ? innerOp.getOperand(1) : innerOp.getOperand(0));
} else {
binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
}
}
llvm::Value *llvmExpr = moduleTranslation.lookupValue(mlirExpr);
llvm::Value *llvmX =
moduleTranslation.lookupValue(atomicCaptureOp.getAtomicReadOp().getX());
llvm::Value *llvmV =
moduleTranslation.lookupValue(atomicCaptureOp.getAtomicReadOp().getV());
llvm::Type *llvmXElementType = moduleTranslation.convertType(
atomicCaptureOp.getAtomicReadOp().getElementType());
llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
/*isSigned=*/false,
/*isVolatile=*/false};
llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicV = {llvmV, llvmXElementType,
/*isSigned=*/false,
/*isVolatile=*/false};
llvm::AtomicOrdering atomicOrdering =
convertAtomicOrdering(atomicCaptureOp.getMemoryOrder());
auto updateFn =
[&](llvm::Value *atomicx,
llvm::IRBuilder<> &builder) -> llvm::Expected<llvm::Value *> {
if (atomicWriteOp)
return moduleTranslation.lookupValue(atomicWriteOp.getExpr());
Block &bb = *atomicUpdateOp.getRegion().begin();
moduleTranslation.mapValue(*atomicUpdateOp.getRegion().args_begin(),
atomicx);
moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
if (failed(moduleTranslation.convertBlock(bb, true, builder)))
return llvm::make_error<PreviouslyReportedError>();
omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
assert(yieldop && yieldop.getResults().size() == 1 &&
"terminator must be omp.yield op and it must have exactly one "
"argument");
return moduleTranslation.lookupValue(yieldop.getResults()[0]);
};
bool isIgnoreDenormalMode;
bool isFineGrainedMemory;
bool isRemoteMemory;
extractAtomicControlFlags(atomicUpdateOp, isIgnoreDenormalMode,
isFineGrainedMemory, isRemoteMemory);
// Handle ambiguous alloca, if any.
auto allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createAtomicCapture(
ompLoc, allocaIP, llvmAtomicX, llvmAtomicV, llvmExpr, atomicOrdering,
binop, updateFn, atomicUpdateOp, isPostfixUpdate, isXBinopExpr,
isIgnoreDenormalMode, isFineGrainedMemory, isRemoteMemory);
if (failed(handleError(afterIP, *atomicCaptureOp)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
static llvm::omp::Directive convertCancellationConstructType(
omp::ClauseCancellationConstructType directive) {
switch (directive) {
case omp::ClauseCancellationConstructType::Loop:
return llvm::omp::Directive::OMPD_for;
case omp::ClauseCancellationConstructType::Parallel:
return llvm::omp::Directive::OMPD_parallel;
case omp::ClauseCancellationConstructType::Sections:
return llvm::omp::Directive::OMPD_sections;
case omp::ClauseCancellationConstructType::Taskgroup:
return llvm::omp::Directive::OMPD_taskgroup;
}
llvm_unreachable("Unhandled cancellation construct type");
}
static LogicalResult
convertOmpCancel(omp::CancelOp op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
if (failed(checkImplementationStatus(*op.getOperation())))
return failure();
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::Value *ifCond = nullptr;
if (Value ifVar = op.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
llvm::omp::Directive cancelledDirective =
convertCancellationConstructType(op.getCancelDirective());
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createCancel(ompLoc, ifCond, cancelledDirective);
if (failed(handleError(afterIP, *op.getOperation())))
return failure();
builder.restoreIP(afterIP.get());
return success();
}
static LogicalResult
convertOmpCancellationPoint(omp::CancellationPointOp op,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
if (failed(checkImplementationStatus(*op.getOperation())))
return failure();
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::omp::Directive cancelledDirective =
convertCancellationConstructType(op.getCancelDirective());
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createCancellationPoint(ompLoc, cancelledDirective);
if (failed(handleError(afterIP, *op.getOperation())))
return failure();
builder.restoreIP(afterIP.get());
return success();
}
/// Converts an OpenMP Threadprivate operation into LLVM IR using
/// OpenMPIRBuilder.
static LogicalResult
convertOmpThreadprivate(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
auto threadprivateOp = cast<omp::ThreadprivateOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
Value symAddr = threadprivateOp.getSymAddr();
auto *symOp = symAddr.getDefiningOp();
if (auto asCast = dyn_cast<LLVM::AddrSpaceCastOp>(symOp))
symOp = asCast.getOperand().getDefiningOp();
if (!isa<LLVM::AddressOfOp>(symOp))
return opInst.emitError("Addressing symbol not found");
LLVM::AddressOfOp addressOfOp = dyn_cast<LLVM::AddressOfOp>(symOp);
LLVM::GlobalOp global =
addressOfOp.getGlobal(moduleTranslation.symbolTable());
llvm::GlobalValue *globalValue = moduleTranslation.lookupGlobal(global);
llvm::Type *type = globalValue->getValueType();
llvm::TypeSize typeSize =
builder.GetInsertBlock()->getModule()->getDataLayout().getTypeStoreSize(
type);
llvm::ConstantInt *size = builder.getInt64(typeSize.getFixedValue());
llvm::Value *callInst = ompBuilder->createCachedThreadPrivate(
ompLoc, globalValue, size, global.getSymName() + ".cache");
moduleTranslation.mapValue(opInst.getResult(0), callInst);
return success();
}
static llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseKind
convertToDeviceClauseKind(mlir::omp::DeclareTargetDeviceType deviceClause) {
switch (deviceClause) {
case mlir::omp::DeclareTargetDeviceType::host:
return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseHost;
break;
case mlir::omp::DeclareTargetDeviceType::nohost:
return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseNoHost;
break;
case mlir::omp::DeclareTargetDeviceType::any:
return llvm::OffloadEntriesInfoManager::OMPTargetDeviceClauseAny;
break;
}
llvm_unreachable("unhandled device clause");
}
static llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryKind
convertToCaptureClauseKind(
mlir::omp::DeclareTargetCaptureClause captureClause) {
switch (captureClause) {
case mlir::omp::DeclareTargetCaptureClause::to:
return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryTo;
case mlir::omp::DeclareTargetCaptureClause::link:
return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryLink;
case mlir::omp::DeclareTargetCaptureClause::enter:
return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryEnter;
case mlir::omp::DeclareTargetCaptureClause::none:
return llvm::OffloadEntriesInfoManager::OMPTargetGlobalVarEntryNone;
}
llvm_unreachable("unhandled capture clause");
}
static Operation *getGlobalOpFromValue(Value value) {
Operation *op = value.getDefiningOp();
if (auto addrCast = dyn_cast_if_present<LLVM::AddrSpaceCastOp>(op))
op = addrCast->getOperand(0).getDefiningOp();
if (auto addressOfOp = dyn_cast_if_present<LLVM::AddressOfOp>(op)) {
auto modOp = addressOfOp->getParentOfType<mlir::ModuleOp>();
return modOp.lookupSymbol(addressOfOp.getGlobalName());
}
return nullptr;
}
static llvm::SmallString<64>
getDeclareTargetRefPtrSuffix(LLVM::GlobalOp globalOp,
llvm::OpenMPIRBuilder &ompBuilder) {
llvm::SmallString<64> suffix;
llvm::raw_svector_ostream os(suffix);
if (globalOp.getVisibility() == mlir::SymbolTable::Visibility::Private) {
auto loc = globalOp->getLoc()->findInstanceOf<FileLineColLoc>();
auto fileInfoCallBack = [&loc]() {
return std::pair<std::string, uint64_t>(
llvm::StringRef(loc.getFilename()), loc.getLine());
};
auto vfs = llvm::vfs::getRealFileSystem();
os << llvm::format(
"_%x",
ompBuilder.getTargetEntryUniqueInfo(fileInfoCallBack, *vfs).FileID);
}
os << "_decl_tgt_ref_ptr";
return suffix;
}
static bool isDeclareTargetLink(Value value) {
if (auto declareTargetGlobal =
dyn_cast_if_present<omp::DeclareTargetInterface>(
getGlobalOpFromValue(value)))
if (declareTargetGlobal.getDeclareTargetCaptureClause() ==
omp::DeclareTargetCaptureClause::link)
return true;
return false;
}
static bool isDeclareTargetTo(Value value) {
if (auto declareTargetGlobal =
dyn_cast_if_present<omp::DeclareTargetInterface>(
getGlobalOpFromValue(value)))
if (declareTargetGlobal.getDeclareTargetCaptureClause() ==
omp::DeclareTargetCaptureClause::to ||
declareTargetGlobal.getDeclareTargetCaptureClause() ==
omp::DeclareTargetCaptureClause::enter)
return true;
return false;
}
// Returns the reference pointer generated by the lowering of the declare
// target operation in cases where the link clause is used or the to clause is
// used in USM mode.
static llvm::Value *
getRefPtrIfDeclareTarget(Value value,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
if (auto gOp =
dyn_cast_or_null<LLVM::GlobalOp>(getGlobalOpFromValue(value))) {
if (auto declareTargetGlobal =
dyn_cast<omp::DeclareTargetInterface>(gOp.getOperation())) {
// In this case, we must utilise the reference pointer generated by
// the declare target operation, similar to Clang
if ((declareTargetGlobal.getDeclareTargetCaptureClause() ==
omp::DeclareTargetCaptureClause::link) ||
(declareTargetGlobal.getDeclareTargetCaptureClause() ==
omp::DeclareTargetCaptureClause::to &&
ompBuilder->Config.hasRequiresUnifiedSharedMemory())) {
llvm::SmallString<64> suffix =
getDeclareTargetRefPtrSuffix(gOp, *ompBuilder);
if (gOp.getSymName().contains(suffix))
return moduleTranslation.getLLVMModule()->getNamedValue(
gOp.getSymName());
return moduleTranslation.getLLVMModule()->getNamedValue(
(gOp.getSymName().str() + suffix.str()).str());
}
}
}
return nullptr;
}
namespace {
// Append customMappers information to existing MapInfosTy
struct MapInfosTy : llvm::OpenMPIRBuilder::MapInfosTy {
SmallVector<Operation *, 4> Mappers;
/// Append arrays in \a CurInfo.
void append(MapInfosTy &curInfo) {
Mappers.append(curInfo.Mappers.begin(), curInfo.Mappers.end());
llvm::OpenMPIRBuilder::MapInfosTy::append(curInfo);
}
};
// A small helper structure to contain data gathered
// for map lowering and coalese it into one area and
// avoiding extra computations such as searches in the
// llvm module for lowered mapped variables or checking
// if something is declare target (and retrieving the
// value) more than neccessary.
struct MapInfoData : MapInfosTy {
llvm::SmallVector<bool, 4> IsDeclareTarget;
llvm::SmallVector<bool, 4> IsAMember;
// Identify if mapping was added by mapClause or use_device clauses.
llvm::SmallVector<bool, 4> IsAMapping;
llvm::SmallVector<mlir::Operation *, 4> MapClause;
llvm::SmallVector<llvm::Value *, 4> OriginalValue;
// Stripped off array/pointer to get the underlying
// element type
llvm::SmallVector<llvm::Type *, 4> BaseType;
/// Append arrays in \a CurInfo.
void append(MapInfoData &CurInfo) {
IsDeclareTarget.append(CurInfo.IsDeclareTarget.begin(),
CurInfo.IsDeclareTarget.end());
MapClause.append(CurInfo.MapClause.begin(), CurInfo.MapClause.end());
OriginalValue.append(CurInfo.OriginalValue.begin(),
CurInfo.OriginalValue.end());
BaseType.append(CurInfo.BaseType.begin(), CurInfo.BaseType.end());
MapInfosTy::append(CurInfo);
}
};
enum class TargetDirectiveEnumTy : uint32_t {
None = 0,
Target = 1,
TargetData = 2,
TargetEnterData = 3,
TargetExitData = 4,
TargetUpdate = 5
};
static TargetDirectiveEnumTy getTargetDirectiveEnumTyFromOp(Operation *op) {
return llvm::TypeSwitch<Operation *, TargetDirectiveEnumTy>(op)
.Case([](omp::TargetDataOp) { return TargetDirectiveEnumTy::TargetData; })
.Case([](omp::TargetEnterDataOp) {
return TargetDirectiveEnumTy::TargetEnterData;
})
.Case([&](omp::TargetExitDataOp) {
return TargetDirectiveEnumTy::TargetExitData;
})
.Case([&](omp::TargetUpdateOp) {
return TargetDirectiveEnumTy::TargetUpdate;
})
.Case([&](omp::TargetOp) { return TargetDirectiveEnumTy::Target; })
.Default([&](Operation *op) { return TargetDirectiveEnumTy::None; });
}
} // namespace
static uint64_t getArrayElementSizeInBits(LLVM::LLVMArrayType arrTy,
DataLayout &dl) {
if (auto nestedArrTy = llvm::dyn_cast_if_present<LLVM::LLVMArrayType>(
arrTy.getElementType()))
return getArrayElementSizeInBits(nestedArrTy, dl);
return dl.getTypeSizeInBits(arrTy.getElementType());
}
// This function calculates the size to be offloaded for a specified type, given
// its associated map clause (which can contain bounds information which affects
// the total size), this size is calculated based on the underlying element type
// e.g. given a 1-D array of ints, we will calculate the size from the integer
// type * number of elements in the array. This size can be used in other
// calculations but is ultimately used as an argument to the OpenMP runtimes
// kernel argument structure which is generated through the combinedInfo data
// structures.
// This function is somewhat equivalent to Clang's getExprTypeSize inside of
// CGOpenMPRuntime.cpp.
static llvm::Value *getSizeInBytes(DataLayout &dl, const mlir::Type &type,
Operation *clauseOp,
llvm::Value *basePointer,
llvm::Type *baseType,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
if (auto memberClause =
mlir::dyn_cast_if_present<mlir::omp::MapInfoOp>(clauseOp)) {
// This calculates the size to transfer based on bounds and the underlying
// element type, provided bounds have been specified (Fortran
// pointers/allocatables/target and arrays that have sections specified fall
// into this as well)
if (!memberClause.getBounds().empty()) {
llvm::Value *elementCount = builder.getInt64(1);
for (auto bounds : memberClause.getBounds()) {
if (auto boundOp = mlir::dyn_cast_if_present<mlir::omp::MapBoundsOp>(
bounds.getDefiningOp())) {
// The below calculation for the size to be mapped calculated from the
// map.info's bounds is: (elemCount * [UB - LB] + 1), later we
// multiply by the underlying element types byte size to get the full
// size to be offloaded based on the bounds
elementCount = builder.CreateMul(
elementCount,
builder.CreateAdd(
builder.CreateSub(
moduleTranslation.lookupValue(boundOp.getUpperBound()),
moduleTranslation.lookupValue(boundOp.getLowerBound())),
builder.getInt64(1)));
}
}
// utilising getTypeSizeInBits instead of getTypeSize as getTypeSize gives
// the size in inconsistent byte or bit format.
uint64_t underlyingTypeSzInBits = dl.getTypeSizeInBits(type);
if (auto arrTy = llvm::dyn_cast_if_present<LLVM::LLVMArrayType>(type))
underlyingTypeSzInBits = getArrayElementSizeInBits(arrTy, dl);
// The size in bytes x number of elements, the sizeInBytes stored is
// the underyling types size, e.g. if ptr<i32>, it'll be the i32's
// size, so we do some on the fly runtime math to get the size in
// bytes from the extent (ub - lb) * sizeInBytes. NOTE: This may need
// some adjustment for members with more complex types.
return builder.CreateMul(elementCount,
builder.getInt64(underlyingTypeSzInBits / 8));
}
}
return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
}
// Convert the MLIR map flag set to the runtime map flag set for embedding
// in LLVM-IR. This is important as the two bit-flag lists do not correspond
// 1-to-1 as there's flags the runtime doesn't care about and vice versa.
// Certain flags are discarded here such as RefPtee and co.
static llvm::omp::OpenMPOffloadMappingFlags
convertClauseMapFlags(omp::ClauseMapFlags mlirFlags) {
auto mapTypeToBool = [&mlirFlags](omp::ClauseMapFlags flag) {
return (mlirFlags & flag) == flag;
};
const bool hasExplicitMap =
(mlirFlags & ~omp::ClauseMapFlags::is_device_ptr) !=
omp::ClauseMapFlags::none;
llvm::omp::OpenMPOffloadMappingFlags mapType =
llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
if (mapTypeToBool(omp::ClauseMapFlags::to))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TO;
if (mapTypeToBool(omp::ClauseMapFlags::from))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_FROM;
if (mapTypeToBool(omp::ClauseMapFlags::always))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
if (mapTypeToBool(omp::ClauseMapFlags::del))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_DELETE;
if (mapTypeToBool(omp::ClauseMapFlags::return_param))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
if (mapTypeToBool(omp::ClauseMapFlags::priv))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PRIVATE;
if (mapTypeToBool(omp::ClauseMapFlags::literal))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
if (mapTypeToBool(omp::ClauseMapFlags::implicit))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT;
if (mapTypeToBool(omp::ClauseMapFlags::close))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_CLOSE;
if (mapTypeToBool(omp::ClauseMapFlags::present))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PRESENT;
if (mapTypeToBool(omp::ClauseMapFlags::ompx_hold))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_OMPX_HOLD;
if (mapTypeToBool(omp::ClauseMapFlags::attach))
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ATTACH;
if (mapTypeToBool(omp::ClauseMapFlags::is_device_ptr)) {
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
if (!hasExplicitMap)
mapType |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
}
return mapType;
}
static void collectMapDataFromMapOperands(
MapInfoData &mapData, SmallVectorImpl<Value> &mapVars,
LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
llvm::IRBuilderBase &builder, ArrayRef<Value> useDevPtrOperands = {},
ArrayRef<Value> useDevAddrOperands = {},
ArrayRef<Value> hasDevAddrOperands = {}) {
auto checkIsAMember = [](const auto &mapVars, auto mapOp) {
// Check if this is a member mapping and correctly assign that it is, if
// it is a member of a larger object.
// TODO: Need better handling of members, and distinguishing of members
// that are implicitly allocated on device vs explicitly passed in as
// arguments.
// TODO: May require some further additions to support nested record
// types, i.e. member maps that can have member maps.
for (Value mapValue : mapVars) {
auto map = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
for (auto member : map.getMembers())
if (member == mapOp)
return true;
}
return false;
};
// Process MapOperands
for (Value mapValue : mapVars) {
auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
Value offloadPtr =
mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
mapData.Pointers.push_back(mapData.OriginalValue.back());
if (llvm::Value *refPtr =
getRefPtrIfDeclareTarget(offloadPtr, moduleTranslation)) {
mapData.IsDeclareTarget.push_back(true);
mapData.BasePointers.push_back(refPtr);
} else if (isDeclareTargetTo(offloadPtr)) {
mapData.IsDeclareTarget.push_back(true);
mapData.BasePointers.push_back(mapData.OriginalValue.back());
} else { // regular mapped variable
mapData.IsDeclareTarget.push_back(false);
mapData.BasePointers.push_back(mapData.OriginalValue.back());
}
mapData.BaseType.push_back(
moduleTranslation.convertType(mapOp.getVarType()));
mapData.Sizes.push_back(
getSizeInBytes(dl, mapOp.getVarType(), mapOp, mapData.Pointers.back(),
mapData.BaseType.back(), builder, moduleTranslation));
mapData.MapClause.push_back(mapOp.getOperation());
mapData.Types.push_back(convertClauseMapFlags(mapOp.getMapType()));
mapData.Names.push_back(LLVM::createMappingInformation(
mapOp.getLoc(), *moduleTranslation.getOpenMPBuilder()));
mapData.DevicePointers.push_back(llvm::OpenMPIRBuilder::DeviceInfoTy::None);
if (mapOp.getMapperId())
mapData.Mappers.push_back(
SymbolTable::lookupNearestSymbolFrom<omp::DeclareMapperOp>(
mapOp, mapOp.getMapperIdAttr()));
else
mapData.Mappers.push_back(nullptr);
mapData.IsAMapping.push_back(true);
mapData.IsAMember.push_back(checkIsAMember(mapVars, mapOp));
}
auto findMapInfo = [&mapData](llvm::Value *val,
llvm::OpenMPIRBuilder::DeviceInfoTy devInfoTy) {
unsigned index = 0;
bool found = false;
for (llvm::Value *basePtr : mapData.OriginalValue) {
if (basePtr == val && mapData.IsAMapping[index]) {
found = true;
mapData.Types[index] |=
llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM;
mapData.DevicePointers[index] = devInfoTy;
}
index++;
}
return found;
};
// Process useDevPtr(Addr)Operands
auto addDevInfos = [&](const llvm::ArrayRef<Value> &useDevOperands,
llvm::OpenMPIRBuilder::DeviceInfoTy devInfoTy) {
for (Value mapValue : useDevOperands) {
auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
Value offloadPtr =
mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
llvm::Value *origValue = moduleTranslation.lookupValue(offloadPtr);
// Check if map info is already present for this entry.
if (!findMapInfo(origValue, devInfoTy)) {
mapData.OriginalValue.push_back(origValue);
mapData.Pointers.push_back(mapData.OriginalValue.back());
mapData.IsDeclareTarget.push_back(false);
mapData.BasePointers.push_back(mapData.OriginalValue.back());
mapData.BaseType.push_back(
moduleTranslation.convertType(mapOp.getVarType()));
mapData.Sizes.push_back(builder.getInt64(0));
mapData.MapClause.push_back(mapOp.getOperation());
mapData.Types.push_back(
llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_RETURN_PARAM);
mapData.Names.push_back(LLVM::createMappingInformation(
mapOp.getLoc(), *moduleTranslation.getOpenMPBuilder()));
mapData.DevicePointers.push_back(devInfoTy);
mapData.Mappers.push_back(nullptr);
mapData.IsAMapping.push_back(false);
mapData.IsAMember.push_back(checkIsAMember(useDevOperands, mapOp));
}
}
};
addDevInfos(useDevAddrOperands, llvm::OpenMPIRBuilder::DeviceInfoTy::Address);
addDevInfos(useDevPtrOperands, llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer);
for (Value mapValue : hasDevAddrOperands) {
auto mapOp = cast<omp::MapInfoOp>(mapValue.getDefiningOp());
Value offloadPtr =
mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
llvm::Value *origValue = moduleTranslation.lookupValue(offloadPtr);
auto mapType = convertClauseMapFlags(mapOp.getMapType());
auto mapTypeAlways = llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_ALWAYS;
bool isDevicePtr =
(mapOp.getMapType() & omp::ClauseMapFlags::is_device_ptr) !=
omp::ClauseMapFlags::none;
mapData.OriginalValue.push_back(origValue);
mapData.BasePointers.push_back(origValue);
mapData.Pointers.push_back(origValue);
mapData.IsDeclareTarget.push_back(false);
mapData.BaseType.push_back(
moduleTranslation.convertType(mapOp.getVarType()));
mapData.Sizes.push_back(
builder.getInt64(dl.getTypeSize(mapOp.getVarType())));
mapData.MapClause.push_back(mapOp.getOperation());
if (llvm::to_underlying(mapType & mapTypeAlways)) {
// Descriptors are mapped with the ALWAYS flag, since they can get
// rematerialized, so the address of the decriptor for a given object
// may change from one place to another.
mapData.Types.push_back(mapType);
// Technically it's possible for a non-descriptor mapping to have
// both has-device-addr and ALWAYS, so lookup the mapper in case it
// exists.
if (mapOp.getMapperId()) {
mapData.Mappers.push_back(
SymbolTable::lookupNearestSymbolFrom<omp::DeclareMapperOp>(
mapOp, mapOp.getMapperIdAttr()));
} else {
mapData.Mappers.push_back(nullptr);
}
} else {
// For is_device_ptr we need the map type to propagate so the runtime
// can materialize the device-side copy of the pointer container.
mapData.Types.push_back(
isDevicePtr ? mapType
: llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL);
mapData.Mappers.push_back(nullptr);
}
mapData.Names.push_back(LLVM::createMappingInformation(
mapOp.getLoc(), *moduleTranslation.getOpenMPBuilder()));
mapData.DevicePointers.push_back(
isDevicePtr ? llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer
: llvm::OpenMPIRBuilder::DeviceInfoTy::Address);
mapData.IsAMapping.push_back(false);
mapData.IsAMember.push_back(checkIsAMember(hasDevAddrOperands, mapOp));
}
}
static int getMapDataMemberIdx(MapInfoData &mapData, omp::MapInfoOp memberOp) {
auto *res = llvm::find(mapData.MapClause, memberOp);
assert(res != mapData.MapClause.end() &&
"MapInfoOp for member not found in MapData, cannot return index");
return std::distance(mapData.MapClause.begin(), res);
}
static void sortMapIndices(llvm::SmallVectorImpl<size_t> &indices,
omp::MapInfoOp mapInfo) {
ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
llvm::SmallVector<size_t> occludedChildren;
llvm::sort(
indices.begin(), indices.end(), [&](const size_t a, const size_t b) {
// Bail early if we are asked to look at the same index. If we do not
// bail early, we can end up mistakenly adding indices to
// occludedChildren. This can occur with some types of libc++ hardening.
if (a == b)
return false;
auto memberIndicesA = cast<ArrayAttr>(indexAttr[a]);
auto memberIndicesB = cast<ArrayAttr>(indexAttr[b]);
for (auto it : llvm::zip(memberIndicesA, memberIndicesB)) {
int64_t aIndex = mlir::cast<IntegerAttr>(std::get<0>(it)).getInt();
int64_t bIndex = mlir::cast<IntegerAttr>(std::get<1>(it)).getInt();
if (aIndex == bIndex)
continue;
if (aIndex < bIndex)
return true;
if (aIndex > bIndex)
return false;
}
// Iterated up until the end of the smallest member and
// they were found to be equal up to that point, so select
// the member with the lowest index count, so the "parent"
bool memberAParent = memberIndicesA.size() < memberIndicesB.size();
if (memberAParent)
occludedChildren.push_back(b);
else
occludedChildren.push_back(a);
return memberAParent;
});
// We remove children from the index list that are overshadowed by
// a parent, this prevents us retrieving these as the first or last
// element when the parent is the correct element in these cases.
for (auto v : occludedChildren)
indices.erase(std::remove(indices.begin(), indices.end(), v),
indices.end());
}
static omp::MapInfoOp getFirstOrLastMappedMemberPtr(omp::MapInfoOp mapInfo,
bool first) {
ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
// Only 1 member has been mapped, we can return it.
if (indexAttr.size() == 1)
return cast<omp::MapInfoOp>(mapInfo.getMembers()[0].getDefiningOp());
llvm::SmallVector<size_t> indices(indexAttr.size());
std::iota(indices.begin(), indices.end(), 0);
sortMapIndices(indices, mapInfo);
return llvm::cast<omp::MapInfoOp>(
mapInfo.getMembers()[first ? indices.front() : indices.back()]
.getDefiningOp());
}
/// This function calculates the array/pointer offset for map data provided
/// with bounds operations, e.g. when provided something like the following:
///
/// Fortran
/// map(tofrom: array(2:5, 3:2))
///
/// We must calculate the initial pointer offset to pass across, this function
/// performs this using bounds.
///
/// TODO/WARNING: This only supports Fortran's column major indexing currently
/// as is noted in the note below and comments in the function, we must extend
/// this function when we add a C++ frontend.
/// NOTE: which while specified in row-major order it currently needs to be
/// flipped for Fortran's column order array allocation and access (as
/// opposed to C++'s row-major, hence the backwards processing where order is
/// important). This is likely important to keep in mind for the future when
/// we incorporate a C++ frontend, both frontends will need to agree on the
/// ordering of generated bounds operations (one may have to flip them) to
/// make the below lowering frontend agnostic. The offload size
/// calcualtion may also have to be adjusted for C++.
static std::vector<llvm::Value *>
calculateBoundsOffset(LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase &builder, bool isArrayTy,
OperandRange bounds) {
std::vector<llvm::Value *> idx;
// There's no bounds to calculate an offset from, we can safely
// ignore and return no indices.
if (bounds.empty())
return idx;
// If we have an array type, then we have its type so can treat it as a
// normal GEP instruction where the bounds operations are simply indexes
// into the array. We currently do reverse order of the bounds, which
// I believe leans more towards Fortran's column-major in memory.
if (isArrayTy) {
idx.push_back(builder.getInt64(0));
for (int i = bounds.size() - 1; i >= 0; --i) {
if (auto boundOp = dyn_cast_if_present<omp::MapBoundsOp>(
bounds[i].getDefiningOp())) {
idx.push_back(moduleTranslation.lookupValue(boundOp.getLowerBound()));
}
}
} else {
// If we do not have an array type, but we have bounds, then we're dealing
// with a pointer that's being treated like an array and we have the
// underlying type e.g. an i32, or f64 etc, e.g. a fortran descriptor base
// address (pointer pointing to the actual data) so we must caclulate the
// offset using a single index which the following loop attempts to
// compute using the standard column-major algorithm e.g for a 3D array:
//
// ((((c_idx * b_len) + b_idx) * a_len) + a_idx)
//
// It is of note that it's doing column-major rather than row-major at the
// moment, but having a way for the frontend to indicate which major format
// to use or standardizing/canonicalizing the order of the bounds to compute
// the offset may be useful in the future when there's other frontends with
// different formats.
std::vector<llvm::Value *> dimensionIndexSizeOffset;
for (int i = bounds.size() - 1; i >= 0; --i) {
if (auto boundOp = dyn_cast_if_present<omp::MapBoundsOp>(
bounds[i].getDefiningOp())) {
if (i == ((int)bounds.size() - 1))
idx.emplace_back(
moduleTranslation.lookupValue(boundOp.getLowerBound()));
else
idx.back() = builder.CreateAdd(
builder.CreateMul(idx.back(), moduleTranslation.lookupValue(
boundOp.getExtent())),
moduleTranslation.lookupValue(boundOp.getLowerBound()));
}
}
}
return idx;
}
static void getAsIntegers(ArrayAttr values, llvm::SmallVector<int64_t> &ints) {
llvm::transform(values, std::back_inserter(ints), [](Attribute value) {
return cast<IntegerAttr>(value).getInt();
});
}
// Gathers members that are overlapping in the parent, excluding members that
// themselves overlap, keeping the top-most (closest to parents level) map.
static void
getOverlappedMembers(llvm::SmallVectorImpl<size_t> &overlapMapDataIdxs,
omp::MapInfoOp parentOp) {
// No members mapped, no overlaps.
if (parentOp.getMembers().empty())
return;
// Single member, we can insert and return early.
if (parentOp.getMembers().size() == 1) {
overlapMapDataIdxs.push_back(0);
return;
}
// 1) collect list of top-level overlapping members from MemberOp
llvm::SmallVector<std::pair<int, ArrayAttr>> memberByIndex;
ArrayAttr indexAttr = parentOp.getMembersIndexAttr();
for (auto [memIndex, indicesAttr] : llvm::enumerate(indexAttr))
memberByIndex.push_back(
std::make_pair(memIndex, cast<ArrayAttr>(indicesAttr)));
// Sort the smallest first (higher up the parent -> member chain), so that
// when we remove members, we remove as much as we can in the initial
// iterations, shortening the number of passes required.
llvm::sort(memberByIndex.begin(), memberByIndex.end(),
[&](auto a, auto b) { return a.second.size() < b.second.size(); });
// Remove elements from the vector if there is a parent element that
// supersedes it. i.e. if member [0] is mapped, we can remove members [0,1],
// [0,2].. etc.
llvm::SmallVector<std::pair<int, ArrayAttr>> skipList;
for (auto v : memberByIndex) {
llvm::SmallVector<int64_t> vArr(v.second.size());
getAsIntegers(v.second, vArr);
skipList.push_back(
*std::find_if(memberByIndex.begin(), memberByIndex.end(), [&](auto x) {
if (v == x)
return false;
llvm::SmallVector<int64_t> xArr(x.second.size());
getAsIntegers(x.second, xArr);
return std::equal(vArr.begin(), vArr.end(), xArr.begin()) &&
xArr.size() >= vArr.size();
}));
}
// Collect the indices, as we need the base pointer etc. from the MapData
// structure which is primarily accessible via index at the moment.
for (auto v : memberByIndex)
if (find(skipList.begin(), skipList.end(), v) == skipList.end())
overlapMapDataIdxs.push_back(v.first);
}
// The intent is to verify if the mapped data being passed is a
// pointer -> pointee that requires special handling in certain cases,
// e.g. applying the OMP_MAP_PTR_AND_OBJ map type.
//
// There may be a better way to verify this, but unfortunately with
// opaque pointers we lose the ability to easily check if something is
// a pointer whilst maintaining access to the underlying type.
static bool checkIfPointerMap(omp::MapInfoOp mapOp) {
// If we have a varPtrPtr field assigned then the underlying type is a pointer
if (mapOp.getVarPtrPtr())
return true;
// If the map data is declare target with a link clause, then it's represented
// as a pointer when we lower it to LLVM-IR even if at the MLIR level it has
// no relation to pointers.
if (isDeclareTargetLink(mapOp.getVarPtr()))
return true;
return false;
}
// This creates two insertions into the MapInfosTy data structure for the
// "parent" of a set of members, (usually a container e.g.
// class/structure/derived type) when subsequent members have also been
// explicitly mapped on the same map clause. Certain types, such as Fortran
// descriptors are mapped like this as well, however, the members are
// implicit as far as a user is concerned, but we must explicitly map them
// internally.
//
// This function also returns the memberOfFlag for this particular parent,
// which is utilised in subsequent member mappings (by modifying there map type
// with it) to indicate that a member is part of this parent and should be
// treated by the runtime as such. Important to achieve the correct mapping.
//
// This function borrows a lot from Clang's emitCombinedEntry function
// inside of CGOpenMPRuntime.cpp
static llvm::omp::OpenMPOffloadMappingFlags mapParentWithMembers(
LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder,
llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo,
MapInfoData &mapData, uint64_t mapDataIndex,
TargetDirectiveEnumTy targetDirective) {
assert(!ompBuilder.Config.isTargetDevice() &&
"function only supported for host device codegen");
auto parentClause =
llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
auto *parentMapper = mapData.Mappers[mapDataIndex];
// Map the first segment of the parent. If a user-defined mapper is attached,
// include the parent's to/from-style bits (and common modifiers) in this
// base entry so the mapper receives correct copy semantics via its 'type'
// parameter. Also keep TARGET_PARAM when required for kernel arguments.
llvm::omp::OpenMPOffloadMappingFlags baseFlag =
(targetDirective == TargetDirectiveEnumTy::Target &&
!mapData.IsDeclareTarget[mapDataIndex])
? llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM
: llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
if (parentMapper) {
using mapFlags = llvm::omp::OpenMPOffloadMappingFlags;
// Preserve relevant map-type bits from the parent clause. These include
// the copy direction (TO/FROM), as well as commonly used modifiers that
// should be visible to the mapper for correct behaviour.
mapFlags parentFlags = mapData.Types[mapDataIndex];
mapFlags preserve = mapFlags::OMP_MAP_TO | mapFlags::OMP_MAP_FROM |
mapFlags::OMP_MAP_ALWAYS | mapFlags::OMP_MAP_CLOSE |
mapFlags::OMP_MAP_PRESENT | mapFlags::OMP_MAP_OMPX_HOLD;
baseFlag |= (parentFlags & preserve);
}
combinedInfo.Types.emplace_back(baseFlag);
combinedInfo.DevicePointers.emplace_back(
mapData.DevicePointers[mapDataIndex]);
// Only attach the mapper to the base entry when we are mapping the whole
// parent. Combined/segment entries must not carry a mapper; otherwise the
// mapper can be invoked with a partial size, which is undefined behaviour.
combinedInfo.Mappers.emplace_back(
parentMapper && !parentClause.getPartialMap() ? parentMapper : nullptr);
combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder));
combinedInfo.BasePointers.emplace_back(mapData.BasePointers[mapDataIndex]);
// Calculate size of the parent object being mapped based on the
// addresses at runtime, highAddr - lowAddr = size. This of course
// doesn't factor in allocated data like pointers, hence the further
// processing of members specified by users, or in the case of
// Fortran pointers and allocatables, the mapping of the pointed to
// data by the descriptor (which itself, is a structure containing
// runtime information on the dynamically allocated data).
llvm::Value *lowAddr, *highAddr;
if (!parentClause.getPartialMap()) {
lowAddr = builder.CreatePointerCast(mapData.Pointers[mapDataIndex],
builder.getPtrTy());
highAddr = builder.CreatePointerCast(
builder.CreateConstGEP1_32(mapData.BaseType[mapDataIndex],
mapData.Pointers[mapDataIndex], 1),
builder.getPtrTy());
combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIndex]);
} else {
auto mapOp = dyn_cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
int firstMemberIdx = getMapDataMemberIdx(
mapData, getFirstOrLastMappedMemberPtr(mapOp, true));
lowAddr = builder.CreatePointerCast(mapData.Pointers[firstMemberIdx],
builder.getPtrTy());
int lastMemberIdx = getMapDataMemberIdx(
mapData, getFirstOrLastMappedMemberPtr(mapOp, false));
highAddr = builder.CreatePointerCast(
builder.CreateGEP(mapData.BaseType[lastMemberIdx],
mapData.Pointers[lastMemberIdx], builder.getInt64(1)),
builder.getPtrTy());
combinedInfo.Pointers.emplace_back(mapData.Pointers[firstMemberIdx]);
}
llvm::Value *size = builder.CreateIntCast(
builder.CreatePtrDiff(builder.getInt8Ty(), highAddr, lowAddr),
builder.getInt64Ty(),
/*isSigned=*/false);
combinedInfo.Sizes.push_back(size);
llvm::omp::OpenMPOffloadMappingFlags memberOfFlag =
ompBuilder.getMemberOfFlag(combinedInfo.BasePointers.size() - 1);
// This creates the initial MEMBER_OF mapping that consists of
// the parent/top level container (same as above effectively, except
// with a fixed initial compile time size and separate maptype which
// indicates the true mape type (tofrom etc.). This parent mapping is
// only relevant if the structure in its totality is being mapped,
// otherwise the above suffices.
if (!parentClause.getPartialMap()) {
// TODO: This will need to be expanded to include the whole host of logic
// for the map flags that Clang currently supports (e.g. it should do some
// further case specific flag modifications). For the moment, it handles
// what we support as expected.
llvm::omp::OpenMPOffloadMappingFlags mapFlag = mapData.Types[mapDataIndex];
bool hasMapClose = (llvm::omp::OpenMPOffloadMappingFlags(mapFlag) &
llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_CLOSE) ==
llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_CLOSE;
ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
if (targetDirective == TargetDirectiveEnumTy::TargetUpdate || hasMapClose) {
combinedInfo.Types.emplace_back(mapFlag);
combinedInfo.DevicePointers.emplace_back(
mapData.DevicePointers[mapDataIndex]);
combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder));
combinedInfo.BasePointers.emplace_back(
mapData.BasePointers[mapDataIndex]);
combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIndex]);
combinedInfo.Sizes.emplace_back(mapData.Sizes[mapDataIndex]);
combinedInfo.Mappers.emplace_back(nullptr);
} else {
llvm::SmallVector<size_t> overlapIdxs;
// Find all of the members that "overlap", i.e. occlude other members that
// were mapped alongside the parent, e.g. member [0], occludes [0,1] and
// [0,2], but not [1,0].
getOverlappedMembers(overlapIdxs, parentClause);
// We need to make sure the overlapped members are sorted in order of
// lowest address to highest address.
sortMapIndices(overlapIdxs, parentClause);
lowAddr = builder.CreatePointerCast(mapData.Pointers[mapDataIndex],
builder.getPtrTy());
highAddr = builder.CreatePointerCast(
builder.CreateConstGEP1_32(mapData.BaseType[mapDataIndex],
mapData.Pointers[mapDataIndex], 1),
builder.getPtrTy());
// TODO: We may want to skip arrays/array sections in this as Clang does.
// It appears to be an optimisation rather than a necessity though,
// but this requires further investigation. However, we would have to make
// sure to not exclude maps with bounds that ARE pointers, as these are
// processed as separate components, i.e. pointer + data.
for (auto v : overlapIdxs) {
auto mapDataOverlapIdx = getMapDataMemberIdx(
mapData,
cast<omp::MapInfoOp>(parentClause.getMembers()[v].getDefiningOp()));
combinedInfo.Types.emplace_back(mapFlag);
combinedInfo.DevicePointers.emplace_back(
mapData.DevicePointers[mapDataOverlapIdx]);
combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder));
combinedInfo.BasePointers.emplace_back(
mapData.BasePointers[mapDataIndex]);
combinedInfo.Mappers.emplace_back(nullptr);
combinedInfo.Pointers.emplace_back(lowAddr);
combinedInfo.Sizes.emplace_back(builder.CreateIntCast(
builder.CreatePtrDiff(builder.getInt8Ty(),
mapData.OriginalValue[mapDataOverlapIdx],
lowAddr),
builder.getInt64Ty(), /*isSigned=*/true));
lowAddr = builder.CreateConstGEP1_32(
checkIfPointerMap(llvm::cast<omp::MapInfoOp>(
mapData.MapClause[mapDataOverlapIdx]))
? builder.getPtrTy()
: mapData.BaseType[mapDataOverlapIdx],
mapData.BasePointers[mapDataOverlapIdx], 1);
}
combinedInfo.Types.emplace_back(mapFlag);
combinedInfo.DevicePointers.emplace_back(
mapData.DevicePointers[mapDataIndex]);
combinedInfo.Names.emplace_back(LLVM::createMappingInformation(
mapData.MapClause[mapDataIndex]->getLoc(), ompBuilder));
combinedInfo.BasePointers.emplace_back(
mapData.BasePointers[mapDataIndex]);
combinedInfo.Mappers.emplace_back(nullptr);
combinedInfo.Pointers.emplace_back(lowAddr);
combinedInfo.Sizes.emplace_back(builder.CreateIntCast(
builder.CreatePtrDiff(builder.getInt8Ty(), highAddr, lowAddr),
builder.getInt64Ty(), true));
}
}
return memberOfFlag;
}
// This function is intended to add explicit mappings of members
static void processMapMembersWithParent(
LLVM::ModuleTranslation &moduleTranslation, llvm::IRBuilderBase &builder,
llvm::OpenMPIRBuilder &ompBuilder, DataLayout &dl, MapInfosTy &combinedInfo,
MapInfoData &mapData, uint64_t mapDataIndex,
llvm::omp::OpenMPOffloadMappingFlags memberOfFlag,
TargetDirectiveEnumTy targetDirective) {
assert(!ompBuilder.Config.isTargetDevice() &&
"function only supported for host device codegen");
auto parentClause =
llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
for (auto mappedMembers : parentClause.getMembers()) {
auto memberClause =
llvm::cast<omp::MapInfoOp>(mappedMembers.getDefiningOp());
int memberDataIdx = getMapDataMemberIdx(mapData, memberClause);
assert(memberDataIdx >= 0 && "could not find mapped member of structure");
// If we're currently mapping a pointer to a block of data, we must
// initially map the pointer, and then attatch/bind the data with a
// subsequent map to the pointer. This segment of code generates the
// pointer mapping, which can in certain cases be optimised out as Clang
// currently does in its lowering. However, for the moment we do not do so,
// in part as we currently have substantially less information on the data
// being mapped at this stage.
if (checkIfPointerMap(memberClause)) {
auto mapFlag = convertClauseMapFlags(memberClause.getMapType());
mapFlag &= ~llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
combinedInfo.Types.emplace_back(mapFlag);
combinedInfo.DevicePointers.emplace_back(
llvm::OpenMPIRBuilder::DeviceInfoTy::None);
combinedInfo.Mappers.emplace_back(nullptr);
combinedInfo.Names.emplace_back(
LLVM::createMappingInformation(memberClause.getLoc(), ompBuilder));
combinedInfo.BasePointers.emplace_back(
mapData.BasePointers[mapDataIndex]);
combinedInfo.Pointers.emplace_back(mapData.BasePointers[memberDataIdx]);
combinedInfo.Sizes.emplace_back(builder.getInt64(
moduleTranslation.getLLVMModule()->getDataLayout().getPointerSize()));
}
// Same MemberOfFlag to indicate its link with parent and other members
// of.
auto mapFlag = convertClauseMapFlags(memberClause.getMapType());
mapFlag &= ~llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_MEMBER_OF;
ompBuilder.setCorrectMemberOfFlag(mapFlag, memberOfFlag);
bool isDeclTargetTo = isDeclareTargetTo(parentClause.getVarPtr()
? parentClause.getVarPtr()
: parentClause.getVarPtrPtr());
if (checkIfPointerMap(memberClause) &&
(!isDeclTargetTo ||
(targetDirective != TargetDirectiveEnumTy::TargetUpdate &&
targetDirective != TargetDirectiveEnumTy::TargetData))) {
mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ;
}
combinedInfo.Types.emplace_back(mapFlag);
combinedInfo.DevicePointers.emplace_back(
mapData.DevicePointers[memberDataIdx]);
combinedInfo.Mappers.emplace_back(mapData.Mappers[memberDataIdx]);
combinedInfo.Names.emplace_back(
LLVM::createMappingInformation(memberClause.getLoc(), ompBuilder));
uint64_t basePointerIndex =
checkIfPointerMap(memberClause) ? memberDataIdx : mapDataIndex;
combinedInfo.BasePointers.emplace_back(
mapData.BasePointers[basePointerIndex]);
combinedInfo.Pointers.emplace_back(mapData.Pointers[memberDataIdx]);
llvm::Value *size = mapData.Sizes[memberDataIdx];
if (checkIfPointerMap(memberClause)) {
size = builder.CreateSelect(
builder.CreateIsNull(mapData.Pointers[memberDataIdx]),
builder.getInt64(0), size);
}
combinedInfo.Sizes.emplace_back(size);
}
}
static void processIndividualMap(MapInfoData &mapData, size_t mapDataIdx,
MapInfosTy &combinedInfo,
TargetDirectiveEnumTy targetDirective,
int mapDataParentIdx = -1) {
// Declare Target Mappings are excluded from being marked as
// OMP_MAP_TARGET_PARAM as they are not passed as parameters, they're
// marked with OMP_MAP_PTR_AND_OBJ instead.
auto mapFlag = mapData.Types[mapDataIdx];
auto mapInfoOp = llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIdx]);
bool isPtrTy = checkIfPointerMap(mapInfoOp);
if (isPtrTy)
mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_PTR_AND_OBJ;
if (targetDirective == TargetDirectiveEnumTy::Target &&
!mapData.IsDeclareTarget[mapDataIdx])
mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TARGET_PARAM;
if (mapInfoOp.getMapCaptureType() == omp::VariableCaptureKind::ByCopy &&
!isPtrTy)
mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_LITERAL;
// if we're provided a mapDataParentIdx, then the data being mapped is
// part of a larger object (in a parent <-> member mapping) and in this
// case our BasePointer should be the parent.
if (mapDataParentIdx >= 0)
combinedInfo.BasePointers.emplace_back(
mapData.BasePointers[mapDataParentIdx]);
else
combinedInfo.BasePointers.emplace_back(mapData.BasePointers[mapDataIdx]);
combinedInfo.Pointers.emplace_back(mapData.Pointers[mapDataIdx]);
combinedInfo.DevicePointers.emplace_back(mapData.DevicePointers[mapDataIdx]);
combinedInfo.Mappers.emplace_back(mapData.Mappers[mapDataIdx]);
combinedInfo.Names.emplace_back(mapData.Names[mapDataIdx]);
combinedInfo.Types.emplace_back(mapFlag);
combinedInfo.Sizes.emplace_back(mapData.Sizes[mapDataIdx]);
}
static void processMapWithMembersOf(LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase &builder,
llvm::OpenMPIRBuilder &ompBuilder,
DataLayout &dl, MapInfosTy &combinedInfo,
MapInfoData &mapData, uint64_t mapDataIndex,
TargetDirectiveEnumTy targetDirective) {
assert(!ompBuilder.Config.isTargetDevice() &&
"function only supported for host device codegen");
auto parentClause =
llvm::cast<omp::MapInfoOp>(mapData.MapClause[mapDataIndex]);
// If we have a partial map (no parent referenced in the map clauses of the
// directive, only members) and only a single member, we do not need to bind
// the map of the member to the parent, we can pass the member separately.
if (parentClause.getMembers().size() == 1 && parentClause.getPartialMap()) {
auto memberClause = llvm::cast<omp::MapInfoOp>(
parentClause.getMembers()[0].getDefiningOp());
int memberDataIdx = getMapDataMemberIdx(mapData, memberClause);
// Note: Clang treats arrays with explicit bounds that fall into this
// category as a parent with map case, however, it seems this isn't a
// requirement, and processing them as an individual map is fine. So,
// we will handle them as individual maps for the moment, as it's
// difficult for us to check this as we always require bounds to be
// specified currently and it's also marginally more optimal (single
// map rather than two). The difference may come from the fact that
// Clang maps array without bounds as pointers (which we do not
// currently do), whereas we treat them as arrays in all cases
// currently.
processIndividualMap(mapData, memberDataIdx, combinedInfo, targetDirective,
mapDataIndex);
return;
}
llvm::omp::OpenMPOffloadMappingFlags memberOfParentFlag =
mapParentWithMembers(moduleTranslation, builder, ompBuilder, dl,
combinedInfo, mapData, mapDataIndex,
targetDirective);
processMapMembersWithParent(moduleTranslation, builder, ompBuilder, dl,
combinedInfo, mapData, mapDataIndex,
memberOfParentFlag, targetDirective);
}
// This is a variation on Clang's GenerateOpenMPCapturedVars, which
// generates different operation (e.g. load/store) combinations for
// arguments to the kernel, based on map capture kinds which are then
// utilised in the combinedInfo in place of the original Map value.
static void
createAlteredByCaptureMap(MapInfoData &mapData,
LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase &builder) {
assert(!moduleTranslation.getOpenMPBuilder()->Config.isTargetDevice() &&
"function only supported for host device codegen");
for (size_t i = 0; i < mapData.MapClause.size(); ++i) {
// if it's declare target, skip it, it's handled separately.
if (!mapData.IsDeclareTarget[i]) {
auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
omp::VariableCaptureKind captureKind = mapOp.getMapCaptureType();
bool isPtrTy = checkIfPointerMap(mapOp);
// Currently handles array sectioning lowerbound case, but more
// logic may be required in the future. Clang invokes EmitLValue,
// which has specialised logic for special Clang types such as user
// defines, so it is possible we will have to extend this for
// structures or other complex types. As the general idea is that this
// function mimics some of the logic from Clang that we require for
// kernel argument passing from host -> device.
switch (captureKind) {
case omp::VariableCaptureKind::ByRef: {
llvm::Value *newV = mapData.Pointers[i];
std::vector<llvm::Value *> offsetIdx = calculateBoundsOffset(
moduleTranslation, builder, mapData.BaseType[i]->isArrayTy(),
mapOp.getBounds());
if (isPtrTy)
newV = builder.CreateLoad(builder.getPtrTy(), newV);
if (!offsetIdx.empty())
newV = builder.CreateInBoundsGEP(mapData.BaseType[i], newV, offsetIdx,
"array_offset");
mapData.Pointers[i] = newV;
} break;
case omp::VariableCaptureKind::ByCopy: {
llvm::Type *type = mapData.BaseType[i];
llvm::Value *newV;
if (mapData.Pointers[i]->getType()->isPointerTy())
newV = builder.CreateLoad(type, mapData.Pointers[i]);
else
newV = mapData.Pointers[i];
if (!isPtrTy) {
auto curInsert = builder.saveIP();
llvm::DebugLoc DbgLoc = builder.getCurrentDebugLocation();
builder.restoreIP(findAllocaInsertPoint(builder, moduleTranslation));
auto *memTempAlloc =
builder.CreateAlloca(builder.getPtrTy(), nullptr, ".casted");
builder.SetCurrentDebugLocation(DbgLoc);
builder.restoreIP(curInsert);
builder.CreateStore(newV, memTempAlloc);
newV = builder.CreateLoad(builder.getPtrTy(), memTempAlloc);
}
mapData.Pointers[i] = newV;
mapData.BasePointers[i] = newV;
} break;
case omp::VariableCaptureKind::This:
case omp::VariableCaptureKind::VLAType:
mapData.MapClause[i]->emitOpError("Unhandled capture kind");
break;
}
}
}
}
// Generate all map related information and fill the combinedInfo.
static void genMapInfos(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
DataLayout &dl, MapInfosTy &combinedInfo,
MapInfoData &mapData,
TargetDirectiveEnumTy targetDirective) {
assert(!moduleTranslation.getOpenMPBuilder()->Config.isTargetDevice() &&
"function only supported for host device codegen");
// We wish to modify some of the methods in which arguments are
// passed based on their capture type by the target region, this can
// involve generating new loads and stores, which changes the
// MLIR value to LLVM value mapping, however, we only wish to do this
// locally for the current function/target and also avoid altering
// ModuleTranslation, so we remap the base pointer or pointer stored
// in the map infos corresponding MapInfoData, which is later accessed
// by genMapInfos and createTarget to help generate the kernel and
// kernel arg structure. It primarily becomes relevant in cases like
// bycopy, or byref range'd arrays. In the default case, we simply
// pass thee pointer byref as both basePointer and pointer.
createAlteredByCaptureMap(mapData, moduleTranslation, builder);
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
// We operate under the assumption that all vectors that are
// required in MapInfoData are of equal lengths (either filled with
// default constructed data or appropiate information) so we can
// utilise the size from any component of MapInfoData, if we can't
// something is missing from the initial MapInfoData construction.
for (size_t i = 0; i < mapData.MapClause.size(); ++i) {
// NOTE/TODO: We currently do not support arbitrary depth record
// type mapping.
if (mapData.IsAMember[i])
continue;
auto mapInfoOp = dyn_cast<omp::MapInfoOp>(mapData.MapClause[i]);
if (!mapInfoOp.getMembers().empty()) {
processMapWithMembersOf(moduleTranslation, builder, *ompBuilder, dl,
combinedInfo, mapData, i, targetDirective);
continue;
}
processIndividualMap(mapData, i, combinedInfo, targetDirective);
}
}
static llvm::Expected<llvm::Function *>
emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::StringRef mapperFuncName,
TargetDirectiveEnumTy targetDirective);
static llvm::Expected<llvm::Function *>
getOrCreateUserDefinedMapperFunc(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
TargetDirectiveEnumTy targetDirective) {
assert(!moduleTranslation.getOpenMPBuilder()->Config.isTargetDevice() &&
"function only supported for host device codegen");
auto declMapperOp = cast<omp::DeclareMapperOp>(op);
std::string mapperFuncName =
moduleTranslation.getOpenMPBuilder()->createPlatformSpecificName(
{"omp_mapper", declMapperOp.getSymName()});
if (auto *lookupFunc = moduleTranslation.lookupFunction(mapperFuncName))
return lookupFunc;
// Recursive types can cause re-entrant mapper emission. The mapper function
// is created by OpenMPIRBuilder before the callbacks run, so it may already
// exist in the LLVM module even though it is not yet registered in the
// ModuleTranslation mapping table. Reuse and register it to break the
// recursion.
if (llvm::Function *existingFunc =
moduleTranslation.getLLVMModule()->getFunction(mapperFuncName)) {
moduleTranslation.mapFunction(mapperFuncName, existingFunc);
return existingFunc;
}
return emitUserDefinedMapper(declMapperOp, builder, moduleTranslation,
mapperFuncName, targetDirective);
}
static llvm::Expected<llvm::Function *>
emitUserDefinedMapper(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::StringRef mapperFuncName,
TargetDirectiveEnumTy targetDirective) {
assert(!moduleTranslation.getOpenMPBuilder()->Config.isTargetDevice() &&
"function only supported for host device codegen");
auto declMapperOp = cast<omp::DeclareMapperOp>(op);
auto declMapperInfoOp = declMapperOp.getDeclareMapperInfo();
DataLayout dl = DataLayout(declMapperOp->getParentOfType<ModuleOp>());
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::Type *varType = moduleTranslation.convertType(declMapperOp.getType());
SmallVector<Value> mapVars = declMapperInfoOp.getMapVars();
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
// Fill up the arrays with all the mapped variables.
MapInfosTy combinedInfo;
auto genMapInfoCB =
[&](InsertPointTy codeGenIP, llvm::Value *ptrPHI,
llvm::Value *unused2) -> llvm::OpenMPIRBuilder::MapInfosOrErrorTy {
builder.restoreIP(codeGenIP);
moduleTranslation.mapValue(declMapperOp.getSymVal(), ptrPHI);
moduleTranslation.mapBlock(&declMapperOp.getRegion().front(),
builder.GetInsertBlock());
if (failed(moduleTranslation.convertBlock(declMapperOp.getRegion().front(),
/*ignoreArguments=*/true,
builder)))
return llvm::make_error<PreviouslyReportedError>();
MapInfoData mapData;
collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, dl,
builder);
genMapInfos(builder, moduleTranslation, dl, combinedInfo, mapData,
targetDirective);
// Drop the mapping that is no longer necessary so that the same region
// can be processed multiple times.
moduleTranslation.forgetMapping(declMapperOp.getRegion());
return combinedInfo;
};
auto customMapperCB = [&](unsigned i) -> llvm::Expected<llvm::Function *> {
if (!combinedInfo.Mappers[i])
return nullptr;
return getOrCreateUserDefinedMapperFunc(combinedInfo.Mappers[i], builder,
moduleTranslation, targetDirective);
};
llvm::Expected<llvm::Function *> newFn = ompBuilder->emitUserDefinedMapper(
genMapInfoCB, varType, mapperFuncName, customMapperCB);
if (!newFn)
return newFn.takeError();
if (llvm::Function *mappedFunc =
moduleTranslation.lookupFunction(mapperFuncName)) {
assert(mappedFunc == *newFn &&
"mapper function mapping disagrees with emitted function");
} else {
moduleTranslation.mapFunction(mapperFuncName, *newFn);
}
return *newFn;
}
static LogicalResult
convertOmpTargetData(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *ifCond = nullptr;
llvm::Value *deviceID = builder.getInt64(llvm::omp::OMP_DEVICEID_UNDEF);
SmallVector<Value> mapVars;
SmallVector<Value> useDevicePtrVars;
SmallVector<Value> useDeviceAddrVars;
llvm::omp::RuntimeFunction RTLFn;
DataLayout DL = DataLayout(op->getParentOfType<ModuleOp>());
TargetDirectiveEnumTy targetDirective = getTargetDirectiveEnumTyFromOp(op);
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::TargetDataInfo info(
/*RequiresDevicePointerInfo=*/true,
/*SeparateBeginEndCalls=*/true);
assert(!ompBuilder->Config.isTargetDevice() &&
"target data/enter/exit/update are host ops");
bool isOffloadEntry = !ompBuilder->Config.TargetTriples.empty();
auto getDeviceID = [&](mlir::Value dev) -> llvm::Value * {
llvm::Value *v = moduleTranslation.lookupValue(dev);
return builder.CreateIntCast(v, builder.getInt64Ty(), /*isSigned=*/true);
};
LogicalResult result =
llvm::TypeSwitch<Operation *, LogicalResult>(op)
.Case([&](omp::TargetDataOp dataOp) {
if (failed(checkImplementationStatus(*dataOp)))
return failure();
if (auto ifVar = dataOp.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
if (mlir::Value devId = dataOp.getDevice())
deviceID = getDeviceID(devId);
mapVars = dataOp.getMapVars();
useDevicePtrVars = dataOp.getUseDevicePtrVars();
useDeviceAddrVars = dataOp.getUseDeviceAddrVars();
return success();
})
.Case([&](omp::TargetEnterDataOp enterDataOp) -> LogicalResult {
if (failed(checkImplementationStatus(*enterDataOp)))
return failure();
if (auto ifVar = enterDataOp.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
if (mlir::Value devId = enterDataOp.getDevice())
deviceID = getDeviceID(devId);
RTLFn =
enterDataOp.getNowait()
? llvm::omp::OMPRTL___tgt_target_data_begin_nowait_mapper
: llvm::omp::OMPRTL___tgt_target_data_begin_mapper;
mapVars = enterDataOp.getMapVars();
info.HasNoWait = enterDataOp.getNowait();
return success();
})
.Case([&](omp::TargetExitDataOp exitDataOp) -> LogicalResult {
if (failed(checkImplementationStatus(*exitDataOp)))
return failure();
if (auto ifVar = exitDataOp.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
if (mlir::Value devId = exitDataOp.getDevice())
deviceID = getDeviceID(devId);
RTLFn = exitDataOp.getNowait()
? llvm::omp::OMPRTL___tgt_target_data_end_nowait_mapper
: llvm::omp::OMPRTL___tgt_target_data_end_mapper;
mapVars = exitDataOp.getMapVars();
info.HasNoWait = exitDataOp.getNowait();
return success();
})
.Case([&](omp::TargetUpdateOp updateDataOp) -> LogicalResult {
if (failed(checkImplementationStatus(*updateDataOp)))
return failure();
if (auto ifVar = updateDataOp.getIfExpr())
ifCond = moduleTranslation.lookupValue(ifVar);
if (mlir::Value devId = updateDataOp.getDevice())
deviceID = getDeviceID(devId);
RTLFn =
updateDataOp.getNowait()
? llvm::omp::OMPRTL___tgt_target_data_update_nowait_mapper
: llvm::omp::OMPRTL___tgt_target_data_update_mapper;
mapVars = updateDataOp.getMapVars();
info.HasNoWait = updateDataOp.getNowait();
return success();
})
.DefaultUnreachable("unexpected operation");
if (failed(result))
return failure();
// Pretend we have IF(false) if we're not doing offload.
if (!isOffloadEntry)
ifCond = builder.getFalse();
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
MapInfoData mapData;
collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, DL,
builder, useDevicePtrVars, useDeviceAddrVars);
// Fill up the arrays with all the mapped variables.
MapInfosTy combinedInfo;
auto genMapInfoCB = [&](InsertPointTy codeGenIP) -> MapInfosTy & {
builder.restoreIP(codeGenIP);
genMapInfos(builder, moduleTranslation, DL, combinedInfo, mapData,
targetDirective);
return combinedInfo;
};
// Define a lambda to apply mappings between use_device_addr and
// use_device_ptr base pointers, and their associated block arguments.
auto mapUseDevice =
[&moduleTranslation](
llvm::OpenMPIRBuilder::DeviceInfoTy type,
llvm::ArrayRef<BlockArgument> blockArgs,
llvm::SmallVectorImpl<Value> &useDeviceVars, MapInfoData &mapInfoData,
llvm::function_ref<llvm::Value *(llvm::Value *)> mapper = nullptr) {
for (auto [arg, useDevVar] :
llvm::zip_equal(blockArgs, useDeviceVars)) {
auto getMapBasePtr = [](omp::MapInfoOp mapInfoOp) {
return mapInfoOp.getVarPtrPtr() ? mapInfoOp.getVarPtrPtr()
: mapInfoOp.getVarPtr();
};
auto useDevMap = cast<omp::MapInfoOp>(useDevVar.getDefiningOp());
for (auto [mapClause, devicePointer, basePointer] : llvm::zip_equal(
mapInfoData.MapClause, mapInfoData.DevicePointers,
mapInfoData.BasePointers)) {
auto mapOp = cast<omp::MapInfoOp>(mapClause);
if (getMapBasePtr(mapOp) != getMapBasePtr(useDevMap) ||
devicePointer != type)
continue;
if (llvm::Value *devPtrInfoMap =
mapper ? mapper(basePointer) : basePointer) {
moduleTranslation.mapValue(arg, devPtrInfoMap);
break;
}
}
}
};
using BodyGenTy = llvm::OpenMPIRBuilder::BodyGenTy;
auto bodyGenCB = [&](InsertPointTy codeGenIP, BodyGenTy bodyGenType)
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
// We must always restoreIP regardless of doing anything the caller
// does not restore it, leading to incorrect (no) branch generation.
builder.restoreIP(codeGenIP);
assert(isa<omp::TargetDataOp>(op) &&
"BodyGen requested for non TargetDataOp");
auto blockArgIface = cast<omp::BlockArgOpenMPOpInterface>(op);
Region ®ion = cast<omp::TargetDataOp>(op).getRegion();
switch (bodyGenType) {
case BodyGenTy::Priv:
// Check if any device ptr/addr info is available
if (!info.DevicePtrInfoMap.empty()) {
mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Address,
blockArgIface.getUseDeviceAddrBlockArgs(),
useDeviceAddrVars, mapData,
[&](llvm::Value *basePointer) -> llvm::Value * {
if (!info.DevicePtrInfoMap[basePointer].second)
return nullptr;
return builder.CreateLoad(
builder.getPtrTy(),
info.DevicePtrInfoMap[basePointer].second);
});
mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer,
blockArgIface.getUseDevicePtrBlockArgs(), useDevicePtrVars,
mapData, [&](llvm::Value *basePointer) {
return info.DevicePtrInfoMap[basePointer].second;
});
if (failed(inlineConvertOmpRegions(region, "omp.data.region", builder,
moduleTranslation)))
return llvm::make_error<PreviouslyReportedError>();
}
break;
case BodyGenTy::DupNoPriv:
if (info.DevicePtrInfoMap.empty()) {
// For host device we still need to do the mapping for codegen,
// otherwise it may try to lookup a missing value.
mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Address,
blockArgIface.getUseDeviceAddrBlockArgs(),
useDeviceAddrVars, mapData);
mapUseDevice(llvm::OpenMPIRBuilder::DeviceInfoTy::Pointer,
blockArgIface.getUseDevicePtrBlockArgs(), useDevicePtrVars,
mapData);
}
break;
case BodyGenTy::NoPriv:
// If device info is available then region has already been generated
if (info.DevicePtrInfoMap.empty()) {
if (failed(inlineConvertOmpRegions(region, "omp.data.region", builder,
moduleTranslation)))
return llvm::make_error<PreviouslyReportedError>();
}
break;
}
return builder.saveIP();
};
auto customMapperCB =
[&](unsigned int i) -> llvm::Expected<llvm::Function *> {
if (!combinedInfo.Mappers[i])
return nullptr;
info.HasMapper = true;
return getOrCreateUserDefinedMapperFunc(combinedInfo.Mappers[i], builder,
moduleTranslation, targetDirective);
};
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP = [&]() {
if (isa<omp::TargetDataOp>(op))
return ompBuilder->createTargetData(ompLoc, allocaIP, builder.saveIP(),
deviceID, ifCond, info, genMapInfoCB,
customMapperCB,
/*MapperFunc=*/nullptr, bodyGenCB,
/*DeviceAddrCB=*/nullptr);
return ompBuilder->createTargetData(ompLoc, allocaIP, builder.saveIP(),
deviceID, ifCond, info, genMapInfoCB,
customMapperCB, &RTLFn);
}();
if (failed(handleError(afterIP, *op)))
return failure();
builder.restoreIP(*afterIP);
return success();
}
static LogicalResult
convertOmpDistribute(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
auto distributeOp = cast<omp::DistributeOp>(opInst);
if (failed(checkImplementationStatus(opInst)))
return failure();
/// Process teams op reduction in distribute if the reduction is contained in
/// the distribute op.
omp::TeamsOp teamsOp = opInst.getParentOfType<omp::TeamsOp>();
bool doDistributeReduction =
teamsOp ? teamsReductionContainedInDistribute(teamsOp) : false;
DenseMap<Value, llvm::Value *> reductionVariableMap;
unsigned numReductionVars = teamsOp ? teamsOp.getNumReductionVars() : 0;
SmallVector<omp::DeclareReductionOp> reductionDecls;
SmallVector<llvm::Value *> privateReductionVariables(numReductionVars);
llvm::ArrayRef<bool> isByRef;
if (doDistributeReduction) {
isByRef = getIsByRef(teamsOp.getReductionByref());
assert(isByRef.size() == teamsOp.getNumReductionVars());
collectReductionDecls(teamsOp, reductionDecls);
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
MutableArrayRef<BlockArgument> reductionArgs =
llvm::cast<omp::BlockArgOpenMPOpInterface>(*teamsOp)
.getReductionBlockArgs();
if (failed(allocAndInitializeReductionVars(
teamsOp, reductionArgs, builder, moduleTranslation, allocaIP,
reductionDecls, privateReductionVariables, reductionVariableMap,
isByRef)))
return failure();
}
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
auto bodyGenCB = [&](InsertPointTy allocaIP,
InsertPointTy codeGenIP) -> llvm::Error {
// Save the alloca insertion point on ModuleTranslation stack for use in
// nested regions.
LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame(
moduleTranslation, allocaIP);
// DistributeOp has only one region associated with it.
builder.restoreIP(codeGenIP);
PrivateVarsInfo privVarsInfo(distributeOp);
llvm::Expected<llvm::BasicBlock *> afterAllocas =
allocatePrivateVars(builder, moduleTranslation, privVarsInfo, allocaIP);
if (handleError(afterAllocas, opInst).failed())
return llvm::make_error<PreviouslyReportedError>();
if (handleError(initPrivateVars(builder, moduleTranslation, privVarsInfo),
opInst)
.failed())
return llvm::make_error<PreviouslyReportedError>();
if (failed(copyFirstPrivateVars(
distributeOp, builder, moduleTranslation, privVarsInfo.mlirVars,
privVarsInfo.llvmVars, privVarsInfo.privatizers,
distributeOp.getPrivateNeedsBarrier())))
return llvm::make_error<PreviouslyReportedError>();
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::Expected<llvm::BasicBlock *> regionBlock =
convertOmpOpRegions(distributeOp.getRegion(), "omp.distribute.region",
builder, moduleTranslation);
if (!regionBlock)
return regionBlock.takeError();
builder.SetInsertPoint(*regionBlock, (*regionBlock)->begin());
// Skip applying a workshare loop below when translating 'distribute
// parallel do' (it's been already handled by this point while translating
// the nested omp.wsloop).
if (!isa_and_present<omp::WsloopOp>(distributeOp.getNestedWrapper())) {
// TODO: Add support for clauses which are valid for DISTRIBUTE
// constructs. Static schedule is the default.
bool hasDistSchedule = distributeOp.getDistScheduleStatic();
auto schedule = hasDistSchedule ? omp::ClauseScheduleKind::Distribute
: omp::ClauseScheduleKind::Static;
// dist_schedule clauses are ordered - otherise this should be false
bool isOrdered = hasDistSchedule;
std::optional<omp::ScheduleModifier> scheduleMod;
bool isSimd = false;
llvm::omp::WorksharingLoopType workshareLoopType =
llvm::omp::WorksharingLoopType::DistributeStaticLoop;
bool loopNeedsBarrier = false;
llvm::Value *chunk = moduleTranslation.lookupValue(
distributeOp.getDistScheduleChunkSize());
llvm::CanonicalLoopInfo *loopInfo =
findCurrentLoopInfo(moduleTranslation);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy wsloopIP =
ompBuilder->applyWorkshareLoop(
ompLoc.DL, loopInfo, allocaIP, loopNeedsBarrier,
convertToScheduleKind(schedule), chunk, isSimd,
scheduleMod == omp::ScheduleModifier::monotonic,
scheduleMod == omp::ScheduleModifier::nonmonotonic, isOrdered,
workshareLoopType, false, hasDistSchedule, chunk);
if (!wsloopIP)
return wsloopIP.takeError();
}
if (failed(cleanupPrivateVars(builder, moduleTranslation,
distributeOp.getLoc(), privVarsInfo.llvmVars,
privVarsInfo.privatizers)))
return llvm::make_error<PreviouslyReportedError>();
return llvm::Error::success();
};
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createDistribute(ompLoc, allocaIP, bodyGenCB);
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
if (doDistributeReduction) {
// Process the reductions if required.
return createReductionsAndCleanup(
teamsOp, builder, moduleTranslation, allocaIP, reductionDecls,
privateReductionVariables, isByRef,
/*isNoWait*/ false, /*isTeamsReduction*/ true);
}
return success();
}
/// Lowers the FlagsAttr which is applied to the module on the device
/// pass when offloading, this attribute contains OpenMP RTL globals that can
/// be passed as flags to the frontend, otherwise they are set to default
static LogicalResult
convertFlagsAttr(Operation *op, mlir::omp::FlagsAttr attribute,
LLVM::ModuleTranslation &moduleTranslation) {
if (!cast<mlir::ModuleOp>(op))
return failure();
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
ompBuilder->M.addModuleFlag(llvm::Module::Max, "openmp-device",
attribute.getOpenmpDeviceVersion());
if (attribute.getNoGpuLib())
return success();
ompBuilder->createGlobalFlag(
attribute.getDebugKind() /*LangOpts().OpenMPTargetDebug*/,
"__omp_rtl_debug_kind");
ompBuilder->createGlobalFlag(
attribute
.getAssumeTeamsOversubscription() /*LangOpts().OpenMPTeamSubscription*/
,
"__omp_rtl_assume_teams_oversubscription");
ompBuilder->createGlobalFlag(
attribute
.getAssumeThreadsOversubscription() /*LangOpts().OpenMPThreadSubscription*/
,
"__omp_rtl_assume_threads_oversubscription");
ompBuilder->createGlobalFlag(
attribute.getAssumeNoThreadState() /*LangOpts().OpenMPNoThreadState*/,
"__omp_rtl_assume_no_thread_state");
ompBuilder->createGlobalFlag(
attribute
.getAssumeNoNestedParallelism() /*LangOpts().OpenMPNoNestedParallelism*/
,
"__omp_rtl_assume_no_nested_parallelism");
return success();
}
static void getTargetEntryUniqueInfo(llvm::TargetRegionEntryInfo &targetInfo,
omp::TargetOp targetOp,
llvm::StringRef parentName = "") {
auto fileLoc = targetOp.getLoc()->findInstanceOf<FileLineColLoc>();
assert(fileLoc && "No file found from location");
StringRef fileName = fileLoc.getFilename().getValue();
llvm::sys::fs::UniqueID id;
uint64_t line = fileLoc.getLine();
if (auto ec = llvm::sys::fs::getUniqueID(fileName, id)) {
size_t fileHash = llvm::hash_value(fileName.str());
size_t deviceId = 0xdeadf17e;
targetInfo =
llvm::TargetRegionEntryInfo(parentName, deviceId, fileHash, line);
} else {
targetInfo = llvm::TargetRegionEntryInfo(parentName, id.getDevice(),
id.getFile(), line);
}
}
static void
handleDeclareTargetMapVar(MapInfoData &mapData,
LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase &builder, llvm::Function *func) {
assert(moduleTranslation.getOpenMPBuilder()->Config.isTargetDevice() &&
"function only supported for target device codegen");
llvm::IRBuilderBase::InsertPointGuard guard(builder);
for (size_t i = 0; i < mapData.MapClause.size(); ++i) {
// In the case of declare target mapped variables, the basePointer is
// the reference pointer generated by the convertDeclareTargetAttr
// method. Whereas the kernelValue is the original variable, so for
// the device we must replace all uses of this original global variable
// (stored in kernelValue) with the reference pointer (stored in
// basePointer for declare target mapped variables), as for device the
// data is mapped into this reference pointer and should be loaded
// from it, the original variable is discarded. On host both exist and
// metadata is generated (elsewhere in the convertDeclareTargetAttr)
// function to link the two variables in the runtime and then both the
// reference pointer and the pointer are assigned in the kernel argument
// structure for the host.
if (mapData.IsDeclareTarget[i]) {
// If the original map value is a constant, then we have to make sure all
// of it's uses within the current kernel/function that we are going to
// rewrite are converted to instructions, as we will be altering the old
// use (OriginalValue) from a constant to an instruction, which will be
// illegal and ICE the compiler if the user is a constant expression of
// some kind e.g. a constant GEP.
if (auto *constant = dyn_cast<llvm::Constant>(mapData.OriginalValue[i]))
convertUsersOfConstantsToInstructions(constant, func, false);
// The users iterator will get invalidated if we modify an element,
// so we populate this vector of uses to alter each user on an
// individual basis to emit its own load (rather than one load for
// all).
llvm::SmallVector<llvm::User *> userVec;
for (llvm::User *user : mapData.OriginalValue[i]->users())
userVec.push_back(user);
for (llvm::User *user : userVec) {
if (auto *insn = dyn_cast<llvm::Instruction>(user)) {
if (insn->getFunction() == func) {
auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
llvm::Value *substitute = mapData.BasePointers[i];
if (isDeclareTargetLink(mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr()
: mapOp.getVarPtr())) {
builder.SetCurrentDebugLocation(insn->getDebugLoc());
substitute = builder.CreateLoad(
mapData.BasePointers[i]->getType(), mapData.BasePointers[i]);
cast<llvm::LoadInst>(substitute)->moveBefore(insn->getIterator());
}
user->replaceUsesOfWith(mapData.OriginalValue[i], substitute);
}
}
}
}
}
}
// The createDeviceArgumentAccessor function generates
// instructions for retrieving (acessing) kernel
// arguments inside of the device kernel for use by
// the kernel. This enables different semantics such as
// the creation of temporary copies of data allowing
// semantics like read-only/no host write back kernel
// arguments.
//
// This currently implements a very light version of Clang's
// EmitParmDecl's handling of direct argument handling as well
// as a portion of the argument access generation based on
// capture types found at the end of emitOutlinedFunctionPrologue
// in Clang. The indirect path handling of EmitParmDecl's may be
// required for future work, but a direct 1-to-1 copy doesn't seem
// possible as the logic is rather scattered throughout Clang's
// lowering and perhaps we wish to deviate slightly.
//
// \param mapData - A container containing vectors of information
// corresponding to the input argument, which should have a
// corresponding entry in the MapInfoData containers
// OrigialValue's.
// \param arg - This is the generated kernel function argument that
// corresponds to the passed in input argument. We generated different
// accesses of this Argument, based on capture type and other Input
// related information.
// \param input - This is the host side value that will be passed to
// the kernel i.e. the kernel input, we rewrite all uses of this within
// the kernel (as we generate the kernel body based on the target's region
// which maintians references to the original input) to the retVal argument
// apon exit of this function inside of the OMPIRBuilder. This interlinks
// the kernel argument to future uses of it in the function providing
// appropriate "glue" instructions inbetween.
// \param retVal - This is the value that all uses of input inside of the
// kernel will be re-written to, the goal of this function is to generate
// an appropriate location for the kernel argument to be accessed from,
// e.g. ByRef will result in a temporary allocation location and then
// a store of the kernel argument into this allocated memory which
// will then be loaded from, ByCopy will use the allocated memory
// directly.
static llvm::IRBuilderBase::InsertPoint
createDeviceArgumentAccessor(MapInfoData &mapData, llvm::Argument &arg,
llvm::Value *input, llvm::Value *&retVal,
llvm::IRBuilderBase &builder,
llvm::OpenMPIRBuilder &ompBuilder,
LLVM::ModuleTranslation &moduleTranslation,
llvm::IRBuilderBase::InsertPoint allocaIP,
llvm::IRBuilderBase::InsertPoint codeGenIP) {
assert(ompBuilder.Config.isTargetDevice() &&
"function only supported for target device codegen");
builder.restoreIP(allocaIP);
omp::VariableCaptureKind capture = omp::VariableCaptureKind::ByRef;
LLVM::TypeToLLVMIRTranslator typeToLLVMIRTranslator(
ompBuilder.M.getContext());
unsigned alignmentValue = 0;
// Find the associated MapInfoData entry for the current input
for (size_t i = 0; i < mapData.MapClause.size(); ++i)
if (mapData.OriginalValue[i] == input) {
auto mapOp = cast<omp::MapInfoOp>(mapData.MapClause[i]);
capture = mapOp.getMapCaptureType();
// Get information of alignment of mapped object
alignmentValue = typeToLLVMIRTranslator.getPreferredAlignment(
mapOp.getVarType(), ompBuilder.M.getDataLayout());
break;
}
unsigned int allocaAS = ompBuilder.M.getDataLayout().getAllocaAddrSpace();
unsigned int defaultAS =
ompBuilder.M.getDataLayout().getProgramAddressSpace();
// Create the alloca for the argument the current point.
llvm::Value *v = builder.CreateAlloca(arg.getType(), allocaAS);
if (allocaAS != defaultAS && arg.getType()->isPointerTy())
v = builder.CreateAddrSpaceCast(v, builder.getPtrTy(defaultAS));
builder.CreateStore(&arg, v);
builder.restoreIP(codeGenIP);
switch (capture) {
case omp::VariableCaptureKind::ByCopy: {
retVal = v;
break;
}
case omp::VariableCaptureKind::ByRef: {
llvm::LoadInst *loadInst = builder.CreateAlignedLoad(
v->getType(), v,
ompBuilder.M.getDataLayout().getPrefTypeAlign(v->getType()));
// CreateAlignedLoad function creates similar LLVM IR:
// %res = load ptr, ptr %input, align 8
// This LLVM IR does not contain information about alignment
// of the loaded value. We need to add !align metadata to unblock
// optimizer. The existence of the !align metadata on the instruction
// tells the optimizer that the value loaded is known to be aligned to
// a boundary specified by the integer value in the metadata node.
// Example:
// %res = load ptr, ptr %input, align 8, !align !align_md_node
// ^ ^
// | |
// alignment of %input address |
// |
// alignment of %res object
if (v->getType()->isPointerTy() && alignmentValue) {
llvm::MDBuilder MDB(builder.getContext());
loadInst->setMetadata(
llvm::LLVMContext::MD_align,
llvm::MDNode::get(builder.getContext(),
MDB.createConstant(llvm::ConstantInt::get(
llvm::Type::getInt64Ty(builder.getContext()),
alignmentValue))));
}
retVal = loadInst;
break;
}
case omp::VariableCaptureKind::This:
case omp::VariableCaptureKind::VLAType:
// TODO: Consider returning error to use standard reporting for
// unimplemented features.
assert(false && "Currently unsupported capture kind");
break;
}
return builder.saveIP();
}
/// Follow uses of `host_eval`-defined block arguments of the given `omp.target`
/// operation and populate output variables with their corresponding host value
/// (i.e. operand evaluated outside of the target region), based on their uses
/// inside of the target region.
///
/// Loop bounds and steps are only optionally populated, if output vectors are
/// provided.
static void
extractHostEvalClauses(omp::TargetOp targetOp, Value &numThreads,
Value &numTeamsLower, Value &numTeamsUpper,
Value &threadLimit,
llvm::SmallVectorImpl<Value> *lowerBounds = nullptr,
llvm::SmallVectorImpl<Value> *upperBounds = nullptr,
llvm::SmallVectorImpl<Value> *steps = nullptr) {
auto blockArgIface = llvm::cast<omp::BlockArgOpenMPOpInterface>(*targetOp);
for (auto item : llvm::zip_equal(targetOp.getHostEvalVars(),
blockArgIface.getHostEvalBlockArgs())) {
Value hostEvalVar = std::get<0>(item), blockArg = std::get<1>(item);
for (Operation *user : blockArg.getUsers()) {
llvm::TypeSwitch<Operation *>(user)
.Case([&](omp::TeamsOp teamsOp) {
if (teamsOp.getNumTeamsLower() == blockArg)
numTeamsLower = hostEvalVar;
else if (llvm::is_contained(teamsOp.getNumTeamsUpperVars(),
blockArg))
numTeamsUpper = hostEvalVar;
else if (!teamsOp.getThreadLimitVars().empty() &&
teamsOp.getThreadLimit(0) == blockArg)
threadLimit = hostEvalVar;
else
llvm_unreachable("unsupported host_eval use");
})
.Case([&](omp::ParallelOp parallelOp) {
if (!parallelOp.getNumThreadsVars().empty() &&
parallelOp.getNumThreads(0) == blockArg)
numThreads = hostEvalVar;
else
llvm_unreachable("unsupported host_eval use");
})
.Case([&](omp::LoopNestOp loopOp) {
auto processBounds =
[&](OperandRange opBounds,
llvm::SmallVectorImpl<Value> *outBounds) -> bool {
bool found = false;
for (auto [i, lb] : llvm::enumerate(opBounds)) {
if (lb == blockArg) {
found = true;
if (outBounds)
(*outBounds)[i] = hostEvalVar;
}
}
return found;
};
bool found =
processBounds(loopOp.getLoopLowerBounds(), lowerBounds);
found = processBounds(loopOp.getLoopUpperBounds(), upperBounds) ||
found;
found = processBounds(loopOp.getLoopSteps(), steps) || found;
(void)found;
assert(found && "unsupported host_eval use");
})
.DefaultUnreachable("unsupported host_eval use");
}
}
}
/// If \p op is of the given type parameter, return it casted to that type.
/// Otherwise, if its immediate parent operation (or some other higher-level
/// parent, if \p immediateParent is false) is of that type, return that parent
/// casted to the given type.
///
/// If \p op is \c null or neither it or its parent(s) are of the specified
/// type, return a \c null operation.
template <typename OpTy>
static OpTy castOrGetParentOfType(Operation *op, bool immediateParent = false) {
if (!op)
return OpTy();
if (OpTy casted = dyn_cast<OpTy>(op))
return casted;
if (immediateParent)
return dyn_cast_if_present<OpTy>(op->getParentOp());
return op->getParentOfType<OpTy>();
}
/// If the given \p value is defined by an \c llvm.mlir.constant operation and
/// it is of an integer type, return its value.
static std::optional<int64_t> extractConstInteger(Value value) {
if (!value)
return std::nullopt;
if (auto constOp = value.getDefiningOp<LLVM::ConstantOp>())
if (auto constAttr = dyn_cast<IntegerAttr>(constOp.getValue()))
return constAttr.getInt();
return std::nullopt;
}
static uint64_t getTypeByteSize(mlir::Type type, const DataLayout &dl) {
uint64_t sizeInBits = dl.getTypeSizeInBits(type);
uint64_t sizeInBytes = sizeInBits / 8;
return sizeInBytes;
}
template <typename OpTy>
static uint64_t getReductionDataSize(OpTy &op) {
if (op.getNumReductionVars() > 0) {
SmallVector<omp::DeclareReductionOp> reductions;
collectReductionDecls(op, reductions);
llvm::SmallVector<mlir::Type> members;
members.reserve(reductions.size());
for (omp::DeclareReductionOp &red : reductions)
members.push_back(red.getType());
Operation *opp = op.getOperation();
auto structType = mlir::LLVM::LLVMStructType::getLiteral(
opp->getContext(), members, /*isPacked=*/false);
DataLayout dl = DataLayout(opp->getParentOfType<ModuleOp>());
return getTypeByteSize(structType, dl);
}
return 0;
}
/// Populate default `MinTeams`, `MaxTeams` and `MaxThreads` to their default
/// values as stated by the corresponding clauses, if constant.
///
/// These default values must be set before the creation of the outlined LLVM
/// function for the target region, so that they can be used to initialize the
/// corresponding global `ConfigurationEnvironmentTy` structure.
static void
initTargetDefaultAttrs(omp::TargetOp targetOp, Operation *capturedOp,
llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs &attrs,
bool isTargetDevice, bool isGPU) {
// TODO: Handle constant 'if' clauses.
Value numThreads, numTeamsLower, numTeamsUpper, threadLimit;
if (!isTargetDevice) {
extractHostEvalClauses(targetOp, numThreads, numTeamsLower, numTeamsUpper,
threadLimit);
} else {
// In the target device, values for these clauses are not passed as
// host_eval, but instead evaluated prior to entry to the region. This
// ensures values are mapped and available inside of the target region.
if (auto teamsOp = castOrGetParentOfType<omp::TeamsOp>(capturedOp)) {
numTeamsLower = teamsOp.getNumTeamsLower();
// Handle num_teams upper bounds (only first value for now)
if (!teamsOp.getNumTeamsUpperVars().empty())
numTeamsUpper = teamsOp.getNumTeams(0);
if (!teamsOp.getThreadLimitVars().empty())
threadLimit = teamsOp.getThreadLimit(0);
}
if (auto parallelOp = castOrGetParentOfType<omp::ParallelOp>(capturedOp)) {
if (!parallelOp.getNumThreadsVars().empty())
numThreads = parallelOp.getNumThreads(0);
}
}
// Handle clauses impacting the number of teams.
int32_t minTeamsVal = 1, maxTeamsVal = -1;
if (castOrGetParentOfType<omp::TeamsOp>(capturedOp)) {
// TODO: Use `hostNumTeamsLower` to initialize `minTeamsVal`. For now,
// match clang and set min and max to the same value.
if (numTeamsUpper) {
if (auto val = extractConstInteger(numTeamsUpper))
minTeamsVal = maxTeamsVal = *val;
} else {
minTeamsVal = maxTeamsVal = 0;
}
} else if (castOrGetParentOfType<omp::ParallelOp>(capturedOp,
/*immediateParent=*/true) ||
castOrGetParentOfType<omp::SimdOp>(capturedOp,
/*immediateParent=*/true)) {
minTeamsVal = maxTeamsVal = 1;
} else {
minTeamsVal = maxTeamsVal = -1;
}
// Handle clauses impacting the number of threads.
auto setMaxValueFromClause = [](Value clauseValue, int32_t &result) {
if (!clauseValue)
return;
if (auto val = extractConstInteger(clauseValue))
result = *val;
// Found an applicable clause, so it's not undefined. Mark as unknown
// because it's not constant.
if (result < 0)
result = 0;
};
// Extract 'thread_limit' clause from 'target' and 'teams' directives.
int32_t targetThreadLimitVal = -1, teamsThreadLimitVal = -1;
if (!targetOp.getThreadLimitVars().empty())
setMaxValueFromClause(targetOp.getThreadLimit(0), targetThreadLimitVal);
setMaxValueFromClause(threadLimit, teamsThreadLimitVal);
// Extract 'max_threads' clause from 'parallel' or set to 1 if it's SIMD.
int32_t maxThreadsVal = -1;
if (castOrGetParentOfType<omp::ParallelOp>(capturedOp))
setMaxValueFromClause(numThreads, maxThreadsVal);
else if (castOrGetParentOfType<omp::SimdOp>(capturedOp,
/*immediateParent=*/true))
maxThreadsVal = 1;
// For max values, < 0 means unset, == 0 means set but unknown. Select the
// minimum value between 'max_threads' and 'thread_limit' clauses that were
// set.
int32_t combinedMaxThreadsVal = targetThreadLimitVal;
if (combinedMaxThreadsVal < 0 ||
(teamsThreadLimitVal >= 0 && teamsThreadLimitVal < combinedMaxThreadsVal))
combinedMaxThreadsVal = teamsThreadLimitVal;
if (combinedMaxThreadsVal < 0 ||
(maxThreadsVal >= 0 && maxThreadsVal < combinedMaxThreadsVal))
combinedMaxThreadsVal = maxThreadsVal;
int32_t reductionDataSize = 0;
if (isGPU && capturedOp) {
if (auto teamsOp = castOrGetParentOfType<omp::TeamsOp>(capturedOp))
reductionDataSize = getReductionDataSize(teamsOp);
}
// Update kernel bounds structure for the `OpenMPIRBuilder` to use.
omp::TargetRegionFlags kernelFlags = targetOp.getKernelExecFlags(capturedOp);
assert(
omp::bitEnumContainsAny(kernelFlags, omp::TargetRegionFlags::generic |
omp::TargetRegionFlags::spmd) &&
"invalid kernel flags");
attrs.ExecFlags =
omp::bitEnumContainsAny(kernelFlags, omp::TargetRegionFlags::generic)
? omp::bitEnumContainsAny(kernelFlags, omp::TargetRegionFlags::spmd)
? llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD
: llvm::omp::OMP_TGT_EXEC_MODE_GENERIC
: llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
if (omp::bitEnumContainsAll(kernelFlags,
omp::TargetRegionFlags::spmd |
omp::TargetRegionFlags::no_loop) &&
!omp::bitEnumContainsAny(kernelFlags, omp::TargetRegionFlags::generic))
attrs.ExecFlags = llvm::omp::OMP_TGT_EXEC_MODE_SPMD_NO_LOOP;
attrs.MinTeams = minTeamsVal;
attrs.MaxTeams.front() = maxTeamsVal;
attrs.MinThreads = 1;
attrs.MaxThreads.front() = combinedMaxThreadsVal;
attrs.ReductionDataSize = reductionDataSize;
// TODO: Allow modified buffer length similar to
// fopenmp-cuda-teams-reduction-recs-num flag in clang.
if (attrs.ReductionDataSize != 0)
attrs.ReductionBufferLength = 1024;
}
/// Gather LLVM runtime values for all clauses evaluated in the host that are
/// passed to the kernel invocation.
///
/// This function must be called only when compiling for the host. Also, it will
/// only provide correct results if it's called after the body of \c targetOp
/// has been fully generated.
static void
initTargetRuntimeAttrs(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation,
omp::TargetOp targetOp, Operation *capturedOp,
llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs &attrs) {
omp::LoopNestOp loopOp = castOrGetParentOfType<omp::LoopNestOp>(capturedOp);
unsigned numLoops = loopOp ? loopOp.getNumLoops() : 0;
Value numThreads, numTeamsLower, numTeamsUpper, teamsThreadLimit;
llvm::SmallVector<Value> lowerBounds(numLoops), upperBounds(numLoops),
steps(numLoops);
extractHostEvalClauses(targetOp, numThreads, numTeamsLower, numTeamsUpper,
teamsThreadLimit, &lowerBounds, &upperBounds, &steps);
// TODO: Handle constant 'if' clauses.
if (!targetOp.getThreadLimitVars().empty()) {
Value targetThreadLimit = targetOp.getThreadLimit(0);
attrs.TargetThreadLimit.front() =
moduleTranslation.lookupValue(targetThreadLimit);
}
// The __kmpc_push_num_teams_51 function expects int32 as the arguments. So,
// truncate or sign extend lower and upper num_teams bounds as well as
// thread_limit to match int32 ABI requirements for the OpenMP runtime.
if (numTeamsLower)
attrs.MinTeams = builder.CreateSExtOrTrunc(
moduleTranslation.lookupValue(numTeamsLower), builder.getInt32Ty());
if (numTeamsUpper)
attrs.MaxTeams.front() = builder.CreateSExtOrTrunc(
moduleTranslation.lookupValue(numTeamsUpper), builder.getInt32Ty());
if (teamsThreadLimit)
attrs.TeamsThreadLimit.front() = builder.CreateSExtOrTrunc(
moduleTranslation.lookupValue(teamsThreadLimit), builder.getInt32Ty());
if (numThreads)
attrs.MaxThreads = moduleTranslation.lookupValue(numThreads);
if (omp::bitEnumContainsAny(targetOp.getKernelExecFlags(capturedOp),
omp::TargetRegionFlags::trip_count)) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
attrs.LoopTripCount = nullptr;
// To calculate the trip count, we multiply together the trip counts of
// every collapsed canonical loop. We don't need to create the loop nests
// here, since we're only interested in the trip count.
for (auto [loopLower, loopUpper, loopStep] :
llvm::zip_equal(lowerBounds, upperBounds, steps)) {
llvm::Value *lowerBound = moduleTranslation.lookupValue(loopLower);
llvm::Value *upperBound = moduleTranslation.lookupValue(loopUpper);
llvm::Value *step = moduleTranslation.lookupValue(loopStep);
if (!lowerBound || !upperBound || !step) {
attrs.LoopTripCount = nullptr;
break;
}
llvm::OpenMPIRBuilder::LocationDescription loc(builder);
llvm::Value *tripCount = ompBuilder->calculateCanonicalLoopTripCount(
loc, lowerBound, upperBound, step, /*IsSigned=*/true,
loopOp.getLoopInclusive());
if (!attrs.LoopTripCount) {
attrs.LoopTripCount = tripCount;
continue;
}
// TODO: Enable UndefinedSanitizer to diagnose an overflow here.
attrs.LoopTripCount = builder.CreateMul(attrs.LoopTripCount, tripCount,
{}, /*HasNUW=*/true);
}
}
attrs.DeviceID = builder.getInt64(llvm::omp::OMP_DEVICEID_UNDEF);
if (mlir::Value devId = targetOp.getDevice()) {
attrs.DeviceID = moduleTranslation.lookupValue(devId);
attrs.DeviceID =
builder.CreateSExtOrTrunc(attrs.DeviceID, builder.getInt64Ty());
}
}
static LogicalResult
convertOmpTarget(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto targetOp = cast<omp::TargetOp>(opInst);
// The current debug location already has the DISubprogram for the outlined
// function that will be created for the target op. We save it here so that
// we can set it on the outlined function.
llvm::DebugLoc outlinedFnLoc = builder.getCurrentDebugLocation();
if (failed(checkImplementationStatus(opInst)))
return failure();
// During the handling of target op, we will generate instructions in the
// parent function like call to the oulined function or branch to a new
// BasicBlock. We set the debug location here to parent function so that those
// get the correct debug locations. For outlined functions, the normal MLIR op
// conversion will automatically pick the correct location.
llvm::BasicBlock *parentBB = builder.GetInsertBlock();
assert(parentBB && "No insert block is set for the builder");
llvm::Function *parentLLVMFn = parentBB->getParent();
assert(parentLLVMFn && "Parent Function must be valid");
if (llvm::DISubprogram *SP = parentLLVMFn->getSubprogram())
builder.SetCurrentDebugLocation(llvm::DILocation::get(
parentLLVMFn->getContext(), outlinedFnLoc.getLine(),
outlinedFnLoc.getCol(), SP, outlinedFnLoc.getInlinedAt()));
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
bool isTargetDevice = ompBuilder->Config.isTargetDevice();
bool isGPU = ompBuilder->Config.isGPU();
auto parentFn = opInst.getParentOfType<LLVM::LLVMFuncOp>();
auto argIface = cast<omp::BlockArgOpenMPOpInterface>(opInst);
auto &targetRegion = targetOp.getRegion();
// Holds the private vars that have been mapped along with the block
// argument that corresponds to the MapInfoOp corresponding to the private
// var in question. So, for instance:
//
// %10 = omp.map.info var_ptr(%6#0 : !fir.ref<!fir.box<!fir.heap<i32>>>, ..)
// omp.target map_entries(%10 -> %arg0) private(@box.privatizer %6#0-> %arg1)
//
// Then, %10 has been created so that the descriptor can be used by the
// privatizer @box.privatizer on the device side. Here we'd record {%6#0,
// %arg0} in the mappedPrivateVars map.
llvm::DenseMap<Value, Value> mappedPrivateVars;
DataLayout dl = DataLayout(opInst.getParentOfType<ModuleOp>());
SmallVector<Value> mapVars = targetOp.getMapVars();
SmallVector<Value> hdaVars = targetOp.getHasDeviceAddrVars();
ArrayRef<BlockArgument> mapBlockArgs = argIface.getMapBlockArgs();
ArrayRef<BlockArgument> hdaBlockArgs = argIface.getHasDeviceAddrBlockArgs();
llvm::Function *llvmOutlinedFn = nullptr;
TargetDirectiveEnumTy targetDirective =
getTargetDirectiveEnumTyFromOp(&opInst);
// TODO: It can also be false if a compile-time constant `false` IF clause is
// specified.
bool isOffloadEntry =
isTargetDevice || !ompBuilder->Config.TargetTriples.empty();
// For some private variables, the MapsForPrivatizedVariablesPass
// creates MapInfoOp instances. Go through the private variables and
// the mapped variables so that during codegeneration we are able
// to quickly look up the corresponding map variable, if any for each
// private variable.
if (!targetOp.getPrivateVars().empty() && !targetOp.getMapVars().empty()) {
OperandRange privateVars = targetOp.getPrivateVars();
std::optional<ArrayAttr> privateSyms = targetOp.getPrivateSyms();
std::optional<DenseI64ArrayAttr> privateMapIndices =
targetOp.getPrivateMapsAttr();
for (auto [privVarIdx, privVarSymPair] :
llvm::enumerate(llvm::zip_equal(privateVars, *privateSyms))) {
auto privVar = std::get<0>(privVarSymPair);
auto privSym = std::get<1>(privVarSymPair);
SymbolRefAttr privatizerName = llvm::cast<SymbolRefAttr>(privSym);
omp::PrivateClauseOp privatizer =
findPrivatizer(targetOp, privatizerName);
if (!privatizer.needsMap())
continue;
mlir::Value mappedValue =
targetOp.getMappedValueForPrivateVar(privVarIdx);
assert(mappedValue && "Expected to find mapped value for a privatized "
"variable that needs mapping");
// The MapInfoOp defining the map var isn't really needed later.
// So, we don't store it in any datastructure. Instead, we just
// do some sanity checks on it right now.
auto mapInfoOp = mappedValue.getDefiningOp<omp::MapInfoOp>();
[[maybe_unused]] Type varType = mapInfoOp.getVarType();
// Check #1: Check that the type of the private variable matches
// the type of the variable being mapped.
if (!isa<LLVM::LLVMPointerType>(privVar.getType()))
assert(
varType == privVar.getType() &&
"Type of private var doesn't match the type of the mapped value");
// Ok, only 1 sanity check for now.
// Record the block argument corresponding to this mapvar.
mappedPrivateVars.insert(
{privVar,
targetRegion.getArgument(argIface.getMapBlockArgsStart() +
(*privateMapIndices)[privVarIdx])});
}
}
using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP)
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
llvm::IRBuilderBase::InsertPointGuard guard(builder);
builder.SetCurrentDebugLocation(llvm::DebugLoc());
// Forward target-cpu and target-features function attributes from the
// original function to the new outlined function.
llvm::Function *llvmParentFn =
moduleTranslation.lookupFunction(parentFn.getName());
llvmOutlinedFn = codeGenIP.getBlock()->getParent();
assert(llvmParentFn && llvmOutlinedFn &&
"Both parent and outlined functions must exist at this point");
if (outlinedFnLoc && llvmParentFn->getSubprogram())
llvmOutlinedFn->setSubprogram(outlinedFnLoc->getScope()->getSubprogram());
if (auto attr = llvmParentFn->getFnAttribute("target-cpu");
attr.isStringAttribute())
llvmOutlinedFn->addFnAttr(attr);
if (auto attr = llvmParentFn->getFnAttribute("target-features");
attr.isStringAttribute())
llvmOutlinedFn->addFnAttr(attr);
for (auto [arg, mapOp] : llvm::zip_equal(mapBlockArgs, mapVars)) {
auto mapInfoOp = cast<omp::MapInfoOp>(mapOp.getDefiningOp());
llvm::Value *mapOpValue =
moduleTranslation.lookupValue(mapInfoOp.getVarPtr());
moduleTranslation.mapValue(arg, mapOpValue);
}
for (auto [arg, mapOp] : llvm::zip_equal(hdaBlockArgs, hdaVars)) {
auto mapInfoOp = cast<omp::MapInfoOp>(mapOp.getDefiningOp());
llvm::Value *mapOpValue =
moduleTranslation.lookupValue(mapInfoOp.getVarPtr());
moduleTranslation.mapValue(arg, mapOpValue);
}
// Do privatization after moduleTranslation has already recorded
// mapped values.
PrivateVarsInfo privateVarsInfo(targetOp);
llvm::Expected<llvm::BasicBlock *> afterAllocas =
allocatePrivateVars(builder, moduleTranslation, privateVarsInfo,
allocaIP, &mappedPrivateVars);
if (failed(handleError(afterAllocas, *targetOp)))
return llvm::make_error<PreviouslyReportedError>();
builder.restoreIP(codeGenIP);
if (handleError(initPrivateVars(builder, moduleTranslation, privateVarsInfo,
&mappedPrivateVars),
*targetOp)
.failed())
return llvm::make_error<PreviouslyReportedError>();
if (failed(copyFirstPrivateVars(
targetOp, builder, moduleTranslation, privateVarsInfo.mlirVars,
privateVarsInfo.llvmVars, privateVarsInfo.privatizers,
targetOp.getPrivateNeedsBarrier(), &mappedPrivateVars)))
return llvm::make_error<PreviouslyReportedError>();
SmallVector<Region *> privateCleanupRegions;
llvm::transform(privateVarsInfo.privatizers,
std::back_inserter(privateCleanupRegions),
[](omp::PrivateClauseOp privatizer) {
return &privatizer.getDeallocRegion();
});
llvm::Expected<llvm::BasicBlock *> exitBlock = convertOmpOpRegions(
targetRegion, "omp.target", builder, moduleTranslation);
if (!exitBlock)
return exitBlock.takeError();
builder.SetInsertPoint(*exitBlock);
if (!privateCleanupRegions.empty()) {
if (failed(inlineOmpRegionCleanup(
privateCleanupRegions, privateVarsInfo.llvmVars,
moduleTranslation, builder, "omp.targetop.private.cleanup",
/*shouldLoadCleanupRegionArg=*/false))) {
return llvm::createStringError(
"failed to inline `dealloc` region of `omp.private` "
"op in the target region");
}
return builder.saveIP();
}
return InsertPointTy(exitBlock.get(), exitBlock.get()->end());
};
StringRef parentName = parentFn.getName();
llvm::TargetRegionEntryInfo entryInfo;
getTargetEntryUniqueInfo(entryInfo, targetOp, parentName);
MapInfoData mapData;
collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, dl,
builder, /*useDevPtrOperands=*/{},
/*useDevAddrOperands=*/{}, hdaVars);
MapInfosTy combinedInfos;
auto genMapInfoCB =
[&](llvm::OpenMPIRBuilder::InsertPointTy codeGenIP) -> MapInfosTy & {
builder.restoreIP(codeGenIP);
genMapInfos(builder, moduleTranslation, dl, combinedInfos, mapData,
targetDirective);
return combinedInfos;
};
auto argAccessorCB = [&](llvm::Argument &arg, llvm::Value *input,
llvm::Value *&retVal, InsertPointTy allocaIP,
InsertPointTy codeGenIP)
-> llvm::OpenMPIRBuilder::InsertPointOrErrorTy {
llvm::IRBuilderBase::InsertPointGuard guard(builder);
builder.SetCurrentDebugLocation(llvm::DebugLoc());
// We just return the unaltered argument for the host function
// for now, some alterations may be required in the future to
// keep host fallback functions working identically to the device
// version (e.g. pass ByCopy values should be treated as such on
// host and device, currently not always the case)
if (!isTargetDevice) {
retVal = cast<llvm::Value>(&arg);
return codeGenIP;
}
return createDeviceArgumentAccessor(mapData, arg, input, retVal, builder,
*ompBuilder, moduleTranslation,
allocaIP, codeGenIP);
};
llvm::OpenMPIRBuilder::TargetKernelRuntimeAttrs runtimeAttrs;
llvm::OpenMPIRBuilder::TargetKernelDefaultAttrs defaultAttrs;
Operation *targetCapturedOp = targetOp.getInnermostCapturedOmpOp();
initTargetDefaultAttrs(targetOp, targetCapturedOp, defaultAttrs,
isTargetDevice, isGPU);
// Collect host-evaluated values needed to properly launch the kernel from the
// host.
if (!isTargetDevice)
initTargetRuntimeAttrs(builder, moduleTranslation, targetOp,
targetCapturedOp, runtimeAttrs);
// Pass host-evaluated values as parameters to the kernel / host fallback,
// except if they are constants. In any case, map the MLIR block argument to
// the corresponding LLVM values.
llvm::SmallVector<llvm::Value *, 4> kernelInput;
SmallVector<Value> hostEvalVars = targetOp.getHostEvalVars();
ArrayRef<BlockArgument> hostEvalBlockArgs = argIface.getHostEvalBlockArgs();
for (auto [arg, var] : llvm::zip_equal(hostEvalBlockArgs, hostEvalVars)) {
llvm::Value *value = moduleTranslation.lookupValue(var);
moduleTranslation.mapValue(arg, value);
if (!llvm::isa<llvm::Constant>(value))
kernelInput.push_back(value);
}
for (size_t i = 0, e = mapData.OriginalValue.size(); i != e; ++i) {
// declare target arguments are not passed to kernels as arguments
// TODO: We currently do not handle cases where a member is explicitly
// passed in as an argument, this will likley need to be handled in
// the near future, rather than using IsAMember, it may be better to
// test if the relevant BlockArg is used within the target region and
// then use that as a basis for exclusion in the kernel inputs.
if (!mapData.IsDeclareTarget[i] && !mapData.IsAMember[i])
kernelInput.push_back(mapData.OriginalValue[i]);
}
SmallVector<llvm::OpenMPIRBuilder::DependData> dds;
buildDependData(targetOp.getDependKinds(), targetOp.getDependVars(),
moduleTranslation, dds);
llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
findAllocaInsertPoint(builder, moduleTranslation);
llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
llvm::OpenMPIRBuilder::TargetDataInfo info(
/*RequiresDevicePointerInfo=*/false,
/*SeparateBeginEndCalls=*/true);
auto customMapperCB =
[&](unsigned int i) -> llvm::Expected<llvm::Function *> {
if (!combinedInfos.Mappers[i])
return nullptr;
info.HasMapper = true;
return getOrCreateUserDefinedMapperFunc(combinedInfos.Mappers[i], builder,
moduleTranslation, targetDirective);
};
llvm::Value *ifCond = nullptr;
if (Value targetIfCond = targetOp.getIfExpr())
ifCond = moduleTranslation.lookupValue(targetIfCond);
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
moduleTranslation.getOpenMPBuilder()->createTarget(
ompLoc, isOffloadEntry, allocaIP, builder.saveIP(), info, entryInfo,
defaultAttrs, runtimeAttrs, ifCond, kernelInput, genMapInfoCB, bodyCB,
argAccessorCB, customMapperCB, dds, targetOp.getNowait());
if (failed(handleError(afterIP, opInst)))
return failure();
builder.restoreIP(*afterIP);
// Remap access operations to declare target reference pointers for the
// device, essentially generating extra loadop's as necessary
if (moduleTranslation.getOpenMPBuilder()->Config.isTargetDevice())
handleDeclareTargetMapVar(mapData, moduleTranslation, builder,
llvmOutlinedFn);
return success();
}
static LogicalResult
convertDeclareTargetAttr(Operation *op, mlir::omp::DeclareTargetAttr attribute,
LLVM::ModuleTranslation &moduleTranslation) {
// Amend omp.declare_target by deleting the IR of the outlined functions
// created for target regions. They cannot be filtered out from MLIR earlier
// because the omp.target operation inside must be translated to LLVM, but
// the wrapper functions themselves must not remain at the end of the
// process. We know that functions where omp.declare_target does not match
// omp.is_target_device at this stage can only be wrapper functions because
// those that aren't are removed earlier as an MLIR transformation pass.
if (FunctionOpInterface funcOp = dyn_cast<FunctionOpInterface>(op)) {
if (auto offloadMod = dyn_cast<omp::OffloadModuleInterface>(
op->getParentOfType<ModuleOp>().getOperation())) {
if (!offloadMod.getIsTargetDevice())
return success();
omp::DeclareTargetDeviceType declareType =
attribute.getDeviceType().getValue();
if (declareType == omp::DeclareTargetDeviceType::host) {
llvm::Function *llvmFunc =
moduleTranslation.lookupFunction(funcOp.getName());
llvmFunc->dropAllReferences();
llvmFunc->eraseFromParent();
}
}
return success();
}
if (LLVM::GlobalOp gOp = dyn_cast<LLVM::GlobalOp>(op)) {
llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
if (auto *gVal = llvmModule->getNamedValue(gOp.getSymName())) {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
bool isDeclaration = gOp.isDeclaration();
bool isExternallyVisible =
gOp.getVisibility() != mlir::SymbolTable::Visibility::Private;
auto loc = op->getLoc()->findInstanceOf<FileLineColLoc>();
llvm::StringRef mangledName = gOp.getSymName();
auto captureClause =
convertToCaptureClauseKind(attribute.getCaptureClause().getValue());
auto deviceClause =
convertToDeviceClauseKind(attribute.getDeviceType().getValue());
// unused for MLIR at the moment, required in Clang for book
// keeping
std::vector<llvm::GlobalVariable *> generatedRefs;
std::vector<llvm::Triple> targetTriple;
auto targetTripleAttr = dyn_cast_or_null<mlir::StringAttr>(
op->getParentOfType<mlir::ModuleOp>()->getAttr(
LLVM::LLVMDialect::getTargetTripleAttrName()));
if (targetTripleAttr)
targetTriple.emplace_back(targetTripleAttr.data());
auto fileInfoCallBack = [&loc]() {
std::string filename = "";
std::uint64_t lineNo = 0;
if (loc) {
filename = loc.getFilename().str();
lineNo = loc.getLine();
}
return std::pair<std::string, std::uint64_t>(llvm::StringRef(filename),
lineNo);
};
auto vfs = llvm::vfs::getRealFileSystem();
ompBuilder->registerTargetGlobalVariable(
captureClause, deviceClause, isDeclaration, isExternallyVisible,
ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, *vfs),
mangledName, generatedRefs, /*OpenMPSimd*/ false, targetTriple,
/*GlobalInitializer*/ nullptr, /*VariableLinkage*/ nullptr,
gVal->getType(), gVal);
if (ompBuilder->Config.isTargetDevice() &&
(attribute.getCaptureClause().getValue() !=
mlir::omp::DeclareTargetCaptureClause::to ||
ompBuilder->Config.hasRequiresUnifiedSharedMemory())) {
ompBuilder->getAddrOfDeclareTargetVar(
captureClause, deviceClause, isDeclaration, isExternallyVisible,
ompBuilder->getTargetEntryUniqueInfo(fileInfoCallBack, *vfs),
mangledName, generatedRefs, /*OpenMPSimd*/ false, targetTriple,
gVal->getType(), /*GlobalInitializer*/ nullptr,
/*VariableLinkage*/ nullptr);
}
}
}
return success();
}
namespace {
/// Implementation of the dialect interface that converts operations belonging
/// to the OpenMP dialect to LLVM IR.
class OpenMPDialectLLVMIRTranslationInterface
: public LLVMTranslationDialectInterface {
public:
using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
/// Translates the given operation to LLVM IR using the provided IR builder
/// and saving the state in `moduleTranslation`.
LogicalResult
convertOperation(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) const final;
/// Given an OpenMP MLIR attribute, create the corresponding LLVM-IR,
/// runtime calls, or operation amendments
LogicalResult
amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
NamedAttribute attribute,
LLVM::ModuleTranslation &moduleTranslation) const final;
};
} // namespace
LogicalResult OpenMPDialectLLVMIRTranslationInterface::amendOperation(
Operation *op, ArrayRef<llvm::Instruction *> instructions,
NamedAttribute attribute,
LLVM::ModuleTranslation &moduleTranslation) const {
return llvm::StringSwitch<llvm::function_ref<LogicalResult(Attribute)>>(
attribute.getName())
.Case("omp.is_target_device",
[&](Attribute attr) {
if (auto deviceAttr = dyn_cast<BoolAttr>(attr)) {
llvm::OpenMPIRBuilderConfig &config =
moduleTranslation.getOpenMPBuilder()->Config;
config.setIsTargetDevice(deviceAttr.getValue());
return success();
}
return failure();
})
.Case("omp.is_gpu",
[&](Attribute attr) {
if (auto gpuAttr = dyn_cast<BoolAttr>(attr)) {
llvm::OpenMPIRBuilderConfig &config =
moduleTranslation.getOpenMPBuilder()->Config;
config.setIsGPU(gpuAttr.getValue());
return success();
}
return failure();
})
.Case("omp.host_ir_filepath",
[&](Attribute attr) {
if (auto filepathAttr = dyn_cast<StringAttr>(attr)) {
llvm::OpenMPIRBuilder *ompBuilder =
moduleTranslation.getOpenMPBuilder();
auto VFS = llvm::vfs::getRealFileSystem();
ompBuilder->loadOffloadInfoMetadata(*VFS,
filepathAttr.getValue());
return success();
}
return failure();
})
.Case("omp.flags",
[&](Attribute attr) {
if (auto rtlAttr = dyn_cast<omp::FlagsAttr>(attr))
return convertFlagsAttr(op, rtlAttr, moduleTranslation);
return failure();
})
.Case("omp.version",
[&](Attribute attr) {
if (auto versionAttr = dyn_cast<omp::VersionAttr>(attr)) {
llvm::OpenMPIRBuilder *ompBuilder =
moduleTranslation.getOpenMPBuilder();
ompBuilder->M.addModuleFlag(llvm::Module::Max, "openmp",
versionAttr.getVersion());
return success();
}
return failure();
})
.Case("omp.declare_target",
[&](Attribute attr) {
if (auto declareTargetAttr =
dyn_cast<omp::DeclareTargetAttr>(attr))
return convertDeclareTargetAttr(op, declareTargetAttr,
moduleTranslation);
return failure();
})
.Case("omp.requires",
[&](Attribute attr) {
if (auto requiresAttr = dyn_cast<omp::ClauseRequiresAttr>(attr)) {
using Requires = omp::ClauseRequires;
Requires flags = requiresAttr.getValue();
llvm::OpenMPIRBuilderConfig &config =
moduleTranslation.getOpenMPBuilder()->Config;
config.setHasRequiresReverseOffload(
bitEnumContainsAll(flags, Requires::reverse_offload));
config.setHasRequiresUnifiedAddress(
bitEnumContainsAll(flags, Requires::unified_address));
config.setHasRequiresUnifiedSharedMemory(
bitEnumContainsAll(flags, Requires::unified_shared_memory));
config.setHasRequiresDynamicAllocators(
bitEnumContainsAll(flags, Requires::dynamic_allocators));
return success();
}
return failure();
})
.Case("omp.target_triples",
[&](Attribute attr) {
if (auto triplesAttr = dyn_cast<ArrayAttr>(attr)) {
llvm::OpenMPIRBuilderConfig &config =
moduleTranslation.getOpenMPBuilder()->Config;
config.TargetTriples.clear();
config.TargetTriples.reserve(triplesAttr.size());
for (Attribute tripleAttr : triplesAttr) {
if (auto tripleStrAttr = dyn_cast<StringAttr>(tripleAttr))
config.TargetTriples.emplace_back(tripleStrAttr.getValue());
else
return failure();
}
return success();
}
return failure();
})
.Default([](Attribute) {
// Fall through for omp attributes that do not require lowering.
return success();
})(attribute.getValue());
return failure();
}
// Returns true if the operation is not inside a TargetOp, it is part of a
// function and that function is not declare target.
static bool isHostDeviceOp(Operation *op) {
// Assumes no reverse offloading
if (op->getParentOfType<omp::TargetOp>())
return false;
if (auto parentFn = op->getParentOfType<LLVM::LLVMFuncOp>()) {
if (auto declareTargetIface =
llvm::dyn_cast<mlir::omp::DeclareTargetInterface>(
parentFn.getOperation()))
if (declareTargetIface.isDeclareTarget() &&
declareTargetIface.getDeclareTargetDeviceType() !=
mlir::omp::DeclareTargetDeviceType::host)
return false;
return true;
}
return false;
}
static llvm::Function *getOmpTargetAlloc(llvm::IRBuilderBase &builder,
llvm::Module *llvmModule) {
llvm::Type *i64Ty = builder.getInt64Ty();
llvm::Type *i32Ty = builder.getInt32Ty();
llvm::Type *returnType = builder.getPtrTy(0);
llvm::FunctionType *fnType =
llvm::FunctionType::get(returnType, {i64Ty, i32Ty}, false);
llvm::Function *func = cast<llvm::Function>(
llvmModule->getOrInsertFunction("omp_target_alloc", fnType).getCallee());
return func;
}
static LogicalResult
convertTargetAllocMemOp(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto allocMemOp = cast<omp::TargetAllocMemOp>(opInst);
if (!allocMemOp)
return failure();
// Get "omp_target_alloc" function
llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
llvm::Function *ompTargetAllocFunc = getOmpTargetAlloc(builder, llvmModule);
// Get the corresponding device value in llvm
mlir::Value deviceNum = allocMemOp.getDevice();
llvm::Value *llvmDeviceNum = moduleTranslation.lookupValue(deviceNum);
// Get the allocation size.
llvm::DataLayout dataLayout = llvmModule->getDataLayout();
mlir::Type heapTy = allocMemOp.getAllocatedType();
llvm::Type *llvmHeapTy = moduleTranslation.convertType(heapTy);
llvm::TypeSize typeSize = dataLayout.getTypeStoreSize(llvmHeapTy);
llvm::Value *allocSize = builder.getInt64(typeSize.getFixedValue());
for (auto typeParam : allocMemOp.getTypeparams())
allocSize =
builder.CreateMul(allocSize, moduleTranslation.lookupValue(typeParam));
// Create call to "omp_target_alloc" with the args as translated llvm values.
llvm::CallInst *call =
builder.CreateCall(ompTargetAllocFunc, {allocSize, llvmDeviceNum});
llvm::Value *resultI64 = builder.CreatePtrToInt(call, builder.getInt64Ty());
// Map the result
moduleTranslation.mapValue(allocMemOp.getResult(), resultI64);
return success();
}
static llvm::Function *getOmpTargetFree(llvm::IRBuilderBase &builder,
llvm::Module *llvmModule) {
llvm::Type *ptrTy = builder.getPtrTy(0);
llvm::Type *i32Ty = builder.getInt32Ty();
llvm::Type *voidTy = builder.getVoidTy();
llvm::FunctionType *fnType =
llvm::FunctionType::get(voidTy, {ptrTy, i32Ty}, false);
llvm::Function *func = dyn_cast<llvm::Function>(
llvmModule->getOrInsertFunction("omp_target_free", fnType).getCallee());
return func;
}
static LogicalResult
convertTargetFreeMemOp(Operation &opInst, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto freeMemOp = cast<omp::TargetFreeMemOp>(opInst);
if (!freeMemOp)
return failure();
// Get "omp_target_free" function
llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
llvm::Function *ompTragetFreeFunc = getOmpTargetFree(builder, llvmModule);
// Get the corresponding device value in llvm
mlir::Value deviceNum = freeMemOp.getDevice();
llvm::Value *llvmDeviceNum = moduleTranslation.lookupValue(deviceNum);
// Get the corresponding heapref value in llvm
mlir::Value heapref = freeMemOp.getHeapref();
llvm::Value *llvmHeapref = moduleTranslation.lookupValue(heapref);
// Convert heapref int to ptr and call "omp_target_free"
llvm::Value *intToPtr =
builder.CreateIntToPtr(llvmHeapref, builder.getPtrTy(0));
builder.CreateCall(ompTragetFreeFunc, {intToPtr, llvmDeviceNum});
return success();
}
/// Given an OpenMP MLIR operation, create the corresponding LLVM IR (including
/// OpenMP runtime calls).
LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) const {
llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
if (ompBuilder->Config.isTargetDevice() &&
!isa<omp::TargetOp, omp::MapInfoOp, omp::TerminatorOp, omp::YieldOp>(
op) &&
isHostDeviceOp(op))
return op->emitOpError() << "unsupported host op found in device";
// For each loop, introduce one stack frame to hold loop information. Ensure
// this is only done for the outermost loop wrapper to prevent introducing
// multiple stack frames for a single loop. Initially set to null, the loop
// information structure is initialized during translation of the nested
// omp.loop_nest operation, making it available to translation of all loop
// wrappers after their body has been successfully translated.
bool isOutermostLoopWrapper =
isa_and_present<omp::LoopWrapperInterface>(op) &&
!dyn_cast_if_present<omp::LoopWrapperInterface>(op->getParentOp());
if (isOutermostLoopWrapper)
moduleTranslation.stackPush<OpenMPLoopInfoStackFrame>();
auto result =
llvm::TypeSwitch<Operation *, LogicalResult>(op)
.Case([&](omp::BarrierOp op) -> LogicalResult {
if (failed(checkImplementationStatus(*op)))
return failure();
llvm::OpenMPIRBuilder::InsertPointOrErrorTy afterIP =
ompBuilder->createBarrier(builder.saveIP(),
llvm::omp::OMPD_barrier);
LogicalResult res = handleError(afterIP, *op);
if (res.succeeded()) {
// If the barrier generated a cancellation check, the insertion
// point might now need to be changed to a new continuation block
builder.restoreIP(*afterIP);
}
return res;
})
.Case([&](omp::TaskyieldOp op) {
if (failed(checkImplementationStatus(*op)))
return failure();
ompBuilder->createTaskyield(builder.saveIP());
return success();
})
.Case([&](omp::FlushOp op) {
if (failed(checkImplementationStatus(*op)))
return failure();
// No support in Openmp runtime function (__kmpc_flush) to accept
// the argument list.
// OpenMP standard states the following:
// "An implementation may implement a flush with a list by ignoring
// the list, and treating it the same as a flush without a list."
//
// The argument list is discarded so that, flush with a list is
// treated same as a flush without a list.
ompBuilder->createFlush(builder.saveIP());
return success();
})
.Case([&](omp::ParallelOp op) {
return convertOmpParallel(op, builder, moduleTranslation);
})
.Case([&](omp::MaskedOp) {
return convertOmpMasked(*op, builder, moduleTranslation);
})
.Case([&](omp::MasterOp) {
return convertOmpMaster(*op, builder, moduleTranslation);
})
.Case([&](omp::CriticalOp) {
return convertOmpCritical(*op, builder, moduleTranslation);
})
.Case([&](omp::OrderedRegionOp) {
return convertOmpOrderedRegion(*op, builder, moduleTranslation);
})
.Case([&](omp::OrderedOp) {
return convertOmpOrdered(*op, builder, moduleTranslation);
})
.Case([&](omp::WsloopOp) {
return convertOmpWsloop(*op, builder, moduleTranslation);
})
.Case([&](omp::SimdOp) {
return convertOmpSimd(*op, builder, moduleTranslation);
})
.Case([&](omp::AtomicReadOp) {
return convertOmpAtomicRead(*op, builder, moduleTranslation);
})
.Case([&](omp::AtomicWriteOp) {
return convertOmpAtomicWrite(*op, builder, moduleTranslation);
})
.Case([&](omp::AtomicUpdateOp op) {
return convertOmpAtomicUpdate(op, builder, moduleTranslation);
})
.Case([&](omp::AtomicCaptureOp op) {
return convertOmpAtomicCapture(op, builder, moduleTranslation);
})
.Case([&](omp::CancelOp op) {
return convertOmpCancel(op, builder, moduleTranslation);
})
.Case([&](omp::CancellationPointOp op) {
return convertOmpCancellationPoint(op, builder, moduleTranslation);
})
.Case([&](omp::SectionsOp) {
return convertOmpSections(*op, builder, moduleTranslation);
})
.Case([&](omp::SingleOp op) {
return convertOmpSingle(op, builder, moduleTranslation);
})
.Case([&](omp::TeamsOp op) {
return convertOmpTeams(op, builder, moduleTranslation);
})
.Case([&](omp::TaskOp op) {
return convertOmpTaskOp(op, builder, moduleTranslation);
})
.Case([&](omp::TaskloopOp op) {
return convertOmpTaskloopOp(*op, builder, moduleTranslation);
})
.Case([&](omp::TaskgroupOp op) {
return convertOmpTaskgroupOp(op, builder, moduleTranslation);
})
.Case([&](omp::TaskwaitOp op) {
return convertOmpTaskwaitOp(op, builder, moduleTranslation);
})
.Case<omp::YieldOp, omp::TerminatorOp, omp::DeclareMapperOp,
omp::DeclareMapperInfoOp, omp::DeclareReductionOp,
omp::CriticalDeclareOp>([](auto op) {
// `yield` and `terminator` can be just omitted. The block structure
// was created in the region that handles their parent operation.
// `declare_reduction` will be used by reductions and is not
// converted directly, skip it.
// `declare_mapper` and `declare_mapper.info` are handled whenever
// they are referred to through a `map` clause.
// `critical.declare` is only used to declare names of critical
// sections which will be used by `critical` ops and hence can be
// ignored for lowering. The OpenMP IRBuilder will create unique
// name for critical section names.
return success();
})
.Case([&](omp::ThreadprivateOp) {
return convertOmpThreadprivate(*op, builder, moduleTranslation);
})
.Case<omp::TargetDataOp, omp::TargetEnterDataOp,
omp::TargetExitDataOp, omp::TargetUpdateOp>([&](auto op) {
return convertOmpTargetData(op, builder, moduleTranslation);
})
.Case([&](omp::TargetOp) {
return convertOmpTarget(*op, builder, moduleTranslation);
})
.Case([&](omp::DistributeOp) {
return convertOmpDistribute(*op, builder, moduleTranslation);
})
.Case([&](omp::LoopNestOp) {
return convertOmpLoopNest(*op, builder, moduleTranslation);
})
.Case<omp::MapInfoOp, omp::MapBoundsOp, omp::PrivateClauseOp>(
[&](auto op) {
// No-op, should be handled by relevant owning operations e.g.
// TargetOp, TargetEnterDataOp, TargetExitDataOp, TargetDataOp
// etc. and then discarded
return success();
})
.Case([&](omp::NewCliOp op) {
// Meta-operation: Doesn't do anything by itself, but used to
// identify a loop.
return success();
})
.Case([&](omp::CanonicalLoopOp op) {
return convertOmpCanonicalLoopOp(op, builder, moduleTranslation);
})
.Case([&](omp::UnrollHeuristicOp op) {
// FIXME: Handling omp.unroll_heuristic as an executable requires
// that the generator (e.g. omp.canonical_loop) has been seen first.
// For construct that require all codegen to occur inside a callback
// (e.g. OpenMPIRBilder::createParallel), all codegen of that
// contained region including their transformations must occur at
// the omp.canonical_loop.
return applyUnrollHeuristic(op, builder, moduleTranslation);
})
.Case([&](omp::TileOp op) {
return applyTile(op, builder, moduleTranslation);
})
.Case([&](omp::TargetAllocMemOp) {
return convertTargetAllocMemOp(*op, builder, moduleTranslation);
})
.Case([&](omp::TargetFreeMemOp) {
return convertTargetFreeMemOp(*op, builder, moduleTranslation);
})
.Default([&](Operation *inst) {
return inst->emitError()
<< "not yet implemented: " << inst->getName();
});
if (isOutermostLoopWrapper)
moduleTranslation.stackPop();
return result;
}
void mlir::registerOpenMPDialectTranslation(DialectRegistry ®istry) {
registry.insert<omp::OpenMPDialect>();
registry.addExtension(+[](MLIRContext *ctx, omp::OpenMPDialect *dialect) {
dialect->addInterfaces<OpenMPDialectLLVMIRTranslationInterface>();
});
}
void mlir::registerOpenMPDialectTranslation(MLIRContext &context) {
DialectRegistry registry;
registerOpenMPDialectTranslation(registry);
context.appendDialectRegistry(registry);
}
|