o
    Y۷i+^                     @   s  d Z ddlZddlZddlZddlZddlmZmZmZm	Z	m
Z
mZmZ ddlZddlmZ ddlmZmZmZ ddlmZmZmZ ddlmZmZ eeZdZdZd	Z d
Z!dZ"eZ#eZ$d% Z&e'e&D ]\Z(Z)e*ej+e e)e( qedZ,dZ-dd Z.e/ Z0G dd de1Z2G dd de1Z3dZ4dddddddddddddZ5dd Z6dd Z7dd  Z8d!d" Z9d#Z:G d$d% d%e1Z;d&Z<d'Z=d(Z>d)Z?d*Z@d+d, ZAd-d. ZBd/d0 ZCd1d2 ZDd3d4 ZEd5d6 ZFd7d8 ZGeHd9ZId:d; ZJd<d= ZKd>d? ZLdS )@z(
This is a direct translation of nvvm.h
    N)c_void_pc_intPOINTERc_char_pc_size_tbyrefc_char)ir   )	NvvmErrorNvvmSupportErrorNvvmWarning)get_libdeviceopen_libdeviceopen_cudalib)cgutilsconfig         a  
NVVM_SUCCESS
NVVM_ERROR_OUT_OF_MEMORY
NVVM_ERROR_PROGRAM_CREATION_FAILURE
NVVM_ERROR_IR_VERSION_MISMATCH
NVVM_ERROR_INVALID_INPUT
NVVM_ERROR_INVALID_PROGRAM
NVVM_ERROR_INVALID_IR
NVVM_ERROR_INVALID_OPTION
NVVM_ERROR_NO_MODULE_IN_PROGRAM
NVVM_ERROR_COMPILATION
ze-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64ze-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64c                   C   s"   zt   W dS  ty   Y dS w )z(
    Return if libNVVM is available
    FT)NVVMr    r   r   M/home/ubuntu/vllm_env/lib/python3.10/site-packages/numba/cuda/cudadrv/nvvm.pyis_available<   s   r   c                   @   s   e Zd ZdZeeeeefeeefeeefeeee	efeeee	efeeeeefeeee	feeefeeee	feeefeeeeeeeeefeeeeefdZ
dZdd Zdd Zedd	 Zed
d Zdd Zdd ZdddZdS )r   zProcess-wide singleton.
    )nvvmVersionnvvmCreateProgramnvvmDestroyProgramnvvmAddModuleToProgramnvvmLazyAddModuleToProgramnvvmCompileProgramnvvmGetCompiledResultSizenvvmGetCompiledResultnvvmGetProgramLogSizenvvmGetProgramLognvvmIRVersionnvvmVerifyProgramNc                 C   s   t a | jd u rQt|  | _}ztd|_W n ty. } zd | _d}t|| d }~ww |j	 D ]%\}}t
|j|}|d |_|dd  |_t||| q4W d    | jS W d    | jS 1 sfw   Y  | jS )Nnvvmz;libNVVM cannot be found. Do `conda install cudatoolkit`:
%sr   r
   )
_nvvm_lock_NVVM__INSTANCEobject__new__r   driverOSErrorr   _PROTOTYPESitemsgetattrrestypeargtypessetattr)clsinsteerrmsgnameprotofuncr   r   r   r*      s0   



zNVVM.__new__c                 C   s<   |   }|d | _|d | _|d | _|d | _t | _d S )Nr   r
      r   )get_ir_version_majorIR_minorIR	_majorDbg	_minorDbgget_supported_ccs_supported_ccs)selfir_versionsr   r   r   __init__   s   



zNVVM.__init__c                 C   s   | j | jfdk r
tS tS )N)r
      )r<   r=   _datalayout_original_datalayout_i128rB   r   r   r   data_layout   s   zNVVM.data_layoutc                 C      | j S N)rA   rH   r   r   r   supported_ccs   s   zNVVM.supported_ccsc                 C   s8   t  }t  }| t|t|}| |d |j|jfS )NzFailed to get version.)r   r   r   check_errorvalue)rB   majorminorerrr   r   r   get_version   s
   zNVVM.get_versionc                 C   sX   t  }t  }t  }t  }| t|t|t|t|}| |d |j|j|j|jfS )NzFailed to get IR version.)r   r$   r   rM   rN   )rB   majorIRminorIRmajorDbgminorDbgrQ   r   r   r   r;      s   zNVVM.get_ir_versionFc                 C   s4   |rt |t| }|rt| td d S |d S )Nr
   )r   RESULT_CODE_NAMESprintsysexit)rB   errormsgrZ   excr   r   r   rM      s   zNVVM.check_error)F)__name__
__module____qualname____doc__nvvm_resultr   r   nvvm_programr   r   r-   r(   r*   rD   propertyrI   rL   rR   r;   rM   r   r   r   r   r   K   sB    




6


r   c                   @   sD   e Z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 )CompilationUnitc                 C   s4   t  | _t | _| jt| j}| j|d d S )NzFailed to create CU)r   r+   rc   _handler   r   rM   )rB   rQ   r   r   r   rD      s   zCompilationUnit.__init__c                 C   s*   t  }|t| j}|j|ddd d S )NzFailed to destroy CUT)rZ   )r   r   r   rf   rM   )rB   r+   rQ   r   r   r   __del__   s   zCompilationUnit.__del__c                 C   *   | j | j|t|d}| j |d dS )z
         Add a module level NVVM IR to a compilation unit.
         - The buffer should contain an NVVM module IR either in the bitcode
           representation (LLVM3.0) or in the text representation.
        NFailed to add module)r+   r   rf   lenrM   rB   bufferrQ   r   r   r   
add_module      zCompilationUnit.add_modulec                 C   rh   )z
        Lazily add an NVVM IR module to a compilation unit.
        The buffer should contain NVVM module IR either in the bitcode
        representation or in the text representation.
        Nri   )r+   r   rf   rj   rM   rk   r   r   r   lazy_add_module   rn   zCompilationUnit.lazy_add_modulec                    s   dd   fdd|  D }tt| dd |D  }| j| jt||}| |d | j| jt||}| |d t }| j	| jt
|}| |d t|j  }| j| j|}| |d	 |  | _| jrutj| jtd
 |dd S )a  Perform Compilation.

        Compilation options are accepted as keyword arguments, with the
        following considerations:

        - Underscores (`_`) in option names are converted to dashes (`-`), to
          match NVVM's option name format.
        - Options that take a value will be emitted in the form
          "-<name>=<value>".
        - Booleans passed as option values will be converted to integers.
        - Options which take no value (such as `-gen-lto`) should have a value
          of `None` passed in and will be emitted in the form "-<name>".

        For documentation on NVVM compilation options, see the CUDA Toolkit
        Documentation:

        https://docs.nvidia.com/cuda/libnvvm-api/index.html#_CPPv418nvvmCompileProgram11nvvmProgramiPPKc
        c                 S   s@   |  dd} |d u rd|  S t|trt|}d|  d| S )N_-=)replace
isinstanceboolint)kvr   r   r   stringify_option   s   

z1CompilationUnit.compile.<locals>.stringify_optionc                    s   g | ]	\}} ||qS r   r   ).0rw   rx   ry   r   r   
<listcomp>  s    z+CompilationUnit.compile.<locals>.<listcomp>c                 S   s   g | ]	}t |d qS )utf8)r   encode)rz   xr   r   r   r|   
  s    zFailed to verify
zFailed to compile
z&Failed to get size of compiled result.zFailed to get compiled result.)categoryN)r.   r   rj   r+   r%   rf   
_try_errorr   r   r    r   r   rN   r!   get_loglogwarningswarnr   )rB   optionsc_optsrQ   reslenoutput_bufferr   r{   r   compile   s&   
zCompilationUnit.compilec                 C   s   | j |d||  f  d S )Nz%s
%s)r+   rM   r   )rB   rQ   r\   r   r   r   r   %  s   zCompilationUnit._try_errorc                 C   sl   t  }| j| jt|}| j|d |jdkr4t|j  }| j| j|}| j|d |j	dS dS )Nz#Failed to get compilation log size.r
   zFailed to get compilation log.r}    )
r   r+   r"   rf   r   rM   rN   r   r#   decode)rB   r   rQ   logbufr   r   r   r   (  s   
zCompilationUnit.get_logN)
r^   r_   r`   rD   rg   rm   ro   r   r   r   r   r   r   r   re      s    

<re   )r   r   )r      r   r   )r   r:   )r   r   )   r   )r   r
   )r   r:   )r   r   )r   r:   )r   r   )rE   r   rE   r   rE   r   )rE   	   r   r   )r   r   )r   r   )r   r   )r   r   ))   r:   )r   r   )r   r   )r   r   )r   r   )r   r   )r   rE   )   r   )r   r
   )r   r:   )r   r   )r   r   c                    sL   zt |  \ t fddtD W S  ty%   tdd tD  Y S w )Nc                    s(   g | ]}|  kr krn n|qS r   r   rz   ccmax_ccmin_ccr   r   r|   U  s    z(ccs_supported_by_ctk.<locals>.<listcomp>c                 S   s   g | ]	}|t jkr|qS r   )r   CUDA_DEFAULT_PTX_CCr   r   r   r   r|   Z  s    
)CTK_SUPPORTEDtupleCOMPUTE_CAPABILITIESKeyError)ctk_versionr   r   r   ccs_supported_by_ctkQ  s   r   c                  C   s   zddl m}  |  }W n	   d}| Y S tt}||k rBd}|d  d|d  }d| d|d  d|d  d}t| |S t|}|S )	Nr   )runtimer   .r
   zCUDA Toolkit z is unsupported by Numba - z! is the minimum required version.)numba.cuda.cudadrv.runtimer   rR   minr   r   r   r   )r   cudart_version_supported_cc
min_cudartctk_verunsupported_verr   r   r   r@   ^  s&   
r@   c                 C   sv   t  j}|sd}t|t|D ]&\}}|| kr|  S || kr6|dkr.d| |  }t|||d    S q|d S )z
    Given a compute capability, return the closest compute capability supported
    by the CUDA toolkit.

    :param mycc: Compute capability as a tuple ``(MAJOR, MINOR)``
    :return: Closest supported CC as a tuple ``(MAJOR, MINOR)``
    zmNo supported GPU compute capabilities found. Please check your cudatoolkit version matches your CUDA version.r   z?GPU compute capability %d.%d is not supported(requires >=%d.%d)r
   )r   rL   r   	enumerate)myccrL   r\   ir   r   r   r   find_closest_archw  s    r   c                 C   s(   t jr
t j}d| S t| |f}d| S )z1Matches with the closest architecture option
    zcompute_%d%d)r   FORCE_CUDA_CCr   )rO   rP   archr   r   r   get_arch_option  s
   r   aN  Missing libdevice file.
Please ensure you have a CUDA Toolkit 11.2 or higher.
For CUDA 12, ``cuda-nvcc`` and ``cuda-nvrtc`` are required:

    $ conda install -c conda-forge cuda-nvcc cuda-nvrtc "cuda-version>=12.0"

For CUDA 11, ``cudatoolkit`` is required:

    $ conda install -c conda-forge cudatoolkit "cuda-version>=11.2,<12.0"
c                   @   s    e Zd ZdZdd Zdd ZdS )	LibDeviceNc                 C   s0   | j d u rt d u rttt | _ | j | _d S rK   )_cache_r   RuntimeErrorMISSING_LIBDEVICE_FILE_MSGr   bcrH   r   r   r   rD     s
   

zLibDevice.__init__c                 C   rJ   rK   )r   rH   r   r   r   get  s   zLibDevice.get)r^   r_   r`   r   rD   r   r   r   r   r   r     s    r   z
    %cas_success = cmpxchg volatile {Ti}* %iptr, {Ti} %old, {Ti} %new monotonic monotonic
    %cas = extractvalue {{ {Ti}, i1 }} %cas_success, 0
a  
define internal {T} @___numba_atomic_{T}_{FUNC}({T}* %ptr, {T} %val) alwaysinline {{
entry:
    %iptr = bitcast {T}* %ptr to {Ti}*
    %old2 = load volatile {Ti}, {Ti}* %iptr
    br label %attempt

attempt:
    %old = phi {Ti} [ %old2, %entry ], [ %cas, %attempt ]
    %dold = bitcast {Ti} %old to {T}
    %dnew = {OP} {T} %dold, %val
    %new = bitcast {T} %dnew to {Ti}
    {CAS}
    %repeat = icmp ne {Ti} %cas, %old
    br i1 %repeat, label %attempt, label %done

done:
    %result = bitcast {Ti} %old to {T}
    ret {T} %result
}}
a  
define internal {T} @___numba_atomic_{Tu}_inc({T}* %iptr, {T} %val) alwaysinline {{
entry:
    %old2 = load volatile {T}, {T}* %iptr
    br label %attempt

attempt:
    %old = phi {T} [ %old2, %entry ], [ %cas, %attempt ]
    %bndchk = icmp ult {T} %old, %val
    %inc = add {T} %old, 1
    %new = select i1 %bndchk, {T} %inc, {T} 0
    {CAS}
    %repeat = icmp ne {T} %cas, %old
    br i1 %repeat, label %attempt, label %done

done:
    ret {T} %old
}}
a  
define internal {T} @___numba_atomic_{Tu}_dec({T}* %iptr, {T} %val) alwaysinline {{
entry:
    %old2 = load volatile {T}, {T}* %iptr
    br label %attempt

attempt:
    %old = phi {T} [ %old2, %entry ], [ %cas, %attempt ]
    %dec = add {T} %old, -1
    %bndchk = icmp ult {T} %dec, %val
    %new = select i1 %bndchk, {T} %dec, {T} %val
    {CAS}
    %repeat = icmp ne {T} %cas, %old
    br i1 %repeat, label %attempt, label %done

done:
    ret {T} %old
}}
a  
define internal {T} @___numba_atomic_{T}_{NAN}{FUNC}({T}* %ptr, {T} %val) alwaysinline {{
entry:
    %ptrval = load volatile {T}, {T}* %ptr
    ; Return early when:
    ; - For nanmin / nanmax when val is a NaN
    ; - For min / max when val or ptr is a NaN
    %early_return = fcmp uno {T} %val, %{PTR_OR_VAL}val
    br i1 %early_return, label %done, label %lt_check

lt_check:
    %dold = phi {T} [ %ptrval, %entry ], [ %dcas, %attempt ]
    ; Continue attempts if dold less or greater than val (depending on whether min or max)
    ; or if dold is NaN (for nanmin / nanmax)
    %cmp = fcmp {OP} {T} %dold, %val
    br i1 %cmp, label %attempt, label %done

attempt:
    ; Attempt to swap in the value
    %old = bitcast {T} %dold to {Ti}
    %iptr = bitcast {T}* %ptr to {Ti}*
    %new = bitcast {T} %val to {Ti}
    {CAS}
    %dcas = bitcast {Ti} %cas to {T}
    br label %lt_check

done:
    ret {T} %ptrval
}}
c                 C   s   t j| dS )NTi)cas_nvvmformatr   r   r   r   ir_cas#  s   r   c                 C   s&   t | |||t|d}tjdi |S )N)Tr   OPFUNCCASr   )dictr   ir_numba_atomic_binary_templater   )r   r   r   r   paramsr   r   r   ir_numba_atomic_binary'  s   r   c              	   C   s*   t | |||||t|d}tjdi |S )N)r   r   NANr   
PTR_OR_VALr   r   r   )r   r   ir_numba_atomic_minmax_templater   )r   r   r   r   r   r   r   r   r   r   ir_numba_atomic_minmax,  s   r   c                 C      t j| |t| dS N)r   Tur   )ir_numba_atomic_inc_templater   r   r   r   r   r   r   ir_numba_atomic_inc3     r   c                 C   r   r   )ir_numba_atomic_dec_templater   r   r   r   r   r   ir_numba_atomic_dec7  r   r   c                 C   s.  dt dddddfdt dd	d
ddfdt ddd
ddfdtdddfdtdddfdtdd	dddddfdtdddddddfdtdd	dddddfdtdddddddfdtdd	dddddfdtdddddddfd tdd	dd!dddfd"tdddd!dddfd#g}|D ]
\}}| ||} qt| } | S )$NzIdeclare double @"___numba_atomic_double_add"(double* %".1", double %".2")doublei64faddadd)r   r   r   r   zEdeclare float @"___numba_atomic_float_sub"(float* %".1", float %".2")floati32fsubsubzIdeclare double @"___numba_atomic_double_sub"(double* %".1", double %".2")z=declare i64 @"___numba_atomic_u64_inc"(i64* %".1", i64 %".2")u64r   z=declare i64 @"___numba_atomic_u64_dec"(i64* %".1", i64 %".2")zEdeclare float @"___numba_atomic_float_max"(float* %".1", float %".2")r   znnan oltptrmax)r   r   r   r   r   r   zIdeclare double @"___numba_atomic_double_max"(double* %".1", double %".2")zEdeclare float @"___numba_atomic_float_min"(float* %".1", float %".2")znnan ogtr   zIdeclare double @"___numba_atomic_double_min"(double* %".1", double %".2")zHdeclare float @"___numba_atomic_float_nanmax"(float* %".1", float %".2")nanultzLdeclare double @"___numba_atomic_double_nanmax"(double* %".1", double %".2")zHdeclare float @"___numba_atomic_float_nanmin"(float* %".1", float %".2")ugtzLdeclare double @"___numba_atomic_double_nanmin"(double* %".1", double %".2"))immargr   )r   r   r   r   rs   llvm140_to_70_ir)llvmirreplacementsdeclfnr   r   r   llvm_replace;  sz   









&r   c                 K   s|   t | tr| g} |ddr|ddddd t }t }| D ]}t|}||d q |	|
  |jdi |S )NfastmathFT)ftzfmaprec_div	prec_sqrtr}   r   )rt   strpopupdatere   r   r   rm   r~   ro   r   r   )r   optscu	libdevicemodr   r   r   
compile_irj  s    
r   z"^attributes #\d+ = \{ ([\w\s]+)\ }c                 C   sn   g }|   D ]+}|dr,t|}|d }ddd |D }||d|}|| qd|S )z,
    Convert LLVM 14.0 IR for LLVM 7.0.
    zattributes #r
    c                 s   s    | ]	}|d kr|V  qdS )
willreturnNr   )rz   ar   r   r   	<genexpr>  s    z#llvm140_to_70_ir.<locals>.<genexpr>
)	
splitlines
startswithre_attributes_defmatchgroupsplitjoinrs   append)r	   buflinemattrsr   r   r   r     s   


r   c           
      C   s   | j }t|d}ttdd}|| ||f}t|d}|| td	 }t
|d}| |}t||d}	d|	_d|	_t||g|	_| jd	 d
S )al  
    Mark a function as a CUDA kernel. Kernels have the following requirements:

    - Metadata that marks them as a kernel.
    - Addition to the @llvm.used list, so that they will not be discarded.
    - The noinline attribute is not permitted, because this causes NVVM to emit
      a warning, which counts as failing IR verification.

    Presently it is assumed that there is one kernel per module, which holds
    for Numba-jitted functions. If this changes in future or this function is
    to be used externally, this function may need modification to add to the
    @llvm.used list rather than creating it.
    kernel    r
   znvvm.annotationsrE   z	llvm.used	appendingzllvm.metadatanoinlineN)moduler	   MetaDataStringConstantIntTypeadd_metadatar   get_or_insert_named_metadatar   
as_pointer	ArrayTypebitcastGlobalVariablelinkagesectioninitializer
attributesdiscard)
functionr  mdstrmdvaluemdnmdptrtyusedtyfnptr	llvm_usedr   r   r   set_cuda_kernel  s   

r$  c                    s<   t d  fddt  D }| |}| d| dS )zAdd NVVM IR version to moduler	  c                    s   g | ]} |qS r   r   )rz   rx   r   r   r   r|     s    z"add_ir_version.<locals>.<listcomp>znvvmir.versionN)r	   r  r   r;   r  add_named_metadata)r   rC   md_verr   r%  r   add_ir_version  s   

r(  )Mra   loggingrerY   r   ctypesr   r   r   r   r   r   r   	threadingllvmliter	   r[   r   r   r   libsr   r   r   
numba.corer   r   	getLoggerr^   loggerADDRSPACE_GENERICADDRSPACE_GLOBALADDRSPACE_SHAREDADDRSPACE_CONSTANTADDRSPACE_LOCALrc   rb   r  rW   r   r   rw   r2   modulesrF   rG   r   Lockr'   r)   r   re   r   r   r   r@   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r$  r(  r   r   r   r   <module>   s    $
~n"
 /
'