m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2572 lines
94 KiB

6 months ago
  1. """Provides the `CCompilerOpt` class, used for handling the CPU/hardware
  2. optimization, starting from parsing the command arguments, to managing the
  3. relation between the CPU baseline and dispatch-able features,
  4. also generating the required C headers and ending with compiling
  5. the sources with proper compiler's flags.
  6. `CCompilerOpt` doesn't provide runtime detection for the CPU features,
  7. instead only focuses on the compiler side, but it creates abstract C headers
  8. that can be used later for the final runtime dispatching process."""
  9. import sys, io, os, re, textwrap, pprint, inspect, atexit, subprocess
  10. class _Config:
  11. """An abstract class holds all configurable attributes of `CCompilerOpt`,
  12. these class attributes can be used to change the default behavior
  13. of `CCompilerOpt` in order to fit other requirements.
  14. Attributes
  15. ----------
  16. conf_nocache : bool
  17. Set True to disable memory and file cache.
  18. Default is False.
  19. conf_noopt : bool
  20. Set True to forces the optimization to be disabled,
  21. in this case `CCompilerOpt` tends to generate all
  22. expected headers in order to 'not' break the build.
  23. Default is False.
  24. conf_cache_factors : list
  25. Add extra factors to the primary caching factors. The caching factors
  26. are utilized to determine if there are changes had happened that
  27. requires to discard the cache and re-updating it. The primary factors
  28. are the arguments of `CCompilerOpt` and `CCompiler`'s properties(type, flags, etc).
  29. Default is list of two items, containing the time of last modification
  30. of `ccompiler_opt` and value of attribute "conf_noopt"
  31. conf_tmp_path : str,
  32. The path of temporary directory. Default is auto-created
  33. temporary directory via ``tempfile.mkdtemp()``.
  34. conf_check_path : str
  35. The path of testing files. Each added CPU feature must have a
  36. **C** source file contains at least one intrinsic or instruction that
  37. related to this feature, so it can be tested against the compiler.
  38. Default is ``./distutils/checks``.
  39. conf_target_groups : dict
  40. Extra tokens that can be reached from dispatch-able sources through
  41. the special mark ``@targets``. Default is an empty dictionary.
  42. **Notes**:
  43. - case-insensitive for tokens and group names
  44. - sign '#' must stick in the begin of group name and only within ``@targets``
  45. **Example**:
  46. .. code-block:: console
  47. $ "@targets #avx_group other_tokens" > group_inside.c
  48. >>> CCompilerOpt.conf_target_groups["avx_group"] = \\
  49. "$werror $maxopt avx2 avx512f avx512_skx"
  50. >>> cco = CCompilerOpt(cc_instance)
  51. >>> cco.try_dispatch(["group_inside.c"])
  52. conf_c_prefix : str
  53. The prefix of public C definitions. Default is ``"NPY_"``.
  54. conf_c_prefix_ : str
  55. The prefix of internal C definitions. Default is ``"NPY__"``.
  56. conf_cc_flags : dict
  57. Nested dictionaries defining several compiler flags
  58. that linked to some major functions, the main key
  59. represent the compiler name and sub-keys represent
  60. flags names. Default is already covers all supported
  61. **C** compilers.
  62. Sub-keys explained as follows:
  63. "native": str or None
  64. used by argument option `native`, to detect the current
  65. machine support via the compiler.
  66. "werror": str or None
  67. utilized to treat warning as errors during testing CPU features
  68. against the compiler and also for target's policy `$werror`
  69. via dispatch-able sources.
  70. "maxopt": str or None
  71. utilized for target's policy '$maxopt' and the value should
  72. contains the maximum acceptable optimization by the compiler.
  73. e.g. in gcc `'-O3'`
  74. **Notes**:
  75. * case-sensitive for compiler names and flags
  76. * use space to separate multiple flags
  77. * any flag will tested against the compiler and it will skipped
  78. if it's not applicable.
  79. conf_min_features : dict
  80. A dictionary defines the used CPU features for
  81. argument option `'min'`, the key represent the CPU architecture
  82. name e.g. `'x86'`. Default values provide the best effort
  83. on wide range of users platforms.
  84. **Note**: case-sensitive for architecture names.
  85. conf_features : dict
  86. Nested dictionaries used for identifying the CPU features.
  87. the primary key is represented as a feature name or group name
  88. that gathers several features. Default values covers all
  89. supported features but without the major options like "flags",
  90. these undefined options handle it by method `conf_features_partial()`.
  91. Default value is covers almost all CPU features for *X86*, *IBM/Power64*
  92. and *ARM 7/8*.
  93. Sub-keys explained as follows:
  94. "implies" : str or list, optional,
  95. List of CPU feature names to be implied by it,
  96. the feature name must be defined within `conf_features`.
  97. Default is None.
  98. "flags": str or list, optional
  99. List of compiler flags. Default is None.
  100. "detect": str or list, optional
  101. List of CPU feature names that required to be detected
  102. in runtime. By default, its the feature name or features
  103. in "group" if its specified.
  104. "implies_detect": bool, optional
  105. If True, all "detect" of implied features will be combined.
  106. Default is True. see `feature_detect()`.
  107. "group": str or list, optional
  108. Same as "implies" but doesn't require the feature name to be
  109. defined within `conf_features`.
  110. "interest": int, required
  111. a key for sorting CPU features
  112. "headers": str or list, optional
  113. intrinsics C header file
  114. "disable": str, optional
  115. force disable feature, the string value should contains the
  116. reason of disabling.
  117. "autovec": bool or None, optional
  118. True or False to declare that CPU feature can be auto-vectorized
  119. by the compiler.
  120. By default(None), treated as True if the feature contains at
  121. least one applicable flag. see `feature_can_autovec()`
  122. "extra_checks": str or list, optional
  123. Extra test case names for the CPU feature that need to be tested
  124. against the compiler.
  125. Each test case must have a C file named ``extra_xxxx.c``, where
  126. ``xxxx`` is the case name in lower case, under 'conf_check_path'.
  127. It should contain at least one intrinsic or function related to the test case.
  128. If the compiler able to successfully compile the C file then `CCompilerOpt`
  129. will add a C ``#define`` for it into the main dispatch header, e.g.
  130. ```#define {conf_c_prefix}_XXXX`` where ``XXXX`` is the case name in upper case.
  131. **NOTES**:
  132. * space can be used as separator with options that supports "str or list"
  133. * case-sensitive for all values and feature name must be in upper-case.
  134. * if flags aren't applicable, its will skipped rather than disable the
  135. CPU feature
  136. * the CPU feature will disabled if the compiler fail to compile
  137. the test file
  138. """
  139. conf_nocache = False
  140. conf_noopt = False
  141. conf_cache_factors = None
  142. conf_tmp_path = None
  143. conf_check_path = os.path.join(
  144. os.path.dirname(os.path.realpath(__file__)), "checks"
  145. )
  146. conf_target_groups = {}
  147. conf_c_prefix = 'NPY_'
  148. conf_c_prefix_ = 'NPY__'
  149. conf_cc_flags = dict(
  150. gcc = dict(
  151. # native should always fail on arm and ppc64,
  152. # native usually works only with x86
  153. native = '-march=native',
  154. opt = '-O3',
  155. werror = '-Werror'
  156. ),
  157. clang = dict(
  158. native = '-march=native',
  159. opt = "-O3",
  160. # One of the following flags needs to be applicable for Clang to
  161. # guarantee the sanity of the testing process, however in certain
  162. # cases `-Werror` gets skipped during the availability test due to
  163. # "unused arguments" warnings.
  164. # see https://github.com/numpy/numpy/issues/19624
  165. werror = '-Werror-implicit-function-declaration -Werror'
  166. ),
  167. icc = dict(
  168. native = '-xHost',
  169. opt = '-O3',
  170. werror = '-Werror'
  171. ),
  172. iccw = dict(
  173. native = '/QxHost',
  174. opt = '/O3',
  175. werror = '/Werror'
  176. ),
  177. msvc = dict(
  178. native = None,
  179. opt = '/O2',
  180. werror = '/WX'
  181. )
  182. )
  183. conf_min_features = dict(
  184. x86 = "SSE SSE2",
  185. x64 = "SSE SSE2 SSE3",
  186. ppc64 = '', # play it safe
  187. ppc64le = "VSX VSX2",
  188. armhf = '', # play it safe
  189. aarch64 = "NEON NEON_FP16 NEON_VFPV4 ASIMD"
  190. )
  191. conf_features = dict(
  192. # X86
  193. SSE = dict(
  194. interest=1, headers="xmmintrin.h",
  195. # enabling SSE without SSE2 is useless also
  196. # it's non-optional for x86_64
  197. implies="SSE2"
  198. ),
  199. SSE2 = dict(interest=2, implies="SSE", headers="emmintrin.h"),
  200. SSE3 = dict(interest=3, implies="SSE2", headers="pmmintrin.h"),
  201. SSSE3 = dict(interest=4, implies="SSE3", headers="tmmintrin.h"),
  202. SSE41 = dict(interest=5, implies="SSSE3", headers="smmintrin.h"),
  203. POPCNT = dict(interest=6, implies="SSE41", headers="popcntintrin.h"),
  204. SSE42 = dict(interest=7, implies="POPCNT"),
  205. AVX = dict(
  206. interest=8, implies="SSE42", headers="immintrin.h",
  207. implies_detect=False
  208. ),
  209. XOP = dict(interest=9, implies="AVX", headers="x86intrin.h"),
  210. FMA4 = dict(interest=10, implies="AVX", headers="x86intrin.h"),
  211. F16C = dict(interest=11, implies="AVX"),
  212. FMA3 = dict(interest=12, implies="F16C"),
  213. AVX2 = dict(interest=13, implies="F16C"),
  214. AVX512F = dict(
  215. interest=20, implies="FMA3 AVX2", implies_detect=False,
  216. extra_checks="AVX512F_REDUCE"
  217. ),
  218. AVX512CD = dict(interest=21, implies="AVX512F"),
  219. AVX512_KNL = dict(
  220. interest=40, implies="AVX512CD", group="AVX512ER AVX512PF",
  221. detect="AVX512_KNL", implies_detect=False
  222. ),
  223. AVX512_KNM = dict(
  224. interest=41, implies="AVX512_KNL",
  225. group="AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ",
  226. detect="AVX512_KNM", implies_detect=False
  227. ),
  228. AVX512_SKX = dict(
  229. interest=42, implies="AVX512CD", group="AVX512VL AVX512BW AVX512DQ",
  230. detect="AVX512_SKX", implies_detect=False,
  231. extra_checks="AVX512BW_MASK AVX512DQ_MASK"
  232. ),
  233. AVX512_CLX = dict(
  234. interest=43, implies="AVX512_SKX", group="AVX512VNNI",
  235. detect="AVX512_CLX"
  236. ),
  237. AVX512_CNL = dict(
  238. interest=44, implies="AVX512_SKX", group="AVX512IFMA AVX512VBMI",
  239. detect="AVX512_CNL", implies_detect=False
  240. ),
  241. AVX512_ICL = dict(
  242. interest=45, implies="AVX512_CLX AVX512_CNL",
  243. group="AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ",
  244. detect="AVX512_ICL", implies_detect=False
  245. ),
  246. # IBM/Power
  247. ## Power7/ISA 2.06
  248. VSX = dict(interest=1, headers="altivec.h", extra_checks="VSX_ASM"),
  249. ## Power8/ISA 2.07
  250. VSX2 = dict(interest=2, implies="VSX", implies_detect=False),
  251. ## Power9/ISA 3.00
  252. VSX3 = dict(interest=3, implies="VSX2", implies_detect=False),
  253. # ARM
  254. NEON = dict(interest=1, headers="arm_neon.h"),
  255. NEON_FP16 = dict(interest=2, implies="NEON"),
  256. ## FMA
  257. NEON_VFPV4 = dict(interest=3, implies="NEON_FP16"),
  258. ## Advanced SIMD
  259. ASIMD = dict(interest=4, implies="NEON_FP16 NEON_VFPV4", implies_detect=False),
  260. ## ARMv8.2 half-precision & vector arithm
  261. ASIMDHP = dict(interest=5, implies="ASIMD"),
  262. ## ARMv8.2 dot product
  263. ASIMDDP = dict(interest=6, implies="ASIMD"),
  264. ## ARMv8.2 Single & half-precision Multiply
  265. ASIMDFHM = dict(interest=7, implies="ASIMDHP"),
  266. )
  267. def conf_features_partial(self):
  268. """Return a dictionary of supported CPU features by the platform,
  269. and accumulate the rest of undefined options in `conf_features`,
  270. the returned dict has same rules and notes in
  271. class attribute `conf_features`, also its override
  272. any options that been set in 'conf_features'.
  273. """
  274. if self.cc_noopt:
  275. # optimization is disabled
  276. return {}
  277. on_x86 = self.cc_on_x86 or self.cc_on_x64
  278. is_unix = self.cc_is_gcc or self.cc_is_clang
  279. if on_x86 and is_unix: return dict(
  280. SSE = dict(flags="-msse"),
  281. SSE2 = dict(flags="-msse2"),
  282. SSE3 = dict(flags="-msse3"),
  283. SSSE3 = dict(flags="-mssse3"),
  284. SSE41 = dict(flags="-msse4.1"),
  285. POPCNT = dict(flags="-mpopcnt"),
  286. SSE42 = dict(flags="-msse4.2"),
  287. AVX = dict(flags="-mavx"),
  288. F16C = dict(flags="-mf16c"),
  289. XOP = dict(flags="-mxop"),
  290. FMA4 = dict(flags="-mfma4"),
  291. FMA3 = dict(flags="-mfma"),
  292. AVX2 = dict(flags="-mavx2"),
  293. AVX512F = dict(flags="-mavx512f"),
  294. AVX512CD = dict(flags="-mavx512cd"),
  295. AVX512_KNL = dict(flags="-mavx512er -mavx512pf"),
  296. AVX512_KNM = dict(
  297. flags="-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq"
  298. ),
  299. AVX512_SKX = dict(flags="-mavx512vl -mavx512bw -mavx512dq"),
  300. AVX512_CLX = dict(flags="-mavx512vnni"),
  301. AVX512_CNL = dict(flags="-mavx512ifma -mavx512vbmi"),
  302. AVX512_ICL = dict(
  303. flags="-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq"
  304. )
  305. )
  306. if on_x86 and self.cc_is_icc: return dict(
  307. SSE = dict(flags="-msse"),
  308. SSE2 = dict(flags="-msse2"),
  309. SSE3 = dict(flags="-msse3"),
  310. SSSE3 = dict(flags="-mssse3"),
  311. SSE41 = dict(flags="-msse4.1"),
  312. POPCNT = {},
  313. SSE42 = dict(flags="-msse4.2"),
  314. AVX = dict(flags="-mavx"),
  315. F16C = {},
  316. XOP = dict(disable="Intel Compiler doesn't support it"),
  317. FMA4 = dict(disable="Intel Compiler doesn't support it"),
  318. # Intel Compiler doesn't support AVX2 or FMA3 independently
  319. FMA3 = dict(
  320. implies="F16C AVX2", flags="-march=core-avx2"
  321. ),
  322. AVX2 = dict(implies="FMA3", flags="-march=core-avx2"),
  323. # Intel Compiler doesn't support AVX512F or AVX512CD independently
  324. AVX512F = dict(
  325. implies="AVX2 AVX512CD", flags="-march=common-avx512"
  326. ),
  327. AVX512CD = dict(
  328. implies="AVX2 AVX512F", flags="-march=common-avx512"
  329. ),
  330. AVX512_KNL = dict(flags="-xKNL"),
  331. AVX512_KNM = dict(flags="-xKNM"),
  332. AVX512_SKX = dict(flags="-xSKYLAKE-AVX512"),
  333. AVX512_CLX = dict(flags="-xCASCADELAKE"),
  334. AVX512_CNL = dict(flags="-xCANNONLAKE"),
  335. AVX512_ICL = dict(flags="-xICELAKE-CLIENT"),
  336. )
  337. if on_x86 and self.cc_is_iccw: return dict(
  338. SSE = dict(flags="/arch:SSE"),
  339. SSE2 = dict(flags="/arch:SSE2"),
  340. SSE3 = dict(flags="/arch:SSE3"),
  341. SSSE3 = dict(flags="/arch:SSSE3"),
  342. SSE41 = dict(flags="/arch:SSE4.1"),
  343. POPCNT = {},
  344. SSE42 = dict(flags="/arch:SSE4.2"),
  345. AVX = dict(flags="/arch:AVX"),
  346. F16C = {},
  347. XOP = dict(disable="Intel Compiler doesn't support it"),
  348. FMA4 = dict(disable="Intel Compiler doesn't support it"),
  349. # Intel Compiler doesn't support FMA3 or AVX2 independently
  350. FMA3 = dict(
  351. implies="F16C AVX2", flags="/arch:CORE-AVX2"
  352. ),
  353. AVX2 = dict(
  354. implies="FMA3", flags="/arch:CORE-AVX2"
  355. ),
  356. # Intel Compiler doesn't support AVX512F or AVX512CD independently
  357. AVX512F = dict(
  358. implies="AVX2 AVX512CD", flags="/Qx:COMMON-AVX512"
  359. ),
  360. AVX512CD = dict(
  361. implies="AVX2 AVX512F", flags="/Qx:COMMON-AVX512"
  362. ),
  363. AVX512_KNL = dict(flags="/Qx:KNL"),
  364. AVX512_KNM = dict(flags="/Qx:KNM"),
  365. AVX512_SKX = dict(flags="/Qx:SKYLAKE-AVX512"),
  366. AVX512_CLX = dict(flags="/Qx:CASCADELAKE"),
  367. AVX512_CNL = dict(flags="/Qx:CANNONLAKE"),
  368. AVX512_ICL = dict(flags="/Qx:ICELAKE-CLIENT")
  369. )
  370. if on_x86 and self.cc_is_msvc: return dict(
  371. SSE = dict(flags="/arch:SSE"),
  372. SSE2 = dict(flags="/arch:SSE2"),
  373. SSE3 = {},
  374. SSSE3 = {},
  375. SSE41 = {},
  376. POPCNT = dict(headers="nmmintrin.h"),
  377. SSE42 = {},
  378. AVX = dict(flags="/arch:AVX"),
  379. F16C = {},
  380. XOP = dict(headers="ammintrin.h"),
  381. FMA4 = dict(headers="ammintrin.h"),
  382. # MSVC doesn't support FMA3 or AVX2 independently
  383. FMA3 = dict(
  384. implies="F16C AVX2", flags="/arch:AVX2"
  385. ),
  386. AVX2 = dict(
  387. implies="F16C FMA3", flags="/arch:AVX2"
  388. ),
  389. # MSVC doesn't support AVX512F or AVX512CD independently,
  390. # always generate instructions belong to (VL/VW/DQ)
  391. AVX512F = dict(
  392. implies="AVX2 AVX512CD AVX512_SKX", flags="/arch:AVX512"
  393. ),
  394. AVX512CD = dict(
  395. implies="AVX512F AVX512_SKX", flags="/arch:AVX512"
  396. ),
  397. AVX512_KNL = dict(
  398. disable="MSVC compiler doesn't support it"
  399. ),
  400. AVX512_KNM = dict(
  401. disable="MSVC compiler doesn't support it"
  402. ),
  403. AVX512_SKX = dict(flags="/arch:AVX512"),
  404. AVX512_CLX = {},
  405. AVX512_CNL = {},
  406. AVX512_ICL = {}
  407. )
  408. on_power = self.cc_on_ppc64le or self.cc_on_ppc64
  409. if on_power:
  410. partial = dict(
  411. VSX = dict(
  412. implies=("VSX2" if self.cc_on_ppc64le else ""),
  413. flags="-mvsx"
  414. ),
  415. VSX2 = dict(
  416. flags="-mcpu=power8", implies_detect=False
  417. ),
  418. VSX3 = dict(
  419. flags="-mcpu=power9 -mtune=power9", implies_detect=False
  420. )
  421. )
  422. if self.cc_is_clang:
  423. partial["VSX"]["flags"] = "-maltivec -mvsx"
  424. partial["VSX2"]["flags"] = "-mpower8-vector"
  425. partial["VSX3"]["flags"] = "-mpower9-vector"
  426. return partial
  427. if self.cc_on_aarch64 and is_unix: return dict(
  428. NEON = dict(
  429. implies="NEON_FP16 NEON_VFPV4 ASIMD", autovec=True
  430. ),
  431. NEON_FP16 = dict(
  432. implies="NEON NEON_VFPV4 ASIMD", autovec=True
  433. ),
  434. NEON_VFPV4 = dict(
  435. implies="NEON NEON_FP16 ASIMD", autovec=True
  436. ),
  437. ASIMD = dict(
  438. implies="NEON NEON_FP16 NEON_VFPV4", autovec=True
  439. ),
  440. ASIMDHP = dict(
  441. flags="-march=armv8.2-a+fp16"
  442. ),
  443. ASIMDDP = dict(
  444. flags="-march=armv8.2-a+dotprod"
  445. ),
  446. ASIMDFHM = dict(
  447. flags="-march=armv8.2-a+fp16fml"
  448. ),
  449. )
  450. if self.cc_on_armhf and is_unix: return dict(
  451. NEON = dict(
  452. flags="-mfpu=neon"
  453. ),
  454. NEON_FP16 = dict(
  455. flags="-mfpu=neon-fp16 -mfp16-format=ieee"
  456. ),
  457. NEON_VFPV4 = dict(
  458. flags="-mfpu=neon-vfpv4",
  459. ),
  460. ASIMD = dict(
  461. flags="-mfpu=neon-fp-armv8 -march=armv8-a+simd",
  462. ),
  463. ASIMDHP = dict(
  464. flags="-march=armv8.2-a+fp16"
  465. ),
  466. ASIMDDP = dict(
  467. flags="-march=armv8.2-a+dotprod",
  468. ),
  469. ASIMDFHM = dict(
  470. flags="-march=armv8.2-a+fp16fml"
  471. )
  472. )
  473. # TODO: ARM MSVC
  474. return {}
  475. def __init__(self):
  476. if self.conf_tmp_path is None:
  477. import tempfile, shutil
  478. tmp = tempfile.mkdtemp()
  479. def rm_temp():
  480. try:
  481. shutil.rmtree(tmp)
  482. except IOError:
  483. pass
  484. atexit.register(rm_temp)
  485. self.conf_tmp_path = tmp
  486. if self.conf_cache_factors is None:
  487. self.conf_cache_factors = [
  488. os.path.getmtime(__file__),
  489. self.conf_nocache
  490. ]
  491. class _Distutils:
  492. """A helper class that provides a collection of fundamental methods
  493. implemented in a top of Python and NumPy Distutils.
  494. The idea behind this class is to gather all methods that it may
  495. need to override in case of reuse 'CCompilerOpt' in environment
  496. different than of what NumPy has.
  497. Parameters
  498. ----------
  499. ccompiler : `CCompiler`
  500. The generate instance that returned from `distutils.ccompiler.new_compiler()`.
  501. """
  502. def __init__(self, ccompiler):
  503. self._ccompiler = ccompiler
  504. def dist_compile(self, sources, flags, ccompiler=None, **kwargs):
  505. """Wrap CCompiler.compile()"""
  506. assert(isinstance(sources, list))
  507. assert(isinstance(flags, list))
  508. flags = kwargs.pop("extra_postargs", []) + flags
  509. if not ccompiler:
  510. ccompiler = self._ccompiler
  511. return ccompiler.compile(sources, extra_postargs=flags, **kwargs)
  512. def dist_test(self, source, flags, macros=[]):
  513. """Return True if 'CCompiler.compile()' able to compile
  514. a source file with certain flags.
  515. """
  516. assert(isinstance(source, str))
  517. from distutils.errors import CompileError
  518. cc = self._ccompiler;
  519. bk_spawn = getattr(cc, 'spawn', None)
  520. if bk_spawn:
  521. cc_type = getattr(self._ccompiler, "compiler_type", "")
  522. if cc_type in ("msvc",):
  523. setattr(cc, 'spawn', self._dist_test_spawn_paths)
  524. else:
  525. setattr(cc, 'spawn', self._dist_test_spawn)
  526. test = False
  527. try:
  528. self.dist_compile(
  529. [source], flags, macros=macros, output_dir=self.conf_tmp_path
  530. )
  531. test = True
  532. except CompileError as e:
  533. self.dist_log(str(e), stderr=True)
  534. if bk_spawn:
  535. setattr(cc, 'spawn', bk_spawn)
  536. return test
  537. def dist_info(self):
  538. """
  539. Return a tuple containing info about (platform, compiler, extra_args),
  540. required by the abstract class '_CCompiler' for discovering the
  541. platform environment. This is also used as a cache factor in order
  542. to detect any changes happening from outside.
  543. """
  544. if hasattr(self, "_dist_info"):
  545. return self._dist_info
  546. cc_type = getattr(self._ccompiler, "compiler_type", '')
  547. if cc_type in ("intelem", "intelemw"):
  548. platform = "x86_64"
  549. elif cc_type in ("intel", "intelw", "intele"):
  550. platform = "x86"
  551. else:
  552. from distutils.util import get_platform
  553. platform = get_platform()
  554. cc_info = getattr(self._ccompiler, "compiler", getattr(self._ccompiler, "compiler_so", ''))
  555. if not cc_type or cc_type == "unix":
  556. if hasattr(cc_info, "__iter__"):
  557. compiler = cc_info[0]
  558. else:
  559. compiler = str(cc_info)
  560. else:
  561. compiler = cc_type
  562. if hasattr(cc_info, "__iter__") and len(cc_info) > 1:
  563. extra_args = ' '.join(cc_info[1:])
  564. else:
  565. extra_args = os.environ.get("CFLAGS", "")
  566. extra_args += os.environ.get("CPPFLAGS", "")
  567. self._dist_info = (platform, compiler, extra_args)
  568. return self._dist_info
  569. @staticmethod
  570. def dist_error(*args):
  571. """Raise a compiler error"""
  572. from distutils.errors import CompileError
  573. raise CompileError(_Distutils._dist_str(*args))
  574. @staticmethod
  575. def dist_fatal(*args):
  576. """Raise a distutils error"""
  577. from distutils.errors import DistutilsError
  578. raise DistutilsError(_Distutils._dist_str(*args))
  579. @staticmethod
  580. def dist_log(*args, stderr=False):
  581. """Print a console message"""
  582. from numpy.distutils import log
  583. out = _Distutils._dist_str(*args)
  584. if stderr:
  585. log.warn(out)
  586. else:
  587. log.info(out)
  588. @staticmethod
  589. def dist_load_module(name, path):
  590. """Load a module from file, required by the abstract class '_Cache'."""
  591. from .misc_util import exec_mod_from_location
  592. try:
  593. return exec_mod_from_location(name, path)
  594. except Exception as e:
  595. _Distutils.dist_log(e, stderr=True)
  596. return None
  597. @staticmethod
  598. def _dist_str(*args):
  599. """Return a string to print by log and errors."""
  600. def to_str(arg):
  601. if not isinstance(arg, str) and hasattr(arg, '__iter__'):
  602. ret = []
  603. for a in arg:
  604. ret.append(to_str(a))
  605. return '('+ ' '.join(ret) + ')'
  606. return str(arg)
  607. stack = inspect.stack()[2]
  608. start = "CCompilerOpt.%s[%d] : " % (stack.function, stack.lineno)
  609. out = ' '.join([
  610. to_str(a)
  611. for a in (*args,)
  612. ])
  613. return start + out
  614. def _dist_test_spawn_paths(self, cmd, display=None):
  615. """
  616. Fix msvc SDK ENV path same as distutils do
  617. without it we get c1: fatal error C1356: unable to find mspdbcore.dll
  618. """
  619. if not hasattr(self._ccompiler, "_paths"):
  620. self._dist_test_spawn(cmd)
  621. return
  622. old_path = os.getenv("path")
  623. try:
  624. os.environ["path"] = self._ccompiler._paths
  625. self._dist_test_spawn(cmd)
  626. finally:
  627. os.environ["path"] = old_path
  628. _dist_warn_regex = re.compile(
  629. # intel and msvc compilers don't raise
  630. # fatal errors when flags are wrong or unsupported
  631. ".*("
  632. "warning D9002|" # msvc, it should be work with any language.
  633. "invalid argument for option" # intel
  634. ").*"
  635. )
  636. @staticmethod
  637. def _dist_test_spawn(cmd, display=None):
  638. from distutils.errors import CompileError
  639. try:
  640. o = subprocess.check_output(cmd, stderr=subprocess.STDOUT,
  641. universal_newlines=True)
  642. if o and re.match(_Distutils._dist_warn_regex, o):
  643. _Distutils.dist_error(
  644. "Flags in command", cmd ,"aren't supported by the compiler"
  645. ", output -> \n%s" % o
  646. )
  647. except subprocess.CalledProcessError as exc:
  648. o = exc.output
  649. s = exc.returncode
  650. except OSError as e:
  651. o = e
  652. s = 127
  653. else:
  654. return None
  655. _Distutils.dist_error(
  656. "Command", cmd, "failed with exit status %d output -> \n%s" % (
  657. s, o
  658. ))
  659. _share_cache = {}
  660. class _Cache:
  661. """An abstract class handles caching functionality, provides two
  662. levels of caching, in-memory by share instances attributes among
  663. each other and by store attributes into files.
  664. **Note**:
  665. any attributes that start with ``_`` or ``conf_`` will be ignored.
  666. Parameters
  667. ----------
  668. cache_path: str or None
  669. The path of cache file, if None then cache in file will disabled.
  670. *factors:
  671. The caching factors that need to utilize next to `conf_cache_factors`.
  672. Attributes
  673. ----------
  674. cache_private: set
  675. Hold the attributes that need be skipped from "in-memory cache".
  676. cache_infile: bool
  677. Utilized during initializing this class, to determine if the cache was able
  678. to loaded from the specified cache path in 'cache_path'.
  679. """
  680. # skip attributes from cache
  681. _cache_ignore = re.compile("^(_|conf_)")
  682. def __init__(self, cache_path=None, *factors):
  683. self.cache_me = {}
  684. self.cache_private = set()
  685. self.cache_infile = False
  686. self._cache_path = None
  687. if self.conf_nocache:
  688. self.dist_log("cache is disabled by `Config`")
  689. return
  690. self._cache_hash = self.cache_hash(*factors, *self.conf_cache_factors)
  691. self._cache_path = cache_path
  692. if cache_path:
  693. if os.path.exists(cache_path):
  694. self.dist_log("load cache from file ->", cache_path)
  695. cache_mod = self.dist_load_module("cache", cache_path)
  696. if not cache_mod:
  697. self.dist_log(
  698. "unable to load the cache file as a module",
  699. stderr=True
  700. )
  701. elif not hasattr(cache_mod, "hash") or \
  702. not hasattr(cache_mod, "data"):
  703. self.dist_log("invalid cache file", stderr=True)
  704. elif self._cache_hash == cache_mod.hash:
  705. self.dist_log("hit the file cache")
  706. for attr, val in cache_mod.data.items():
  707. setattr(self, attr, val)
  708. self.cache_infile = True
  709. else:
  710. self.dist_log("miss the file cache")
  711. if not self.cache_infile:
  712. other_cache = _share_cache.get(self._cache_hash)
  713. if other_cache:
  714. self.dist_log("hit the memory cache")
  715. for attr, val in other_cache.__dict__.items():
  716. if attr in other_cache.cache_private or \
  717. re.match(self._cache_ignore, attr):
  718. continue
  719. setattr(self, attr, val)
  720. _share_cache[self._cache_hash] = self
  721. atexit.register(self.cache_flush)
  722. def __del__(self):
  723. for h, o in _share_cache.items():
  724. if o == self:
  725. _share_cache.pop(h)
  726. break
  727. def cache_flush(self):
  728. """
  729. Force update the cache.
  730. """
  731. if not self._cache_path:
  732. return
  733. # TODO: don't write if the cache doesn't change
  734. self.dist_log("write cache to path ->", self._cache_path)
  735. cdict = self.__dict__.copy()
  736. for attr in self.__dict__.keys():
  737. if re.match(self._cache_ignore, attr):
  738. cdict.pop(attr)
  739. d = os.path.dirname(self._cache_path)
  740. if not os.path.exists(d):
  741. os.makedirs(d)
  742. repr_dict = pprint.pformat(cdict, compact=True)
  743. with open(self._cache_path, "w") as f:
  744. f.write(textwrap.dedent("""\
  745. # AUTOGENERATED DON'T EDIT
  746. # Please make changes to the code generator \
  747. (distutils/ccompiler_opt.py)
  748. hash = {}
  749. data = \\
  750. """).format(self._cache_hash))
  751. f.write(repr_dict)
  752. def cache_hash(self, *factors):
  753. # is there a built-in non-crypto hash?
  754. # sdbm
  755. chash = 0
  756. for f in factors:
  757. for char in str(f):
  758. chash = ord(char) + (chash << 6) + (chash << 16) - chash
  759. chash &= 0xFFFFFFFF
  760. return chash
  761. @staticmethod
  762. def me(cb):
  763. """
  764. A static method that can be treated as a decorator to
  765. dynamically cache certain methods.
  766. """
  767. def cache_wrap_me(self, *args, **kwargs):
  768. # good for normal args
  769. cache_key = str((
  770. cb.__name__, *args, *kwargs.keys(), *kwargs.values()
  771. ))
  772. if cache_key in self.cache_me:
  773. return self.cache_me[cache_key]
  774. ccb = cb(self, *args, **kwargs)
  775. self.cache_me[cache_key] = ccb
  776. return ccb
  777. return cache_wrap_me
  778. class _CCompiler:
  779. """A helper class for `CCompilerOpt` containing all utilities that
  780. related to the fundamental compiler's functions.
  781. Attributes
  782. ----------
  783. cc_on_x86 : bool
  784. True when the target architecture is 32-bit x86
  785. cc_on_x64 : bool
  786. True when the target architecture is 64-bit x86
  787. cc_on_ppc64 : bool
  788. True when the target architecture is 64-bit big-endian PowerPC
  789. cc_on_armhf : bool
  790. True when the target architecture is 32-bit ARMv7+
  791. cc_on_aarch64 : bool
  792. True when the target architecture is 64-bit Armv8-a+
  793. cc_on_noarch : bool
  794. True when the target architecture is unknown or not supported
  795. cc_is_gcc : bool
  796. True if the compiler is GNU or
  797. if the compiler is unknown
  798. cc_is_clang : bool
  799. True if the compiler is Clang
  800. cc_is_icc : bool
  801. True if the compiler is Intel compiler (unix like)
  802. cc_is_iccw : bool
  803. True if the compiler is Intel compiler (msvc like)
  804. cc_is_nocc : bool
  805. True if the compiler isn't supported directly,
  806. Note: that cause a fail-back to gcc
  807. cc_has_debug : bool
  808. True if the compiler has debug flags
  809. cc_has_native : bool
  810. True if the compiler has native flags
  811. cc_noopt : bool
  812. True if the compiler has definition 'DISABLE_OPT*',
  813. or 'cc_on_noarch' is True
  814. cc_march : str
  815. The target architecture name, or "unknown" if
  816. the architecture isn't supported
  817. cc_name : str
  818. The compiler name, or "unknown" if the compiler isn't supported
  819. cc_flags : dict
  820. Dictionary containing the initialized flags of `_Config.conf_cc_flags`
  821. """
  822. def __init__(self):
  823. if hasattr(self, "cc_is_cached"):
  824. return
  825. # attr regex
  826. detect_arch = (
  827. ("cc_on_x64", ".*(x|x86_|amd)64.*"),
  828. ("cc_on_x86", ".*(win32|x86|i386|i686).*"),
  829. ("cc_on_ppc64le", ".*(powerpc|ppc)64(el|le).*"),
  830. ("cc_on_ppc64", ".*(powerpc|ppc)64.*"),
  831. ("cc_on_aarch64", ".*(aarch64|arm64).*"),
  832. ("cc_on_armhf", ".*arm.*"),
  833. # undefined platform
  834. ("cc_on_noarch", ""),
  835. )
  836. detect_compiler = (
  837. ("cc_is_gcc", r".*(gcc|gnu\-g).*"),
  838. ("cc_is_clang", ".*clang.*"),
  839. ("cc_is_iccw", ".*(intelw|intelemw|iccw).*"), # intel msvc like
  840. ("cc_is_icc", ".*(intel|icc).*"), # intel unix like
  841. ("cc_is_msvc", ".*msvc.*"),
  842. # undefined compiler will be treat it as gcc
  843. ("cc_is_nocc", ""),
  844. )
  845. detect_args = (
  846. ("cc_has_debug", ".*(O0|Od|ggdb|coverage|debug:full).*"),
  847. ("cc_has_native", ".*(-march=native|-xHost|/QxHost).*"),
  848. # in case if the class run with -DNPY_DISABLE_OPTIMIZATION
  849. ("cc_noopt", ".*DISABLE_OPT.*"),
  850. )
  851. dist_info = self.dist_info()
  852. platform, compiler_info, extra_args = dist_info
  853. # set False to all attrs
  854. for section in (detect_arch, detect_compiler, detect_args):
  855. for attr, rgex in section:
  856. setattr(self, attr, False)
  857. for detect, searchin in ((detect_arch, platform), (detect_compiler, compiler_info)):
  858. for attr, rgex in detect:
  859. if rgex and not re.match(rgex, searchin, re.IGNORECASE):
  860. continue
  861. setattr(self, attr, True)
  862. break
  863. for attr, rgex in detect_args:
  864. if rgex and not re.match(rgex, extra_args, re.IGNORECASE):
  865. continue
  866. setattr(self, attr, True)
  867. if self.cc_on_noarch:
  868. self.dist_log(
  869. "unable to detect CPU architecture which lead to disable the optimization. "
  870. f"check dist_info:<<\n{dist_info}\n>>",
  871. stderr=True
  872. )
  873. self.cc_noopt = True
  874. if self.conf_noopt:
  875. self.dist_log("Optimization is disabled by the Config", stderr=True)
  876. self.cc_noopt = True
  877. if self.cc_is_nocc:
  878. """
  879. mingw can be treated as a gcc, and also xlc even if it based on clang,
  880. but still has the same gcc optimization flags.
  881. """
  882. self.dist_log(
  883. "unable to detect compiler type which leads to treating it as GCC. "
  884. "this is a normal behavior if you're using gcc-like compiler such as MinGW or IBM/XLC."
  885. f"check dist_info:<<\n{dist_info}\n>>",
  886. stderr=True
  887. )
  888. self.cc_is_gcc = True
  889. self.cc_march = "unknown"
  890. for arch in ("x86", "x64", "ppc64", "ppc64le", "armhf", "aarch64"):
  891. if getattr(self, "cc_on_" + arch):
  892. self.cc_march = arch
  893. break
  894. self.cc_name = "unknown"
  895. for name in ("gcc", "clang", "iccw", "icc", "msvc"):
  896. if getattr(self, "cc_is_" + name):
  897. self.cc_name = name
  898. break
  899. self.cc_flags = {}
  900. compiler_flags = self.conf_cc_flags.get(self.cc_name)
  901. if compiler_flags is None:
  902. self.dist_fatal(
  903. "undefined flag for compiler '%s', "
  904. "leave an empty dict instead" % self.cc_name
  905. )
  906. for name, flags in compiler_flags.items():
  907. self.cc_flags[name] = nflags = []
  908. if flags:
  909. assert(isinstance(flags, str))
  910. flags = flags.split()
  911. for f in flags:
  912. if self.cc_test_flags([f]):
  913. nflags.append(f)
  914. self.cc_is_cached = True
  915. @_Cache.me
  916. def cc_test_flags(self, flags):
  917. """
  918. Returns True if the compiler supports 'flags'.
  919. """
  920. assert(isinstance(flags, list))
  921. self.dist_log("testing flags", flags)
  922. test_path = os.path.join(self.conf_check_path, "test_flags.c")
  923. test = self.dist_test(test_path, flags)
  924. if not test:
  925. self.dist_log("testing failed", stderr=True)
  926. return test
  927. def cc_normalize_flags(self, flags):
  928. """
  929. Remove the conflicts that caused due gathering implied features flags.
  930. Parameters
  931. ----------
  932. 'flags' list, compiler flags
  933. flags should be sorted from the lowest to the highest interest.
  934. Returns
  935. -------
  936. list, filtered from any conflicts.
  937. Examples
  938. --------
  939. >>> self.cc_normalize_flags(['-march=armv8.2-a+fp16', '-march=armv8.2-a+dotprod'])
  940. ['armv8.2-a+fp16+dotprod']
  941. >>> self.cc_normalize_flags(
  942. ['-msse', '-msse2', '-msse3', '-mssse3', '-msse4.1', '-msse4.2', '-mavx', '-march=core-avx2']
  943. )
  944. ['-march=core-avx2']
  945. """
  946. assert(isinstance(flags, list))
  947. if self.cc_is_gcc or self.cc_is_clang or self.cc_is_icc:
  948. return self._cc_normalize_unix(flags)
  949. if self.cc_is_msvc or self.cc_is_iccw:
  950. return self._cc_normalize_win(flags)
  951. return flags
  952. _cc_normalize_unix_mrgx = re.compile(
  953. # 1- to check the highest of
  954. r"^(-mcpu=|-march=|-x[A-Z0-9\-])"
  955. )
  956. _cc_normalize_unix_frgx = re.compile(
  957. # 2- to remove any flags starts with
  958. # -march, -mcpu, -x(INTEL) and '-m' without '='
  959. r"^(?!(-mcpu=|-march=|-x[A-Z0-9\-]))(?!-m[a-z0-9\-\.]*.$)"
  960. )
  961. _cc_normalize_unix_krgx = re.compile(
  962. # 3- keep only the highest of
  963. r"^(-mfpu|-mtune)"
  964. )
  965. _cc_normalize_arch_ver = re.compile(
  966. r"[0-9.]"
  967. )
  968. def _cc_normalize_unix(self, flags):
  969. def ver_flags(f):
  970. # arch ver subflag
  971. # -march=armv8.2-a+fp16fml
  972. tokens = f.split('+')
  973. ver = float('0' + ''.join(
  974. re.findall(self._cc_normalize_arch_ver, tokens[0])
  975. ))
  976. return ver, tokens[0], tokens[1:]
  977. if len(flags) <= 1:
  978. return flags
  979. # get the highest matched flag
  980. for i, cur_flag in enumerate(reversed(flags)):
  981. if not re.match(self._cc_normalize_unix_mrgx, cur_flag):
  982. continue
  983. lower_flags = flags[:-(i+1)]
  984. upper_flags = flags[-i:]
  985. filterd = list(filter(
  986. self._cc_normalize_unix_frgx.search, lower_flags
  987. ))
  988. # gather subflags
  989. ver, arch, subflags = ver_flags(cur_flag)
  990. if ver > 0 and len(subflags) > 0:
  991. for xflag in lower_flags:
  992. xver, _, xsubflags = ver_flags(xflag)
  993. if ver == xver:
  994. subflags = xsubflags + subflags
  995. cur_flag = arch + '+' + '+'.join(subflags)
  996. flags = filterd + [cur_flag]
  997. if i > 0:
  998. flags += upper_flags
  999. break
  1000. # to remove overridable flags
  1001. final_flags = []
  1002. matched = set()
  1003. for f in reversed(flags):
  1004. match = re.match(self._cc_normalize_unix_krgx, f)
  1005. if not match:
  1006. pass
  1007. elif match[0] in matched:
  1008. continue
  1009. else:
  1010. matched.add(match[0])
  1011. final_flags.insert(0, f)
  1012. return final_flags
  1013. _cc_normalize_win_frgx = re.compile(
  1014. r"^(?!(/arch\:|/Qx\:))"
  1015. )
  1016. _cc_normalize_win_mrgx = re.compile(
  1017. r"^(/arch|/Qx:)"
  1018. )
  1019. def _cc_normalize_win(self, flags):
  1020. for i, f in enumerate(reversed(flags)):
  1021. if not re.match(self._cc_normalize_win_mrgx, f):
  1022. continue
  1023. i += 1
  1024. return list(filter(
  1025. self._cc_normalize_win_frgx.search, flags[:-i]
  1026. )) + flags[-i:]
  1027. return flags
  1028. class _Feature:
  1029. """A helper class for `CCompilerOpt` that managing CPU features.
  1030. Attributes
  1031. ----------
  1032. feature_supported : dict
  1033. Dictionary containing all CPU features that supported
  1034. by the platform, according to the specified values in attribute
  1035. `_Config.conf_features` and `_Config.conf_features_partial()`
  1036. feature_min : set
  1037. The minimum support of CPU features, according to
  1038. the specified values in attribute `_Config.conf_min_features`.
  1039. """
  1040. def __init__(self):
  1041. if hasattr(self, "feature_is_cached"):
  1042. return
  1043. self.feature_supported = pfeatures = self.conf_features_partial()
  1044. for feature_name in list(pfeatures.keys()):
  1045. feature = pfeatures[feature_name]
  1046. cfeature = self.conf_features[feature_name]
  1047. feature.update({
  1048. k:v for k,v in cfeature.items() if k not in feature
  1049. })
  1050. disabled = feature.get("disable")
  1051. if disabled is not None:
  1052. pfeatures.pop(feature_name)
  1053. self.dist_log(
  1054. "feature '%s' is disabled," % feature_name,
  1055. disabled, stderr=True
  1056. )
  1057. continue
  1058. # list is used internally for these options
  1059. for option in (
  1060. "implies", "group", "detect", "headers", "flags", "extra_checks"
  1061. ) :
  1062. oval = feature.get(option)
  1063. if isinstance(oval, str):
  1064. feature[option] = oval.split()
  1065. self.feature_min = set()
  1066. min_f = self.conf_min_features.get(self.cc_march, "")
  1067. for F in min_f.upper().split():
  1068. if F in self.feature_supported:
  1069. self.feature_min.add(F)
  1070. self.feature_is_cached = True
  1071. def feature_names(self, names=None, force_flags=None, macros=[]):
  1072. """
  1073. Returns a set of CPU feature names that supported by platform and the **C** compiler.
  1074. Parameters
  1075. ----------
  1076. names: sequence or None, optional
  1077. Specify certain CPU features to test it against the **C** compiler.
  1078. if None(default), it will test all current supported features.
  1079. **Note**: feature names must be in upper-case.
  1080. force_flags: list or None, optional
  1081. If None(default), default compiler flags for every CPU feature will
  1082. be used during the test.
  1083. macros : list of tuples, optional
  1084. A list of C macro definitions.
  1085. """
  1086. assert(
  1087. names is None or (
  1088. not isinstance(names, str) and
  1089. hasattr(names, "__iter__")
  1090. )
  1091. )
  1092. assert(force_flags is None or isinstance(force_flags, list))
  1093. if names is None:
  1094. names = self.feature_supported.keys()
  1095. supported_names = set()
  1096. for f in names:
  1097. if self.feature_is_supported(
  1098. f, force_flags=force_flags, macros=macros
  1099. ):
  1100. supported_names.add(f)
  1101. return supported_names
  1102. def feature_is_exist(self, name):
  1103. """
  1104. Returns True if a certain feature is exist and covered within
  1105. `_Config.conf_features`.
  1106. Parameters
  1107. ----------
  1108. 'name': str
  1109. feature name in uppercase.
  1110. """
  1111. assert(name.isupper())
  1112. return name in self.conf_features
  1113. def feature_sorted(self, names, reverse=False):
  1114. """
  1115. Sort a list of CPU features ordered by the lowest interest.
  1116. Parameters
  1117. ----------
  1118. 'names': sequence
  1119. sequence of supported feature names in uppercase.
  1120. 'reverse': bool, optional
  1121. If true, the sorted features is reversed. (highest interest)
  1122. Returns
  1123. -------
  1124. list, sorted CPU features
  1125. """
  1126. def sort_cb(k):
  1127. if isinstance(k, str):
  1128. return self.feature_supported[k]["interest"]
  1129. # multiple features
  1130. rank = max([self.feature_supported[f]["interest"] for f in k])
  1131. # FIXME: that's not a safe way to increase the rank for
  1132. # multi targets
  1133. rank += len(k) -1
  1134. return rank
  1135. return sorted(names, reverse=reverse, key=sort_cb)
  1136. def feature_implies(self, names, keep_origins=False):
  1137. """
  1138. Return a set of CPU features that implied by 'names'
  1139. Parameters
  1140. ----------
  1141. names: str or sequence of str
  1142. CPU feature name(s) in uppercase.
  1143. keep_origins: bool
  1144. if False(default) then the returned set will not contain any
  1145. features from 'names'. This case happens only when two features
  1146. imply each other.
  1147. Examples
  1148. --------
  1149. >>> self.feature_implies("SSE3")
  1150. {'SSE', 'SSE2'}
  1151. >>> self.feature_implies("SSE2")
  1152. {'SSE'}
  1153. >>> self.feature_implies("SSE2", keep_origins=True)
  1154. # 'SSE2' found here since 'SSE' and 'SSE2' imply each other
  1155. {'SSE', 'SSE2'}
  1156. """
  1157. def get_implies(name, _caller=set()):
  1158. implies = set()
  1159. d = self.feature_supported[name]
  1160. for i in d.get("implies", []):
  1161. implies.add(i)
  1162. if i in _caller:
  1163. # infinity recursive guard since
  1164. # features can imply each other
  1165. continue
  1166. _caller.add(name)
  1167. implies = implies.union(get_implies(i, _caller))
  1168. return implies
  1169. if isinstance(names, str):
  1170. implies = get_implies(names)
  1171. names = [names]
  1172. else:
  1173. assert(hasattr(names, "__iter__"))
  1174. implies = set()
  1175. for n in names:
  1176. implies = implies.union(get_implies(n))
  1177. if not keep_origins:
  1178. implies.difference_update(names)
  1179. return implies
  1180. def feature_implies_c(self, names):
  1181. """same as feature_implies() but combining 'names'"""
  1182. if isinstance(names, str):
  1183. names = set((names,))
  1184. else:
  1185. names = set(names)
  1186. return names.union(self.feature_implies(names))
  1187. def feature_ahead(self, names):
  1188. """
  1189. Return list of features in 'names' after remove any
  1190. implied features and keep the origins.
  1191. Parameters
  1192. ----------
  1193. 'names': sequence
  1194. sequence of CPU feature names in uppercase.
  1195. Returns
  1196. -------
  1197. list of CPU features sorted as-is 'names'
  1198. Examples
  1199. --------
  1200. >>> self.feature_ahead(["SSE2", "SSE3", "SSE41"])
  1201. ["SSE41"]
  1202. # assume AVX2 and FMA3 implies each other and AVX2
  1203. # is the highest interest
  1204. >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
  1205. ["AVX2"]
  1206. # assume AVX2 and FMA3 don't implies each other
  1207. >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
  1208. ["AVX2", "FMA3"]
  1209. """
  1210. assert(
  1211. not isinstance(names, str)
  1212. and hasattr(names, '__iter__')
  1213. )
  1214. implies = self.feature_implies(names, keep_origins=True)
  1215. ahead = [n for n in names if n not in implies]
  1216. if len(ahead) == 0:
  1217. # return the highest interested feature
  1218. # if all features imply each other
  1219. ahead = self.feature_sorted(names, reverse=True)[:1]
  1220. return ahead
  1221. def feature_untied(self, names):
  1222. """
  1223. same as 'feature_ahead()' but if both features implied each other
  1224. and keep the highest interest.
  1225. Parameters
  1226. ----------
  1227. 'names': sequence
  1228. sequence of CPU feature names in uppercase.
  1229. Returns
  1230. -------
  1231. list of CPU features sorted as-is 'names'
  1232. Examples
  1233. --------
  1234. >>> self.feature_untied(["SSE2", "SSE3", "SSE41"])
  1235. ["SSE2", "SSE3", "SSE41"]
  1236. # assume AVX2 and FMA3 implies each other
  1237. >>> self.feature_untied(["SSE2", "SSE3", "SSE41", "FMA3", "AVX2"])
  1238. ["SSE2", "SSE3", "SSE41", "AVX2"]
  1239. """
  1240. assert(
  1241. not isinstance(names, str)
  1242. and hasattr(names, '__iter__')
  1243. )
  1244. final = []
  1245. for n in names:
  1246. implies = self.feature_implies(n)
  1247. tied = [
  1248. nn for nn in final
  1249. if nn in implies and n in self.feature_implies(nn)
  1250. ]
  1251. if tied:
  1252. tied = self.feature_sorted(tied + [n])
  1253. if n not in tied[1:]:
  1254. continue
  1255. final.remove(tied[:1][0])
  1256. final.append(n)
  1257. return final
  1258. def feature_get_til(self, names, keyisfalse):
  1259. """
  1260. same as `feature_implies_c()` but stop collecting implied
  1261. features when feature's option that provided through
  1262. parameter 'keyisfalse' is False, also sorting the returned
  1263. features.
  1264. """
  1265. def til(tnames):
  1266. # sort from highest to lowest interest then cut if "key" is False
  1267. tnames = self.feature_implies_c(tnames)
  1268. tnames = self.feature_sorted(tnames, reverse=True)
  1269. for i, n in enumerate(tnames):
  1270. if not self.feature_supported[n].get(keyisfalse, True):
  1271. tnames = tnames[:i+1]
  1272. break
  1273. return tnames
  1274. if isinstance(names, str) or len(names) <= 1:
  1275. names = til(names)
  1276. # normalize the sort
  1277. names.reverse()
  1278. return names
  1279. names = self.feature_ahead(names)
  1280. names = {t for n in names for t in til(n)}
  1281. return self.feature_sorted(names)
  1282. def feature_detect(self, names):
  1283. """
  1284. Return a list of CPU features that required to be detected
  1285. sorted from the lowest to highest interest.
  1286. """
  1287. names = self.feature_get_til(names, "implies_detect")
  1288. detect = []
  1289. for n in names:
  1290. d = self.feature_supported[n]
  1291. detect += d.get("detect", d.get("group", [n]))
  1292. return detect
  1293. @_Cache.me
  1294. def feature_flags(self, names):
  1295. """
  1296. Return a list of CPU features flags sorted from the lowest
  1297. to highest interest.
  1298. """
  1299. names = self.feature_sorted(self.feature_implies_c(names))
  1300. flags = []
  1301. for n in names:
  1302. d = self.feature_supported[n]
  1303. f = d.get("flags", [])
  1304. if not f or not self.cc_test_flags(f):
  1305. continue
  1306. flags += f
  1307. return self.cc_normalize_flags(flags)
  1308. @_Cache.me
  1309. def feature_test(self, name, force_flags=None, macros=[]):
  1310. """
  1311. Test a certain CPU feature against the compiler through its own
  1312. check file.
  1313. Parameters
  1314. ----------
  1315. name: str
  1316. Supported CPU feature name.
  1317. force_flags: list or None, optional
  1318. If None(default), the returned flags from `feature_flags()`
  1319. will be used.
  1320. macros : list of tuples, optional
  1321. A list of C macro definitions.
  1322. """
  1323. if force_flags is None:
  1324. force_flags = self.feature_flags(name)
  1325. self.dist_log(
  1326. "testing feature '%s' with flags (%s)" % (
  1327. name, ' '.join(force_flags)
  1328. ))
  1329. # Each CPU feature must have C source code contains at
  1330. # least one intrinsic or instruction related to this feature.
  1331. test_path = os.path.join(
  1332. self.conf_check_path, "cpu_%s.c" % name.lower()
  1333. )
  1334. if not os.path.exists(test_path):
  1335. self.dist_fatal("feature test file is not exist", test_path)
  1336. test = self.dist_test(
  1337. test_path, force_flags + self.cc_flags["werror"], macros=macros
  1338. )
  1339. if not test:
  1340. self.dist_log("testing failed", stderr=True)
  1341. return test
  1342. @_Cache.me
  1343. def feature_is_supported(self, name, force_flags=None, macros=[]):
  1344. """
  1345. Check if a certain CPU feature is supported by the platform and compiler.
  1346. Parameters
  1347. ----------
  1348. name: str
  1349. CPU feature name in uppercase.
  1350. force_flags: list or None, optional
  1351. If None(default), default compiler flags for every CPU feature will
  1352. be used during test.
  1353. macros : list of tuples, optional
  1354. A list of C macro definitions.
  1355. """
  1356. assert(name.isupper())
  1357. assert(force_flags is None or isinstance(force_flags, list))
  1358. supported = name in self.feature_supported
  1359. if supported:
  1360. for impl in self.feature_implies(name):
  1361. if not self.feature_test(impl, force_flags, macros=macros):
  1362. return False
  1363. if not self.feature_test(name, force_flags, macros=macros):
  1364. return False
  1365. return supported
  1366. @_Cache.me
  1367. def feature_can_autovec(self, name):
  1368. """
  1369. check if the feature can be auto-vectorized by the compiler
  1370. """
  1371. assert(isinstance(name, str))
  1372. d = self.feature_supported[name]
  1373. can = d.get("autovec", None)
  1374. if can is None:
  1375. valid_flags = [
  1376. self.cc_test_flags([f]) for f in d.get("flags", [])
  1377. ]
  1378. can = valid_flags and any(valid_flags)
  1379. return can
  1380. @_Cache.me
  1381. def feature_extra_checks(self, name):
  1382. """
  1383. Return a list of supported extra checks after testing them against
  1384. the compiler.
  1385. Parameters
  1386. ----------
  1387. names: str
  1388. CPU feature name in uppercase.
  1389. """
  1390. assert isinstance(name, str)
  1391. d = self.feature_supported[name]
  1392. extra_checks = d.get("extra_checks", [])
  1393. if not extra_checks:
  1394. return []
  1395. self.dist_log("Testing extra checks for feature '%s'" % name, extra_checks)
  1396. flags = self.feature_flags(name)
  1397. available = []
  1398. not_available = []
  1399. for chk in extra_checks:
  1400. test_path = os.path.join(
  1401. self.conf_check_path, "extra_%s.c" % chk.lower()
  1402. )
  1403. if not os.path.exists(test_path):
  1404. self.dist_fatal("extra check file does not exist", test_path)
  1405. is_supported = self.dist_test(test_path, flags + self.cc_flags["werror"])
  1406. if is_supported:
  1407. available.append(chk)
  1408. else:
  1409. not_available.append(chk)
  1410. if not_available:
  1411. self.dist_log("testing failed for checks", not_available, stderr=True)
  1412. return available
  1413. def feature_c_preprocessor(self, feature_name, tabs=0):
  1414. """
  1415. Generate C preprocessor definitions and include headers of a CPU feature.
  1416. Parameters
  1417. ----------
  1418. 'feature_name': str
  1419. CPU feature name in uppercase.
  1420. 'tabs': int
  1421. if > 0, align the generated strings to the right depend on number of tabs.
  1422. Returns
  1423. -------
  1424. str, generated C preprocessor
  1425. Examples
  1426. --------
  1427. >>> self.feature_c_preprocessor("SSE3")
  1428. /** SSE3 **/
  1429. #define NPY_HAVE_SSE3 1
  1430. #include <pmmintrin.h>
  1431. """
  1432. assert(feature_name.isupper())
  1433. feature = self.feature_supported.get(feature_name)
  1434. assert(feature is not None)
  1435. prepr = [
  1436. "/** %s **/" % feature_name,
  1437. "#define %sHAVE_%s 1" % (self.conf_c_prefix, feature_name)
  1438. ]
  1439. prepr += [
  1440. "#include <%s>" % h for h in feature.get("headers", [])
  1441. ]
  1442. extra_defs = feature.get("group", [])
  1443. extra_defs += self.feature_extra_checks(feature_name)
  1444. for edef in extra_defs:
  1445. # Guard extra definitions in case of duplicate with
  1446. # another feature
  1447. prepr += [
  1448. "#ifndef %sHAVE_%s" % (self.conf_c_prefix, edef),
  1449. "\t#define %sHAVE_%s 1" % (self.conf_c_prefix, edef),
  1450. "#endif",
  1451. ]
  1452. if tabs > 0:
  1453. prepr = [('\t'*tabs) + l for l in prepr]
  1454. return '\n'.join(prepr)
  1455. class _Parse:
  1456. """A helper class that parsing main arguments of `CCompilerOpt`,
  1457. also parsing configuration statements in dispatch-able sources.
  1458. Parameters
  1459. ----------
  1460. cpu_baseline: str or None
  1461. minimal set of required CPU features or special options.
  1462. cpu_dispatch: str or None
  1463. dispatched set of additional CPU features or special options.
  1464. Special options can be:
  1465. - **MIN**: Enables the minimum CPU features that utilized via `_Config.conf_min_features`
  1466. - **MAX**: Enables all supported CPU features by the Compiler and platform.
  1467. - **NATIVE**: Enables all CPU features that supported by the current machine.
  1468. - **NONE**: Enables nothing
  1469. - **Operand +/-**: remove or add features, useful with options **MAX**, **MIN** and **NATIVE**.
  1470. NOTE: operand + is only added for nominal reason.
  1471. NOTES:
  1472. - Case-insensitive among all CPU features and special options.
  1473. - Comma or space can be used as a separator.
  1474. - If the CPU feature is not supported by the user platform or compiler,
  1475. it will be skipped rather than raising a fatal error.
  1476. - Any specified CPU features to 'cpu_dispatch' will be skipped if its part of CPU baseline features
  1477. - 'cpu_baseline' force enables implied features.
  1478. Attributes
  1479. ----------
  1480. parse_baseline_names : list
  1481. Final CPU baseline's feature names(sorted from low to high)
  1482. parse_baseline_flags : list
  1483. Compiler flags of baseline features
  1484. parse_dispatch_names : list
  1485. Final CPU dispatch-able feature names(sorted from low to high)
  1486. parse_target_groups : dict
  1487. Dictionary containing initialized target groups that configured
  1488. through class attribute `conf_target_groups`.
  1489. The key is represent the group name and value is a tuple
  1490. contains three items :
  1491. - bool, True if group has the 'baseline' option.
  1492. - list, list of CPU features.
  1493. - list, list of extra compiler flags.
  1494. """
  1495. def __init__(self, cpu_baseline, cpu_dispatch):
  1496. self._parse_policies = dict(
  1497. # POLICY NAME, (HAVE, NOT HAVE, [DEB])
  1498. KEEP_BASELINE = (
  1499. None, self._parse_policy_not_keepbase,
  1500. []
  1501. ),
  1502. KEEP_SORT = (
  1503. self._parse_policy_keepsort,
  1504. self._parse_policy_not_keepsort,
  1505. []
  1506. ),
  1507. MAXOPT = (
  1508. self._parse_policy_maxopt, None,
  1509. []
  1510. ),
  1511. WERROR = (
  1512. self._parse_policy_werror, None,
  1513. []
  1514. ),
  1515. AUTOVEC = (
  1516. self._parse_policy_autovec, None,
  1517. ["MAXOPT"]
  1518. )
  1519. )
  1520. if hasattr(self, "parse_is_cached"):
  1521. return
  1522. self.parse_baseline_names = []
  1523. self.parse_baseline_flags = []
  1524. self.parse_dispatch_names = []
  1525. self.parse_target_groups = {}
  1526. if self.cc_noopt:
  1527. # skip parsing baseline and dispatch args and keep parsing target groups
  1528. cpu_baseline = cpu_dispatch = None
  1529. self.dist_log("check requested baseline")
  1530. if cpu_baseline is not None:
  1531. cpu_baseline = self._parse_arg_features("cpu_baseline", cpu_baseline)
  1532. baseline_names = self.feature_names(cpu_baseline)
  1533. self.parse_baseline_flags = self.feature_flags(baseline_names)
  1534. self.parse_baseline_names = self.feature_sorted(
  1535. self.feature_implies_c(baseline_names)
  1536. )
  1537. self.dist_log("check requested dispatch-able features")
  1538. if cpu_dispatch is not None:
  1539. cpu_dispatch_ = self._parse_arg_features("cpu_dispatch", cpu_dispatch)
  1540. cpu_dispatch = {
  1541. f for f in cpu_dispatch_
  1542. if f not in self.parse_baseline_names
  1543. }
  1544. conflict_baseline = cpu_dispatch_.difference(cpu_dispatch)
  1545. self.parse_dispatch_names = self.feature_sorted(
  1546. self.feature_names(cpu_dispatch)
  1547. )
  1548. if len(conflict_baseline) > 0:
  1549. self.dist_log(
  1550. "skip features", conflict_baseline, "since its part of baseline"
  1551. )
  1552. self.dist_log("initialize targets groups")
  1553. for group_name, tokens in self.conf_target_groups.items():
  1554. self.dist_log("parse target group", group_name)
  1555. GROUP_NAME = group_name.upper()
  1556. if not tokens or not tokens.strip():
  1557. # allow empty groups, useful in case if there's a need
  1558. # to disable certain group since '_parse_target_tokens()'
  1559. # requires at least one valid target
  1560. self.parse_target_groups[GROUP_NAME] = (
  1561. False, [], []
  1562. )
  1563. continue
  1564. has_baseline, features, extra_flags = \
  1565. self._parse_target_tokens(tokens)
  1566. self.parse_target_groups[GROUP_NAME] = (
  1567. has_baseline, features, extra_flags
  1568. )
  1569. self.parse_is_cached = True
  1570. def parse_targets(self, source):
  1571. """
  1572. Fetch and parse configuration statements that required for
  1573. defining the targeted CPU features, statements should be declared
  1574. in the top of source in between **C** comment and start
  1575. with a special mark **@targets**.
  1576. Configuration statements are sort of keywords representing
  1577. CPU features names, group of statements and policies, combined
  1578. together to determine the required optimization.
  1579. Parameters
  1580. ----------
  1581. source: str
  1582. the path of **C** source file.
  1583. Returns
  1584. -------
  1585. - bool, True if group has the 'baseline' option
  1586. - list, list of CPU features
  1587. - list, list of extra compiler flags
  1588. """
  1589. self.dist_log("looking for '@targets' inside -> ", source)
  1590. # get lines between /*@targets and */
  1591. with open(source) as fd:
  1592. tokens = ""
  1593. max_to_reach = 1000 # good enough, isn't?
  1594. start_with = "@targets"
  1595. start_pos = -1
  1596. end_with = "*/"
  1597. end_pos = -1
  1598. for current_line, line in enumerate(fd):
  1599. if current_line == max_to_reach:
  1600. self.dist_fatal("reached the max of lines")
  1601. break
  1602. if start_pos == -1:
  1603. start_pos = line.find(start_with)
  1604. if start_pos == -1:
  1605. continue
  1606. start_pos += len(start_with)
  1607. tokens += line
  1608. end_pos = line.find(end_with)
  1609. if end_pos != -1:
  1610. end_pos += len(tokens) - len(line)
  1611. break
  1612. if start_pos == -1:
  1613. self.dist_fatal("expected to find '%s' within a C comment" % start_with)
  1614. if end_pos == -1:
  1615. self.dist_fatal("expected to end with '%s'" % end_with)
  1616. tokens = tokens[start_pos:end_pos]
  1617. return self._parse_target_tokens(tokens)
  1618. _parse_regex_arg = re.compile(r'\s|,|([+-])')
  1619. def _parse_arg_features(self, arg_name, req_features):
  1620. if not isinstance(req_features, str):
  1621. self.dist_fatal("expected a string in '%s'" % arg_name)
  1622. final_features = set()
  1623. # space and comma can be used as a separator
  1624. tokens = list(filter(None, re.split(self._parse_regex_arg, req_features)))
  1625. append = True # append is the default
  1626. for tok in tokens:
  1627. if tok[0] in ("#", "$"):
  1628. self.dist_fatal(
  1629. arg_name, "target groups and policies "
  1630. "aren't allowed from arguments, "
  1631. "only from dispatch-able sources"
  1632. )
  1633. if tok == '+':
  1634. append = True
  1635. continue
  1636. if tok == '-':
  1637. append = False
  1638. continue
  1639. TOK = tok.upper() # we use upper-case internally
  1640. features_to = set()
  1641. if TOK == "NONE":
  1642. pass
  1643. elif TOK == "NATIVE":
  1644. native = self.cc_flags["native"]
  1645. if not native:
  1646. self.dist_fatal(arg_name,
  1647. "native option isn't supported by the compiler"
  1648. )
  1649. features_to = self.feature_names(
  1650. force_flags=native, macros=[("DETECT_FEATURES", 1)]
  1651. )
  1652. elif TOK == "MAX":
  1653. features_to = self.feature_supported.keys()
  1654. elif TOK == "MIN":
  1655. features_to = self.feature_min
  1656. else:
  1657. if TOK in self.feature_supported:
  1658. features_to.add(TOK)
  1659. else:
  1660. if not self.feature_is_exist(TOK):
  1661. self.dist_fatal(arg_name,
  1662. ", '%s' isn't a known feature or option" % tok
  1663. )
  1664. if append:
  1665. final_features = final_features.union(features_to)
  1666. else:
  1667. final_features = final_features.difference(features_to)
  1668. append = True # back to default
  1669. return final_features
  1670. _parse_regex_target = re.compile(r'\s|[*,/]|([()])')
  1671. def _parse_target_tokens(self, tokens):
  1672. assert(isinstance(tokens, str))
  1673. final_targets = [] # to keep it sorted as specified
  1674. extra_flags = []
  1675. has_baseline = False
  1676. skipped = set()
  1677. policies = set()
  1678. multi_target = None
  1679. tokens = list(filter(None, re.split(self._parse_regex_target, tokens)))
  1680. if not tokens:
  1681. self.dist_fatal("expected one token at least")
  1682. for tok in tokens:
  1683. TOK = tok.upper()
  1684. ch = tok[0]
  1685. if ch in ('+', '-'):
  1686. self.dist_fatal(
  1687. "+/- are 'not' allowed from target's groups or @targets, "
  1688. "only from cpu_baseline and cpu_dispatch parms"
  1689. )
  1690. elif ch == '$':
  1691. if multi_target is not None:
  1692. self.dist_fatal(
  1693. "policies aren't allowed inside multi-target '()'"
  1694. ", only CPU features"
  1695. )
  1696. policies.add(self._parse_token_policy(TOK))
  1697. elif ch == '#':
  1698. if multi_target is not None:
  1699. self.dist_fatal(
  1700. "target groups aren't allowed inside multi-target '()'"
  1701. ", only CPU features"
  1702. )
  1703. has_baseline, final_targets, extra_flags = \
  1704. self._parse_token_group(TOK, has_baseline, final_targets, extra_flags)
  1705. elif ch == '(':
  1706. if multi_target is not None:
  1707. self.dist_fatal("unclosed multi-target, missing ')'")
  1708. multi_target = set()
  1709. elif ch == ')':
  1710. if multi_target is None:
  1711. self.dist_fatal("multi-target opener '(' wasn't found")
  1712. targets = self._parse_multi_target(multi_target)
  1713. if targets is None:
  1714. skipped.add(tuple(multi_target))
  1715. else:
  1716. if len(targets) == 1:
  1717. targets = targets[0]
  1718. if targets and targets not in final_targets:
  1719. final_targets.append(targets)
  1720. multi_target = None # back to default
  1721. else:
  1722. if TOK == "BASELINE":
  1723. if multi_target is not None:
  1724. self.dist_fatal("baseline isn't allowed inside multi-target '()'")
  1725. has_baseline = True
  1726. continue
  1727. if multi_target is not None:
  1728. multi_target.add(TOK)
  1729. continue
  1730. if not self.feature_is_exist(TOK):
  1731. self.dist_fatal("invalid target name '%s'" % TOK)
  1732. is_enabled = (
  1733. TOK in self.parse_baseline_names or
  1734. TOK in self.parse_dispatch_names
  1735. )
  1736. if is_enabled:
  1737. if TOK not in final_targets:
  1738. final_targets.append(TOK)
  1739. continue
  1740. skipped.add(TOK)
  1741. if multi_target is not None:
  1742. self.dist_fatal("unclosed multi-target, missing ')'")
  1743. if skipped:
  1744. self.dist_log(
  1745. "skip targets", skipped,
  1746. "not part of baseline or dispatch-able features"
  1747. )
  1748. final_targets = self.feature_untied(final_targets)
  1749. # add polices dependencies
  1750. for p in list(policies):
  1751. _, _, deps = self._parse_policies[p]
  1752. for d in deps:
  1753. if d in policies:
  1754. continue
  1755. self.dist_log(
  1756. "policy '%s' force enables '%s'" % (
  1757. p, d
  1758. ))
  1759. policies.add(d)
  1760. # release policies filtrations
  1761. for p, (have, nhave, _) in self._parse_policies.items():
  1762. func = None
  1763. if p in policies:
  1764. func = have
  1765. self.dist_log("policy '%s' is ON" % p)
  1766. else:
  1767. func = nhave
  1768. if not func:
  1769. continue
  1770. has_baseline, final_targets, extra_flags = func(
  1771. has_baseline, final_targets, extra_flags
  1772. )
  1773. return has_baseline, final_targets, extra_flags
  1774. def _parse_token_policy(self, token):
  1775. """validate policy token"""
  1776. if len(token) <= 1 or token[-1:] == token[0]:
  1777. self.dist_fatal("'$' must stuck in the begin of policy name")
  1778. token = token[1:]
  1779. if token not in self._parse_policies:
  1780. self.dist_fatal(
  1781. "'%s' is an invalid policy name, available policies are" % token,
  1782. self._parse_policies.keys()
  1783. )
  1784. return token
  1785. def _parse_token_group(self, token, has_baseline, final_targets, extra_flags):
  1786. """validate group token"""
  1787. if len(token) <= 1 or token[-1:] == token[0]:
  1788. self.dist_fatal("'#' must stuck in the begin of group name")
  1789. token = token[1:]
  1790. ghas_baseline, gtargets, gextra_flags = self.parse_target_groups.get(
  1791. token, (False, None, [])
  1792. )
  1793. if gtargets is None:
  1794. self.dist_fatal(
  1795. "'%s' is an invalid target group name, " % token + \
  1796. "available target groups are",
  1797. self.parse_target_groups.keys()
  1798. )
  1799. if ghas_baseline:
  1800. has_baseline = True
  1801. # always keep sorting as specified
  1802. final_targets += [f for f in gtargets if f not in final_targets]
  1803. extra_flags += [f for f in gextra_flags if f not in extra_flags]
  1804. return has_baseline, final_targets, extra_flags
  1805. def _parse_multi_target(self, targets):
  1806. """validate multi targets that defined between parentheses()"""
  1807. # remove any implied features and keep the origins
  1808. if not targets:
  1809. self.dist_fatal("empty multi-target '()'")
  1810. if not all([
  1811. self.feature_is_exist(tar) for tar in targets
  1812. ]) :
  1813. self.dist_fatal("invalid target name in multi-target", targets)
  1814. if not all([
  1815. (
  1816. tar in self.parse_baseline_names or
  1817. tar in self.parse_dispatch_names
  1818. )
  1819. for tar in targets
  1820. ]) :
  1821. return None
  1822. targets = self.feature_ahead(targets)
  1823. if not targets:
  1824. return None
  1825. # force sort multi targets, so it can be comparable
  1826. targets = self.feature_sorted(targets)
  1827. targets = tuple(targets) # hashable
  1828. return targets
  1829. def _parse_policy_not_keepbase(self, has_baseline, final_targets, extra_flags):
  1830. """skip all baseline features"""
  1831. skipped = []
  1832. for tar in final_targets[:]:
  1833. is_base = False
  1834. if isinstance(tar, str):
  1835. is_base = tar in self.parse_baseline_names
  1836. else:
  1837. # multi targets
  1838. is_base = all([
  1839. f in self.parse_baseline_names
  1840. for f in tar
  1841. ])
  1842. if is_base:
  1843. skipped.append(tar)
  1844. final_targets.remove(tar)
  1845. if skipped:
  1846. self.dist_log("skip baseline features", skipped)
  1847. return has_baseline, final_targets, extra_flags
  1848. def _parse_policy_keepsort(self, has_baseline, final_targets, extra_flags):
  1849. """leave a notice that $keep_sort is on"""
  1850. self.dist_log(
  1851. "policy 'keep_sort' is on, dispatch-able targets", final_targets, "\n"
  1852. "are 'not' sorted depend on the highest interest but"
  1853. "as specified in the dispatch-able source or the extra group"
  1854. )
  1855. return has_baseline, final_targets, extra_flags
  1856. def _parse_policy_not_keepsort(self, has_baseline, final_targets, extra_flags):
  1857. """sorted depend on the highest interest"""
  1858. final_targets = self.feature_sorted(final_targets, reverse=True)
  1859. return has_baseline, final_targets, extra_flags
  1860. def _parse_policy_maxopt(self, has_baseline, final_targets, extra_flags):
  1861. """append the compiler optimization flags"""
  1862. if self.cc_has_debug:
  1863. self.dist_log("debug mode is detected, policy 'maxopt' is skipped.")
  1864. elif self.cc_noopt:
  1865. self.dist_log("optimization is disabled, policy 'maxopt' is skipped.")
  1866. else:
  1867. flags = self.cc_flags["opt"]
  1868. if not flags:
  1869. self.dist_log(
  1870. "current compiler doesn't support optimization flags, "
  1871. "policy 'maxopt' is skipped", stderr=True
  1872. )
  1873. else:
  1874. extra_flags += flags
  1875. return has_baseline, final_targets, extra_flags
  1876. def _parse_policy_werror(self, has_baseline, final_targets, extra_flags):
  1877. """force warnings to treated as errors"""
  1878. flags = self.cc_flags["werror"]
  1879. if not flags:
  1880. self.dist_log(
  1881. "current compiler doesn't support werror flags, "
  1882. "warnings will 'not' treated as errors", stderr=True
  1883. )
  1884. else:
  1885. self.dist_log("compiler warnings are treated as errors")
  1886. extra_flags += flags
  1887. return has_baseline, final_targets, extra_flags
  1888. def _parse_policy_autovec(self, has_baseline, final_targets, extra_flags):
  1889. """skip features that has no auto-vectorized support by compiler"""
  1890. skipped = []
  1891. for tar in final_targets[:]:
  1892. if isinstance(tar, str):
  1893. can = self.feature_can_autovec(tar)
  1894. else: # multiple target
  1895. can = all([
  1896. self.feature_can_autovec(t)
  1897. for t in tar
  1898. ])
  1899. if not can:
  1900. final_targets.remove(tar)
  1901. skipped.append(tar)
  1902. if skipped:
  1903. self.dist_log("skip non auto-vectorized features", skipped)
  1904. return has_baseline, final_targets, extra_flags
  1905. class CCompilerOpt(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse):
  1906. """
  1907. A helper class for `CCompiler` aims to provide extra build options
  1908. to effectively control of compiler optimizations that are directly
  1909. related to CPU features.
  1910. """
  1911. def __init__(self, ccompiler, cpu_baseline="min", cpu_dispatch="max", cache_path=None):
  1912. _Config.__init__(self)
  1913. _Distutils.__init__(self, ccompiler)
  1914. _Cache.__init__(self, cache_path, self.dist_info(), cpu_baseline, cpu_dispatch)
  1915. _CCompiler.__init__(self)
  1916. _Feature.__init__(self)
  1917. if not self.cc_noopt and self.cc_has_native:
  1918. self.dist_log(
  1919. "native flag is specified through environment variables. "
  1920. "force cpu-baseline='native'"
  1921. )
  1922. cpu_baseline = "native"
  1923. _Parse.__init__(self, cpu_baseline, cpu_dispatch)
  1924. # keep the requested features untouched, need it later for report
  1925. # and trace purposes
  1926. self._requested_baseline = cpu_baseline
  1927. self._requested_dispatch = cpu_dispatch
  1928. # key is the dispatch-able source and value is a tuple
  1929. # contains two items (has_baseline[boolean], dispatched-features[list])
  1930. self.sources_status = getattr(self, "sources_status", {})
  1931. # every instance should has a separate one
  1932. self.cache_private.add("sources_status")
  1933. # set it at the end to make sure the cache writing was done after init
  1934. # this class
  1935. self.hit_cache = hasattr(self, "hit_cache")
  1936. def is_cached(self):
  1937. """
  1938. Returns True if the class loaded from the cache file
  1939. """
  1940. return self.cache_infile and self.hit_cache
  1941. def cpu_baseline_flags(self):
  1942. """
  1943. Returns a list of final CPU baseline compiler flags
  1944. """
  1945. return self.parse_baseline_flags
  1946. def cpu_baseline_names(self):
  1947. """
  1948. return a list of final CPU baseline feature names
  1949. """
  1950. return self.parse_baseline_names
  1951. def cpu_dispatch_names(self):
  1952. """
  1953. return a list of final CPU dispatch feature names
  1954. """
  1955. return self.parse_dispatch_names
  1956. def try_dispatch(self, sources, src_dir=None, ccompiler=None, **kwargs):
  1957. """
  1958. Compile one or more dispatch-able sources and generates object files,
  1959. also generates abstract C config headers and macros that
  1960. used later for the final runtime dispatching process.
  1961. The mechanism behind it is to takes each source file that specified
  1962. in 'sources' and branching it into several files depend on
  1963. special configuration statements that must be declared in the
  1964. top of each source which contains targeted CPU features,
  1965. then it compiles every branched source with the proper compiler flags.
  1966. Parameters
  1967. ----------
  1968. sources : list
  1969. Must be a list of dispatch-able sources file paths,
  1970. and configuration statements must be declared inside
  1971. each file.
  1972. src_dir : str
  1973. Path of parent directory for the generated headers and wrapped sources.
  1974. If None(default) the files will generated in-place.
  1975. ccompiler: CCompiler
  1976. Distutils `CCompiler` instance to be used for compilation.
  1977. If None (default), the provided instance during the initialization
  1978. will be used instead.
  1979. **kwargs : any
  1980. Arguments to pass on to the `CCompiler.compile()`
  1981. Returns
  1982. -------
  1983. list : generated object files
  1984. Raises
  1985. ------
  1986. CompileError
  1987. Raises by `CCompiler.compile()` on compiling failure.
  1988. DistutilsError
  1989. Some errors during checking the sanity of configuration statements.
  1990. See Also
  1991. --------
  1992. parse_targets :
  1993. Parsing the configuration statements of dispatch-able sources.
  1994. """
  1995. to_compile = {}
  1996. baseline_flags = self.cpu_baseline_flags()
  1997. include_dirs = kwargs.setdefault("include_dirs", [])
  1998. for src in sources:
  1999. output_dir = os.path.dirname(src)
  2000. if src_dir:
  2001. if not output_dir.startswith(src_dir):
  2002. output_dir = os.path.join(src_dir, output_dir)
  2003. if output_dir not in include_dirs:
  2004. # To allow including the generated config header(*.dispatch.h)
  2005. # by the dispatch-able sources
  2006. include_dirs.append(output_dir)
  2007. has_baseline, targets, extra_flags = self.parse_targets(src)
  2008. nochange = self._generate_config(output_dir, src, targets, has_baseline)
  2009. for tar in targets:
  2010. tar_src = self._wrap_target(output_dir, src, tar, nochange=nochange)
  2011. flags = tuple(extra_flags + self.feature_flags(tar))
  2012. to_compile.setdefault(flags, []).append(tar_src)
  2013. if has_baseline:
  2014. flags = tuple(extra_flags + baseline_flags)
  2015. to_compile.setdefault(flags, []).append(src)
  2016. self.sources_status[src] = (has_baseline, targets)
  2017. # For these reasons, the sources are compiled in a separate loop:
  2018. # - Gathering all sources with the same flags to benefit from
  2019. # the parallel compiling as much as possible.
  2020. # - To generate all config headers of the dispatchable sources,
  2021. # before the compilation in case if there are dependency relationships
  2022. # among them.
  2023. objects = []
  2024. for flags, srcs in to_compile.items():
  2025. objects += self.dist_compile(
  2026. srcs, list(flags), ccompiler=ccompiler, **kwargs
  2027. )
  2028. return objects
  2029. def generate_dispatch_header(self, header_path):
  2030. """
  2031. Generate the dispatch header which contains the #definitions and headers
  2032. for platform-specific instruction-sets for the enabled CPU baseline and
  2033. dispatch-able features.
  2034. Its highly recommended to take a look at the generated header
  2035. also the generated source files via `try_dispatch()`
  2036. in order to get the full picture.
  2037. """
  2038. self.dist_log("generate CPU dispatch header: (%s)" % header_path)
  2039. baseline_names = self.cpu_baseline_names()
  2040. dispatch_names = self.cpu_dispatch_names()
  2041. baseline_len = len(baseline_names)
  2042. dispatch_len = len(dispatch_names)
  2043. header_dir = os.path.dirname(header_path)
  2044. if not os.path.exists(header_dir):
  2045. self.dist_log(
  2046. f"dispatch header dir {header_dir} does not exist, creating it",
  2047. stderr=True
  2048. )
  2049. os.makedirs(header_dir)
  2050. with open(header_path, 'w') as f:
  2051. baseline_calls = ' \\\n'.join([
  2052. (
  2053. "\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
  2054. ) % (self.conf_c_prefix, f)
  2055. for f in baseline_names
  2056. ])
  2057. dispatch_calls = ' \\\n'.join([
  2058. (
  2059. "\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
  2060. ) % (self.conf_c_prefix, f)
  2061. for f in dispatch_names
  2062. ])
  2063. f.write(textwrap.dedent("""\
  2064. /*
  2065. * AUTOGENERATED DON'T EDIT
  2066. * Please make changes to the code generator (distutils/ccompiler_opt.py)
  2067. */
  2068. #define {pfx}WITH_CPU_BASELINE "{baseline_str}"
  2069. #define {pfx}WITH_CPU_DISPATCH "{dispatch_str}"
  2070. #define {pfx}WITH_CPU_BASELINE_N {baseline_len}
  2071. #define {pfx}WITH_CPU_DISPATCH_N {dispatch_len}
  2072. #define {pfx}WITH_CPU_EXPAND_(X) X
  2073. #define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \\
  2074. {baseline_calls}
  2075. #define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \\
  2076. {dispatch_calls}
  2077. """).format(
  2078. pfx=self.conf_c_prefix, baseline_str=" ".join(baseline_names),
  2079. dispatch_str=" ".join(dispatch_names), baseline_len=baseline_len,
  2080. dispatch_len=dispatch_len, baseline_calls=baseline_calls,
  2081. dispatch_calls=dispatch_calls
  2082. ))
  2083. baseline_pre = ''
  2084. for name in baseline_names:
  2085. baseline_pre += self.feature_c_preprocessor(name, tabs=1) + '\n'
  2086. dispatch_pre = ''
  2087. for name in dispatch_names:
  2088. dispatch_pre += textwrap.dedent("""\
  2089. #ifdef {pfx}CPU_TARGET_{name}
  2090. {pre}
  2091. #endif /*{pfx}CPU_TARGET_{name}*/
  2092. """).format(
  2093. pfx=self.conf_c_prefix_, name=name, pre=self.feature_c_preprocessor(
  2094. name, tabs=1
  2095. ))
  2096. f.write(textwrap.dedent("""\
  2097. /******* baseline features *******/
  2098. {baseline_pre}
  2099. /******* dispatch features *******/
  2100. {dispatch_pre}
  2101. """).format(
  2102. pfx=self.conf_c_prefix_, baseline_pre=baseline_pre,
  2103. dispatch_pre=dispatch_pre
  2104. ))
  2105. def report(self, full=False):
  2106. report = []
  2107. platform_rows = []
  2108. baseline_rows = []
  2109. dispatch_rows = []
  2110. report.append(("Platform", platform_rows))
  2111. report.append(("", ""))
  2112. report.append(("CPU baseline", baseline_rows))
  2113. report.append(("", ""))
  2114. report.append(("CPU dispatch", dispatch_rows))
  2115. ########## platform ##########
  2116. platform_rows.append(("Architecture", (
  2117. "unsupported" if self.cc_on_noarch else self.cc_march)
  2118. ))
  2119. platform_rows.append(("Compiler", (
  2120. "unix-like" if self.cc_is_nocc else self.cc_name)
  2121. ))
  2122. ########## baseline ##########
  2123. if self.cc_noopt:
  2124. baseline_rows.append(("Requested", "optimization disabled"))
  2125. else:
  2126. baseline_rows.append(("Requested", repr(self._requested_baseline)))
  2127. baseline_names = self.cpu_baseline_names()
  2128. baseline_rows.append((
  2129. "Enabled", (' '.join(baseline_names) if baseline_names else "none")
  2130. ))
  2131. baseline_flags = self.cpu_baseline_flags()
  2132. baseline_rows.append((
  2133. "Flags", (' '.join(baseline_flags) if baseline_flags else "none")
  2134. ))
  2135. extra_checks = []
  2136. for name in baseline_names:
  2137. extra_checks += self.feature_extra_checks(name)
  2138. baseline_rows.append((
  2139. "Extra checks", (' '.join(extra_checks) if extra_checks else "none")
  2140. ))
  2141. ########## dispatch ##########
  2142. if self.cc_noopt:
  2143. baseline_rows.append(("Requested", "optimization disabled"))
  2144. else:
  2145. dispatch_rows.append(("Requested", repr(self._requested_dispatch)))
  2146. dispatch_names = self.cpu_dispatch_names()
  2147. dispatch_rows.append((
  2148. "Enabled", (' '.join(dispatch_names) if dispatch_names else "none")
  2149. ))
  2150. ########## Generated ##########
  2151. # TODO:
  2152. # - collect object names from 'try_dispatch()'
  2153. # then get size of each object and printed
  2154. # - give more details about the features that not
  2155. # generated due compiler support
  2156. # - find a better output's design.
  2157. #
  2158. target_sources = {}
  2159. for source, (_, targets) in self.sources_status.items():
  2160. for tar in targets:
  2161. target_sources.setdefault(tar, []).append(source)
  2162. if not full or not target_sources:
  2163. generated = ""
  2164. for tar in self.feature_sorted(target_sources):
  2165. sources = target_sources[tar]
  2166. name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
  2167. generated += name + "[%d] " % len(sources)
  2168. dispatch_rows.append(("Generated", generated[:-1] if generated else "none"))
  2169. else:
  2170. dispatch_rows.append(("Generated", ''))
  2171. for tar in self.feature_sorted(target_sources):
  2172. sources = target_sources[tar]
  2173. pretty_name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
  2174. flags = ' '.join(self.feature_flags(tar))
  2175. implies = ' '.join(self.feature_sorted(self.feature_implies(tar)))
  2176. detect = ' '.join(self.feature_detect(tar))
  2177. extra_checks = []
  2178. for name in ((tar,) if isinstance(tar, str) else tar):
  2179. extra_checks += self.feature_extra_checks(name)
  2180. extra_checks = (' '.join(extra_checks) if extra_checks else "none")
  2181. dispatch_rows.append(('', ''))
  2182. dispatch_rows.append((pretty_name, implies))
  2183. dispatch_rows.append(("Flags", flags))
  2184. dispatch_rows.append(("Extra checks", extra_checks))
  2185. dispatch_rows.append(("Detect", detect))
  2186. for src in sources:
  2187. dispatch_rows.append(("", src))
  2188. ###############################
  2189. # TODO: add support for 'markdown' format
  2190. text = []
  2191. secs_len = [len(secs) for secs, _ in report]
  2192. cols_len = [len(col) for _, rows in report for col, _ in rows]
  2193. tab = ' ' * 2
  2194. pad = max(max(secs_len), max(cols_len))
  2195. for sec, rows in report:
  2196. if not sec:
  2197. text.append("") # empty line
  2198. continue
  2199. sec += ' ' * (pad - len(sec))
  2200. text.append(sec + tab + ': ')
  2201. for col, val in rows:
  2202. col += ' ' * (pad - len(col))
  2203. text.append(tab + col + ': ' + val)
  2204. return '\n'.join(text)
  2205. def _wrap_target(self, output_dir, dispatch_src, target, nochange=False):
  2206. assert(isinstance(target, (str, tuple)))
  2207. if isinstance(target, str):
  2208. ext_name = target_name = target
  2209. else:
  2210. # multi-target
  2211. ext_name = '.'.join(target)
  2212. target_name = '__'.join(target)
  2213. wrap_path = os.path.join(output_dir, os.path.basename(dispatch_src))
  2214. wrap_path = "{0}.{2}{1}".format(*os.path.splitext(wrap_path), ext_name.lower())
  2215. if nochange and os.path.exists(wrap_path):
  2216. return wrap_path
  2217. self.dist_log("wrap dispatch-able target -> ", wrap_path)
  2218. # sorting for readability
  2219. features = self.feature_sorted(self.feature_implies_c(target))
  2220. target_join = "#define %sCPU_TARGET_" % self.conf_c_prefix_
  2221. target_defs = [target_join + f for f in features]
  2222. target_defs = '\n'.join(target_defs)
  2223. with open(wrap_path, "w") as fd:
  2224. fd.write(textwrap.dedent("""\
  2225. /**
  2226. * AUTOGENERATED DON'T EDIT
  2227. * Please make changes to the code generator \
  2228. (distutils/ccompiler_opt.py)
  2229. */
  2230. #define {pfx}CPU_TARGET_MODE
  2231. #define {pfx}CPU_TARGET_CURRENT {target_name}
  2232. {target_defs}
  2233. #include "{path}"
  2234. """).format(
  2235. pfx=self.conf_c_prefix_, target_name=target_name,
  2236. path=os.path.abspath(dispatch_src), target_defs=target_defs
  2237. ))
  2238. return wrap_path
  2239. def _generate_config(self, output_dir, dispatch_src, targets, has_baseline=False):
  2240. config_path = os.path.basename(dispatch_src)
  2241. config_path = os.path.splitext(config_path)[0] + '.h'
  2242. config_path = os.path.join(output_dir, config_path)
  2243. # check if targets didn't change to avoid recompiling
  2244. cache_hash = self.cache_hash(targets, has_baseline)
  2245. try:
  2246. with open(config_path) as f:
  2247. last_hash = f.readline().split("cache_hash:")
  2248. if len(last_hash) == 2 and int(last_hash[1]) == cache_hash:
  2249. return True
  2250. except IOError:
  2251. pass
  2252. self.dist_log("generate dispatched config -> ", config_path)
  2253. dispatch_calls = []
  2254. for tar in targets:
  2255. if isinstance(tar, str):
  2256. target_name = tar
  2257. else: # multi target
  2258. target_name = '__'.join([t for t in tar])
  2259. req_detect = self.feature_detect(tar)
  2260. req_detect = '&&'.join([
  2261. "CHK(%s)" % f for f in req_detect
  2262. ])
  2263. dispatch_calls.append(
  2264. "\t%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))" % (
  2265. self.conf_c_prefix_, req_detect, target_name
  2266. ))
  2267. dispatch_calls = ' \\\n'.join(dispatch_calls)
  2268. if has_baseline:
  2269. baseline_calls = (
  2270. "\t%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))"
  2271. ) % self.conf_c_prefix_
  2272. else:
  2273. baseline_calls = ''
  2274. with open(config_path, "w") as fd:
  2275. fd.write(textwrap.dedent("""\
  2276. // cache_hash:{cache_hash}
  2277. /**
  2278. * AUTOGENERATED DON'T EDIT
  2279. * Please make changes to the code generator (distutils/ccompiler_opt.py)
  2280. */
  2281. #ifndef {pfx}CPU_DISPATCH_EXPAND_
  2282. #define {pfx}CPU_DISPATCH_EXPAND_(X) X
  2283. #endif
  2284. #undef {pfx}CPU_DISPATCH_BASELINE_CALL
  2285. #undef {pfx}CPU_DISPATCH_CALL
  2286. #define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \\
  2287. {baseline_calls}
  2288. #define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \\
  2289. {dispatch_calls}
  2290. """).format(
  2291. pfx=self.conf_c_prefix_, baseline_calls=baseline_calls,
  2292. dispatch_calls=dispatch_calls, cache_hash=cache_hash
  2293. ))
  2294. return False
  2295. def new_ccompiler_opt(compiler, dispatch_hpath, **kwargs):
  2296. """
  2297. Create a new instance of 'CCompilerOpt' and generate the dispatch header
  2298. which contains the #definitions and headers of platform-specific instruction-sets for
  2299. the enabled CPU baseline and dispatch-able features.
  2300. Parameters
  2301. ----------
  2302. compiler : CCompiler instance
  2303. dispatch_hpath : str
  2304. path of the dispatch header
  2305. **kwargs: passed as-is to `CCompilerOpt(...)`
  2306. Returns
  2307. -------
  2308. new instance of CCompilerOpt
  2309. """
  2310. opt = CCompilerOpt(compiler, **kwargs)
  2311. if not os.path.exists(dispatch_hpath) or not opt.is_cached():
  2312. opt.generate_dispatch_header(dispatch_hpath)
  2313. return opt