o
    ؾgA                     @   s  d dl Z d dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
mZmZmZmZmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d
dlmZ d dlmZmZmZ d dl m!Z! G dd dejZ"e #de j$Z%G dd deZ&G dd deZ'G dd deZ(dS )    N)cached_property)ir)cgutilsconfig	debuginfoitanium_manglertypestypingutils)
Dispatcher)BaseContext)BaseCallConvMinimalCallConv)	cmathdecl)	datamodel   )nvvm)codegen	nvvmutilsufuncs)cuda_data_managerc                       s$   e Zd Zdd Z fddZ  ZS )CUDATypingContextc                 C   s   ddl m}m}m}m} ddlm}m} | |j	 | |j	 | |j	 | t
j	 | |j	 | |j	 | |j d S )Nr   )cudadeclcudamathlibdevicedeclvector_typesr   )enumdecl
cffi_utils) r   r   r   r   numba.core.typingr   r   install_registryregistryr   typing_registry)selfr   r   r   r   r   r    r$   [/var/www/html/backend_erp/backend_erp_env/lib/python3.10/site-packages/numba/cuda/target.pyload_additional_registries   s   z,CUDATypingContext.load_additional_registriesc                    s   ddl m} t|trJt||sJz|j}W n4 tyI   |js#td|j	 }d|d< |
dd|d< |
dd|d< ||j|}||_|}Y nw tt| |S )	Nr   )CUDADispatcherz<using cpu function on device but its compilation is disabledTdevicedebugFopt)numba.cuda.dispatcherr'   
isinstancer   _CUDATypingContext__dispatcherAttributeError_can_compile
ValueErrortargetoptionscopygetpy_funcsuperr   resolve_value_type)r#   valr'   r1   disp	__class__r$   r%   r6   #   s$   


z$CUDATypingContext.resolve_value_type)__name__
__module____qualname__r&   r6   __classcell__r$   r$   r9   r%   r      s    r   z	[^a-z0-9]c                       s   e Zd ZdZdZd* fdd	Zedd Zedd Zd	d
 Z	dd Z
dd Zdd Zedd Zedd Zedd ZdddddZ	d+ddZdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Z  ZS ),CUDATargetContextTcudac                    s    t  || ttj| _d S N)r5   __init__r   chainr   default_managerdata_model_manager)r#   	typingctxtargetr9   r$   r%   rB   G   s   
zCUDATargetContext.__init__c                 C   s   t jS rA   )r   	DIBuilderr#   r$   r$   r%   rH   M   s   zCUDATargetContext.DIBuilderc                 C      dS )NFr$   rI   r$   r$   r%   enable_boundscheckQ      z$CUDATargetContext.enable_boundscheckc                 C   s   | j |S rA   )_internal_codegen_create_empty_module)r#   namer$   r$   r%   create_moduleW   s   zCUDATargetContext.create_modulec                 C   s   t d| _d | _d S )Nznumba.cuda.jit)r   JITCUDACodegenrM   _target_datarI   r$   r$   r%   initZ   s   
zCUDATargetContext.initc                 C   s   ddl m}m}m} ddl m}m}m} ddl m}m} ddl m	}	 ddl
m}
 ddlm} ddlm} d	d
lm}m}m}m}m} ddlm} | |j | |
j | |j | |j | |	j | |j | |j d S )Nr   )numberstupleobjslicing)rangeobj	iteratorsenumimpl)unicodecharseq)	cmathimpl)cffiimpl)arrayobj)
npdatetimer   )cudaimpl	printimpllibdeviceimplmathimplr   )ndarray)numba.cpythonrT   rU   rV   rW   rX   rY   rZ   r[   r\   
numba.miscr]   numba.npr^   r_   r   r`   ra   rb   rc   r   numba.np.unsaferd   r    r!   impl_registry)r#   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   r   rd   r$   r$   r%   r&   ^   s    z,CUDATargetContext.load_additional_registriesc                 C   s   | j S rA   )rM   rI   r$   r$   r%   r   v   s   zCUDATargetContext.codegenc                 C   s"   | j d u rtt j| _ | j S rA   )rR   llcreate_target_datar   NVVMdata_layoutrI   r$   r$   r%   target_datay   s   
zCUDATargetContext.target_datac                    s*   ddl m  d}t fdd|D }|S )z
        Some CUDA intrinsics are at the module level, but cannot be treated as
        constants, because they are loaded from a special register in the PTX.
        These include threadIdx, blockDim, etc.
        r   r@   )	threadIdxblockDimblockIdxgridDimlaneidwarpsizec                    s   g | ]	}t  |fqS r$   )r   Module).0ncro   r$   r%   
<listcomp>   s    z;CUDATargetContext.nonconst_module_attrs.<locals>.<listcomp>)numbar@   tuple)r#   	nonconstsnonconsts_with_modr$   ro   r%   nonconst_module_attrs   s   z'CUDATargetContext.nonconst_module_attrsc                 C   s   t | S rA   )CUDACallConvrI   r$   r$   r%   	call_conv   s   zCUDATargetContext.call_convr$   Nabi_tagsuidc                C   s   t j||||dS )Nr   )r   mangle)r#   rO   argtypesr   r   r$   r$   r%   mangler   s   
zCUDATargetContext.manglerc	              	   C   sV   t j|jdd}	|  j|j d|	||d}
|
| | |
||	||||}|
|fS )a  
        Adapt a code library ``codelib`` with the numba compiled CUDA kernel
        with name ``fname`` and arguments ``argtypes`` for NVVM.
        A new library is created with a wrapper function that can be used as
        the kernel entry point for the given kernel.

        Returns the new code library and the wrapper function.

        Parameters:

        codelib:       The CodeLibrary containing the device function to wrap
                       in a kernel call.
        fndesc:        The FunctionDescriptor of the source function.
        debug:         Whether to compile with debug.
        lineinfo:      Whether to emit line info.
        nvvm_options:  Dict of NVVM options used when compiling the new library.
        filename:      The source filename that the function is contained in.
        linenum:       The source line that the function is on.
        max_registers: The max_registers argument for the code library.
        cudapyns_kernel_)
entry_namenvvm_optionsmax_registers)r   prepend_namespacellvm_func_namer   create_libraryrO   add_linking_librarygenerate_kernel_wrapper)r#   codelibfndescr)   lineinfor   filenamelinenumr   kernel_namelibrarywrapperr$   r$   r%   prepare_cuda_kernel   s   

z%CUDATargetContext.prepare_cuda_kernelc           !   	      s  |j }| |}	t|	j}
tt |
}| dttd| j	
tjg|
 }t||j}tj|jdd}t|| t d}|sN|rl|oR| }| j|| |d}| ||j|| |||  fdd}|d	}g }g }d
D ]}||d|  ||d|  q}|	| j}| j	||tj||\}}|r<t||j |  W d   n1 sw   Y  | |!|j"f t#|j$j%d}|&|||j'dd}|(|d}t)*|}| |3 t+d
|D ]\}}|,|} |-| | qt+d
|D ]\}}|.|} |-| | qW d   n	1 s'w   Y  W d   n	1 s7w   Y  |  t/0  |1 |sP|rT|2  |2  t3j4rbt56| |7 jS )z
        Generate the kernel wrapper in the given ``library``.
        The function being wrapped is described by ``fndesc``.
        The wrapper function is returned.
        zcuda.kernel.wrapper    r   r   r   )modulefilepathcgctxdirectives_onlyc                    s4    j |  }ttd|}t|jjd |_|S )Nr   )	rO   r   add_global_variabler   IntTypeConstanttypepointeeinitializer)postfixrO   gvwrapfnwrapper_moduler$   r%   define_error_gv   s   
zBCUDATargetContext.generate_kernel_wrapper.<locals>.define_error_gv__errcode__xyzz	__tid%s__z__ctaid%s__N	monotonicr   )8r   get_arg_packerlistargument_typesr   FunctionTypeVoidTyperP   r   r   get_return_typer   pyobjectFunctionr   r   r   rO   	IRBuilderappend_basic_blockrH   mark_subprogramargsmark_locationappendfrom_argumentscall_functionvoidr   	if_likelyis_okret_voidif_thennot_is_python_excr   r   r   cmpxchgcodeextract_valuer   SRegBuilderziptidstorectaidr   set_cuda_kerneladd_ir_modulefinalizer   	DUMP_LLVMr
   	dump_llvmget_function)!r#   r   r   r   r)   r   r   r   r   arginfoargtyswrapfntyfntyfuncprefixedbuilderr   r   r   gv_excgv_tidgv_ctaidicallargsstatus_oldxchgchangedsregdimptrr7   r$   r   r%   r      s   









z)CUDATargetContext.generate_kernel_wrapperc              	      s   |j } fddt|jddD }ttdt|}t||}tj	}t
j||jd|d}	d|	_d	|	_||	_ |j}
 |
}d
|d   |	_ttd}||	|d} | |} fdd|jD } fdd|jD } j||||jj|||j|jdd | S )i
        Unlike the parent version.  This returns a a pointer in the constant
        addrspace.
        c                       g | ]	}  tj|qS r$   )get_constantr   byte)rw   r   rI   r$   r%   ry     s    z9CUDATargetContext.make_constant_array.<locals>.<listcomp>A)order   _cudapy_cmem	addrspaceinternalT   r   genericc                    r   r$   r   r   intprw   srI   r$   r%   ry   6      c                    r   r$   r   r   rI   r$   r%   ry   7  r   N)datashapestridesitemsizeparentmeminfo) r   itertobytesr   	ArrayTyper   lenr   r   ADDRSPACE_CONSTANTr   r   r   linkageglobal_constantr   get_data_typedtypeget_abi_sizeof
bit_lengthalignPointerTypeaddrspacecast
make_arrayr   r   populate_arraybitcastr   r   r   	_getvalue)r#   r   arytyarrlmod	constvals
constarytyconstaryr   r   lldtyper  ptrtygenptrarykshapekstridesr$   rI   r%   make_constant_array  s8   

z%CUDATargetContext.make_constant_arrayc                 C   s   t |dd }ddt|g}|j|}|du r2t j||j	|t
jd}d|_d|_||_|j	jj}||t
jS )	r   zutf-8    $__conststring__Nr   r   T)r   make_bytearrayencodejoinr   mangle_identifierglobalsr3   r   r   r   r  r  r  r   r   elementr  
as_pointer)r#   modstringtextrO   r   chartyr$   r$   r%   insert_const_string@  s   
z%CUDATargetContext.insert_const_stringc                 C   s0   |j }| ||}ttd}|||dS )z
        Insert a constant string in the constant addresspace and return a
        generic i8 pointer to the data.

        This function attempts to deduplicate.
        r   r   )r   r.  r   r  r   r  )r#   r   r+  r  r   	charptrtyr$   r$   r%   insert_string_const_addrspaceV  s   z/CUDATargetContext.insert_string_const_addrspacec                 C   rJ   )zRun O1 function passes
        Nr$   r#   r   r$   r$   r%   optimize_functionb  rL   z#CUDATargetContext.optimize_functionc                 C   s
   t |S rA   )r   get_ufunc_info)r#   	ufunc_keyr$   r$   r%   r3  o     
z CUDATargetContext.get_ufunc_inforo   rA   )r;   r<   r=   implement_powi_as_math_callstrict_alignmentrB   propertyrH   rK   rP   rS   r&   r   rn   r   r~   r   r   r   r   r  r.  r0  r2  r3  r>   r$   r$   r9   r%   r?   C   s6    





$\+r?   c                   @   s   e Zd ZdS )r   N)r;   r<   r=   r$   r$   r$   r%   r   s  s    r   c                   @   s`   e Zd ZdZdd Zdd Z		dddZd	d
 Zdd ZdddZ	dd Z
dd Zdd ZdS )CUDACABICallConvz
    Calling convention aimed at matching the CUDA C/C++ ABI. The implemented
    function signature is:

        <Python return type> (<Python arguments>)

    Exceptions are unsupported in this convention.
    c                 C   s   d S rA   r$   )r#   r   r$   r$   r%   _make_call_helper  rL   z"CUDACABICallConv._make_call_helperc                 C   s
   | |S rA   )ret)r#   r   retvalr$   r$   r%   return_value  r5  zCUDACABICallConv.return_valueNc                 C   s   d}t |)Nz7Python exceptions are unsupported in the CUDA C/C++ ABINotImplementedError)r#   r   excexc_argsloc	func_namemsgr$   r$   r%   return_user_exc  s   z CUDACABICallConv.return_user_excc                 C   s   d}t |)Nz2Return status is unsupported in the CUDA C/C++ ABIr>  )r#   r   r   rD  r$   r$   r%   return_status_propagate  s   z(CUDACABICallConv.return_status_propagatec                 C   s*   |  |}t|j}t| ||}|S )zM
        Get the LLVM IR Function type for *restype* and *argtypes*.
        )_get_arg_packerr   r   r   r   r   )r#   restyper   r   r   r$   r$   r%   get_function_type  s   

z"CUDACABICallConv.get_function_typeFc                 C   s2   |rJ |  |}|| |dd |D  dS )zA
        Set names and attributes of function arguments.
        c                 S   s   g | ]}d | qS )zarg.r$   )rw   ar$   r$   r%   ry     s    z6CUDACABICallConv.decorate_function.<locals>.<listcomp>N)rG  assign_namesget_arguments)r#   fnr   fe_argtypesnoaliasr   r$   r$   r%   decorate_function  s
   
z"CUDACABICallConv.decorate_functionc                 C   s   |j S )z@
        Get the Python-level arguments of LLVM *func*.
        )r   r1  r$   r$   r%   rL    s   zCUDACABICallConv.get_argumentsc                 C   s>   |  |}|||}|||}d}	| j|||}
|	|
fS )z3
        Call the Numba-compiled *callee*.
        N)rG  as_argumentscallcontextget_returned_value)r#   r   calleerestyr   r   r   realargsr   r   outr$   r$   r%   r     s   
zCUDACABICallConv.call_functionc                 C   s   | j j|  S rA   )rS  rE   r   )r#   tyr$   r$   r%   r     s   z CUDACABICallConv.get_return_type)NNN)F)r;   r<   r=   __doc__r:  r=  rE  rF  rI  rP  rL  r   r   r$   r$   r$   r%   r9  w  s    	

		r9  ))re	functoolsr   llvmlite.bindingbindingrj   llvmliter   
numba.corer   r   r   r   r   r	   r
   numba.core.dispatcherr   numba.core.baser   numba.core.callconvr   r   r   r   r   cudadrvr   
numba.cudar   r   r   numba.cuda.modelsr   r   compileIVALID_CHARSr?   r   r9  r$   r$   r$   r%   <module>   s(    $*  2