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
|
"""Provides the `CCompilerOpt` class, used for handling the CPU/hardware
optimization, starting from parsing the command arguments, to managing the
relation between the CPU baseline and dispatch-able features,
also generating the required C headers and ending with compiling
the sources with proper compiler's flags.
`CCompilerOpt` doesn't provide runtime detection for the CPU features,
instead only focuses on the compiler side, but it creates abstract C headers
that can be used later for the final runtime dispatching process."""
import sys, io, os, re, textwrap, pprint, inspect, atexit, subprocess
class _Config:
"""An abstract class holds all configurable attributes of `CCompilerOpt`,
these class attributes can be used to change the default behavior
of `CCompilerOpt` in order to fit other requirements.
Attributes
----------
conf_nocache : bool
Set True to disable memory and file cache.
Default is False.
conf_noopt : bool
Set True to forces the optimization to be disabled,
in this case `CCompilerOpt` tends to generate all
expected headers in order to 'not' break the build.
Default is False.
conf_cache_factors : list
Add extra factors to the primary caching factors. The caching factors
are utilized to determine if there are changes had happened that
requires to discard the cache and re-updating it. The primary factors
are the arguments of `CCompilerOpt` and `CCompiler`'s properties(type, flags, etc).
Default is list of two items, containing the time of last modification
of `ccompiler_opt` and value of attribute "conf_noopt"
conf_tmp_path : str,
The path of temporary directory. Default is auto-created
temporary directory via ``tempfile.mkdtemp()``.
conf_check_path : str
The path of testing files. Each added CPU feature must have a
**C** source file contains at least one intrinsic or instruction that
related to this feature, so it can be tested against the compiler.
Default is ``./distutils/checks``.
conf_target_groups : dict
Extra tokens that can be reached from dispatch-able sources through
the special mark ``@targets``. Default is an empty dictionary.
**Notes**:
- case-insensitive for tokens and group names
- sign '#' must stick in the begin of group name and only within ``@targets``
**Example**:
.. code-block:: console
$ "@targets #avx_group other_tokens" > group_inside.c
>>> CCompilerOpt.conf_target_groups["avx_group"] = \\
"$werror $maxopt avx2 avx512f avx512_skx"
>>> cco = CCompilerOpt(cc_instance)
>>> cco.try_dispatch(["group_inside.c"])
conf_c_prefix : str
The prefix of public C definitions. Default is ``"NPY_"``.
conf_c_prefix_ : str
The prefix of internal C definitions. Default is ``"NPY__"``.
conf_cc_flags : dict
Nested dictionaries defining several compiler flags
that linked to some major functions, the main key
represent the compiler name and sub-keys represent
flags names. Default is already covers all supported
**C** compilers.
Sub-keys explained as follows:
"native": str or None
used by argument option `native`, to detect the current
machine support via the compiler.
"werror": str or None
utilized to treat warning as errors during testing CPU features
against the compiler and also for target's policy `$werror`
via dispatch-able sources.
"maxopt": str or None
utilized for target's policy '$maxopt' and the value should
contains the maximum acceptable optimization by the compiler.
e.g. in gcc `'-O3'`
**Notes**:
* case-sensitive for compiler names and flags
* use space to separate multiple flags
* any flag will tested against the compiler and it will skipped
if it's not applicable.
conf_min_features : dict
A dictionary defines the used CPU features for
argument option `'min'`, the key represent the CPU architecture
name e.g. `'x86'`. Default values provide the best effort
on wide range of users platforms.
**Note**: case-sensitive for architecture names.
conf_features : dict
Nested dictionaries used for identifying the CPU features.
the primary key is represented as a feature name or group name
that gathers several features. Default values covers all
supported features but without the major options like "flags",
these undefined options handle it by method `conf_features_partial()`.
Default value is covers almost all CPU features for *X86*, *IBM/Power64*
and *ARM 7/8*.
Sub-keys explained as follows:
"implies" : str or list, optional,
List of CPU feature names to be implied by it,
the feature name must be defined within `conf_features`.
Default is None.
"flags": str or list, optional
List of compiler flags. Default is None.
"detect": str or list, optional
List of CPU feature names that required to be detected
in runtime. By default, its the feature name or features
in "group" if its specified.
"implies_detect": bool, optional
If True, all "detect" of implied features will be combined.
Default is True. see `feature_detect()`.
"group": str or list, optional
Same as "implies" but doesn't require the feature name to be
defined within `conf_features`.
"interest": int, required
a key for sorting CPU features
"headers": str or list, optional
intrinsics C header file
"disable": str, optional
force disable feature, the string value should contains the
reason of disabling.
"autovec": bool or None, optional
True or False to declare that CPU feature can be auto-vectorized
by the compiler.
By default(None), treated as True if the feature contains at
least one applicable flag. see `feature_can_autovec()`
"extra_checks": str or list, optional
Extra test case names for the CPU feature that need to be tested
against the compiler.
Each test case must have a C file named ``extra_xxxx.c``, where
``xxxx`` is the case name in lower case, under 'conf_check_path'.
It should contain at least one intrinsic or function related to the test case.
If the compiler able to successfully compile the C file then `CCompilerOpt`
will add a C ``#define`` for it into the main dispatch header, e.g.
```#define {conf_c_prefix}_XXXX`` where ``XXXX`` is the case name in upper case.
**NOTES**:
* space can be used as separator with options that supports "str or list"
* case-sensitive for all values and feature name must be in upper-case.
* if flags aren't applicable, its will skipped rather than disable the
CPU feature
* the CPU feature will disabled if the compiler fail to compile
the test file
"""
conf_nocache = False
conf_noopt = False
conf_cache_factors = None
conf_tmp_path = None
conf_check_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "checks"
)
conf_target_groups = {}
conf_c_prefix = 'NPY_'
conf_c_prefix_ = 'NPY__'
conf_cc_flags = dict(
gcc = dict(
# native should always fail on arm and ppc64,
# native usually works only with x86
native = '-march=native',
opt = '-O3',
werror = '-Werror'
),
clang = dict(
native = '-march=native',
opt = "-O3",
werror = '-Werror'
),
icc = dict(
native = '-xHost',
opt = '-O3',
werror = '-Werror'
),
iccw = dict(
native = '/QxHost',
opt = '/O3',
werror = '/Werror'
),
msvc = dict(
native = None,
opt = '/O2',
werror = '/WX'
)
)
conf_min_features = dict(
x86 = "SSE SSE2",
x64 = "SSE SSE2 SSE3",
ppc64 = '', # play it safe
ppc64le = "VSX VSX2",
armhf = '', # play it safe
aarch64 = "NEON NEON_FP16 NEON_VFPV4 ASIMD"
)
conf_features = dict(
# X86
SSE = dict(
interest=1, headers="xmmintrin.h",
# enabling SSE without SSE2 is useless also
# it's non-optional for x86_64
implies="SSE2"
),
SSE2 = dict(interest=2, implies="SSE", headers="emmintrin.h"),
SSE3 = dict(interest=3, implies="SSE2", headers="pmmintrin.h"),
SSSE3 = dict(interest=4, implies="SSE3", headers="tmmintrin.h"),
SSE41 = dict(interest=5, implies="SSSE3", headers="smmintrin.h"),
POPCNT = dict(interest=6, implies="SSE41", headers="popcntintrin.h"),
SSE42 = dict(interest=7, implies="POPCNT"),
AVX = dict(
interest=8, implies="SSE42", headers="immintrin.h",
implies_detect=False
),
XOP = dict(interest=9, implies="AVX", headers="x86intrin.h"),
FMA4 = dict(interest=10, implies="AVX", headers="x86intrin.h"),
F16C = dict(interest=11, implies="AVX"),
FMA3 = dict(interest=12, implies="F16C"),
AVX2 = dict(interest=13, implies="F16C"),
AVX512F = dict(
interest=20, implies="FMA3 AVX2", implies_detect=False,
extra_checks="AVX512F_REDUCE"
),
AVX512CD = dict(interest=21, implies="AVX512F"),
AVX512_KNL = dict(
interest=40, implies="AVX512CD", group="AVX512ER AVX512PF",
detect="AVX512_KNL", implies_detect=False
),
AVX512_KNM = dict(
interest=41, implies="AVX512_KNL",
group="AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ",
detect="AVX512_KNM", implies_detect=False
),
AVX512_SKX = dict(
interest=42, implies="AVX512CD", group="AVX512VL AVX512BW AVX512DQ",
detect="AVX512_SKX", implies_detect=False,
extra_checks="AVX512BW_MASK"
),
AVX512_CLX = dict(
interest=43, implies="AVX512_SKX", group="AVX512VNNI",
detect="AVX512_CLX"
),
AVX512_CNL = dict(
interest=44, implies="AVX512_SKX", group="AVX512IFMA AVX512VBMI",
detect="AVX512_CNL", implies_detect=False
),
AVX512_ICL = dict(
interest=45, implies="AVX512_CLX AVX512_CNL",
group="AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ",
detect="AVX512_ICL", implies_detect=False
),
# IBM/Power
## Power7/ISA 2.06
VSX = dict(interest=1, headers="altivec.h"),
## Power8/ISA 2.07
VSX2 = dict(interest=2, implies="VSX", implies_detect=False),
## Power9/ISA 3.00
VSX3 = dict(interest=3, implies="VSX2", implies_detect=False),
# ARM
NEON = dict(interest=1, headers="arm_neon.h"),
NEON_FP16 = dict(interest=2, implies="NEON"),
## FMA
NEON_VFPV4 = dict(interest=3, implies="NEON_FP16"),
## Advanced SIMD
ASIMD = dict(interest=4, implies="NEON_FP16 NEON_VFPV4", implies_detect=False),
## ARMv8.2 half-precision & vector arithm
ASIMDHP = dict(interest=5, implies="ASIMD"),
## ARMv8.2 dot product
ASIMDDP = dict(interest=6, implies="ASIMD"),
## ARMv8.2 Single & half-precision Multiply
ASIMDFHM = dict(interest=7, implies="ASIMDHP"),
)
def conf_features_partial(self):
"""Return a dictionary of supported CPU features by the platform,
and accumulate the rest of undefined options in `conf_features`,
the returned dict has same rules and notes in
class attribute `conf_features`, also its override
any options that been set in 'conf_features'.
"""
if self.cc_noopt:
# optimization is disabled
return {}
on_x86 = self.cc_on_x86 or self.cc_on_x64
is_unix = self.cc_is_gcc or self.cc_is_clang
if on_x86 and is_unix: return dict(
SSE = dict(flags="-msse"),
SSE2 = dict(flags="-msse2"),
SSE3 = dict(flags="-msse3"),
SSSE3 = dict(flags="-mssse3"),
SSE41 = dict(flags="-msse4.1"),
POPCNT = dict(flags="-mpopcnt"),
SSE42 = dict(flags="-msse4.2"),
AVX = dict(flags="-mavx"),
F16C = dict(flags="-mf16c"),
XOP = dict(flags="-mxop"),
FMA4 = dict(flags="-mfma4"),
FMA3 = dict(flags="-mfma"),
AVX2 = dict(flags="-mavx2"),
AVX512F = dict(flags="-mavx512f"),
AVX512CD = dict(flags="-mavx512cd"),
AVX512_KNL = dict(flags="-mavx512er -mavx512pf"),
AVX512_KNM = dict(
flags="-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq"
),
AVX512_SKX = dict(flags="-mavx512vl -mavx512bw -mavx512dq"),
AVX512_CLX = dict(flags="-mavx512vnni"),
AVX512_CNL = dict(flags="-mavx512ifma -mavx512vbmi"),
AVX512_ICL = dict(
flags="-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq"
)
)
if on_x86 and self.cc_is_icc: return dict(
SSE = dict(flags="-msse"),
SSE2 = dict(flags="-msse2"),
SSE3 = dict(flags="-msse3"),
SSSE3 = dict(flags="-mssse3"),
SSE41 = dict(flags="-msse4.1"),
POPCNT = {},
SSE42 = dict(flags="-msse4.2"),
AVX = dict(flags="-mavx"),
F16C = {},
XOP = dict(disable="Intel Compiler doesn't support it"),
FMA4 = dict(disable="Intel Compiler doesn't support it"),
# Intel Compiler doesn't support AVX2 or FMA3 independently
FMA3 = dict(
implies="F16C AVX2", flags="-march=core-avx2"
),
AVX2 = dict(implies="FMA3", flags="-march=core-avx2"),
# Intel Compiler doesn't support AVX512F or AVX512CD independently
AVX512F = dict(
implies="AVX2 AVX512CD", flags="-march=common-avx512"
),
AVX512CD = dict(
implies="AVX2 AVX512F", flags="-march=common-avx512"
),
AVX512_KNL = dict(flags="-xKNL"),
AVX512_KNM = dict(flags="-xKNM"),
AVX512_SKX = dict(flags="-xSKYLAKE-AVX512"),
AVX512_CLX = dict(flags="-xCASCADELAKE"),
AVX512_CNL = dict(flags="-xCANNONLAKE"),
AVX512_ICL = dict(flags="-xICELAKE-CLIENT"),
)
if on_x86 and self.cc_is_iccw: return dict(
SSE = dict(flags="/arch:SSE"),
SSE2 = dict(flags="/arch:SSE2"),
SSE3 = dict(flags="/arch:SSE3"),
SSSE3 = dict(flags="/arch:SSSE3"),
SSE41 = dict(flags="/arch:SSE4.1"),
POPCNT = {},
SSE42 = dict(flags="/arch:SSE4.2"),
AVX = dict(flags="/arch:AVX"),
F16C = {},
XOP = dict(disable="Intel Compiler doesn't support it"),
FMA4 = dict(disable="Intel Compiler doesn't support it"),
# Intel Compiler doesn't support FMA3 or AVX2 independently
FMA3 = dict(
implies="F16C AVX2", flags="/arch:CORE-AVX2"
),
AVX2 = dict(
implies="FMA3", flags="/arch:CORE-AVX2"
),
# Intel Compiler doesn't support AVX512F or AVX512CD independently
AVX512F = dict(
implies="AVX2 AVX512CD", flags="/Qx:COMMON-AVX512"
),
AVX512CD = dict(
implies="AVX2 AVX512F", flags="/Qx:COMMON-AVX512"
),
AVX512_KNL = dict(flags="/Qx:KNL"),
AVX512_KNM = dict(flags="/Qx:KNM"),
AVX512_SKX = dict(flags="/Qx:SKYLAKE-AVX512"),
AVX512_CLX = dict(flags="/Qx:CASCADELAKE"),
AVX512_CNL = dict(flags="/Qx:CANNONLAKE"),
AVX512_ICL = dict(flags="/Qx:ICELAKE-CLIENT")
)
if on_x86 and self.cc_is_msvc: return dict(
SSE = dict(flags="/arch:SSE"),
SSE2 = dict(flags="/arch:SSE2"),
SSE3 = {},
SSSE3 = {},
SSE41 = {},
POPCNT = dict(headers="nmmintrin.h"),
SSE42 = {},
AVX = dict(flags="/arch:AVX"),
F16C = {},
XOP = dict(headers="ammintrin.h"),
FMA4 = dict(headers="ammintrin.h"),
# MSVC doesn't support FMA3 or AVX2 independently
FMA3 = dict(
implies="F16C AVX2", flags="/arch:AVX2"
),
AVX2 = dict(
implies="F16C FMA3", flags="/arch:AVX2"
),
# MSVC doesn't support AVX512F or AVX512CD independently,
# always generate instructions belong to (VL/VW/DQ)
AVX512F = dict(
implies="AVX2 AVX512CD AVX512_SKX", flags="/arch:AVX512"
),
AVX512CD = dict(
implies="AVX512F AVX512_SKX", flags="/arch:AVX512"
),
AVX512_KNL = dict(
disable="MSVC compiler doesn't support it"
),
AVX512_KNM = dict(
disable="MSVC compiler doesn't support it"
),
AVX512_SKX = dict(flags="/arch:AVX512"),
AVX512_CLX = {},
AVX512_CNL = {},
AVX512_ICL = {}
)
on_power = self.cc_on_ppc64le or self.cc_on_ppc64
if on_power:
partial = dict(
VSX = dict(
implies=("VSX2" if self.cc_on_ppc64le else ""),
flags="-mvsx"
),
VSX2 = dict(
flags="-mcpu=power8", implies_detect=False
),
VSX3 = dict(
flags="-mcpu=power9 -mtune=power9", implies_detect=False
)
)
if self.cc_is_clang:
partial["VSX"]["flags"] = "-maltivec -mvsx"
partial["VSX2"]["flags"] = "-mpower8-vector"
partial["VSX3"]["flags"] = "-mpower9-vector"
return partial
if self.cc_on_aarch64 and is_unix: return dict(
NEON = dict(
implies="NEON_FP16 NEON_VFPV4 ASIMD", autovec=True
),
NEON_FP16 = dict(
implies="NEON NEON_VFPV4 ASIMD", autovec=True
),
NEON_VFPV4 = dict(
implies="NEON NEON_FP16 ASIMD", autovec=True
),
ASIMD = dict(
implies="NEON NEON_FP16 NEON_VFPV4", autovec=True
),
ASIMDHP = dict(
flags="-march=armv8.2-a+fp16"
),
ASIMDDP = dict(
flags="-march=armv8.2-a+dotprod"
),
ASIMDFHM = dict(
flags="-march=armv8.2-a+fp16fml"
),
)
if self.cc_on_armhf and is_unix: return dict(
NEON = dict(
flags="-mfpu=neon"
),
NEON_FP16 = dict(
flags="-mfpu=neon-fp16 -mfp16-format=ieee"
),
NEON_VFPV4 = dict(
flags="-mfpu=neon-vfpv4",
),
ASIMD = dict(
flags="-mfpu=neon-fp-armv8 -march=armv8-a+simd",
),
ASIMDHP = dict(
flags="-march=armv8.2-a+fp16"
),
ASIMDDP = dict(
flags="-march=armv8.2-a+dotprod",
),
ASIMDFHM = dict(
flags="-march=armv8.2-a+fp16fml"
)
)
# TODO: ARM MSVC
return {}
def __init__(self):
if self.conf_tmp_path is None:
import tempfile, shutil
tmp = tempfile.mkdtemp()
def rm_temp():
try:
shutil.rmtree(tmp)
except IOError:
pass
atexit.register(rm_temp)
self.conf_tmp_path = tmp
if self.conf_cache_factors is None:
self.conf_cache_factors = [
os.path.getmtime(__file__),
self.conf_nocache
]
class _Distutils:
"""A helper class that provides a collection of fundamental methods
implemented in a top of Python and NumPy Distutils.
The idea behind this class is to gather all methods that it may
need to override in case of reuse 'CCompilerOpt' in environment
different than of what NumPy has.
Parameters
----------
ccompiler : `CCompiler`
The generate instance that returned from `distutils.ccompiler.new_compiler()`.
"""
def __init__(self, ccompiler):
self._ccompiler = ccompiler
def dist_compile(self, sources, flags, **kwargs):
"""Wrap CCompiler.compile()"""
assert(isinstance(sources, list))
assert(isinstance(flags, list))
flags = kwargs.pop("extra_postargs", []) + flags
return self._ccompiler.compile(
sources, extra_postargs=flags, **kwargs
)
def dist_test(self, source, flags):
"""Return True if 'CCompiler.compile()' able to compile
a source file with certain flags.
"""
assert(isinstance(source, str))
from distutils.errors import CompileError
cc = self._ccompiler;
bk_spawn = getattr(cc, 'spawn', None)
if bk_spawn:
cc_type = getattr(self._ccompiler, "compiler_type", "")
if cc_type in ("msvc",):
setattr(cc, 'spawn', self._dist_test_spawn_paths)
else:
setattr(cc, 'spawn', self._dist_test_spawn)
test = False
try:
self.dist_compile(
[source], flags, output_dir=self.conf_tmp_path
)
test = True
except CompileError as e:
self.dist_log(str(e), stderr=True)
if bk_spawn:
setattr(cc, 'spawn', bk_spawn)
return test
def dist_info(self):
"""Return a string containing all environment information, required
by the abstract class '_CCompiler' to discovering the platform
environment, also used as a cache factor in order to detect
any changes from outside.
"""
if hasattr(self, "_dist_info"):
return self._dist_info
# play it safe
cc_info = ""
compiler = getattr(self._ccompiler, "compiler", None)
if compiler is not None:
if isinstance(compiler, str):
cc_info += compiler
elif hasattr(compiler, "__iter__"):
cc_info += ' '.join(compiler)
# in case if 'compiler' attribute doesn't provide anything
cc_type = getattr(self._ccompiler, "compiler_type", "")
if cc_type in ("intelem", "intelemw", "mingw64"):
cc_info += "x86_64"
elif cc_type in ("intel", "intelw", "intele"):
cc_info += "x86"
elif cc_type in ("msvc", "mingw32"):
import platform
if platform.architecture()[0] == "32bit":
cc_info += "x86"
else:
cc_info += "x86_64"
else:
# the last hope, too bad for cross-compiling
import platform
cc_info += platform.machine()
cc_info += cc_type
cflags = os.environ.get("CFLAGS", "")
if cflags not in cc_info:
cc_info += cflags
self._dist_info = cc_info
return cc_info
@staticmethod
def dist_error(*args):
"""Raise a compiler error"""
from distutils.errors import CompileError
raise CompileError(_Distutils._dist_str(*args))
@staticmethod
def dist_fatal(*args):
"""Raise a distutils error"""
from distutils.errors import DistutilsError
raise DistutilsError(_Distutils._dist_str(*args))
@staticmethod
def dist_log(*args, stderr=False):
"""Print a console message"""
from numpy.distutils import log
out = _Distutils._dist_str(*args)
if stderr:
log.warn(out)
else:
log.info(out)
@staticmethod
def dist_load_module(name, path):
"""Load a module from file, required by the abstract class '_Cache'."""
from numpy.compat import npy_load_module
try:
return npy_load_module(name, path)
except Exception as e:
_Distutils.dist_log(e, stderr=True)
return None
@staticmethod
def _dist_str(*args):
"""Return a string to print by log and errors."""
def to_str(arg):
if not isinstance(arg, str) and hasattr(arg, '__iter__'):
ret = []
for a in arg:
ret.append(to_str(a))
return '('+ ' '.join(ret) + ')'
return str(arg)
stack = inspect.stack()[2]
start = "CCompilerOpt.%s[%d] : " % (stack.function, stack.lineno)
out = ' '.join([
to_str(a)
for a in (*args,)
])
return start + out
def _dist_test_spawn_paths(self, cmd, display=None):
"""
Fix msvc SDK ENV path same as distutils do
without it we get c1: fatal error C1356: unable to find mspdbcore.dll
"""
if not hasattr(self._ccompiler, "_paths"):
self._dist_test_spawn(cmd)
return
old_path = os.getenv("path")
try:
os.environ["path"] = self._ccompiler._paths
self._dist_test_spawn(cmd)
finally:
os.environ["path"] = old_path
_dist_warn_regex = re.compile(
# intel and msvc compilers don't raise
# fatal errors when flags are wrong or unsupported
".*("
"warning D9002|" # msvc, it should be work with any language.
"invalid argument for option" # intel
").*"
)
@staticmethod
def _dist_test_spawn(cmd, display=None):
from distutils.errors import CompileError
try:
o = subprocess.check_output(cmd, stderr=subprocess.STDOUT,
universal_newlines=True)
if o and re.match(_Distutils._dist_warn_regex, o):
_Distutils.dist_error(
"Flags in command", cmd ,"aren't supported by the compiler"
", output -> \n%s" % o
)
except subprocess.CalledProcessError as exc:
o = exc.output
s = exc.returncode
except OSError:
o = b''
s = 127
else:
return None
_Distutils.dist_error(
"Command", cmd, "failed with exit status %d output -> \n%s" % (
s, o
))
_share_cache = {}
class _Cache:
"""An abstract class handles caching functionality, provides two
levels of caching, in-memory by share instances attributes among
each other and by store attributes into files.
**Note**:
any attributes that start with ``_`` or ``conf_`` will be ignored.
Parameters
----------
cache_path: str or None
The path of cache file, if None then cache in file will disabled.
*factors:
The caching factors that need to utilize next to `conf_cache_factors`.
Attributes
----------
cache_private: set
Hold the attributes that need be skipped from "in-memory cache".
cache_infile: bool
Utilized during initializing this class, to determine if the cache was able
to loaded from the specified cache path in 'cache_path'.
"""
# skip attributes from cache
_cache_ignore = re.compile("^(_|conf_)")
def __init__(self, cache_path=None, *factors):
self.cache_me = {}
self.cache_private = set()
self.cache_infile = False
if self.conf_nocache:
self.dist_log("cache is disabled by `Config`")
return
chash = self.cache_hash(*factors, *self.conf_cache_factors)
if cache_path:
if os.path.exists(cache_path):
self.dist_log("load cache from file ->", cache_path)
cache_mod = self.dist_load_module("cache", cache_path)
if not cache_mod:
self.dist_log(
"unable to load the cache file as a module",
stderr=True
)
elif not hasattr(cache_mod, "hash") or \
not hasattr(cache_mod, "data"):
self.dist_log("invalid cache file", stderr=True)
elif chash == cache_mod.hash:
self.dist_log("hit the file cache")
for attr, val in cache_mod.data.items():
setattr(self, attr, val)
self.cache_infile = True
else:
self.dist_log("miss the file cache")
atexit.register(self._cache_write, cache_path, chash)
if not self.cache_infile:
other_cache = _share_cache.get(chash)
if other_cache:
self.dist_log("hit the memory cache")
for attr, val in other_cache.__dict__.items():
if attr in other_cache.cache_private or \
re.match(self._cache_ignore, attr):
continue
setattr(self, attr, val)
_share_cache[chash] = self
def __del__(self):
# TODO: remove the cache form share on del
pass
def _cache_write(self, cache_path, cache_hash):
# TODO: don't write if the cache doesn't change
self.dist_log("write cache to path ->", cache_path)
for attr in list(self.__dict__.keys()):
if re.match(self._cache_ignore, attr):
self.__dict__.pop(attr)
d = os.path.dirname(cache_path)
if not os.path.exists(d):
os.makedirs(d)
repr_dict = pprint.pformat(self.__dict__, compact=True)
with open(cache_path, "w") as f:
f.write(textwrap.dedent("""\
# AUTOGENERATED DON'T EDIT
# Please make changes to the code generator \
(distutils/ccompiler_opt.py)
hash = {}
data = \\
""").format(cache_hash))
f.write(repr_dict)
def cache_hash(self, *factors):
# is there a built-in non-crypto hash?
# sdbm
chash = 0
for f in factors:
for char in str(f):
chash = ord(char) + (chash << 6) + (chash << 16) - chash
chash &= 0xFFFFFFFF
return chash
@staticmethod
def me(cb):
"""
A static method that can be treated as a decorator to
dynamically cache certain methods.
"""
def cache_wrap_me(self, *args, **kwargs):
# good for normal args
cache_key = str((
cb.__name__, *args, *kwargs.keys(), *kwargs.values()
))
if cache_key in self.cache_me:
return self.cache_me[cache_key]
ccb = cb(self, *args, **kwargs)
self.cache_me[cache_key] = ccb
return ccb
return cache_wrap_me
class _CCompiler(object):
"""A helper class for `CCompilerOpt` containing all utilities that
related to the fundamental compiler's functions.
Attributes
----------
cc_on_x86 : bool
True when the target architecture is 32-bit x86
cc_on_x64 : bool
True when the target architecture is 64-bit x86
cc_on_ppc64 : bool
True when the target architecture is 64-bit big-endian PowerPC
cc_on_armhf : bool
True when the target architecture is 32-bit ARMv7+
cc_on_aarch64 : bool
True when the target architecture is 64-bit Armv8-a+
cc_on_noarch : bool
True when the target architecture is unknown or not supported
cc_is_gcc : bool
True if the compiler is GNU or
if the compiler is unknown
cc_is_clang : bool
True if the compiler is Clang
cc_is_icc : bool
True if the compiler is Intel compiler (unix like)
cc_is_iccw : bool
True if the compiler is Intel compiler (msvc like)
cc_is_nocc : bool
True if the compiler isn't supported directly,
Note: that cause a fail-back to gcc
cc_has_debug : bool
True if the compiler has debug flags
cc_has_native : bool
True if the compiler has native flags
cc_noopt : bool
True if the compiler has definition 'DISABLE_OPT*',
or 'cc_on_noarch' is True
cc_march : str
The target architecture name, or "unknown" if
the architecture isn't supported
cc_name : str
The compiler name, or "unknown" if the compiler isn't supported
cc_flags : dict
Dictionary containing the initialized flags of `_Config.conf_cc_flags`
"""
def __init__(self):
if hasattr(self, "cc_is_cached"):
return
to_detect = (
# attr regex
(
("cc_on_x64", "^(x|x86_|amd)64"),
("cc_on_x86", "^(x86|i386|i686)"),
("cc_on_ppc64le", "^(powerpc|ppc)64(el|le)"),
("cc_on_ppc64", "^(powerpc|ppc)64"),
("cc_on_armhf", "^arm"),
("cc_on_aarch64", "^aarch64"),
# priority is given to first of string
# if it fail we search in the rest, due
# to append platform.machine() at the end,
# check method 'dist_info()' for more clarification.
("cc_on_x64", ".*(x|x86_|amd)64.*"),
("cc_on_x86", ".*(x86|i386|i686).*"),
("cc_on_ppc64le", ".*(powerpc|ppc)64(el|le).*"),
("cc_on_ppc64", ".*(powerpc|ppc)64.*"),
("cc_on_armhf", ".*arm.*"),
("cc_on_aarch64", ".*aarch64.*"),
# undefined platform
("cc_on_noarch", ""),
),
(
("cc_is_gcc", r".*(gcc|gnu\-g).*"),
("cc_is_clang", ".*clang.*"),
("cc_is_iccw", ".*(intelw|intelemw|iccw).*"), # intel msvc like
("cc_is_icc", ".*(intel|icc).*"), # intel unix like
("cc_is_msvc", ".*msvc.*"),
("cc_is_nocc", ""),
),
(("cc_has_debug", ".*(O0|Od|ggdb|coverage|debug:full).*"),),
(("cc_has_native", ".*(-march=native|-xHost|/QxHost).*"),),
# in case if the class run with -DNPY_DISABLE_OPTIMIZATION
(("cc_noopt", ".*DISABLE_OPT.*"),),
)
for section in to_detect:
for attr, rgex in section:
setattr(self, attr, False)
dist_info = self.dist_info()
for section in to_detect:
for attr, rgex in section:
if rgex and not re.match(rgex, dist_info, re.IGNORECASE):
continue
setattr(self, attr, True)
break
if self.cc_on_noarch:
self.dist_log(
"unable to detect CPU arch via compiler info, "
"optimization is disabled \ninfo << %s >> " % dist_info,
stderr=True
)
self.cc_noopt = True
if self.conf_noopt:
self.dist_log("Optimization is disabled by the Config", stderr=True)
self.cc_noopt = True
if self.cc_is_nocc:
"""
mingw can be treated as a gcc, and also xlc even if it based on clang,
but still has the same gcc optimization flags.
"""
self.dist_log(
"unable to detect compiler name via info <<\n%s\n>> "
"treating it as a gcc" % dist_info,
stderr=True
)
self.cc_is_gcc = True
self.cc_march = "unknown"
for arch in ("x86", "x64", "ppc64", "ppc64le", "armhf", "aarch64"):
if getattr(self, "cc_on_" + arch):
self.cc_march = arch
break
self.cc_name = "unknown"
for name in ("gcc", "clang", "iccw", "icc", "msvc"):
if getattr(self, "cc_is_" + name):
self.cc_name = name
break
self.cc_flags = {}
compiler_flags = self.conf_cc_flags.get(self.cc_name)
if compiler_flags is None:
self.dist_fatal(
"undefined flag for compiler '%s', "
"leave an empty dict instead" % self.cc_name
)
for name, flags in compiler_flags.items():
self.cc_flags[name] = nflags = []
if flags:
assert(isinstance(flags, str))
flags = flags.split()
for f in flags:
if self.cc_test_flags([f]):
nflags.append(f)
self.cc_is_cached = True
@_Cache.me
def cc_test_flags(self, flags):
"""
Returns True if the compiler supports 'flags'.
"""
assert(isinstance(flags, list))
self.dist_log("testing flags", flags)
test_path = os.path.join(self.conf_check_path, "test_flags.c")
test = self.dist_test(test_path, flags)
if not test:
self.dist_log("testing failed", stderr=True)
return test
def cc_normalize_flags(self, flags):
"""
Remove the conflicts that caused due gathering implied features flags.
Parameters
----------
'flags' list, compiler flags
flags should be sorted from the lowest to the highest interest.
Returns
-------
list, filtered from any conflicts.
Examples
--------
>>> self.cc_normalize_flags(['-march=armv8.2-a+fp16', '-march=armv8.2-a+dotprod'])
['armv8.2-a+fp16+dotprod']
>>> self.cc_normalize_flags(
['-msse', '-msse2', '-msse3', '-mssse3', '-msse4.1', '-msse4.2', '-mavx', '-march=core-avx2']
)
['-march=core-avx2']
"""
assert(isinstance(flags, list))
if self.cc_is_gcc or self.cc_is_clang or self.cc_is_icc:
return self._cc_normalize_unix(flags)
if self.cc_is_msvc or self.cc_is_iccw:
return self._cc_normalize_win(flags)
return flags
_cc_normalize_unix_mrgx = re.compile(
# 1- to check the highest of
r"^(-mcpu=|-march=|-x[A-Z0-9\-])"
)
_cc_normalize_unix_frgx = re.compile(
# 2- to remove any flags starts with
# -march, -mcpu, -x(INTEL) and '-m' without '='
r"^(?!(-mcpu=|-march=|-x[A-Z0-9\-]))(?!-m[a-z0-9\-\.]*.$)"
)
_cc_normalize_unix_krgx = re.compile(
# 3- keep only the highest of
r"^(-mfpu|-mtune)"
)
_cc_normalize_arch_ver = re.compile(
r"[0-9.]"
)
def _cc_normalize_unix(self, flags):
def ver_flags(f):
# arch ver subflag
# -march=armv8.2-a+fp16fml
tokens = f.split('+')
ver = float('0' + ''.join(
re.findall(self._cc_normalize_arch_ver, tokens[0])
))
return ver, tokens[0], tokens[1:]
if len(flags) <= 1:
return flags
# get the highest matched flag
for i, cur_flag in enumerate(reversed(flags)):
if not re.match(self._cc_normalize_unix_mrgx, cur_flag):
continue
lower_flags = flags[:-(i+1)]
upper_flags = flags[-i:]
filterd = list(filter(
self._cc_normalize_unix_frgx.search, lower_flags
))
# gather subflags
ver, arch, subflags = ver_flags(cur_flag)
if ver > 0 and len(subflags) > 0:
for xflag in lower_flags:
xver, _, xsubflags = ver_flags(xflag)
if ver == xver:
subflags = xsubflags + subflags
cur_flag = arch + '+' + '+'.join(subflags)
flags = filterd + [cur_flag]
if i > 0:
flags += upper_flags
break
# to remove overridable flags
final_flags = []
matched = set()
for f in reversed(flags):
match = re.match(self._cc_normalize_unix_krgx, f)
if not match:
pass
elif match[0] in matched:
continue
else:
matched.add(match[0])
final_flags.insert(0, f)
return final_flags
_cc_normalize_win_frgx = re.compile(
r"^(?!(/arch\:|/Qx\:))"
)
_cc_normalize_win_mrgx = re.compile(
r"^(/arch|/Qx:)"
)
def _cc_normalize_win(self, flags):
for i, f in enumerate(reversed(flags)):
if not re.match(self._cc_normalize_win_mrgx, f):
continue
i += 1
return list(filter(
self._cc_normalize_win_frgx.search, flags[:-i]
)) + flags[-i:]
return flags
class _Feature:
"""A helper class for `CCompilerOpt` that managing CPU features.
Attributes
----------
feature_supported : dict
Dictionary containing all CPU features that supported
by the platform, according to the specified values in attribute
`_Config.conf_features` and `_Config.conf_features_partial()`
feature_min : set
The minimum support of CPU features, according to
the specified values in attribute `_Config.conf_min_features`.
"""
def __init__(self):
if hasattr(self, "feature_is_cached"):
return
self.feature_supported = pfeatures = self.conf_features_partial()
for feature_name in list(pfeatures.keys()):
feature = pfeatures[feature_name]
cfeature = self.conf_features[feature_name]
feature.update({
k:v for k,v in cfeature.items() if k not in feature
})
disabled = feature.get("disable")
if disabled is not None:
pfeatures.pop(feature_name)
self.dist_log(
"feature '%s' is disabled," % feature_name,
disabled, stderr=True
)
continue
# list is used internally for these options
for option in (
"implies", "group", "detect", "headers", "flags", "extra_checks"
) :
oval = feature.get(option)
if isinstance(oval, str):
feature[option] = oval.split()
self.feature_min = set()
min_f = self.conf_min_features.get(self.cc_march, "")
for F in min_f.upper().split():
if F in self.feature_supported:
self.feature_min.add(F)
self.feature_is_cached = True
def feature_names(self, names=None, force_flags=None):
"""
Returns a set of CPU feature names that supported by platform and the **C** compiler.
Parameters
----------
'names': sequence or None, optional
Specify certain CPU features to test it against the **C** compiler.
if None(default), it will test all current supported features.
**Note**: feature names must be in upper-case.
'force_flags': list or None, optional
If None(default), default compiler flags for every CPU feature will be used
during the test.
"""
assert(
names is None or (
not isinstance(names, str) and
hasattr(names, "__iter__")
)
)
assert(force_flags is None or isinstance(force_flags, list))
if names is None:
names = self.feature_supported.keys()
supported_names = set()
for f in names:
if self.feature_is_supported(f, force_flags=force_flags):
supported_names.add(f)
return supported_names
def feature_is_exist(self, name):
"""
Returns True if a certain feature is exist and covered within
`_Config.conf_features`.
Parameters
----------
'name': str
feature name in uppercase.
"""
assert(name.isupper())
return name in self.conf_features
def feature_sorted(self, names, reverse=False):
"""
Sort a list of CPU features ordered by the lowest interest.
Parameters
----------
'names': sequence
sequence of supported feature names in uppercase.
'reverse': bool, optional
If true, the sorted features is reversed. (highest interest)
Returns
-------
list, sorted CPU features
"""
def sort_cb(k):
if isinstance(k, str):
return self.feature_supported[k]["interest"]
# multiple features
rank = max([self.feature_supported[f]["interest"] for f in k])
# FIXME: that's not a safe way to increase the rank for
# multi targets
rank += len(k) -1
return rank
return sorted(names, reverse=reverse, key=sort_cb)
def feature_implies(self, names, keep_origins=False):
"""
Return a set of CPU features that implied by 'names'
Parameters
----------
names: str or sequence of str
CPU feature name(s) in uppercase.
keep_origins: bool
if False(default) then the returned set will not contain any
features from 'names'. This case happens only when two features
imply each other.
Examples
--------
>>> self.feature_implies("SSE3")
{'SSE', 'SSE2'}
>>> self.feature_implies("SSE2")
{'SSE'}
>>> self.feature_implies("SSE2", keep_origins=True)
# 'SSE2' found here since 'SSE' and 'SSE2' imply each other
{'SSE', 'SSE2'}
"""
def get_implies(name, _caller=set()):
implies = set()
d = self.feature_supported[name]
for i in d.get("implies", []):
implies.add(i)
if i in _caller:
# infinity recursive guard since
# features can imply each other
continue
_caller.add(name)
implies = implies.union(get_implies(i, _caller))
return implies
if isinstance(names, str):
implies = get_implies(names)
names = [names]
else:
assert(hasattr(names, "__iter__"))
implies = set()
for n in names:
implies = implies.union(get_implies(n))
if not keep_origins:
implies.difference_update(names)
return implies
def feature_implies_c(self, names):
"""same as feature_implies() but combining 'names'"""
if isinstance(names, str):
names = set((names,))
else:
names = set(names)
return names.union(self.feature_implies(names))
def feature_ahead(self, names):
"""
Return list of features in 'names' after remove any
implied features and keep the origins.
Parameters
----------
'names': sequence
sequence of CPU feature names in uppercase.
Returns
-------
list of CPU features sorted as-is 'names'
Examples
--------
>>> self.feature_ahead(["SSE2", "SSE3", "SSE41"])
["SSE41"]
# assume AVX2 and FMA3 implies each other and AVX2
# is the highest interest
>>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
["AVX2"]
# assume AVX2 and FMA3 don't implies each other
>>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
["AVX2", "FMA3"]
"""
assert(
not isinstance(names, str)
and hasattr(names, '__iter__')
)
implies = self.feature_implies(names, keep_origins=True)
ahead = [n for n in names if n not in implies]
if len(ahead) == 0:
# return the highest interested feature
# if all features imply each other
ahead = self.feature_sorted(names, reverse=True)[:1]
return ahead
def feature_untied(self, names):
"""
same as 'feature_ahead()' but if both features implied each other
and keep the highest interest.
Parameters
----------
'names': sequence
sequence of CPU feature names in uppercase.
Returns
-------
list of CPU features sorted as-is 'names'
Examples
--------
>>> self.feature_untied(["SSE2", "SSE3", "SSE41"])
["SSE2", "SSE3", "SSE41"]
# assume AVX2 and FMA3 implies each other
>>> self.feature_untied(["SSE2", "SSE3", "SSE41", "FMA3", "AVX2"])
["SSE2", "SSE3", "SSE41", "AVX2"]
"""
assert(
not isinstance(names, str)
and hasattr(names, '__iter__')
)
final = []
for n in names:
implies = self.feature_implies(n)
tied = [
nn for nn in final
if nn in implies and n in self.feature_implies(nn)
]
if tied:
tied = self.feature_sorted(tied + [n])
if n not in tied[1:]:
continue
final.remove(tied[:1][0])
final.append(n)
return final
def feature_get_til(self, names, keyisfalse):
"""
same as `feature_implies_c()` but stop collecting implied
features when feature's option that provided through
parameter 'keyisfalse' is False, also sorting the returned
features.
"""
def til(tnames):
# sort from highest to lowest interest then cut if "key" is False
tnames = self.feature_implies_c(tnames)
tnames = self.feature_sorted(tnames, reverse=True)
for i, n in enumerate(tnames):
if not self.feature_supported[n].get(keyisfalse, True):
tnames = tnames[:i+1]
break
return tnames
if isinstance(names, str) or len(names) <= 1:
names = til(names)
# normalize the sort
names.reverse()
return names
names = self.feature_ahead(names)
names = {t for n in names for t in til(n)}
return self.feature_sorted(names)
def feature_detect(self, names):
"""
Return a list of CPU features that required to be detected
sorted from the lowest to highest interest.
"""
names = self.feature_get_til(names, "implies_detect")
detect = []
for n in names:
d = self.feature_supported[n]
detect += d.get("detect", d.get("group", [n]))
return detect
@_Cache.me
def feature_flags(self, names):
"""
Return a list of CPU features flags sorted from the lowest
to highest interest.
"""
names = self.feature_sorted(self.feature_implies_c(names))
flags = []
for n in names:
d = self.feature_supported[n]
f = d.get("flags", [])
if not f or not self.cc_test_flags(f):
continue
flags += f
return self.cc_normalize_flags(flags)
@_Cache.me
def feature_test(self, name, force_flags=None):
"""
Test a certain CPU feature against the compiler through its own
check file.
Parameters
----------
'name': str
Supported CPU feature name.
'force_flags': list or None, optional
If None(default), the returned flags from `feature_flags()`
will be used.
"""
if force_flags is None:
force_flags = self.feature_flags(name)
self.dist_log(
"testing feature '%s' with flags (%s)" % (
name, ' '.join(force_flags)
))
# Each CPU feature must have C source code contains at
# least one intrinsic or instruction related to this feature.
test_path = os.path.join(
self.conf_check_path, "cpu_%s.c" % name.lower()
)
if not os.path.exists(test_path):
self.dist_fatal("feature test file is not exist", test_path)
test = self.dist_test(test_path, force_flags + self.cc_flags["werror"])
if not test:
self.dist_log("testing failed", stderr=True)
return test
@_Cache.me
def feature_is_supported(self, name, force_flags=None):
"""
Check if a certain CPU feature is supported by the platform and compiler.
Parameters
----------
'name': str
CPU feature name in uppercase.
'force_flags': list or None, optional
If None(default), default compiler flags for every CPU feature will be used
during test.
"""
assert(name.isupper())
assert(force_flags is None or isinstance(force_flags, list))
supported = name in self.feature_supported
if supported:
for impl in self.feature_implies(name):
if not self.feature_test(impl, force_flags):
return False
if not self.feature_test(name, force_flags):
return False
return supported
@_Cache.me
def feature_can_autovec(self, name):
"""
check if the feature can be auto-vectorized by the compiler
"""
assert(isinstance(name, str))
d = self.feature_supported[name]
can = d.get("autovec", None)
if can is None:
valid_flags = [
self.cc_test_flags([f]) for f in d.get("flags", [])
]
can = valid_flags and any(valid_flags)
return can
@_Cache.me
def feature_extra_checks(self, name):
"""
Return a list of supported extra checks after testing them against
the compiler.
Parameters
----------
names: str
CPU feature name in uppercase.
"""
assert isinstance(name, str)
d = self.feature_supported[name]
extra_checks = d.get("extra_checks", [])
if not extra_checks:
return []
self.dist_log("Testing extra checks for feature '%s'" % name, extra_checks)
flags = self.feature_flags(name)
available = []
not_available = []
for chk in extra_checks:
test_path = os.path.join(
self.conf_check_path, "extra_%s.c" % chk.lower()
)
if not os.path.exists(test_path):
self.dist_fatal("extra check file does not exist", test_path)
is_supported = self.dist_test(test_path, flags + self.cc_flags["werror"])
if is_supported:
available.append(chk)
else:
not_available.append(chk)
if not_available:
self.dist_log("testing failed for checks", not_available, stderr=True)
return available
def feature_c_preprocessor(self, feature_name, tabs=0):
"""
Generate C preprocessor definitions and include headers of a CPU feature.
Parameters
----------
'feature_name': str
CPU feature name in uppercase.
'tabs': int
if > 0, align the generated strings to the right depend on number of tabs.
Returns
-------
str, generated C preprocessor
Examples
--------
>>> self.feature_c_preprocessor("SSE3")
/** SSE3 **/
#define NPY_HAVE_SSE3 1
#include <pmmintrin.h>
"""
assert(feature_name.isupper())
feature = self.feature_supported.get(feature_name)
assert(feature is not None)
prepr = [
"/** %s **/" % feature_name,
"#define %sHAVE_%s 1" % (self.conf_c_prefix, feature_name)
]
prepr += [
"#include <%s>" % h for h in feature.get("headers", [])
]
extra_defs = feature.get("group", [])
extra_defs += self.feature_extra_checks(feature_name)
for edef in extra_defs:
# Guard extra definitions in case of duplicate with
# another feature
prepr += [
"#ifndef %sHAVE_%s" % (self.conf_c_prefix, edef),
"\t#define %sHAVE_%s 1" % (self.conf_c_prefix, edef),
"#endif",
]
if tabs > 0:
prepr = [('\t'*tabs) + l for l in prepr]
return '\n'.join(prepr)
class _Parse:
"""A helper class that parsing main arguments of `CCompilerOpt`,
also parsing configuration statements in dispatch-able sources.
Parameters
----------
cpu_baseline: str or None
minimal set of required CPU features or special options.
cpu_dispatch: str or None
dispatched set of additional CPU features or special options.
Special options can be:
- **MIN**: Enables the minimum CPU features that utilized via `_Config.conf_min_features`
- **MAX**: Enables all supported CPU features by the Compiler and platform.
- **NATIVE**: Enables all CPU features that supported by the current machine.
- **NONE**: Enables nothing
- **Operand +/-**: remove or add features, useful with options **MAX**, **MIN** and **NATIVE**.
NOTE: operand + is only added for nominal reason.
NOTES:
- Case-insensitive among all CPU features and special options.
- Comma or space can be used as a separator.
- If the CPU feature is not supported by the user platform or compiler,
it will be skipped rather than raising a fatal error.
- Any specified CPU features to 'cpu_dispatch' will be skipped if its part of CPU baseline features
- 'cpu_baseline' force enables implied features.
Attributes
----------
parse_baseline_names : list
Final CPU baseline's feature names(sorted from low to high)
parse_baseline_flags : list
Compiler flags of baseline features
parse_dispatch_names : list
Final CPU dispatch-able feature names(sorted from low to high)
parse_target_groups : dict
Dictionary containing initialized target groups that configured
through class attribute `conf_target_groups`.
The key is represent the group name and value is a tuple
contains three items :
- bool, True if group has the 'baseline' option.
- list, list of CPU features.
- list, list of extra compiler flags.
"""
def __init__(self, cpu_baseline, cpu_dispatch):
self._parse_policies = dict(
# POLICY NAME, (HAVE, NOT HAVE, [DEB])
KEEP_BASELINE = (
None, self._parse_policy_not_keepbase,
[]
),
KEEP_SORT = (
self._parse_policy_keepsort,
self._parse_policy_not_keepsort,
[]
),
MAXOPT = (
self._parse_policy_maxopt, None,
[]
),
WERROR = (
self._parse_policy_werror, None,
[]
),
AUTOVEC = (
self._parse_policy_autovec, None,
["MAXOPT"]
)
)
if hasattr(self, "parse_is_cached"):
return
self.parse_baseline_names = []
self.parse_baseline_flags = []
self.parse_dispatch_names = []
self.parse_target_groups = {}
if self.cc_noopt:
# skip parsing baseline and dispatch args and keep parsing target groups
cpu_baseline = cpu_dispatch = None
self.dist_log("check requested baseline")
if cpu_baseline is not None:
cpu_baseline = self._parse_arg_features("cpu_baseline", cpu_baseline)
baseline_names = self.feature_names(cpu_baseline)
self.parse_baseline_flags = self.feature_flags(baseline_names)
self.parse_baseline_names = self.feature_sorted(
self.feature_implies_c(baseline_names)
)
self.dist_log("check requested dispatch-able features")
if cpu_dispatch is not None:
cpu_dispatch_ = self._parse_arg_features("cpu_dispatch", cpu_dispatch)
cpu_dispatch = {
f for f in cpu_dispatch_
if f not in self.parse_baseline_names
}
conflict_baseline = cpu_dispatch_.difference(cpu_dispatch)
self.parse_dispatch_names = self.feature_sorted(
self.feature_names(cpu_dispatch)
)
if len(conflict_baseline) > 0:
self.dist_log(
"skip features", conflict_baseline, "since its part of baseline"
)
self.dist_log("initialize targets groups")
for group_name, tokens in self.conf_target_groups.items():
self.dist_log("parse target group", group_name)
GROUP_NAME = group_name.upper()
if not tokens or not tokens.strip():
# allow empty groups, useful in case if there's a need
# to disable certain group since '_parse_target_tokens()'
# requires at least one valid target
self.parse_target_groups[GROUP_NAME] = (
False, [], []
)
continue
has_baseline, features, extra_flags = \
self._parse_target_tokens(tokens)
self.parse_target_groups[GROUP_NAME] = (
has_baseline, features, extra_flags
)
self.parse_is_cached = True
def parse_targets(self, source):
"""
Fetch and parse configuration statements that required for
defining the targeted CPU features, statements should be declared
in the top of source in between **C** comment and start
with a special mark **@targets**.
Configuration statements are sort of keywords representing
CPU features names, group of statements and policies, combined
together to determine the required optimization.
Parameters
----------
source: str
the path of **C** source file.
Returns
-------
- bool, True if group has the 'baseline' option
- list, list of CPU features
- list, list of extra compiler flags
"""
self.dist_log("looking for '@targets' inside -> ", source)
# get lines between /*@targets and */
with open(source) as fd:
tokens = ""
max_to_reach = 1000 # good enough, isn't?
start_with = "@targets"
start_pos = -1
end_with = "*/"
end_pos = -1
for current_line, line in enumerate(fd):
if current_line == max_to_reach:
self.dist_fatal("reached the max of lines")
break
if start_pos == -1:
start_pos = line.find(start_with)
if start_pos == -1:
continue
start_pos += len(start_with)
tokens += line
end_pos = line.find(end_with)
if end_pos != -1:
end_pos += len(tokens) - len(line)
break
if start_pos == -1:
self.dist_fatal("expected to find '%s' within a C comment" % start_with)
if end_pos == -1:
self.dist_fatal("expected to end with '%s'" % end_with)
tokens = tokens[start_pos:end_pos]
return self._parse_target_tokens(tokens)
_parse_regex_arg = re.compile(r'\s|[,]|([+-])')
def _parse_arg_features(self, arg_name, req_features):
if not isinstance(req_features, str):
self.dist_fatal("expected a string in '%s'" % arg_name)
final_features = set()
# space and comma can be used as a separator
tokens = list(filter(None, re.split(self._parse_regex_arg, req_features)))
append = True # append is the default
for tok in tokens:
if tok[0] in ("#", "$"):
self.dist_fatal(
arg_name, "target groups and policies "
"aren't allowed from arguments, "
"only from dispatch-able sources"
)
if tok == '+':
append = True
continue
if tok == '-':
append = False
continue
TOK = tok.upper() # we use upper-case internally
features_to = set()
if TOK == "NONE":
pass
elif TOK == "NATIVE":
native = self.cc_flags["native"]
if not native:
self.dist_fatal(arg_name,
"native option isn't supported by the compiler"
)
features_to = self.feature_names(force_flags=native)
elif TOK == "MAX":
features_to = self.feature_supported.keys()
elif TOK == "MIN":
features_to = self.feature_min
else:
if TOK in self.feature_supported:
features_to.add(TOK)
else:
if not self.feature_is_exist(TOK):
self.dist_fatal(arg_name,
", '%s' isn't a known feature or option" % tok
)
if append:
final_features = final_features.union(features_to)
else:
final_features = final_features.difference(features_to)
append = True # back to default
return final_features
_parse_regex_target = re.compile(r'\s|[*,/]|([()])')
def _parse_target_tokens(self, tokens):
assert(isinstance(tokens, str))
final_targets = [] # to keep it sorted as specified
extra_flags = []
has_baseline = False
skipped = set()
policies = set()
multi_target = None
tokens = list(filter(None, re.split(self._parse_regex_target, tokens)))
if not tokens:
self.dist_fatal("expected one token at least")
for tok in tokens:
TOK = tok.upper()
ch = tok[0]
if ch in ('+', '-'):
self.dist_fatal(
"+/- are 'not' allowed from target's groups or @targets, "
"only from cpu_baseline and cpu_dispatch parms"
)
elif ch == '$':
if multi_target is not None:
self.dist_fatal(
"policies aren't allowed inside multi-target '()'"
", only CPU features"
)
policies.add(self._parse_token_policy(TOK))
elif ch == '#':
if multi_target is not None:
self.dist_fatal(
"target groups aren't allowed inside multi-target '()'"
", only CPU features"
)
has_baseline, final_targets, extra_flags = \
self._parse_token_group(TOK, has_baseline, final_targets, extra_flags)
elif ch == '(':
if multi_target is not None:
self.dist_fatal("unclosed multi-target, missing ')'")
multi_target = set()
elif ch == ')':
if multi_target is None:
self.dist_fatal("multi-target opener '(' wasn't found")
targets = self._parse_multi_target(multi_target)
if targets is None:
skipped.add(tuple(multi_target))
else:
if len(targets) == 1:
targets = targets[0]
if targets and targets not in final_targets:
final_targets.append(targets)
multi_target = None # back to default
else:
if TOK == "BASELINE":
if multi_target is not None:
self.dist_fatal("baseline isn't allowed inside multi-target '()'")
has_baseline = True
continue
if multi_target is not None:
multi_target.add(TOK)
continue
if not self.feature_is_exist(TOK):
self.dist_fatal("invalid target name '%s'" % TOK)
is_enabled = (
TOK in self.parse_baseline_names or
TOK in self.parse_dispatch_names
)
if is_enabled:
if TOK not in final_targets:
final_targets.append(TOK)
continue
skipped.add(TOK)
if multi_target is not None:
self.dist_fatal("unclosed multi-target, missing ')'")
if skipped:
self.dist_log(
"skip targets", skipped,
"not part of baseline or dispatch-able features"
)
final_targets = self.feature_untied(final_targets)
# add polices dependencies
for p in list(policies):
_, _, deps = self._parse_policies[p]
for d in deps:
if d in policies:
continue
self.dist_log(
"policy '%s' force enables '%s'" % (
p, d
))
policies.add(d)
# release policies filtrations
for p, (have, nhave, _) in self._parse_policies.items():
func = None
if p in policies:
func = have
self.dist_log("policy '%s' is ON" % p)
else:
func = nhave
if not func:
continue
has_baseline, final_targets, extra_flags = func(
has_baseline, final_targets, extra_flags
)
return has_baseline, final_targets, extra_flags
def _parse_token_policy(self, token):
"""validate policy token"""
if len(token) <= 1 or token[-1:] == token[0]:
self.dist_fatal("'$' must stuck in the begin of policy name")
token = token[1:]
if token not in self._parse_policies:
self.dist_fatal(
"'%s' is an invalid policy name, available policies are" % token,
self._parse_policies.keys()
)
return token
def _parse_token_group(self, token, has_baseline, final_targets, extra_flags):
"""validate group token"""
if len(token) <= 1 or token[-1:] == token[0]:
self.dist_fatal("'#' must stuck in the begin of group name")
token = token[1:]
ghas_baseline, gtargets, gextra_flags = self.parse_target_groups.get(
token, (False, None, [])
)
if gtargets is None:
self.dist_fatal(
"'%s' is an invalid target group name, " % token + \
"available target groups are",
self.parse_target_groups.keys()
)
if ghas_baseline:
has_baseline = True
# always keep sorting as specified
final_targets += [f for f in gtargets if f not in final_targets]
extra_flags += [f for f in gextra_flags if f not in extra_flags]
return has_baseline, final_targets, extra_flags
def _parse_multi_target(self, targets):
"""validate multi targets that defined between parentheses()"""
# remove any implied features and keep the origins
if not targets:
self.dist_fatal("empty multi-target '()'")
if not all([
self.feature_is_exist(tar) for tar in targets
]) :
self.dist_fatal("invalid target name in multi-target", targets)
if not all([
(
tar in self.parse_baseline_names or
tar in self.parse_dispatch_names
)
for tar in targets
]) :
return None
targets = self.feature_ahead(targets)
if not targets:
return None
# force sort multi targets, so it can be comparable
targets = self.feature_sorted(targets)
targets = tuple(targets) # hashable
return targets
def _parse_policy_not_keepbase(self, has_baseline, final_targets, extra_flags):
"""skip all baseline features"""
skipped = []
for tar in final_targets[:]:
is_base = False
if isinstance(tar, str):
is_base = tar in self.parse_baseline_names
else:
# multi targets
is_base = all([
f in self.parse_baseline_names
for f in tar
])
if is_base:
skipped.append(tar)
final_targets.remove(tar)
if skipped:
self.dist_log("skip baseline features", skipped)
return has_baseline, final_targets, extra_flags
def _parse_policy_keepsort(self, has_baseline, final_targets, extra_flags):
"""leave a notice that $keep_sort is on"""
self.dist_log(
"policy 'keep_sort' is on, dispatch-able targets", final_targets, "\n"
"are 'not' sorted depend on the highest interest but"
"as specified in the dispatch-able source or the extra group"
)
return has_baseline, final_targets, extra_flags
def _parse_policy_not_keepsort(self, has_baseline, final_targets, extra_flags):
"""sorted depend on the highest interest"""
final_targets = self.feature_sorted(final_targets, reverse=True)
return has_baseline, final_targets, extra_flags
def _parse_policy_maxopt(self, has_baseline, final_targets, extra_flags):
"""append the compiler optimization flags"""
if self.cc_has_debug:
self.dist_log("debug mode is detected, policy 'maxopt' is skipped.")
elif self.cc_noopt:
self.dist_log("optimization is disabled, policy 'maxopt' is skipped.")
else:
flags = self.cc_flags["opt"]
if not flags:
self.dist_log(
"current compiler doesn't support optimization flags, "
"policy 'maxopt' is skipped", stderr=True
)
else:
extra_flags += flags
return has_baseline, final_targets, extra_flags
def _parse_policy_werror(self, has_baseline, final_targets, extra_flags):
"""force warnings to treated as errors"""
flags = self.cc_flags["werror"]
if not flags:
self.dist_log(
"current compiler doesn't support werror flags, "
"warnings will 'not' treated as errors", stderr=True
)
else:
self.dist_log("compiler warnings are treated as errors")
extra_flags += flags
return has_baseline, final_targets, extra_flags
def _parse_policy_autovec(self, has_baseline, final_targets, extra_flags):
"""skip features that has no auto-vectorized support by compiler"""
skipped = []
for tar in final_targets[:]:
if isinstance(tar, str):
can = self.feature_can_autovec(tar)
else: # multiple target
can = all([
self.feature_can_autovec(t)
for t in tar
])
if not can:
final_targets.remove(tar)
skipped.append(tar)
if skipped:
self.dist_log("skip non auto-vectorized features", skipped)
return has_baseline, final_targets, extra_flags
class CCompilerOpt(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse):
"""
A helper class for `CCompiler` aims to provide extra build options
to effectively control of compiler optimizations that are directly
related to CPU features.
"""
def __init__(self, ccompiler, cpu_baseline="min", cpu_dispatch="max", cache_path=None):
_Config.__init__(self)
_Distutils.__init__(self, ccompiler)
_Cache.__init__(self, cache_path, self.dist_info(), cpu_baseline, cpu_dispatch)
_CCompiler.__init__(self)
_Feature.__init__(self)
if not self.cc_noopt and self.cc_has_native:
self.dist_log(
"native flag is specified through environment variables. "
"force cpu-baseline='native'"
)
cpu_baseline = "native"
_Parse.__init__(self, cpu_baseline, cpu_dispatch)
# keep the requested features untouched, need it later for report
# and trace purposes
self._requested_baseline = cpu_baseline
self._requested_dispatch = cpu_dispatch
# key is the dispatch-able source and value is a tuple
# contains two items (has_baseline[boolean], dispatched-features[list])
self.sources_status = getattr(self, "sources_status", {})
# every instance should has a separate one
self.cache_private.add("sources_status")
# set it at the end to make sure the cache writing was done after init
# this class
self.hit_cache = hasattr(self, "hit_cache")
def is_cached(self):
"""
Returns True if the class loaded from the cache file
"""
return self.cache_infile and self.hit_cache
def cpu_baseline_flags(self):
"""
Returns a list of final CPU baseline compiler flags
"""
return self.parse_baseline_flags
def cpu_baseline_names(self):
"""
return a list of final CPU baseline feature names
"""
return self.parse_baseline_names
def cpu_dispatch_names(self):
"""
return a list of final CPU dispatch feature names
"""
return self.parse_dispatch_names
def try_dispatch(self, sources, src_dir=None, **kwargs):
"""
Compile one or more dispatch-able sources and generates object files,
also generates abstract C config headers and macros that
used later for the final runtime dispatching process.
The mechanism behind it is to takes each source file that specified
in 'sources' and branching it into several files depend on
special configuration statements that must be declared in the
top of each source which contains targeted CPU features,
then it compiles every branched source with the proper compiler flags.
Parameters
----------
sources : list
Must be a list of dispatch-able sources file paths,
and configuration statements must be declared inside
each file.
src_dir : str
Path of parent directory for the generated headers and wrapped sources.
If None(default) the files will generated in-place.
**kwargs : any
Arguments to pass on to the `CCompiler.compile()`
Returns
-------
list : generated object files
Raises
------
CompileError
Raises by `CCompiler.compile()` on compiling failure.
DistutilsError
Some errors during checking the sanity of configuration statements.
See Also
--------
parse_targets :
Parsing the configuration statements of dispatch-able sources.
"""
to_compile = {}
baseline_flags = self.cpu_baseline_flags()
include_dirs = kwargs.setdefault("include_dirs", [])
for src in sources:
output_dir = os.path.dirname(src)
if src_dir:
if not output_dir.startswith(src_dir):
output_dir = os.path.join(src_dir, output_dir)
if output_dir not in include_dirs:
# To allow including the generated config header(*.dispatch.h)
# by the dispatch-able sources
include_dirs.append(output_dir)
has_baseline, targets, extra_flags = self.parse_targets(src)
nochange = self._generate_config(output_dir, src, targets, has_baseline)
for tar in targets:
tar_src = self._wrap_target(output_dir, src, tar, nochange=nochange)
flags = tuple(extra_flags + self.feature_flags(tar))
to_compile.setdefault(flags, []).append(tar_src)
if has_baseline:
flags = tuple(extra_flags + baseline_flags)
to_compile.setdefault(flags, []).append(src)
self.sources_status[src] = (has_baseline, targets)
# For these reasons, the sources are compiled in a separate loop:
# - Gathering all sources with the same flags to benefit from
# the parallel compiling as much as possible.
# - To generate all config headers of the dispatchable sources,
# before the compilation in case if there are dependency relationships
# among them.
objects = []
for flags, srcs in to_compile.items():
objects += self.dist_compile(srcs, list(flags), **kwargs)
return objects
def generate_dispatch_header(self, header_path):
"""
Generate the dispatch header which containing all definitions
and headers of instruction-sets for the enabled CPU baseline and
dispatch-able features.
Its highly recommended to take a look at the generated header
also the generated source files via `try_dispatch()`
in order to get the full picture.
"""
self.dist_log("generate CPU dispatch header: (%s)" % header_path)
baseline_names = self.cpu_baseline_names()
dispatch_names = self.cpu_dispatch_names()
baseline_len = len(baseline_names)
dispatch_len = len(dispatch_names)
with open(header_path, 'w') as f:
baseline_calls = ' \\\n'.join([
(
"\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
) % (self.conf_c_prefix, f)
for f in baseline_names
])
dispatch_calls = ' \\\n'.join([
(
"\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
) % (self.conf_c_prefix, f)
for f in dispatch_names
])
f.write(textwrap.dedent("""\
/*
* AUTOGENERATED DON'T EDIT
* Please make changes to the code generator (distutils/ccompiler_opt.py)
*/
#define {pfx}WITH_CPU_BASELINE "{baseline_str}"
#define {pfx}WITH_CPU_DISPATCH "{dispatch_str}"
#define {pfx}WITH_CPU_BASELINE_N {baseline_len}
#define {pfx}WITH_CPU_DISPATCH_N {dispatch_len}
#define {pfx}WITH_CPU_EXPAND_(X) X
#define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \\
{baseline_calls}
#define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \\
{dispatch_calls}
""").format(
pfx=self.conf_c_prefix, baseline_str=" ".join(baseline_names),
dispatch_str=" ".join(dispatch_names), baseline_len=baseline_len,
dispatch_len=dispatch_len, baseline_calls=baseline_calls,
dispatch_calls=dispatch_calls
))
baseline_pre = ''
for name in baseline_names:
baseline_pre += self.feature_c_preprocessor(name, tabs=1) + '\n'
dispatch_pre = ''
for name in dispatch_names:
dispatch_pre += textwrap.dedent("""\
#ifdef {pfx}CPU_TARGET_{name}
{pre}
#endif /*{pfx}CPU_TARGET_{name}*/
""").format(
pfx=self.conf_c_prefix_, name=name, pre=self.feature_c_preprocessor(
name, tabs=1
))
f.write(textwrap.dedent("""\
/******* baseline features *******/
{baseline_pre}
/******* dispatch features *******/
{dispatch_pre}
""").format(
pfx=self.conf_c_prefix_, baseline_pre=baseline_pre,
dispatch_pre=dispatch_pre
))
def report(self, full=False):
report = []
baseline_rows = []
dispatch_rows = []
report.append(("CPU baseline", baseline_rows))
report.append(("", ""))
report.append(("CPU dispatch", dispatch_rows))
########## baseline ##########
if self.cc_noopt:
baseline_rows.append((
"Requested", "optimization disabled %s" % (
"(unsupported arch)" if self.cc_on_noarch else ""
)
))
else:
baseline_rows.append(("Requested", repr(self._requested_baseline)))
baseline_names = self.cpu_baseline_names()
baseline_rows.append((
"Enabled", (' '.join(baseline_names) if baseline_names else "none")
))
baseline_flags = self.cpu_baseline_flags()
baseline_rows.append((
"Flags", (' '.join(baseline_flags) if baseline_flags else "none")
))
extra_checks = []
for name in baseline_names:
extra_checks += self.feature_extra_checks(name)
baseline_rows.append((
"Extra checks", (' '.join(extra_checks) if extra_checks else "none")
))
########## dispatch ##########
if self.cc_noopt:
dispatch_rows.append((
"Requested", "optimization disabled %s" % (
"(unsupported arch)" if self.cc_on_noarch else ""
)
))
else:
dispatch_rows.append(("Requested", repr(self._requested_dispatch)))
dispatch_names = self.cpu_dispatch_names()
dispatch_rows.append((
"Enabled", (' '.join(dispatch_names) if dispatch_names else "none")
))
########## Generated ##########
# TODO:
# - collect object names from 'try_dispatch()'
# then get size of each object and printed
# - give more details about the features that not
# generated due compiler support
# - find a better output's design.
#
target_sources = {}
for source, (_, targets) in self.sources_status.items():
for tar in targets:
target_sources.setdefault(tar, []).append(source)
if not full or not target_sources:
generated = ""
for tar in self.feature_sorted(target_sources):
sources = target_sources[tar]
name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
generated += name + "[%d] " % len(sources)
dispatch_rows.append(("Generated", generated[:-1] if generated else "none"))
else:
dispatch_rows.append(("Generated", ''))
for tar in self.feature_sorted(target_sources):
sources = target_sources[tar]
pretty_name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
flags = ' '.join(self.feature_flags(tar))
implies = ' '.join(self.feature_sorted(self.feature_implies(tar)))
detect = ' '.join(self.feature_detect(tar))
extra_checks = []
for name in ((tar,) if isinstance(tar, str) else tar):
extra_checks += self.feature_extra_checks(name)
extra_checks = (' '.join(extra_checks) if extra_checks else "none")
dispatch_rows.append(('', ''))
dispatch_rows.append((pretty_name, implies))
dispatch_rows.append(("Flags", flags))
dispatch_rows.append(("Extra checks", extra_checks))
dispatch_rows.append(("Detect", detect))
for src in sources:
dispatch_rows.append(("", src))
###############################
# TODO: add support for 'markdown' format
text = []
secs_len = [len(secs) for secs, _ in report]
cols_len = [len(col) for _, rows in report for col, _ in rows]
tab = ' ' * 2
pad = max(max(secs_len), max(cols_len))
for sec, rows in report:
if not sec:
text.append("") # empty line
continue
sec += ' ' * (pad - len(sec))
text.append(sec + tab + ': ')
for col, val in rows:
col += ' ' * (pad - len(col))
text.append(tab + col + ': ' + val)
return '\n'.join(text)
def _wrap_target(self, output_dir, dispatch_src, target, nochange=False):
assert(isinstance(target, (str, tuple)))
if isinstance(target, str):
ext_name = target_name = target
else:
# multi-target
ext_name = '.'.join(target)
target_name = '__'.join(target)
wrap_path = os.path.join(output_dir, os.path.basename(dispatch_src))
wrap_path = "{0}.{2}{1}".format(*os.path.splitext(wrap_path), ext_name.lower())
if nochange and os.path.exists(wrap_path):
return wrap_path
self.dist_log("wrap dispatch-able target -> ", wrap_path)
# sorting for readability
features = self.feature_sorted(self.feature_implies_c(target))
target_join = "#define %sCPU_TARGET_" % self.conf_c_prefix_
target_defs = [target_join + f for f in features]
target_defs = '\n'.join(target_defs)
with open(wrap_path, "w") as fd:
fd.write(textwrap.dedent("""\
/**
* AUTOGENERATED DON'T EDIT
* Please make changes to the code generator \
(distutils/ccompiler_opt.py)
*/
#define {pfx}CPU_TARGET_MODE
#define {pfx}CPU_TARGET_CURRENT {target_name}
{target_defs}
#include "{path}"
""").format(
pfx=self.conf_c_prefix_, target_name=target_name,
path=os.path.abspath(dispatch_src), target_defs=target_defs
))
return wrap_path
def _generate_config(self, output_dir, dispatch_src, targets, has_baseline=False):
config_path = os.path.basename(dispatch_src).replace(".c", ".h")
config_path = os.path.join(output_dir, config_path)
# check if targets didn't change to avoid recompiling
cache_hash = self.cache_hash(targets, has_baseline)
try:
with open(config_path) as f:
last_hash = f.readline().split("cache_hash:")
if len(last_hash) == 2 and int(last_hash[1]) == cache_hash:
return True
except IOError:
pass
self.dist_log("generate dispatched config -> ", config_path)
dispatch_calls = []
for tar in targets:
if isinstance(tar, str):
target_name = tar
else: # multi target
target_name = '__'.join([t for t in tar])
req_detect = self.feature_detect(tar)
req_detect = '&&'.join([
"CHK(%s)" % f for f in req_detect
])
dispatch_calls.append(
"\t%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))" % (
self.conf_c_prefix_, req_detect, target_name
))
dispatch_calls = ' \\\n'.join(dispatch_calls)
if has_baseline:
baseline_calls = (
"\t%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))"
) % self.conf_c_prefix_
else:
baseline_calls = ''
with open(config_path, "w") as fd:
fd.write(textwrap.dedent("""\
// cache_hash:{cache_hash}
/**
* AUTOGENERATED DON'T EDIT
* Please make changes to the code generator (distutils/ccompiler_opt.py)
*/
#ifndef {pfx}CPU_DISPATCH_EXPAND_
#define {pfx}CPU_DISPATCH_EXPAND_(X) X
#endif
#undef {pfx}CPU_DISPATCH_BASELINE_CALL
#undef {pfx}CPU_DISPATCH_CALL
#define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \\
{baseline_calls}
#define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \\
{dispatch_calls}
""").format(
pfx=self.conf_c_prefix_, baseline_calls=baseline_calls,
dispatch_calls=dispatch_calls, cache_hash=cache_hash
))
return False
def new_ccompiler_opt(compiler, **kwargs):
"""
Create a new instance of 'CCompilerOpt' and generate the dispatch header
inside NumPy source dir.
Parameters
----------
'compiler' : CCompiler instance
'**kwargs': passed as-is to `CCompilerOpt(...)`
Returns
-------
new instance of CCompilerOpt
"""
opt = CCompilerOpt(compiler, **kwargs)
npy_path = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
header_dir = os.path.join(npy_path, *("core/src/common".split("/")))
header_path = os.path.join(header_dir, "_cpu_dispatch.h")
if not os.path.exists(header_path) or not opt.is_cached():
if not os.path.exists(header_dir):
opt.dist_log(
"dispatch header dir '%s' isn't exist, creating it" % header_dir,
stderr=True
)
os.makedirs(header_dir)
opt.generate_dispatch_header(header_path)
return opt
|