o
    "g,                 	   @   s   d Z ddlZddlZddlZddlZddlZddlZddlZG dd dZG dd dZ	i Z
G dd dZG d	d
 d
ZG dd dZG dd dZG dd dee	eeeeZdd ZdS )a  Provides the `CCompilerOpt` class, used for handling the CPU/hardware
optimization, starting from parsing the command arguments, to managing the
relation between the CPU baseline and dispatch-able features,
also generating the required C headers and ending with compiling
the sources with proper compiler's flags.

`CCompilerOpt` doesn't provide runtime detection for the CPU features,
instead only focuses on the compiler side, but it creates abstract C headers
that can be used later for the final runtime dispatching process.    Nc                   @   s  e Zd ZdZdZdZdZdZej	
ej	ej	edZi ZdZdZeeddd	d
edddd
eddd	d
edddd
edddd
edddd
dZeddddddddZed}i dedddddeddd d!d"ed#dd$d!d%ed&d"d'd!d(ed)d%d*d!d+ed,d(d-d!d.ed/d+d0d1ed2d.d3dd4d5ed6d1d7d!d8ed9d1d7d!d:ed;d1d0d<ed=d:d0d>ed?d:d0d@edAdBddCdDdEedFd@d0dGedHdEdIdGddJdKedLdGdMdKddJdNedOdEdPdNddQdRdSedTdNdUdSdVdWedXdNdYdWddJdZed[d\d]dZddJd^ed_dZd`d^ddJdaeddbdcdddeeddaddfdged#deddhdDdied&dgddjdDdkeddldmdneddkddfdoed#dnddfdpeddqdmdreddpd0dsed#drd0dted&duddfdved)dtd0dwed,dtd0dxed/dvd0Zdydz Zd{d| ZdS )~_Configa  An abstract class holds all configurable attributes of `CCompilerOpt`,
    these class attributes can be used to change the default behavior
    of `CCompilerOpt` in order to fit other requirements.

    Attributes
    ----------
    conf_nocache : bool
        Set True to disable memory and file cache.
        Default is False.

    conf_noopt : bool
        Set True to forces the optimization to be disabled,
        in this case `CCompilerOpt` tends to generate all
        expected headers in order to 'not' break the build.
        Default is False.

    conf_cache_factors : list
        Add extra factors to the primary caching factors. The caching factors
        are utilized to determine if there are changes had happened that
        requires to discard the cache and re-updating it. The primary factors
        are the arguments of `CCompilerOpt` and `CCompiler`'s properties(type, flags, etc).
        Default is list of two items, containing the time of last modification
        of `ccompiler_opt` and value of attribute "conf_noopt"

    conf_tmp_path : str,
        The path of temporary directory. Default is auto-created
        temporary directory via ``tempfile.mkdtemp()``.

    conf_check_path : str
        The path of testing files. Each added CPU feature must have a
        **C** source file contains at least one intrinsic or instruction that
        related to this feature, so it can be tested against the compiler.
        Default is ``./distutils/checks``.

    conf_target_groups : dict
        Extra tokens that can be reached from dispatch-able sources through
        the special mark ``@targets``. Default is an empty dictionary.

        **Notes**:
            - case-insensitive for tokens and group names
            - sign '#' must stick in the begin of group name and only within ``@targets``

        **Example**:
            .. code-block:: console

                $ "@targets #avx_group other_tokens" > group_inside.c

            >>> CCompilerOpt.conf_target_groups["avx_group"] = \
            "$werror $maxopt avx2 avx512f avx512_skx"
            >>> cco = CCompilerOpt(cc_instance)
            >>> cco.try_dispatch(["group_inside.c"])

    conf_c_prefix : str
        The prefix of public C definitions. Default is ``"NPY_"``.

    conf_c_prefix_ : str
        The prefix of internal C definitions. Default is ``"NPY__"``.

    conf_cc_flags : dict
        Nested dictionaries defining several compiler flags
        that linked to some major functions, the main key
        represent the compiler name and sub-keys represent
        flags names. Default is already covers all supported
        **C** compilers.

        Sub-keys explained as follows:

        "native": str or None
            used by argument option `native`, to detect the current
            machine support via the compiler.
        "werror": str or None
            utilized to treat warning as errors during testing CPU features
            against the compiler and also for target's policy `$werror`
            via dispatch-able sources.
        "maxopt": str or None
            utilized for target's policy '$maxopt' and the value should
            contains the maximum acceptable optimization by the compiler.
            e.g. in gcc ``'-O3'``

        **Notes**:
            * case-sensitive for compiler names and flags
            * use space to separate multiple flags
            * any flag will tested against the compiler and it will skipped
              if it's not applicable.

    conf_min_features : dict
        A dictionary defines the used CPU features for
        argument option ``'min'``, the key represent the CPU architecture
        name e.g. ``'x86'``. Default values provide the best effort
        on wide range of users platforms.

        **Note**: case-sensitive for architecture names.

    conf_features : dict
        Nested dictionaries used for identifying the CPU features.
        the primary key is represented as a feature name or group name
        that gathers several features. Default values covers all
        supported features but without the major options like "flags",
        these undefined options handle it by method `conf_features_partial()`.
        Default value is covers almost all CPU features for *X86*, *IBM/Power64*
        and *ARM 7/8*.

        Sub-keys explained as follows:

        "implies" : str or list, optional,
            List of CPU feature names to be implied by it,
            the feature name must be defined within `conf_features`.
            Default is None.

        "flags": str or list, optional
            List of compiler flags. Default is None.

        "detect": str or list, optional
            List of CPU feature names that required to be detected
            in runtime. By default, its the feature name or features
            in "group" if its specified.

        "implies_detect": bool, optional
            If True, all "detect" of implied features will be combined.
            Default is True. see `feature_detect()`.

        "group": str or list, optional
            Same as "implies" but doesn't require the feature name to be
            defined within `conf_features`.

        "interest": int, required
            a key for sorting CPU features

        "headers": str or list, optional
            intrinsics C header file

        "disable": str, optional
            force disable feature, the string value should contains the
            reason of disabling.

        "autovec": bool or None, optional
            True or False to declare that CPU feature can be auto-vectorized
            by the compiler.
            By default(None), treated as True if the feature contains at
            least one applicable flag. see `feature_can_autovec()`

        "extra_checks": str or list, optional
            Extra test case names for the CPU feature that need to be tested
            against the compiler.

            Each test case must have a C file named ``extra_xxxx.c``, where
            ``xxxx`` is the case name in lower case, under 'conf_check_path'.
            It should contain at least one intrinsic or function related to the test case.

            If the compiler able to successfully compile the C file then `CCompilerOpt`
            will add a C ``#define`` for it into the main dispatch header, e.g.
            ``#define {conf_c_prefix}_XXXX`` where ``XXXX`` is the case name in upper case.

        **NOTES**:
            * space can be used as separator with options that supports "str or list"
            * case-sensitive for all values and feature name must be in upper-case.
            * if flags aren't applicable, its will skipped rather than disable the
              CPU feature
            * the CPU feature will disabled if the compiler fail to compile
              the test file
    FNchecksNPY_NPY__z-march=nativez-O3z-Werror)nativeoptwerrorz-Werror=switch -Werrorz-xHostz/QxHostz/O3z/Werrorz/O2z/WXz-mcpu=a64fx)gccclangicciccwmsvcfcczSSE SSE2zSSE SSE2 SSE3 zVSX VSX2zNEON NEON_FP16 NEON_VFPV4 ASIMD)x86x64ppc64ppc64les390xarmhfaarch64SSE   zxmmintrin.hSSE2)interestheadersimplies   zemmintrin.h)r   r   r   SSE3   zpmmintrin.hSSSE3   ztmmintrin.hSSE41   zsmmintrin.hPOPCNT   zpopcntintrin.hSSE42   )r   r   AVX   zimmintrin.h)r   r   r   implies_detectXOP	   zx86intrin.hFMA4
   F16C   FMA3   AVX2   AVX512F   z	FMA3 AVX2AVX512F_REDUCE)r   r   r*   extra_checksAVX512CD   
AVX512_KNL(   zAVX512ER AVX512PF)r   r   groupdetectr*   
AVX512_KNM)   z)AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ
AVX512_SKX*   zAVX512VL AVX512BW AVX512DQzAVX512BW_MASK AVX512DQ_MASK)r   r   r=   r>   r*   r8   
AVX512_CLX+   
AVX512VNNI)r   r   r=   r>   
AVX512_CNL,   zAVX512IFMA AVX512VBMI
AVX512_ICL-   zAVX512_CLX AVX512_CNLz(AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ
AVX512_SPR.   
AVX512FP16VSXz	altivec.hVSX_ASM)r   r   r8   VSX2)r   r   r*   VSX3VSX3_HALF_DOUBLEVSX4VSX4_MMAVXzvecintrin.h)r   r   VXEVXE2NEONz
arm_neon.h	NEON_FP16
NEON_VFPV4ASIMDzNEON_FP16 NEON_VFPV4ASIMDHPASIMDDPASIMDFHMc              
   C   s  | j ri S | jp
| j}| jp| jp| j}|r|rtdxi dtdddtdddtdddtd	dd
tdddtdddtdddtdddtdddtdddtdddtdddtdddtdddtddd td!dd"td#dd$td%dd&td'dd(td)dd*td+dd,td-dS |r/| jr/tdxi dtdddtdddtdddtd	dd
tdddi dtdddtdddi dtd.d/dtd.d/dtd0d1d2dtdd1d2dtd3d4d2dtd5d4d2d td6dd"td7dd$td8dd&td9dd(td:dd*td;dd,td<d/S |r| jrtdxi dtd=ddtd>ddtd?ddtd@dd
tdAddi dtdBddtdCddi dtd.d/dtd.d/dtd0dDd2dtddDd2dtd3dEd2dtd5dEd2d tdFdd"tdGdd$tdHdd&tdIdd(tdJdd*tdKdd,td<d/S |r| j	rtdxi d| jrtd=dni d| jrtd>dnhi di di d
i dtdLdMdi dtdCddi dtdNdMdtdNdMdtd0dOd2dtdPdOd2dtdQdRd2dtdSdRd2d tdTd/d"tdTd/d$tdRdd&i d(i d*i d,tdTd/S di di d
i dtdLdMdi dtdCddi dtdNdMdtdNdMdtd0dOd2dtdPdOd2dtdQdRd2dtdSdRd2d tdTd/d"tdTd/d$tdRdd&i d(i d*i d,tdTd/S | j
p| j}|rtt| j
rdUndVdWd2tdXdYdZtd[dYdZtd\dYdZd]}| jrd^|d_ d`< dX|dU d`< da|db d`< dc|dd d`< |S | j}|rttdedtdfdYdZtdgdYdZdh}|S | jr7|r7ttdidjdktdldjdktdmdjdktdndjdktdodtdpdtdqddrS | jr^|r^ttdsdtdtdtdudtdvdtdodtdpdtdqddrS i S )ya7  Return a dictionary of supported CPU features by the platform,
        and accumulate the rest of undefined options in `conf_features`,
        the returned dict has same rules and notes in
        class attribute `conf_features`, also its override
        any options that been set in 'conf_features'.
        r   z-msse)flagsr   z-msse2r   z-msse3r    z-mssse3r"   z-msse4.1r$   z-mpopcntr&   z-msse4.2r(   z-mavxr/   z-mf16cr+   z-mxopr-   z-mfma4r1   z-mfmar3   z-mavx2r5   z-mavx512f -mno-mmxr9   z
-mavx512cdr;   z-mavx512er -mavx512pfr?   z/-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdqrA   z -mavx512vl -mavx512bw -mavx512dqrC   z-mavx512vnnirF   z-mavx512ifma -mavx512vbmirH   z.-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdqrJ   z-mavx512fp16z!Intel Compiler doesn't support it)disablez	F16C AVX2z-march=core-avx2)r   r^   zAVX2 AVX512CDz-march=common-avx512zAVX2 AVX512Fz-xKNLz-xKNMz-xSKYLAKE-AVX512z-xCASCADELAKEz-xCANNONLAKEz-xICELAKE-CLIENTzNot supported yetz	/arch:SSEz
/arch:SSE2z
/arch:SSE3z/arch:SSSE3z/arch:SSE4.1z/arch:SSE4.2z	/arch:AVXz/arch:CORE-AVX2z/Qx:COMMON-AVX512z/Qx:KNLz/Qx:KNMz/Qx:SKYLAKE-AVX512z/Qx:CASCADELAKEz/Qx:CANNONLAKEz/Qx:ICELAKE-CLIENTznmmintrin.h)r   zammintrin.hz
/arch:AVX2z	F16C FMA3zAVX2 AVX512CD AVX512_SKXz/arch:AVX512zAVX512F AVX512_SKXz MSVC compiler doesn't support itrO   r   z-mvsxz-mcpu=power8F)r^   r*   z-mcpu=power9 -mtune=power9z-mcpu=power10 -mtune=power10)rM   rO   rP   rR   z-maltivec -mvsxrM   r^   z-mcpu=power9rP   z-mcpu=power10rR   z-march=arch11 -mzvectorz-march=arch12z-march=arch13)rT   rU   rV   zNEON_FP16 NEON_VFPV4 ASIMDT)r   autoveczNEON NEON_VFPV4 ASIMDzNEON NEON_FP16 ASIMDzNEON NEON_FP16 NEON_VFPV4z-march=armv8.2-a+fp16z-march=armv8.2-a+dotprodz-march=armv8.2-a+fp16fml)rW   rX   rY   rZ   r[   r\   r]   z
-mfpu=neonz"-mfpu=neon-fp16 -mfp16-format=ieeez-mfpu=neon-vfpv4z'-mfpu=neon-fp-armv8 -march=armv8-a+simdN )cc_noopt	cc_on_x86	cc_on_x64	cc_is_gcccc_is_clang	cc_is_fccdict	cc_is_icc
cc_is_iccw
cc_is_msvccc_on_ppc64lecc_on_ppc64cc_on_s390xcc_on_aarch64cc_on_armhf)selfon_x86is_unixon_powerpartialon_zarchra   ra   _/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/numpy/distutils/ccompiler_opt.pyconf_features_partialJ  s  








	


















	









 






	









 "

	



!"#$%

	



!"#$%*z_Config.conf_features_partialc                    sf   | j d u r dd l dd l}|  fdd}t| | _ | jd u r1tj	t
| jg| _d S d S )Nr   c                      s&   z   W d S  ty   Y d S w N)rmtreeOSErrorra   shutiltmpra   rw   rm_temp@  s
   z!_Config.__init__.<locals>.rm_temp)conf_tmp_pathr}   tempfilemkdtempatexitregisterconf_cache_factorsospathgetmtime__file__conf_nocache)rq   r   r   ra   r|   rw   __init__;  s   




z_Config.__init__ra   )__name__
__module____qualname____doc__r   
conf_nooptr   r   r   r   joindirnamerealpathr   conf_check_pathconf_target_groupsconf_c_prefixconf_c_prefix_rh   conf_cc_flagsconf_min_featuresconf_featuresrx   r   ra   ra   ra   rw   r      sN    "
'		
 %*.27=?ADHJLNOQSUWY[ rr   c                   @   s   e Zd ZdZdd ZdddZg fddZd	d
 Zedd Z	edd Z
eddddZedd Zedd ZdddZedZedddZdS )
_Distutilsa  A helper class that provides a collection of fundamental methods
    implemented in a top of Python and NumPy Distutils.

    The idea behind this class is to gather all methods that it may
    need to override in case of reuse 'CCompilerOpt' in environment
    different than of what NumPy has.

    Parameters
    ----------
    ccompiler : `CCompiler`
        The generate instance that returned from `distutils.ccompiler.new_compiler()`.
    c                 C   s
   || _ d S ry   )
_ccompiler)rq   	ccompilerra   ra   rw   r   [  s   
z_Distutils.__init__Nc                 K   sL   t |tsJ t |tsJ |dg | }|s| j}|j|fd|i|S )zWrap CCompiler.compile()extra_postargs)
isinstancelistpopr   compile)rq   sourcesr^   r   kwargsra   ra   rw   dist_compile^  s   z_Distutils.dist_compilec           
   
   C   s   t |tsJ ddlm} | j}t|dd}|r2t| jdd}|dv r+t|d| j nt|d| j d}z| j	|g||| j
d	 d
}W n |y^ }	 z| jt|	d
d W Y d}	~	nd}	~	ww |rgt|d| |S )zgReturn True if 'CCompiler.compile()' able to compile
        a source file with certain flags.
        r   CompileErrorspawnNcompiler_typer   )r   F)macros
output_dirTstderr)r   strdistutils.errorsr   r   getattrsetattr_dist_test_spawn_paths_dist_test_spawnr   r   dist_log)
rq   sourcer^   r   r   ccbk_spawncc_typetestera   ra   rw   	dist_testh  s,   z_Distutils.dist_testc                 C   s   t | dr| jS t| jdd}|dv rd}n|dv rd}n	dd	lm} | }t| jd
t| jdd}|r8|dkrGt |drB|d }nt|}n|}t |dr^t|dkr^d|dd }nt	j
dd}|t	j
dd7 }|||f| _| jS )a!  
        Return a tuple containing info about (platform, compiler, extra_args),
        required by the abstract class '_CCompiler' for discovering the
        platform environment. This is also used as a cache factor in order
        to detect any changes happening from outside.
        
_dist_infor   r   )intelemintelemwx86_64)intelintelwinteler   r   )get_platformcompilercompiler_sounix__iter__r    NCFLAGSCPPFLAGS)hasattrr   r   r   distutils.utilr   r   lenr   r   environget)rq   r   platformr   cc_infor   
extra_argsra   ra   rw   	dist_info  s*   



z_Distutils.dist_infoc                  G      ddl m} |tj|  )zRaise a compiler errorr   r   )r   r   r   	_dist_str)argsr   ra   ra   rw   
dist_error     z_Distutils.dist_errorc                  G   r   )zRaise a distutils errorr   )DistutilsError)r   r   r   r   )r   r   ra   ra   rw   
dist_fatal  r   z_Distutils.dist_fatalFr   c                 G   s6   ddl m} tj| }| r|| dS || dS )zPrint a console messager   )logN)numpy.distutilsr   r   r   warninfo)r   r   r   outra   ra   rw   r     s
   
z_Distutils.dist_logc              
   C   sN   ddl m} z|| |W S  ty& } ztj|dd W Y d}~dS d}~ww )zALoad a module from file, required by the abstract class '_Cache'.r   )exec_mod_from_locationTr   N)	misc_utilr   	Exceptionr   r   )namer   r   r   ra   ra   rw   dist_load_module  s   z_Distutils.dist_load_modulec                     sN    fdd t  d }d|j|jf }d fddg | R D }|| S )z+Return a string to print by log and errors.c                    sJ   t | ts!t| dr!g }| D ]	}| | qdd| d S t| S )Nr   (r   ))r   r   r   appendr   )argretato_strra   rw   r     s   z$_Distutils._dist_str.<locals>.to_strr   zCCompilerOpt.%s[%d] : r   c                    s   g | ]} |qS ra   ra   ).0r   r   ra   rw   
<listcomp>  s    z(_Distutils._dist_str.<locals>.<listcomp>)inspectstackfunctionlinenor   )r   r   startr   ra   r   rw   r     s   z_Distutils._dist_strc              	   C   sZ   t | jds| | dS td}z| jjtjd< | | W |tjd< dS |tjd< w )z
        Fix msvc SDK ENV path same as distutils do
        without it we get c1: fatal error C1356: unable to find mspdbcore.dll
        _pathsNr   )r   r   r   r   getenvr   r   )rq   cmddisplayold_pathra   ra   rw   r     s   

z!_Distutils._dist_test_spawn_pathsz/.*(warning D9002|invalid argument for option).*c              
   C   s   z$t j| t jdd}|rttj|r"td| d|  W d S W d S W d S  t jy= } z|j	}|j
}W Y d }~nd }~w tyR } z
|}d}W Y d }~nd }~ww td| d||f  d S )NT)r   textzFlags in commandz/aren't supported by the compiler, output -> 
%s   Commandz(failed with exit status %d output -> 
%s)
subprocesscheck_outputSTDOUTrematchr   _dist_warn_regexr   CalledProcessErroroutput
returncoder{   )r   r   oexcsr   ra   ra   rw   r     s:   
z_Distutils._dist_test_spawnry   )r   r   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r  r   ra   ra   ra   rw   r   N  s,    

%

	
	

r   c                   @   sH   e Zd ZdZedZdddZdd Zdd	 Z	d
d Z
edd ZdS )_Cachea'  An abstract class handles caching functionality, provides two
    levels of caching, in-memory by share instances attributes among
    each other and by store attributes into files.

    **Note**:
        any attributes that start with ``_`` or ``conf_`` will be ignored.

    Parameters
    ----------
    cache_path : str or None
        The path of cache file, if None then cache in file will disabled.

    *factors :
        The caching factors that need to utilize next to `conf_cache_factors`.

    Attributes
    ----------
    cache_private : set
        Hold the attributes that need be skipped from "in-memory cache".

    cache_infile : bool
        Utilized during initializing this class, to determine if the cache was able
        to loaded from the specified cache path in 'cache_path'.
    z
^(_|conf_)Nc                 G   sh  i | _ t | _d| _d | _| jr| d d S | jg || jR  | _	|| _|rzt
j|rz| d| | d|}|sD| jddd n6t|drNt|d	sV| jd
dd n$| j	|jkru| d |j D ]
\}}t| || qfd| _n| d | jst| j	}|r| d |j D ]\}}||jv st| j|rqt| || q| t| j	< t| j d S )NFzcache is disabled by `Config`zload cache from file ->cachez)unable to load the cache file as a moduleTr   hashdatazinvalid cache filezhit the file cachezmiss the file cachezhit the memory cache)cache_mesetcache_privatecache_infile_cache_pathr   r   
cache_hashr   _cache_hashr   r   existsr   r   r  r  itemsr   _share_cacher   __dict__r   r   _cache_ignorer   r   cache_flush)rq   
cache_pathfactors	cache_modattrvalother_cachera   ra   rw   r   &  sP   






z_Cache.__init__c                 C   s.   t  D ]\}}|| krt |  d S qd S ry   )r  r  r   )rq   hr  ra   ra   rw   __del__S  s   
z_Cache.__del__c                 C   s   | j sdS | d| j  | j }| j D ]}t| j|r$|| qt	j
| j }t	j
|s7t	| tj|dd}t| j d}|td| j || W d   dS 1 saw   Y  dS )z)
        Force update the cache.
        Nzwrite cache to path ->T)compactwz            # AUTOGENERATED DON'T EDIT
            # Please make changes to the code generator             (distutils/ccompiler_opt.py)
            hash = {}
            data = \
            )r  r   r  copykeysr   r   r  r   r   r   r   r  makedirspprintpformatopenwritetextwrapdedentformatr  )rq   cdictr  d	repr_dictfra   ra   rw   r  Y  s$   


"z_Cache.cache_flushc                 G   sD   d}|D ]}t |D ]}t||d>  |d>  | }|dM }q
q|S )Nr   r%      l    )r   ord)rq   r  chashr1  charra   ra   rw   r  u  s   
z_Cache.cache_hashc                    s    fdd}|S )zr
        A static method that can be treated as a decorator to
        dynamically cache certain methods.
        c                    sZ   t  jg|| | R }|| jv r| j| S  | g|R i |}|| j|< |S ry   )r   r   r%  valuesr  )rq   r   r   	cache_keyccbcbra   rw   cache_wrap_me  s   


z _Cache.me.<locals>.cache_wrap_mera   )r:  r;  ra   r9  rw   me  s   
z	_Cache.mery   )r   r   r   r   r   r   r  r   r!  r  r  r  r<  ra   ra   ra   rw   r	  	  s    

-
r	  c                   @   s   e Zd ZdZdd Zejdd Zejg fddZdd	 Z	e
d
Ze
dZe
dZe
dZdd Ze
dZe
dZdd ZdS )
_CCompilera2  A helper class for `CCompilerOpt` containing all utilities that
    related to the fundamental compiler's functions.

    Attributes
    ----------
    cc_on_x86 : bool
        True when the target architecture is 32-bit x86
    cc_on_x64 : bool
        True when the target architecture is 64-bit x86
    cc_on_ppc64 : bool
        True when the target architecture is 64-bit big-endian powerpc
    cc_on_ppc64le : bool
        True when the target architecture is 64-bit litle-endian powerpc
    cc_on_s390x : bool
        True when the target architecture is IBM/ZARCH on linux
    cc_on_armhf : bool
        True when the target architecture is 32-bit ARMv7+
    cc_on_aarch64 : bool
        True when the target architecture is 64-bit Armv8-a+
    cc_on_noarch : bool
        True when the target architecture is unknown or not supported
    cc_is_gcc : bool
        True if the compiler is GNU or
        if the compiler is unknown
    cc_is_clang : bool
        True if the compiler is Clang
    cc_is_icc : bool
        True if the compiler is Intel compiler (unix like)
    cc_is_iccw : bool
        True if the compiler is Intel compiler (msvc like)
    cc_is_nocc : bool
        True if the compiler isn't supported directly,
        Note: that cause a fail-back to gcc
    cc_has_debug : bool
        True if the compiler has debug flags
    cc_has_native : bool
        True if the compiler has native flags
    cc_noopt : bool
        True if the compiler has definition 'DISABLE_OPT*',
        or 'cc_on_noarch' is True
    cc_march : str
        The target architecture name, or "unknown" if
        the architecture isn't supported
    cc_name : str
        The compiler name, or "unknown" if the compiler isn't supported
    cc_flags : dict
        Dictionary containing the initialized flags of `_Config.conf_cc_flags`
    c                 C   s>  t | drd S d}d}d}|  }|\}}}|||fD ]}|D ]\}	}
}t| |	d qq||f||ffD ]%\}}|D ]\}	}
}|
rJt|
|tjsJq:|rR| |sRq:t| |	d  q4|D ]\}	}
}|
rlt|
|tjslq\|rt| |stq\t| |	d q\| jr| jd| ddd	 d| _	| j
r| jd
dd	 d| _	| jr	 | jd| ddd	 d| _d| _dD ]}t| d| r|| _ nqd| _dD ]}t| d| r|| _ nqi | _| j| j}|d u r| d| j  | D ],\}}g  | j|< }|rt|tsJ | }|D ]}| |gr|| q	qd| _d S )Ncc_is_cached))rd   z.*(x|x86_|amd)64.*r   )rc   z.*(win32|x86|i386|i686).*r   )rl   z&.*(powerpc|ppc)64(el|le).*|.*powerpc.*z4defined(__powerpc64__) && defined(__LITTLE_ENDIAN__))rm   z.*(powerpc|ppc).*|.*powerpc.*z1defined(__powerpc64__) && defined(__BIG_ENDIAN__))ro   z.*(aarch64|arm64).*r   )rp   z.*arm.*z3defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__))rn   z	.*s390x.*r   )cc_on_noarchr   r   ))re   z.*(gcc|gnu\-g).*r   )rf   z	.*clang.*r   )rj   z.*(intelw|intelemw|iccw).*r   )ri   z.*(intel|icc).*r   )rk   z.*msvc.*r   )rg   z.*fcc.*r   )
cc_is_noccr   r   ))cc_has_debugz$.*(O0|Od|ggdb|coverage|debug:full).*r   )cc_has_nativez..*(-march=native|-xHost|/QxHost|-mcpu=a64fx).*r   )rb   z.*DISABLE_OPT.*r   FTz]unable to detect CPU architecture which lead to disable the optimization. check dist_info:<<
z
>>r   z&Optimization is disabled by the Configzunable to detect compiler type which leads to treating it as GCC. this is a normal behavior if you're using gcc-like compiler such as MinGW or IBM/XLC.check dist_info:<<
unknown)r   r   r   r   r   r   r   cc_on_)r	   r
   r   r   r   r   cc_is_z=undefined flag for compiler '%s', leave an empty dict instead)r   r   r   r   r   
IGNORECASEcc_test_cexprr?  r   rb   r   r@  re   cc_marchr   cc_namecc_flagsr   r   r   r  r   r   splitcc_test_flagsr   r>  )rq   detect_archdetect_compilerdetect_argsr   r   compiler_infor   sectionr  rgexcexprr>   searchinarchr   compiler_flagsr^   nflagsr1  ra   ra   rw   r     s   



z_CCompiler.__init__c                 C   sL   t |tsJ | d| tj| jd}| ||}|s$| jddd |S )z@
        Returns True if the compiler supports 'flags'.
        ztesting flagsztest_flags.ctesting failedTr   )r   r   r   r   r   r   r   r   )rq   r^   	test_pathr   ra   ra   rw   rL  8  s   z_CCompiler.cc_test_flagsc                 C   s   |  d| tj| jd}t|d}|td| d W d   n1 s*w   Y  | 	||}|s>| j ddd	 |S )
zJ
        Same as the above but supports compile-time expressions.
        ztesting compiler expressionznpy_dist_test_cexpr.cr#  z               #if !(zq)
                   #error "unsupported expression"
               #endif
               int dummy;
            NrX  Tr   )
r   r   r   r   r   r)  r*  r+  r,  r   )rq   rS  r^   rY  fdr   ra   ra   rw   rG  E  s   
z_CCompiler.cc_test_cexprc                 C   sD   t |tsJ | js| js| jr| |S | js| jr | |S |S )a  
        Remove the conflicts that caused due gathering implied features flags.

        Parameters
        ----------
        'flags' list, compiler flags
            flags should be sorted from the lowest to the highest interest.

        Returns
        -------
        list, filtered from any conflicts.

        Examples
        --------
        >>> self.cc_normalize_flags(['-march=armv8.2-a+fp16', '-march=armv8.2-a+dotprod'])
        ['armv8.2-a+fp16+dotprod']

        >>> self.cc_normalize_flags(
            ['-msse', '-msse2', '-msse3', '-mssse3', '-msse4.1', '-msse4.2', '-mavx', '-march=core-avx2']
        )
        ['-march=core-avx2']
        )	r   r   re   rf   ri   _cc_normalize_unixrk   rj   _cc_normalize_win)rq   r^   ra   ra   rw   cc_normalize_flagsX  s   

z_CCompiler.cc_normalize_flagsz^(-mcpu=|-march=|-x[A-Z0-9\-])zB^(?!(-mcpu=|-march=|-x[A-Z0-9\-]|-m[a-z0-9\-\.]*.$))|(?:-mzvector)z^(-mfpu|-mtune)z[0-9.]c                    sB   fdd}t |dkr|S tt|D ]`\}}t j|s q|d |d   }|| d  }tt jj	|}||\}}	}
|dkrgt |
dkrg|D ]}||\}}}||kr]||
 }
qL|	d d
|
 }||g }|dkrt||7 } g }t }t|D ] }t j|}|sn|d |v rq~||d  |d| q~|S )Nc              	      s@   |  d}tddt j|d  }||d |dd  fS )N+0r   r   r   )rK  floatr   r   findall_cc_normalize_arch_ver)r1  tokensverrq   ra   rw   	ver_flags  s
   
z0_CCompiler._cc_normalize_unix.<locals>.ver_flagsr   r   r^  )r   	enumeratereversedr   r   _cc_normalize_unix_mrgxr   filter_cc_normalize_unix_frgxsearchr   r  _cc_normalize_unix_krgxaddinsert)rq   r^   rf  icur_flaglower_flagsupper_flagsfilteredrd  rU  subflagsxflagxver_	xsubflagsfinal_flagsmatchedr1  r   ra   re  rw   r[    sD   	
z_CCompiler._cc_normalize_unixz^(?!(/arch\:|/Qx\:))z^(/arch|/Qx:)c                 C   s^   t t|D ]&\}}t| j|sq|d7 }tt| jj|d |  || d     S |S )Nr   )	rg  rh  r   r   _cc_normalize_win_mrgxr   rj  _cc_normalize_win_frgxrl  )rq   r^   rp  r1  ra   ra   rw   r\    s   z_CCompiler._cc_normalize_winN)r   r   r   r   r   r	  r<  rL  rG  r]  r   r   ri  rk  rm  rb  r[  r}  r|  r\  ra   ra   ra   rw   r=    s8    0v
1r=  c                   @   s   e Zd ZdZdd Zddg fddZdd Zd%d
dZd%ddZdd Z	dd Z
dd Zdd Zdd Zejdd Zejdg fddZejdg fddZejdd Zejd d! Zd&d#d$ZdS )'_Featurea  A helper class for `CCompilerOpt` that managing CPU features.

    Attributes
    ----------
    feature_supported : dict
        Dictionary containing all CPU features that supported
        by the platform, according to the specified values in attribute
        `_Config.conf_features` and `_Config.conf_features_partial()`

    feature_min : set
        The minimum support of CPU features, according to
        the specified values in attribute `_Config.conf_min_features`.
    c           	         s  t | drd S |   | _}t| D ]G}||  | j| }  fdd| D   d}|d urF|	| | j
d| |dd qdD ]} |}t|trZ|  |< qHqt | _| j| jd	}|  D ]}|| jv r{| j| qnd| _d S )
Nfeature_is_cachedc                    s   i | ]\}}| vr||qS ra   ra   )r   kvfeaturera   rw   
<dictcomp>  s    z%_Feature.__init__.<locals>.<dictcomp>r_   zfeature '%s' is disabled,Tr   )r   r=   r>   r   r^   r8   r   )r   rx   feature_supportedr   r%  r   updater  r   r   r   r   r   rK  r  feature_minr   rH  upperrn  r  )	rq   	pfeaturesfeature_namecfeaturedisabledoptionovalmin_fFra   r  rw   r     s<   







z_Feature.__init__Nc                 C   sv   |du st |tst|dsJ |du st |tsJ |du r$| j }t }|D ]}| j|||dr8|| q)|S )a  
        Returns a set of CPU feature names that supported by platform and the **C** compiler.

        Parameters
        ----------
        names : sequence or None, optional
            Specify certain CPU features to test it against the **C** compiler.
            if None(default), it will test all current supported features.
            **Note**: feature names must be in upper-case.

        force_flags : list or None, optional
            If None(default), default compiler flags for every CPU feature will
            be used during the test.

        macros : list of tuples, optional
            A list of C macro definitions.
        Nr   force_flagsr   )	r   r   r   r   r  r%  r  feature_is_supportedrn  )rq   namesr  r   supported_namesr1  ra   ra   rw   feature_names  s    

z_Feature.feature_namesc                 C   s   |  sJ || jv S )z
        Returns True if a certain feature is exist and covered within
        ``_Config.conf_features``.

        Parameters
        ----------
        'name': str
            feature name in uppercase.
        )isupperr   )rq   r   ra   ra   rw   feature_is_exist  s   

z_Feature.feature_is_existFc                    s    fdd}t |||dS )az  
        Sort a list of CPU features ordered by the lowest interest.

        Parameters
        ----------
        'names': sequence
            sequence of supported feature names in uppercase.
        'reverse': bool, optional
            If true, the sorted features is reversed. (highest interest)

        Returns
        -------
        list, sorted CPU features
        c                    sB   t | tr j|  d S t fdd| D }|t| d 7 }|S )Nr   c                    s   g | ]	} j | d  qS )r   )r  r   r1  re  ra   rw   r   =  s    z<_Feature.feature_sorted.<locals>.sort_cb.<locals>.<listcomp>r   )r   r   r  maxr   )r  rankre  ra   rw   sort_cb9  s
   
z(_Feature.feature_sorted.<locals>.sort_cb)reversekey)sorted)rq   r  r  r  ra   re  rw   feature_sorted*  s   	z_Feature.feature_sortedc                    sl   t  f fdd	 t|tr |}|g}nt|dsJ t  }|D ]	}| |}q#|s4|| |S )a  
        Return a set of CPU features that implied by 'names'

        Parameters
        ----------
        names : str or sequence of str
            CPU feature name(s) in uppercase.

        keep_origins : bool
            if False(default) then the returned set will not contain any
            features from 'names'. This case happens only when two features
            imply each other.

        Examples
        --------
        >>> self.feature_implies("SSE3")
        {'SSE', 'SSE2'}
        >>> self.feature_implies("SSE2")
        {'SSE'}
        >>> self.feature_implies("SSE2", keep_origins=True)
        # 'SSE2' found here since 'SSE' and 'SSE2' imply each other
        {'SSE', 'SSE2'}
        c                    sT   t  }j|  }|dg D ]}|| ||v rq||  | ||}q|S )Nr   )r  r  r   rn  union)r   _callerr   r/  rp  get_impliesrq   ra   rw   r  \  s   


z-_Feature.feature_implies.<locals>.get_impliesr   )r  r   r   r   r  difference_update)rq   r  keep_originsr   nra   r  rw   feature_impliesD  s   

z_Feature.feature_impliesc                 C   s.   t |trt|f}nt|}|| |S )z/same as feature_implies() but combining 'names')r   r   r  r  r  )rq   r  ra   ra   rw   feature_implies_cu  s   
z_Feature.feature_implies_cc                    s^   t |ts
t|dsJ | j|dd  fdd|D }t|dkr-| j|dddd	 }|S )
a  
        Return list of features in 'names' after remove any
        implied features and keep the origins.

        Parameters
        ----------
        'names': sequence
            sequence of CPU feature names in uppercase.

        Returns
        -------
        list of CPU features sorted as-is 'names'

        Examples
        --------
        >>> self.feature_ahead(["SSE2", "SSE3", "SSE41"])
        ["SSE41"]
        # assume AVX2 and FMA3 implies each other and AVX2
        # is the highest interest
        >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
        ["AVX2"]
        # assume AVX2 and FMA3 don't implies each other
        >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
        ["AVX2", "FMA3"]
        r   T)r  c                       g | ]}| vr|qS ra   ra   )r   r  r   ra   rw   r         z*_Feature.feature_ahead.<locals>.<listcomp>r   r  Nr   )r   r   r   r  r   r  )rq   r  aheadra   r  rw   feature_ahead}  s   z_Feature.feature_aheadc                    s   t |ts
t|dsJ g }|D ]5  fdd|D }|r@|g }|dd vr5q||dd d  | q|S )am  
        same as 'feature_ahead()' but if both features implied each other
        and keep the highest interest.

        Parameters
        ----------
        'names': sequence
            sequence of CPU feature names in uppercase.

        Returns
        -------
        list of CPU features sorted as-is 'names'

        Examples
        --------
        >>> self.feature_untied(["SSE2", "SSE3", "SSE41"])
        ["SSE2", "SSE3", "SSE41"]
        # assume AVX2 and FMA3 implies each other
        >>> self.feature_untied(["SSE2", "SSE3", "SSE41", "FMA3", "AVX2"])
        ["SSE2", "SSE3", "SSE41", "AVX2"]
        r   c                    s&   g | ]}| v r |v r|qS ra   )r  )r   nnr   r  rq   ra   rw   r     s
    z+_Feature.feature_untied.<locals>.<listcomp>r   Nr   )r   r   r   r  r  remover   )rq   r  finaltiedra   r  rw   feature_untied  s"   
z_Feature.feature_untiedc                    s^    fddt |tst|dkr|}|  |S |}fdd|D }|S )z
        same as `feature_implies_c()` but stop collecting implied
        features when feature's option that provided through
        parameter 'keyisfalse' is False, also sorting the returned
        features.
        c                    sV    | } j| dd} t| D ]\}}j|  ds(| d |d  }  | S q| S )NTr  r   )r  r  rg  r  r   )tnamesrp  r  )
keyisfalserq   ra   rw   til  s   
z%_Feature.feature_get_til.<locals>.tilr   c                    s   h | ]} |D ]}|qqS ra   ra   )r   r  t)r  ra   rw   	<setcomp>  s    z+_Feature.feature_get_til.<locals>.<setcomp>)r   r   r   r  r  r  )rq   r  r  ra   )r  rq   r  rw   feature_get_til  s   


z_Feature.feature_get_tilc              	   C   sB   |  |d}g }|D ]}| j| }||d|d|g7 }q
|S )z
        Return a list of CPU features that required to be detected
        sorted from the lowest to highest interest.
        r*   r>   r=   )r  r  r   )rq   r  r>   r  r/  ra   ra   rw   feature_detect  s   
z_Feature.feature_detectc                 C   sV   |  | |}g }|D ]}| j| }|dg }|r | |s!q||7 }q| |S )zi
        Return a list of CPU features flags sorted from the lowest
        to highest interest.
        r^   )r  r  r  r   rL  r]  )rq   r  r^   r  r/  r1  ra   ra   rw   feature_flags  s   


z_Feature.feature_flagsc                 C   s   |du r	|  |}| d|d|f  tj| jd|  }tj|s-| d| | j	||| j
d  |d}|sC| jdd	d
 |S )a  
        Test a certain CPU feature against the compiler through its own
        check file.

        Parameters
        ----------
        name : str
            Supported CPU feature name.

        force_flags : list or None, optional
            If None(default), the returned flags from `feature_flags()`
            will be used.

        macros : list of tuples, optional
            A list of C macro definitions.
        Nz$testing feature '%s' with flags (%s)r   zcpu_%s.czfeature test file is not existr   r   rX  Tr   )r  r   r   r   r   r   lowerr  r   r   rJ  )rq   r   r  r   rY  r   ra   ra   rw   feature_test  s$   

z_Feature.feature_testc                 C   sn   |  sJ |du st|tsJ || jv }|r5| |D ]}| j|||ds* dS q| j|||ds5dS |S )a  
        Check if a certain CPU feature is supported by the platform and compiler.

        Parameters
        ----------
        name : str
            CPU feature name in uppercase.

        force_flags : list or None, optional
            If None(default), default compiler flags for every CPU feature will
            be used during test.

        macros : list of tuples, optional
            A list of C macro definitions.
        Nr  F)r  r   r   r  r  r  )rq   r   r  r   	supportedimplra   ra   rw   r  +  s   
z_Feature.feature_is_supportedc                    sV   t |tsJ  j| }|dd}|du r) fdd|dg D }|o(t|}|S )zM
        check if the feature can be auto-vectorized by the compiler
        r`   Nc                    s   g | ]}  |gqS ra   )rL  r  re  ra   rw   r   Q  s    z0_Feature.feature_can_autovec.<locals>.<listcomp>r^   )r   r   r  r   any)rq   r   r/  canvalid_flagsra   re  rw   feature_can_autovecH  s   


z_Feature.feature_can_autovecc           
      C   s   t |tsJ | j| }|dg }|sg S | d| | | |}g }g }|D ]2}tj| j	d|
  }tj|sC| d| | ||| jd  }	|	rV|| q)|| q)|rf| jd|dd |S )	z
        Return a list of supported extra checks after testing them against
        the compiler.

        Parameters
        ----------
        names : str
            CPU feature name in uppercase.
        r8   z%Testing extra checks for feature '%s'z
extra_%s.czextra check file does not existr   ztesting failed for checksTr   )r   r   r  r   r   r  r   r   r   r   r  r  r   r   rJ  r   )
rq   r   r/  r8   r^   	availablenot_availablechkrY  is_supportedra   ra   rw   feature_extra_checksW  s,   

z_Feature.feature_extra_checksr   c                    s   |  sJ | j|}|dusJ d| d| j|f g}|dd |dg D 7 }|dg }|| |7 }|D ]}|d| j|f d	| j|f d
g7 }q9 dkrZ fdd|D }d|S )a"  
        Generate C preprocessor definitions and include headers of a CPU feature.

        Parameters
        ----------
        'feature_name': str
            CPU feature name in uppercase.
        'tabs': int
            if > 0, align the generated strings to the right depend on number of tabs.

        Returns
        -------
        str, generated C preprocessor

        Examples
        --------
        >>> self.feature_c_preprocessor("SSE3")
        /** SSE3 **/
        #define NPY_HAVE_SSE3 1
        #include <pmmintrin.h>
        Nz
/** %s **/z#define %sHAVE_%s 1c                 S      g | ]}d | qS )z#include <%s>ra   )r   r   ra   ra   rw   r         z3_Feature.feature_c_preprocessor.<locals>.<listcomp>r   r=   z#ifndef %sHAVE_%sz	#define %sHAVE_%s 1z#endifr   c                    s   g | ]}d   | qS )	ra   )r   ltabsra   rw   r     r  
)r  r  r   r   r  r   )rq   r  r  r  prepr
extra_defsedefra   r  rw   feature_c_preprocessor~  s(   

z_Feature.feature_c_preprocessorF)r   )r   r   r   r   r   r  r  r  r  r  r  r  r  r  r	  r<  r  r  r  r  r  r  ra   ra   ra   rw   r~    s.    "#

1&)
'

&r~  c                   @   s   e Zd ZdZdd Zdd ZedZdd Z	ed	Z
d
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )_Parsea  A helper class that parsing main arguments of `CCompilerOpt`,
    also parsing configuration statements in dispatch-able sources.

    Parameters
    ----------
    cpu_baseline : str or None
        minimal set of required CPU features or special options.

    cpu_dispatch : str or None
        dispatched set of additional CPU features or special options.

    Special options can be:
        - **MIN**: Enables the minimum CPU features that utilized via `_Config.conf_min_features`
        - **MAX**: Enables all supported CPU features by the Compiler and platform.
        - **NATIVE**: Enables all CPU features that supported by the current machine.
        - **NONE**: Enables nothing
        - **Operand +/-**: remove or add features, useful with options **MAX**, **MIN** and **NATIVE**.
            NOTE: operand + is only added for nominal reason.

    NOTES:
        - Case-insensitive among all CPU features and special options.
        - Comma or space can be used as a separator.
        - If the CPU feature is not supported by the user platform or compiler,
          it will be skipped rather than raising a fatal error.
        - Any specified CPU features to 'cpu_dispatch' will be skipped if its part of CPU baseline features
        - 'cpu_baseline' force enables implied features.

    Attributes
    ----------
    parse_baseline_names : list
        Final CPU baseline's feature names(sorted from low to high)
    parse_baseline_flags : list
        Compiler flags of baseline features
    parse_dispatch_names : list
        Final CPU dispatch-able feature names(sorted from low to high)
    parse_target_groups : dict
        Dictionary containing initialized target groups that configured
        through class attribute `conf_target_groups`.

        The key is represent the group name and value is a tuple
        contains three items :
            - bool, True if group has the 'baseline' option.
            - list, list of CPU features.
            - list, list of extra compiler flags.

    c                    s  t d  jg f j jg f jd g f jd g f jd dgfd _t dr'd S g  _	g  _
g  _i  _ jr:d  }} d |d ur] d|} |} | _
  | _	 d |d ur d|} fdd	|D }||}  | _t|d
kr d|d  d  j D ]-\}} d| | }|r| sdg g f j|< q |\}	}
}|	|
|f j|< qd _d S )NMAXOPT)KEEP_BASELINE	KEEP_SORTr  WERRORAUTOVECparse_is_cachedzcheck requested baselinecpu_baselinez&check requested dispatch-able featurescpu_dispatchc                    s   h | ]	}| j vr|qS ra   parse_baseline_namesr  re  ra   rw   r    s
    
z"_Parse.__init__.<locals>.<setcomp>r   zskip featureszsince its part of baselinezinitialize targets groupszparse target groupFT)rh   _parse_policy_not_keepbase_parse_policy_keepsort_parse_policy_not_keepsort_parse_policy_maxopt_parse_policy_werror_parse_policy_autovec_parse_policiesr   r  parse_baseline_flagsparse_dispatch_namesparse_target_groupsrb   r   _parse_arg_featuresr  r  r  r  
differencer   r   r  r  strip_parse_target_tokensr  )rq   r  r  baseline_namescpu_dispatch_conflict_baseline
group_namerc  
GROUP_NAMEhas_baselinefeaturesextra_flagsra   re  rw   r     sz   








z_Parse.__init__c                 C   s  |  d| t|U}d}d}d}d}d}d}t|D ]<\}	}
|	|kr*| d  n.|dkr>|
|}|dkr8q|t|7 }||
7 }|
|}|dkrW|t|t|
 7 } nqW d   n1 sbw   Y  |dkrr| d	|  |dkr}| d
|  ||| }| |S )a  
        Fetch and parse configuration statements that required for
        defining the targeted CPU features, statements should be declared
        in the top of source in between **C** comment and start
        with a special mark **@targets**.

        Configuration statements are sort of keywords representing
        CPU features names, group of statements and policies, combined
        together to determine the required optimization.

        Parameters
        ----------
        source : str
            the path of **C** source file.

        Returns
        -------
        - bool, True if group has the 'baseline' option
        - list, list of CPU features
        - list, list of extra compiler flags
        z!looking for '@targets' inside -> r   i  z@targetsz*/zreached the max of linesNz(expected to find '%s' within a C commentzexpected to end with '%s')r   r)  rg  r   findr   r  )rq   r   rZ  rc  max_to_reach
start_with	start_posend_withend_poscurrent_linelinera   ra   rw   parse_targets0  s>   




z_Parse.parse_targetsz\s|,|([+-])c           
      C   s:  t |ts| d|  t }ttd t| j|}d}|D ]{}|d dv r-| |d |dkr4d}q|dkr;d}q|	 }t }|d	krGnD|d
kra| j
d }	|	sX| |d | j|	dgd}n*|dkrk| j }n |dkrs| j}n|| jv r~|| n| |s| |d|  |r||}n||}d}q|S )Nzexpected a string in '%s'Tr   )#$zYtarget groups and policies aren't allowed from arguments, only from dispatch-able sourcesr^  -FNONENATIVEr   z-native option isn't supported by the compiler)DETECT_FEATURESr   r  MAXMINz&, '%s' isn't a known feature or option)r   r   r   r  r   rj  r   rK  _parse_regex_argr  rJ  r  r  r%  r  rn  r  r  r  )
rq   arg_namereq_featuresfinal_featuresrc  r   tokTOKfeatures_tor   ra   ra   rw   r  g  sX   




z_Parse._parse_arg_featuresz\s|[*,/]|([()])c                 C   s  t |tsJ g }g }d}t }t }d }ttd t| j|}|s(| d |D ]}|	 }	|d }
|
dv r>| d q*|
dkrT|d urK| d |
| |	 q*|
dkrm|d ura| d	 | |	|||\}}}q*|
d
kr~|d urz| d t }q*|
dkr|d u r| d | |}|d u r|
t| nt|dkr|d }|r||vr|| d }q*|	dkr|d ur| d d}q*|d ur|
|	 q*| |	s| d|	  |	| jv p|	| jv }|r|	|vr||	 q*|
|	 q*|d ur| d |r	| d|d | |}t|D ]&}| j| \}}}|D ]}||v r'q| d||f  |
| qq| j D ])\}\}}}d }||v rV|}| d|  n|}|s]q>||||\}}}q>|||fS )NFzexpected one token at leastr   )r^  r  ze+/- are 'not' allowed from target's groups or @targets, only from cpu_baseline and cpu_dispatch parmsr  zCpolicies aren't allowed inside multi-target '()', only CPU featuresr  zHtarget groups aren't allowed inside multi-target '()', only CPU featuresr   z"unclosed multi-target, missing ')'r   z$multi-target opener '(' wasn't foundr   BASELINEz/baseline isn't allowed inside multi-target '()'Tzinvalid target name '%s'zskip targetsz.not part of baseline or dispatch-able featureszpolicy '%s' force enables '%s'zpolicy '%s' is ON)r   r   r  r   rj  r   rK  _parse_regex_targetr   r  rn  _parse_token_policy_parse_token_group_parse_multi_targettupler   r   r  r  r  r   r  r  r  )rq   rc  final_targetsr  r  skippedpoliciesmulti_targetr  r  chtargets
is_enabledprx  depsr/  havenhavefuncra   ra   rw   r    s   
















z_Parse._parse_target_tokensc                 C   sZ   t |dks|dd |d kr| d |dd }|| jvr+| d| | j  |S )zvalidate policy tokenr   r  Nr   z*'$' must stuck in the begin of policy namez6'%s' is an invalid policy name, available policies are)r   r   r  r%  )rq   tokenra   ra   rw   r    s    

z_Parse._parse_token_policyc                    s   t |dks|dd |d kr| d |dd }| j|ddg f\}}}|du r9| d| d | j  |r=d	}fd
d|D 7   fdd|D 7  | fS )zvalidate group tokenr   r  Nr   z)'#' must stuck in the begin of group nameFz&'%s' is an invalid target group name, zavailable target groups areTc                    r  ra   ra   r  )r  ra   rw   r   2  r  z-_Parse._parse_token_group.<locals>.<listcomp>c                    r  ra   ra   r  )r  ra   rw   r   3  r  )r   r   r  r   r%  )rq   r$  r  r  r  ghas_baselinegtargetsgextra_flagsra   )r  r  rw   r     s$    



z_Parse._parse_token_groupc                    sr   |s  d t fdd|D s  d| t fdd|D s%dS  |}|s.dS  |}t|}|S )z9validate multi targets that defined between parentheses()zempty multi-target '()'c                       g | ]}  |qS ra   )r  r   tarre  ra   rw   r   ;  s    
z._Parse._parse_multi_target.<locals>.<listcomp>z#invalid target name in multi-targetc                    s    g | ]}| j v p| jv qS ra   )r  r  r)  re  ra   rw   r   ?  s
    
N)r   allr  r  r  )rq   r  ra   re  rw   r  6  s    


z_Parse._parse_multi_targetc                    sx   g }|dd D ]&}d}t |tr| jv }nt fdd|D }|r.|| || q|r7 d| |||fS )zskip all baseline featuresNFc                    s   g | ]}| j v qS ra   r  r  re  ra   rw   r   X      z5_Parse._parse_policy_not_keepbase.<locals>.<listcomp>zskip baseline features)r   r   r  r+  r   r  r   )rq   r  r  r  r  r*  is_basera   re  rw   r  O  s   



z!_Parse._parse_policy_not_keepbasec                 C   s   |  d|d |||fS )z$leave a notice that $keep_sort is onz/policy 'keep_sort' is on, dispatch-able targetszo
are 'not' sorted depend on the highest interest butas specified in the dispatch-able source or the extra group)r   rq   r  r  r  ra   ra   rw   r  e  s   
z_Parse._parse_policy_keepsortc                 C   s   | j |dd}|||fS )z%sorted depend on the highest interestTr  )r  r.  ra   ra   rw   r  n  s   
z!_Parse._parse_policy_not_keepsortc                 C   sT   | j r	| d n| jr| d n| jd }|s!| jddd n||7 }|||fS )z&append the compiler optimization flagsz3debug mode is detected, policy 'maxopt' is skipped.z5optimization is disabled, policy 'maxopt' is skipped.r   zOcurrent compiler doesn't support optimization flags, policy 'maxopt' is skippedTr   )rA  r   rb   rJ  rq   r  r  r  r^   ra   ra   rw   r  s  s   

z_Parse._parse_policy_maxoptc                 C   s:   | j d }|s| jddd n	| d ||7 }|||fS )z#force warnings to treated as errorsr   zTcurrent compiler doesn't support werror flags, warnings will 'not' treated as errorsTr   z'compiler warnings are treated as errors)rJ  r   r/  ra   ra   rw   r    s   


z_Parse._parse_policy_werrorc                    st   g }|dd D ]$}t |tr |}nt fdd|D }|s,|| || q|r5 d| |||fS )z=skip features that has no auto-vectorized support by compilerNc                    r(  ra   )r  r   r  re  ra   rw   r     r,  z0_Parse._parse_policy_autovec.<locals>.<listcomp>z!skip non auto-vectorized features)r   r   r  r+  r  r   r   )rq   r  r  r  r  r*  r  ra   re  rw   r    s   



z_Parse._parse_policy_autovecN)r   r   r   r   r   r  r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  ra   ra   ra   rw   r    s"    .R
6
8t	r  c                   @   sj   e Zd ZdZdddZdd Zd	d
 Zdd Zdd ZdddZ	dd Z
dddZdddZdddZdS )CCompilerOptz
    A helper class for `CCompiler` aims to provide extra build options
    to effectively control of compiler optimizations that are directly
    related to CPU features.
    minr  Nc                 C   s   t |  t| | t| ||  || t|  t|  | js-| jr-| 	d d}t
| || || _|| _t| di | _| jd t| d| _d S )NzSnative flag is specified through environment variables. force cpu-baseline='native'r   sources_status	hit_cache)r   r   r   r	  r   r=  r~  rb   rB  r   r  _requested_baseline_requested_dispatchr   r3  r  rn  r   r4  )rq   r   r  r  r  ra   ra   rw   r     s    


zCCompilerOpt.__init__c                 C   s   | j o| jS )zF
        Returns True if the class loaded from the cache file
        )r  r4  re  ra   ra   rw   	is_cached  s   zCCompilerOpt.is_cachedc                 C      | j S )zE
        Returns a list of final CPU baseline compiler flags
        )r  re  ra   ra   rw   cpu_baseline_flags     zCCompilerOpt.cpu_baseline_flagsc                 C   r8  )zC
        return a list of final CPU baseline feature names
        r  re  ra   ra   rw   cpu_baseline_names  r:  zCCompilerOpt.cpu_baseline_namesc                 C   r8  )zC
        return a list of final CPU dispatch feature names
        )r  re  ra   ra   rw   cpu_dispatch_names  r:  zCCompilerOpt.cpu_dispatch_namesc                 K   s&  i }|   }|dg }|D ]g}tj|}	|r-|	|s$tj||	}	|	|vr-||	 | |\}
}}| 	|	|||
}|D ]}| j
|	|||d}t|| | }||g | q?|
rnt|| }||g | |
|f| j|< qg }| D ]\}}|| j|t|fd|i|7 }q||S )a  
        Compile one or more dispatch-able sources and generates object files,
        also generates abstract C config headers and macros that
        used later for the final runtime dispatching process.

        The mechanism behind it is to takes each source file that specified
        in 'sources' and branching it into several files depend on
        special configuration statements that must be declared in the
        top of each source which contains targeted CPU features,
        then it compiles every branched source with the proper compiler flags.

        Parameters
        ----------
        sources : list
            Must be a list of dispatch-able sources file paths,
            and configuration statements must be declared inside
            each file.

        src_dir : str
            Path of parent directory for the generated headers and wrapped sources.
            If None(default) the files will generated in-place.

        ccompiler : CCompiler
            Distutils `CCompiler` instance to be used for compilation.
            If None (default), the provided instance during the initialization
            will be used instead.

        **kwargs : any
            Arguments to pass on to the `CCompiler.compile()`

        Returns
        -------
        list : generated object files

        Raises
        ------
        CompileError
            Raises by `CCompiler.compile()` on compiling failure.
        DistutilsError
            Some errors during checking the sanity of configuration statements.

        See Also
        --------
        parse_targets :
            Parsing the configuration statements of dispatch-able sources.
        include_dirs)nochanger   )r9  
setdefaultr   r   r   
startswithr   r   r  _generate_config_wrap_targetr  r  r3  r  r   r   )rq   r   src_dirr   r   
to_compilebaseline_flagsr=  srcr   r  r  r  r>  r*  tar_srcr^   objectssrcsra   ra   rw   try_dispatch  s<   /


zCCompilerOpt.try_dispatchc                    sn    d|    }  }t|}t|}tj|}tj|s3 j d| ddd t| t	|du}d
 fdd	|D }d
 fd
d	|D }	|tdj jd
|d
|||||	d d}
|D ]}|
 j|ddd 7 }
qnd}|D ]}|tdj j| j|ddd7 }q|tdj j|
|d W d   dS 1 sw   Y  dS )ax  
        Generate the dispatch header which contains the #definitions and headers
        for platform-specific instruction-sets for the enabled CPU baseline and
        dispatch-able features.

        Its highly recommended to take a look at the generated header
        also the generated source files via `try_dispatch()`
        in order to get the full picture.
        z"generate CPU dispatch header: (%s)zdispatch header dir z does not exist, creating itTr   r#   \
c                       g | ]	}d  j |f qS z3	%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))r   r  re  ra   rw   r   N	      z9CCompilerOpt.generate_dispatch_header.<locals>.<listcomp>c                    rL  rM  rN  r  re  ra   rw   r   T	  rO  a                  /*
                 * AUTOGENERATED DON'T EDIT
                 * Please make changes to the code generator (distutils/ccompiler_opt.py)
                */
                #define {pfx}WITH_CPU_BASELINE  "{baseline_str}"
                #define {pfx}WITH_CPU_DISPATCH  "{dispatch_str}"
                #define {pfx}WITH_CPU_BASELINE_N {baseline_len}
                #define {pfx}WITH_CPU_DISPATCH_N {dispatch_len}
                #define {pfx}WITH_CPU_EXPAND_(X) X
                #define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \
                {baseline_calls}
                #define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \
                {dispatch_calls}
            r   )pfxbaseline_strdispatch_strbaseline_lendispatch_lenbaseline_callsdispatch_callsr   r   r  r  z                #ifdef {pfx}CPU_TARGET_{name}
                {pre}
                #endif /*{pfx}CPU_TARGET_{name}*/
                )rP  r   prez            /******* baseline features *******/
            {baseline_pre}
            /******* dispatch features *******/
            {dispatch_pre}
            )rP  baseline_predispatch_preN)r   r;  r<  r   r   r   r   r  r&  r)  r   r*  r+  r,  r-  r   r  r   )rq   header_pathr  dispatch_namesrS  rT  
header_dirr1  rU  rV  rX  r   rY  ra   re  rw   generate_dispatch_header4	  sV   






	
"z%CCompilerOpt.generate_dispatch_headerFc                  C   s  g }g }g }g }| d|f | d | d|f | d | d|f | d| jr/dn| jf | d| jr<dn| jf | jrJ| d	 n
| d
t| jf |  }| d|rbd	|ndf | 
 }| d|rtd	|ndf g }|D ]	}	|| |	7 }q|| d|rd	|ndf | jr| d	 n
| d
t| jf |  }
| d|
rd	|
ndf i }| j D ]\}\}}|D ]}||g  | qq|r|sd}| |D ]}|| }t|tr|ndd	| }	||	dt|  7 }q| d|r|d d ndf n| d | |D ]}|| }t|tr)|ndd	| }d	| |}d	| | |}d	| |}g }t|trV|fn|D ]
}	|| |	7 }qX|rkd	|nd}| d | ||f | d|f | d|f | d|f |D ]
}| d|f qqg }dd |D }dd |D }d}tt|t|}|D ]?\}}|s| d q|d|t|  7 }| || d  |D ]\}}|d|t|  7 }| || d |  qݐqd	|S )NPlatform)r   r   zCPU baselinezCPU dispatchArchitectureunsupportedCompilerz	unix-like)	Requestedzoptimization disabledrb  Enabledr   noneFlagszExtra checksr   z(%s)z[%d] 	Generatedr  )rf  r   Detectc                 S   s   g | ]\}}t |qS ra   r   )r   secsrx  ra   ra   rw   r   	  r  z'CCompilerOpt.report.<locals>.<listcomp>c                 S   s&   g | ]\}}|D ]\}}t |qqS ra   rh  )r   rx  rowscolra   ra   rw   r   	  s   & z  z: r  )r   r?  rH  r@  rI  rb   reprr5  r;  r   r9  r  r6  r<  r3  r  r?  r  r   r   r   r  r  r  r  ) rq   fullreportplatform_rowsbaseline_rowsdispatch_rowsr  rE  r8   r   r[  target_sourcesr   rx  r  r*  	generatedr   pretty_namer^   r   r>   rF  r   secs_lencols_lentabpadsecrj  rk  r  ra   ra   rw   rn  	  s   


"



zCCompilerOpt.reportc              	      s  t |ttfs	J t |tr| }}n
d|}d|}tj|tj|}djg tj||	 R  }|rBtj
|rB|S | d| | | |}d| j   fdd|D }	d|	}	t|d	}
|
td
j| j|tj||	d W d    |S 1 sw   Y  |S )N.__z
{0}.{2}{1}zwrap dispatch-able target -> z#define %sCPU_TARGET_c                    s   g | ]} | qS ra   ra   r  target_joinra   rw   r   
  s    z-CCompilerOpt._wrap_target.<locals>.<listcomp>r  r#  aR              /**
             * AUTOGENERATED DON'T EDIT
             * Please make changes to the code generator              (distutils/ccompiler_opt.py)
             */
            #define {pfx}CPU_TARGET_MODE
            #define {pfx}CPU_TARGET_CURRENT {target_name}
            {target_defs}
            #include "{path}"
            )rP  target_namer   target_defs)r   r   r  r   r   r   basenamer-  splitextr  r  r   r  r  r   r)  r*  r+  r,  abspath)rq   r   dispatch_srctargetr>  ext_namer~  	wrap_pathr  r  rZ  ra   r|  rw   rB  	  s0   



 




zCCompilerOpt._wrap_targetc              	   C   s  t j|}t j|d d }t j||}| ||}z5t|'}| d}t	|dkrBt
|d |krB	 W d    W dS W d    n1 sLw   Y  W n	 ty[   Y nw t jt j|dd | d| g }	|D ].}
t|
tr{|
}n
d	d
d |
D }| |
}ddd |D }|	d| j||f  qqd|	}	|rd| j }nd}t|d}|tdj| j||	|d W d    dS 1 sw   Y  dS )Nr   z.hzcache_hash:r   r   T)exist_okzgenerate dispatched config -> r{  c                 S   s   g | ]}|qS ra   ra   r0  ra   ra   rw   r   0
  s    z1CCompilerOpt._generate_config.<locals>.<listcomp>z&&c                 S   r  )zCHK(%s)ra   r  ra   ra   rw   r   2
  r  z2	%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))rK  z(	%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))r   r#  aZ              // cache_hash:{cache_hash}
            /**
             * AUTOGENERATED DON'T EDIT
             * Please make changes to the code generator (distutils/ccompiler_opt.py)
             */
            #ifndef {pfx}CPU_DISPATCH_EXPAND_
                #define {pfx}CPU_DISPATCH_EXPAND_(X) X
            #endif
            #undef {pfx}CPU_DISPATCH_BASELINE_CALL
            #undef {pfx}CPU_DISPATCH_CALL
            #define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \
            {baseline_calls}
            #define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \
            {dispatch_calls}
            )rP  rU  rV  r  F)r   r   r  r  r   r  r)  readlinerK  r   intr{   r&  r   r   r   r   r  r   r   r*  r+  r,  r-  )rq   r   r  r  r  config_pathr  r1  	last_hashrV  r*  r~  
req_detectrU  rZ  ra   ra   rw   rA  
  s`   
 





zCCompilerOpt._generate_config)r2  r  N)NNr  )r   r   r   r   r   r7  r9  r;  r<  rJ  r]  rn  rB  rA  ra   ra   ra   rw   r1    s    

W
S
m&r1  c                 K   s2   t | fi |}tj|r| s|| |S )a  
    Create a new instance of 'CCompilerOpt' and generate the dispatch header
    which contains the #definitions and headers of platform-specific instruction-sets for
    the enabled CPU baseline and dispatch-able features.

    Parameters
    ----------
    compiler : CCompiler instance
    dispatch_hpath : str
        path of the dispatch header

    **kwargs: passed as-is to `CCompilerOpt(...)`
    Returns
    -------
    new instance of CCompilerOpt
    )r1  r   r   r  r7  r]  )r   dispatch_hpathr   r   ra   ra   rw   new_ccompiler_optX
  s   
r  )r   r   r   r   r'  r   r   r+  r   r   r  r	  r=  r~  r  r1  r  ra   ra   ra   rw   <module>   sD    
    ? ; 	  ;   h   y   6