ccompiler_opt.py 98 KB

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