a
    
di                     @   sN  d Z ddlZddlmZmZ ddlZddlmZ ddlm	Z	m
Z
mZmZ ddlZedZedZedZee	jZe ZedZedZedZedZd	d
 ZdddZdd Zi ZdddZi fddZ G dd de!Z"G dd de"Z#G dd de"Z$G dd de!Z%dddZ&d d! Z'dd"d#Z(d$d% Z)d&d' Z*d(d) Z+dd*d+Z,d,d- Z-d.d/ Z.d0d1 Z/d2d3 Z0d4d5 Z1d6d7 Z2d8d9 Z3d:d; Z4e5d<d=Z6edd>d?Z7eddAdBZ8edCdD Z9eddFdGZ:edHdI Z;ddJdKZ<dLdM Z=ddNdOZ>ddPdQZ?ddRdSZ@ddTdUZAdVdW ZBdXdY ZCdZd[ ZDd\d] ZEeDZFeCZGd^d_ ZHeed`dadbZIdcdd ZJdedf ZKddgdhZLeddidjZMeKZNdkdl ZOdmdn ZPdodp ZQdqdr ZRdsdt ZSddudvZTdwdx ZUdydz ZVdd|d}ZWd~d ZXdd ZYdd ZZdd Z[dddZ\dddZ]dd Z^dd Z_dd Z`dd Zadd Zbdd Zcdd Zddd ZedS )z+
Generic helpers for LLVM code generation.
    N)contextmanager	ExitStack)ir)utilstypesconfig	debuginfo          c                 C   s   |  d||dS )N!=r   )icmp_unsignedtypebuildervalue r   [/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/numba/core/cgutils.pyas_bool_bit   s    r   c                 C   sJ   |du rt dd |D }|t j}t|D ]\}}| |||}q.|S )zH
    Create an anonymous struct containing the given LLVM *values*.
    Nc                 S   s   g | ]
}|j qS r   r   .0vr   r   r   
<listcomp>%       z)make_anonymous_struct.<locals>.<listcomp>r   ZLiteralStructType	Undefined	enumerateinsert_value)r   valuesZstruct_typeZ
struct_valir   r   r   r   make_anonymous_struct    s    
r!   c                 C   s*   t | }t|}tttd||S )z0
    Make a byte array constant from *buf*.
    r
   )	bytearraylenr   Constant	ArrayTypeIntType)bufbnr   r   r   make_bytearray,   s    r*   r   c                 C   sb   | |f}t |}|du r^ttd| }|jd t|  }|f}t| d}t|||}|t |< |S )zK
    Returns a specialized StructProxy subclass for the given fe_type.
    N)r   data_)_fe_type)_struct_proxy_cachegetValueStructProxyDataStructProxy__name__strdictr   )Zfe_typekind	cache_keyresbaseZclsnamebasesZ
clsmembersr   r   r   create_struct_proxy8   s    

r:   c                 C   sV   |  }|jjD ]"}||t||}t| || q| D ]\}}t| || q<| S )zJ
    Copy structure from *src* to *dst* with replacement from *repl*.
    )copy
_datamodel_fieldspopgetattrsetattritems)dstsrcreplkr   r   r   r   copy_structK   s    rF   c                       s   e Zd ZdZdZd!ddZdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Z fddZdd Zdd Zdd Zdd Zdd Zdd  Z  ZS )"_StructProxyz
    Creates a `Structure` like interface that is constructed with information
    from DataModel instance.  FE type must have a data model that is a
    subclass of StructModel.
    Nc                 C   s   || _ | j j| j | _t| jtjjjs8t	d
| j|| _| | j| _t| jrZJ | |\}}|jj| jkrtd| j |jf |d ur|j|jjkrtd|jj|jf | j|| || _|| _d S )NzNot a structure model: {0}z!bad ref type: expected %s, got %sz#bad value type: expected %s, got %s)_contextZdata_model_managerr-   r<   
isinstancenumbacore	datamodelZStructModel	TypeErrorformat_builder_get_be_type_be_type
is_pointer
_make_refsr   pointeeAssertionError
as_pointerstore_value
_outer_ref)selfcontextr   r   refZ	outer_refr   r   r   __init__c   s,    
z_StructProxy.__init__c                 C   s"   |du rt | j| jdd}||fS )z
        Return an (outer ref, value ref) pair.  By default, these are
        the same pointers, but a derived class may override this.
        NTzfill)alloca_oncerO   rQ   )rZ   r\   r   r   r   rS   |   s    z_StructProxy._make_refsc                 C   s   t d S NNotImplementedErrorrZ   rL   r   r   r   rP      s    z_StructProxy._get_be_typec                 C   s   t d S ra   rb   rZ   indexvalr   r   r   _cast_member_to_value   s    z"_StructProxy._cast_member_to_valuec                 C   s   t d S ra   rb   re   r   r   r   _cast_member_from_value   s    z$_StructProxy._cast_member_from_valuec                 C   s   t | j| jd|S Nr   )gep_inboundsrO   rX   rZ   rf   r   r   r   _get_ptr_by_index   s    z_StructProxy._get_ptr_by_indexc                 C   s   | j |}| |S ra   )r<   get_field_positionrm   )rZ   attrnamerf   r   r   r   _get_ptr_by_name   s    z_StructProxy._get_ptr_by_namec                 C   s&   | ds| | j| S t|dS z;
        Load the LLVM value of the named *field*.
        r,   N)
startswithr<   rn   AttributeErrorrZ   fieldr   r   r   __getattr__   s    
z_StructProxy.__getattr__c                    s0   | drtt| ||S || | j|< dS z@
        Store the LLVM *value* into the named *field*.
        r,   N)rr   superrG   __setattr__r<   rn   rZ   ru   r   	__class__r   r   ry      s    
z_StructProxy.__setattr__c                 C   s   | j | |}| ||S z>
        Load the LLVM value of the field at *index*.
        )rO   loadrm   rh   )rZ   rf   Z
member_valr   r   r   __getitem__   s    z_StructProxy.__getitem__c                 C   s   |  |}| ||}|j|jjkr|t|jrft|jjrf|jj|jjjkrf| j| j||jjj}nt	dj
||| |d| j|| dS )C
        Store the LLVM *value* into the field at *index*.
        zjInvalid store of {value.type} to {ptr.type.pointee} in {self._datamodel} (trying to write member #{index}))r   ptrrZ   rf   N)rm   ri   r   rT   rR   rH   ZaddrspacecastrO   	addrspacerM   rN   rW   )rZ   rf   r   r   r   r   r   __setitem__   s    

z_StructProxy.__setitem__c                 C   s   | j jS z.
        Return the number of fields.
        )r<   Zfield_countrZ   r   r   r   __len__   s    z_StructProxy.__len__c                 C   s   | j S zF
        Return the LLVM pointer to the underlying structure.
        )rY   r   r   r   r   _getpointer   s    z_StructProxy._getpointerc                 C   s   | j | jS zM
        Load and return the value of the underlying LLVM structure.
        )rO   r~   rY   r   r   r   r   	_getvalue   s    z_StructProxy._getvaluec                 C   s>   t |jrJ |j| jks*J |j| jf| j|| j dS )z4
        Store the value in this structure.
        N)rR   r   rQ   rO   rW   rX   rZ   r   r   r   r   	_setvalue   s    z_StructProxy._setvalue)NN)r2   
__module____qualname____doc__r-   r]   rS   rP   rh   ri   rm   rp   rv   ry   r   r   r   r   r   r   __classcell__r   r   r{   r   rG   Z   s"   
		rG   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	r0   zl
    Create a StructProxy suitable for accessing regular values
    (e.g. LLVM values or alloca slots).
    c                 C   s   |  S ra   )Zget_value_typerd   r   r   r   rP      s    zValueStructProxy._get_be_typec                 C   s   |S ra   r   re   r   r   r   rh      s    z&ValueStructProxy._cast_member_to_valuec                 C   s   |S ra   r   re   r   r   r   ri      s    z(ValueStructProxy._cast_member_from_valueNr2   r   r   r   rP   rh   ri   r   r   r   r   r0      s   r0   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	r1   zO
    Create a StructProxy suitable for accessing data persisted in memory.
    c                 C   s   |  S ra   )Zget_data_typerd   r   r   r   rP      s    zDataStructProxy._get_be_typec                 C   s   | j |}|| j|S ra   )r<   	get_modelZ	from_datarO   rZ   rf   rg   modelr   r   r   rh      s    z%DataStructProxy._cast_member_to_valuec                 C   s   | j |}|| j|S ra   )r<   r   Zas_datarO   r   r   r   r   ri      s    z'DataStructProxy._cast_member_from_valueNr   r   r   r   r   r1      s   r1   c                       sr   e Zd ZdZdddZdd Zdd	 Zd
d Z fddZdd Z	dd Z
dd Zdd Zdd Zdd Z  ZS )	Structurezs
    A high-level object wrapping a alloca'ed LLVM structure, including
    named fields and attribute access.
    NFc           
      C   s0  | | | _|| _|| _|d u rtt|| jdd| _|d urt|jrHJ |j| jksdJ |j| jf||| j n\|d u sJ t|jsJ | j|jj	kr|r|
|| j }ntd|jj	| jf || _i | _g | _g | _td}t| jD ]6\}\}}	|| j|< | j|t|f | j|	 qd S )NTr^   z-mismatching pointer type: got %s, expected %sr   )Zget_struct_type_typerH   rO   r`   rX   rR   r   rW   rT   bitcastrV   rM   _namemap_fdmapZ_typemapint32_tr   r=   append)
rZ   r[   r   r   r\   Zcast_refr8   r    rE   tpr   r   r   r]     s8    
zStructure.__init__c                 C   s   | j j| j| j| dd}|S )NT)inbounds)rO   geprX   r   )rZ   rf   r   r   r   r   rm   $  s    zStructure._get_ptr_by_indexc                 C   s   |  | j| S ra   )rm   r   )rZ   ro   r   r   r   rp   (  s    zStructure._get_ptr_by_namec                 C   s$   | ds| | j|  S t|dS rq   )rr   r   rs   rt   r   r   r   rv   +  s    
zStructure.__getattr__c                    s.   | drtt| ||S || | j| < dS rw   )rr   rx   r   ry   r   rz   r{   r   r   ry   4  s    
zStructure.__setattr__c                 C   s   | j | |S r}   )rO   r~   rm   rl   r   r   r   r   <  s    zStructure.__getitem__c                 C   sN   |  |}|jj|jkr<d}t||t|jjt|jf | j|| dS )r   z:Type mismatch: __setitem__(%d, ...) expected %r but got %rN)rm   r   rT   rU   r3   rO   rW   )rZ   rf   r   r   fmtr   r   r   r   C  s    

zStructure.__setitem__c                 C   s
   t | jS r   )r#   r   r   r   r   r   r   O  s    zStructure.__len__c                 C   s   | j S r   )rX   r   r   r   r   r   U  s    zStructure._getpointerc                 C   s   | j | jS r   )rO   r~   rX   r   r   r   r   r   [  s    zStructure._getvaluec                 C   s>   t |jrJ |j| jks*J |j| jf| j|| j dS )z!Store the value in this structureN)rR   r   r   rO   rW   rX   r   r   r   r   r   a  s    zStructure._setvalue)NNF)r2   r   r   r   r]   rm   rp   rv   ry   r   r   r   r   r   r   r   r   r   r{   r   r      s   
	r    Fc              	   C   s   t |trtt|}t| t |  0 | j|||d}| 	|d| W d   n1 s`0    Y  |r| 	|j
d| |W  d   S 1 s0    Y  dS )a  Allocate stack memory at the entry block of the current function
    pointed by ``builder`` with llvm type ``ty``.  The optional ``size`` arg
    set the number of element to allocate.  The default is 1.  The optional
    ``name`` arg set the symbol name inside the llvm IR for debugging.
    If ``zfill`` is set, fill the memory with zeros at the current
    use-site location.  Note that the memory is always zero-filled after the
    ``alloca`` at init-site (the entry block).
    )sizenameN)rI   intr   r$   intp_tr   Zsuspend_emissionZgoto_entry_blockZallocarW   r   rT   )r   tyr   r   r_   r   r   r   r   r`   j  s    	

.r`   c                 C   s$   |d}| tdg}| |tS )zCompute sizeof using GEP
    Nr	   )r   r   ptrtointr   )r   Zptr_typenulloffsetr   r   r   sizeof  s    r   c                 C   s    t | |j|d}| || |S )z
    Like alloca_once(), but passing a *value* instead of a type.  The
    type is inferred and the allocated slot is also initialized with the
    given value.
    r^   )r`   r   rW   )r   r   r   r_   Zstorager   r   r   alloca_once_value  s    r   c                 C   s(   t | ||}|jd |jd |S )z_
    Insert a pure function (in the functional programming sense) in the
    given module.
    readonlyZnounwind)get_or_insert_function
attributesaddmodulefntyr   fnr   r   r   insert_pure_function  s    r   c                 C   s(   | j |d}|du r$t| ||}|S )zm
    Get the function named *name* with type *fnty* from *module*, or insert it
    if it doesn't exist.
    N)globalsr/   r   Functionr   r   r   r   r     s    r   c                 C   s.   z|  |W S  ty(   | | Y S 0 d S ra   )Zget_named_metadataKeyErrorZadd_named_metadata)r   r   r   r   r   get_or_insert_named_metadata  s    r   c                 C   s   |  |}t| |||S ra   )Zget_unique_namer   ZGlobalVariable)r   r   r   r   Zunique_namer   r   r   add_global_variable  s    
r   c                 C   s   | j }|jd u r| | d S ra   )basic_block
terminatorbranch)r   bbendZbbr   r   r   	terminate  s    
r   c                 C   s   | d S ra   r   )Zltyper   r   r   get_null_value  s    r   c                 C   s   t |j}| d||S )N==r   r   r   r   rg   r   r   r   r   is_null  s    
r   c                 C   s   t |j}| d||S )Nr   r   r   r   r   r   is_not_null  s    
r   c                 C   s   | j |ddS )NFlikelyif_thenr   predr   r   r   if_unlikely  s    r   c                 C   s   | j |ddS )NTr   r   r   r   r   r   	if_likely  s    r   c                 C   s   |  | |S ra   )r   not_r   r   r   r   ifnot  s    r   c                 C   s   | d}| j||dgdS )z#
    Increment an index *val*.
    r	   Znsw)flags)r   r   )r   rg   oner   r   r   increment_index  s    
r   Loop)rf   do_breakc                 #   s(  |du r|j }|du r|d}|}d}d}d  fdd}j}| |: j|dd	}	d
|	|}
|
|  W d   n1 s0    Y  |6 t|	|V  j}t	|	}t
| W d   n1 s0    Y  |	|| |	||   dS )a  
    Generate LLVM IR for a for-loop in [start, count).
    *start* is equal to 0 by default.

    Yields a Loop namedtuple with the following members:
    - `index` is the loop index's value
    - `do_break` is a no-argument callable to break out of the loop
    Nr   for.condfor.bodyfor.endc                      s      d S ra   )r   r   r   r   r   r   r     s    zfor_range.<locals>.do_break
loop.indexr   <)r   append_basic_blockr   r   
goto_blockphiicmp_signedcbranchr   r   r   add_incomingposition_at_end)r   countstartintpstopbbcondbbbodyr   bbstartrf   r   incrr   r   r   	for_range  s.    




,
(r   Tc                 c   sT  |du r|j }| d}| d}| d}| j}	| | | |\ | j|dd}
| j|dd}|rx| d|
|}n| d	|
|}| ||| W d   n1 s0    Y  | |@ |
|fV  | j}| |
|}t	| |}t
| | W d   n1 s0    Y  |
||	 |
|| |t|d
|	 ||| | | dS )a[  
    Generate LLVM IR for a for-loop based on a slice.  Yields a
    (index, count) tuple where `index` is the slice index's value
    inside the loop, and `count` the iteration count.

    Parameters
    -------------
    builder : object
        IRBuilder object
    start : int
        The beginning value of the slice
    stop : int
        The end value of the slice
    step : int
        The step value of the slice
    intp :
        The data type
    inc : boolean, optional
        Signals whether the step is positive (True) or negative (False).

    Returns
    -----------
        None
    Nr   r   r   r   r   z
loop.countr   >r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r$   r   )r   r   r   stepr   incr   r   r   r   rf   r   r   r   Z
next_countr   r   r   for_range_slice  s2    



,

*r   c                 c   s   |j }| d|t|d}t| ||||dd}t| ||||dd}tdd }| j|dd*\}	}
||	|||
|fV  W d	   n1 s0    Y  d	S )
a  
    A helper wrapper for for_range_slice().  This is a context manager which
    yields two for_range_slice()-alike context managers, the first for
    the positive step case, the second for the negative step case.

    Use:
        with for_range_slice_generic(...) as (pos_range, neg_range):
            with pos_range as (idx, count):
                ...
            with neg_range as (idx, count):
                ...
    >=r   T)r   Fc              	   s   sR   | : |}|V  W d    n1 s&0    Y  W d    n1 sD0    Y  d S ra   r   )condZinner_cmr   r   r   r   cm_cond`  s    z(for_range_slice_generic.<locals>.cm_condr   N)r   r   r   r$   r   r   if_else)r   r   r   r   r   Zis_pos_stepZpos_for_rangeZneg_for_ranger   then	otherwiser   r   r   for_range_slice_genericL  s    
r   Cc                 c   s   |dv sJ |sdV  nh|dkr*dd }ndd }t | |||.}t|t|ksXJ ||V  W d   n1 sv0    Y  dS )a  
    Generate a loop nest walking a N-dimensional array.
    Yields a tuple of N indices for use in the inner loop body,
    iterating over the *shape* space.

    If *order* is 'C' (the default), indices are incremented inside-out
    (i.e. (0,0), (0,1), (0,2), (1,0) etc.).
    If *order* is 'F', they are incremented outside-in
    (i.e. (0,0), (1,0), (2,0), (0,1) etc.).
    This has performance implications when walking an array as it impacts
    the spatial locality of memory accesses.
    CFr   Fc                 S   s   | d d d S )Nr   xr   r   r   <lambda>~  r   zloop_nest.<locals>.<lambda>c                 S   s   | S ra   r   r   r   r   r   r     r   N)
_loop_nestr#   )r   shaper   orderZ_swapindicesr   r   r   	loop_nestj  s    
r   c              	   c   s   t | |d |dj}t|dkrdt| |dd  |}|jf| V  W d    qn1 sX0    Y  n
|jfV  W d    n1 s0    Y  d S )Nr   r   r	   )r   r#   r   rf   )r   r   r   loopr   r   r   r   r     s
    .r   c                 C   sP   t |}|du r|d j}t||tj}t|D ]\}}| |||}q4|S )z
    Pack a sequence of values in a LLVM array.  *ty* should be given
    if the array may be empty, in which case the type can't be inferred
    from the values.
    Nr   )r#   r   r   r%   r   r   r   )r   r   r   r)   aryr    r   r   r   r   
pack_array  s    
r  c                 C   sB   t dd |D }|t j}t|D ]\}}| |||}q&|S )z7
    Pack a sequence of values into a LLVM struct.
    c                 S   s   g | ]
}|j qS r   r   r   r   r   r   r     r   zpack_struct.<locals>.<listcomp>r   )r   r   Zstructtystr    r   r   r   r   pack_struct  s
    
r  c                    s0   |du rt jj} fddt|D }|S )zH
    Unpack an array or structure of values, return a Python tuple.
    Nc                    s   g | ]}  |qS r   )extract_value)r   r    r   tupr   r   r     s   z unpack_tuple.<locals>.<listcomp>)r#   r   elementsrange)r   r	  r   valsr   r  r   unpack_tuple  s    r  c           	      C   sB   t ||j|jd}t ||j|jd}t| ||j|||j|||d	S )N)r   )r+   r   strideslayoutinds
wraparoundboundscheck)r  r   ndimr  get_item_pointer2r+   r  )	r[   r   Zarytyr  r  r  r  Zshapesr  r   r   r   get_item_pointer  s    r  c           	         s    fdd}d} d}t|. tjr<|  | jt|f W d    n1 sb0    Y   dd}t|. tjr|  | jt|f W d    n1 s0    Y  d S )Nc                      sL    d ur:t  tr(td  qHtd  ntd d S )NzFdebug: IndexError: index %d is out of bounds for axis {} with size %d
zFdebug: IndexError: index %d is out of bounds for axis %d with size %d
z9debug: IndexError: index %d is out of bounds for size %d
)rI   r   printfrN   r   axisr   dimlenindr   r   _dbg  s    
zdo_boundscheck.<locals>._dbgzindex is out of boundsr   r   r   )r   r   r   ZFULL_TRACEBACKS	call_convreturn_user_exc
IndexErrorr   )	r[   r   r  r  r  r  msgZout_of_bounds_upperZout_of_bounds_lowerr   r  r   do_boundscheck  s    0r   c	                    s  |rVg }	t ||D ]@\}
} d|
|
d} ||
} |||
}|	| qn|}	|rtt |	|D ]\}\}
}t|  |
|| ql|	s |t	dgS |	d j}|dv rg }|dkr
t
t|D ]8}|d}||d d  D ]} ||}q|| qnZ|dkr\t
t|D ]8}|d}|d | D ]} ||}q8|| q ntd|d}t |	|D ]"\}} ||} ||}qv ||g}|S  fdd	t ||	D }t j|}t ||S d S )
Nr   r   r   r   r	   r   Zunreachablec                    s   g | ]\}}  ||qS r   )mul)r   sr    r   r   r   r     r   z%get_item_pointer2.<locals>.<listcomp>)zipr   r   r   selectr   r   r   r   r   r  r#   r!  	Exception	functoolsreducepointer_add)r[   r   r+   r   r  r  r  r  r  r   r  r  negativewrappedselectedr  r   Zstepsr    lastjlocr"  tmpr   Zdimoffsr   r   r#  r   r    sL    



r  c                 C   s\   | d}t|j tjtjfr*|||}n.t|j tjrH| |||}ntd|j f |S )Nr   zunexpected value type %s)r   rI   r   Z	FloatTypeZ
DoubleTyper&   r   rM   )r   r   ZfpredZicondZnullvalZisnullr   r   r   _scalar_pred_against_zero  s    
r1  c                 C   s   t | |t| jddS )zK
    Return a predicate representing whether *value* is equal to zero.
    r   r1  r'  partialZfcmp_orderedr   r   r   r   is_scalar_zero%  s    r4  c                 C   s   t | |t| jddS )z
    Return a predicate representing whether a *value* is not equal to zero.
    (not exactly "not is_scalar_zero" because of nans)
    r   r1  r'  r3  Zfcmp_unorderedr   r   r   r   is_not_scalar_zero-  s    r6  c                 C   s   t | |t| jddS )z]
    Return a predicate representing whether *value* is equal to either zero
    or NaN.
    r   r5  r   r   r   r   is_scalar_zero_or_nan6  s    r7  c                 C   s   t | |t| jddS )z:
    Is *value* negative?  Assumes *value* is signed.
    r   r2  r   r   r   r   is_scalar_negC  s    r8  )stackc                 c   sP   | | j|dd\}}| dV  W d   n1 s80    Y  | | dS )a  
    The Python code::

        with contextlib.ExitStack() as stack:
            with early_exit_if(builder, stack, cond):
                cleanup()
            body()

    emits the code::

        if (cond) {
            <cleanup>
        }
        else {
            <body>
        }

    This can be useful for generating code with lots of early exits, without
    having to increase the indentation each time.
    Fr   N)enter_contextr   )r   r9  r   r   r   r   r   r   early_exit_ifK  s    $r;  c                 C   s   t | |t| |S )z
    A convenience wrapper for :func:`early_exit_if`, for the common case where
    the CPython API indicates an error by returning ``NULL``.
    )r;  r   )r   r9  objr   r   r   early_exit_if_nullg  s    r=  c                 C   s`   |j t||dd8 |d }|dd p,d}| j||| W d   n1 sR0    Y  dS )zu
    Guard against *value* being null or zero.
    *exc_tuple* should be a (exception type, arguments...) tuple.
    Fr   r   r	   N)r   r4  r  r  )r[   r   r   Z	exc_tupleexcexc_argsr   r   r   
guard_nullo  s    r@  c                 C   sn   t |jtjsJ |j|r"|fnd}|jt||dd  | j|t| W d   n1 s`0    Y  dS )zG
    Guard against *pointer* being NULL (and raise a MemoryError).
    r   Fr   N)	rI   r   r   PointerTyper   r   r  r  MemoryError)r[   r   pointerr  r?  r   r   r   guard_memory_errorz  s    rD  c                 c   s>   | j t| ||d dV  W d   n1 s00    Y  dS )z>
    Execute the given block if the scalar value is zero.
    r   N)r   r4  )r   r   r   r   r   r   if_zero  s    rE  c                 C   s   t | tjS )z7
    Whether the LLVM type *typ* is a struct type.
    )rI   r   rA  )Zltypr   r   r   rR     s    rR   c                 C   s.   t | |d|}t|jjrJ | || S rj   )rk   rR   r   rT   r   rV   )r   recordr   typZpvalr   r   r   get_record_member  s    rH  c                 C   s   |  d||dS )Nr   r   )r   r   )r   rg   r   r   r   
is_neg_int  s    rI  c                 O   s   t | |g|R ddi|S )z8
    Same as *gep*, but add the `inbounds` keyword.
    r   T)r   )r   r   r  kwsr   r   r   rk     s    rk   c           	      O   sb   | dd}| dd}|r J g }|D ]&}t|tr@t|}n|}|| q(| j||||dS )z
    Emit a getelementptr instruction for the given pointer and indices.
    The indices can be LLVM values or Python int constants.
    r   r   r   F)r   r   )r>   rI   r   r   r   r   )	r   r   r  rJ  r   r   idxr    r  r   r   r   r     s    

r   c                 C   s<   |  |t}t|trt|}| ||}| ||p8|jS )z
    Add an integral *offset* to pointer *ptr*, and return a pointer
    of *return_type* (or, if omitted, the same type as *ptr*).

    Note the computation is done in bytes, and ignores the width of
    the pointed item type.
    )r   r   rI   r   r   Zinttoptrr   )r   r   r   return_typeZintptrr   r   r   r)    s
    
r)  c                 C   sN   | j dt|jf}| |t}t|tr2t|}| ||||t	dg dS )z=
    Fill *size* bytes starting from *ptr* with *value*.
    zllvm.memsetr   N)
r   declare_intrinsic	voidptr_tr   r   rI   r   int8_tcallbool_t)r   r   r   r   r   r   r   r   memset  s
    
rR  c                 C   s0   |  |}t| |t| |jd | || dS )z7
    Fill padding bytes of the pointee with zeros.
    r   N)r~   rR  r   r   rW   )r   r   rg   r   r   r   memset_padding  s    
rS  internalc                 C   s<   t | tjr| }n| j}t||j|}||_d|_||_|S )zO
    Get or create a (LLVM module-)global constant with *name* or *value*.
    T)	rI   r   Moduler   r   r   linkageglobal_constantZinitializer)Zbuilder_or_moduler   r   rV  r   r+   r   r   r   rW    s    rW  c           
   	   C   s  |dksJ | |}| d}t| |j }| t| |\}}|( | ||}| || W d   n1 st0    Y  |< | ||}| ||}| | ||| W d   n1 s0    Y  W d   n1 s0    Y  | |}| || 	||}	||	fS )a  
    Compute the (quotient, remainder) of *val* divided by the constant
    positive *divisor*.  The semantics reflects those of Python integer
    floor division, rather than C's / LLVM's signed division and modulo.
    The difference lies with a negative *val*.
    r   r	   N)
r   r`   r   rI  ZsdivrW   r   subr~   r!  )
r   rg   Zdivisorr   quotZif_negZif_posZquot_valZval_plus_oneZrem_valr   r   r   divmod_by_constant  s    

*P
rZ  c                 C   s&   |  d}| ||| | | |S )z
    Branch conditionally or continue.

    Note: a new block is created and builder is moved to the end of the new
          block.
    z	.continue)r   r   r   )r   r   ZbbtrueZbbcontr   r   r   cbranch_or_continue  s    

r[  c                 C   sv   |j |j ksJ t| ||j dB}| ||jg}| ||jg}| | || W d   n1 sh0    Y  dS )z
    Emit a memcpy to the builder.

    Copies each element of dst to src. Unlike the C equivalent, each element
    can be any LLVM type.

    Assumes
    -------
    * dst.type == src.type
    * count is positive
    r  N)r   r   r   rf   rW   r~   )r   rB   rC   r   r  Zout_ptrZin_ptrr   r   r   memcpy  s
    r\  c           
   	   C   sd   |j }t|trt||}| j|tt|g}t}	| 	|| 
|t| 
|t| |||	g d S ra   )r   rI   r   r   r$   r   rM  rN  	false_bitrP  r   r!  )
r   	func_namerB   rC   r   itemsizealignZsize_tr\  Zis_volatiler   r   r   _raw_memcpy1  s    


ra  c                 C   s   t | d|||||S )za
    Emit a raw memcpy() call for `count` items of size `itemsize`
    from `src` to `dest`.
    zllvm.memcpyra  r   rB   rC   r   r_  r`  r   r   r   
raw_memcpy?  s    rd  c                 C   s   t | d|||||S )zb
    Emit a raw memmove() call for `count` items of size `itemsize`
    from `src` to `dest`.
    zllvm.memmoverb  rc  r   r   r   raw_memmoveG  s    re  c           
      C   sX   |  ||}| |d}| |d}| ||}| |d}| || |d}	||	fS )zq
    Compute (a * b + c) and return a (result, overflow bit) pair.
    The operands must be signed integers.
    r   r	   )Zsmul_with_overflowr  Zsadd_with_overflowor_)
r   ar(   cpprodZprod_ovfr"  r7   Zovfr   r   r   muladd_with_overflowP  s    rk  c           
      G   s   t |tsJ | j}t}t|d d}t|d|}tjt	|gdd}z|
d}W n" tyx   tj||dd}Y n0 | ||}	| ||	gt| S )a  
    Calls printf().
    Argument `format` is expected to be a Python string.
    Values to be printed are listed in `args`.

    Note: There is no checking to ensure there is correct number of values
    in `args` and there type matches the declaration in the format string.
     asciiZprintf_formatTZvar_argr  r   )rI   r3   r   rN  r*   encoderW  r   FunctionTyper   
get_globalr   r   r   rP  list)
r   rN   argsmodcstring	fmt_bytes
global_fmtr   r   ptr_fmtr   r   r   r  ^  s    	r  c                 G   s   t |tsJ | j}t}t|d d}t|d|}tjt	|t
|gdd}	d}
tjr^d|
 }
z||
}W n" ty   tj||	|
d}Y n0 | ||}| ||||gt| S )	z8Calls libc snprintf(buffer, bufsz, format, ...args)
    rl  rm  Zsnprintf_formatTrn  snprintfr,   r   )rI   r3   r   rN  r*   ro  rW  r   rp  r   r   r   ZIS_WIN32rq  r   r   r   rP  rr  )r   bufferbufszrN   rs  rt  ru  rv  rw  r   symbolr   rx  r   r   r   ry  x  s"    ry  c                 G   sX   t |tsJ ttd|}t| |dd}| |t}t| |t	||g|R   |S )z{Similar to `snprintf()` but the buffer is stack allocated to size
    *bufsz*.

    Returns the buffer pointer as i8*.
    r
   Tr^   )
rI   r   r   r%   r&   r`   r   rN  ry  r   )r   r{  rN   rs  Zspacetyspacerz  r   r   r   snprintf_stackbuffer  s    r~  c                 C   s   |  ddS )zk
    Normalize the given string to latin1 compatible encoding that is
    suitable for use in LLVM IR.
    utf8latin1)ro  decode)textr   r   r   normalize_ir_text  s    r  c           
   	   C   s   d}|  |t}t| d|| td}| || }t| |}| |j	t|}| 
d|td}| | t| d W d   n1 s0    Y  | ||j	g}| |}	t| d|	 W d   n1 s0    Y  t| d dS )	zIDebug print the memory region in *ptr* to *ptr + nbytes*
    as hex.
       zhexdump p=%p n=%zur
   r   r   
Nz %02x)Zzextr   r  r   r&   r   rV   r   Zuremrf   r   r   r   r~   )
r   r   nbytesZbytes_per_lineZbyte_trK  Zdiv_byZdo_new_liner   rg   r   r   r   hexdump  s     
(
*r  c                 C   s    | du pt | tjpt | tjS )z returns if 'ty' is none N)rI   r   ZNoneTypeZOmitted)r   r   r   r   is_nonelike  s
    

r  c                 C   s   t t | t||S )z
    Create an LLVM-constant of a fixed-length array from Python values.

    The type provided is the type of the elements.
    )r   r$   r%   r#   )r   rg   r   r   r   create_constant_array  s    r  )N)r   )Nr   F)r   F)r   )NN)NT)r   )N)N)FF)N)FF)N)F)N)rT  )r	   )r	   )fr   collections
contextlibr   r   r'  Zllvmliter   Z
numba.corer   r   r   r   Znumba.core.datamodelrJ   r&   rQ  rO  r   ZMACHINE_BITSr   rV   rN  Ztrue_bitr]  Z	true_byteZ
false_byter   r!   r*   r.   r:   rF   objectrG   r0   r1   r   r`   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
namedtupler   r   r   r   r   r   r  r  r  r  r   r  r1  r4  r6  r7  Zis_trueZis_falser8  r;  r=  r@  rD  rE  Z
guard_zerorR   rH  rI  rk   r   r)  rR  rS  rW  rZ  r[  r\  ra  rd  re  rk  r  ry  r~  r  r  r  r  r   r   r   r   <module>   s   



	
 l


+9

	

  

 
:		





			