
    ܙdu                     4   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mZ d dl	m
Z
 d dlmZmZ d dlmZmZmZ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 d dlm c m!c m"Z# d d
l$m%Z% d dl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, d dl-m.Z. d dl/Z/ e            Z0de0_         e/j1        ej        2                    d           d          Z3 e/j1         ej4                    dvd          Z5 G d de6          Z7 G d de/j(                  Z8 G d de/j(                  Z9 G d de/j(                  Z: G d de(          Z; G d de/j(                  Z< e/j=        e#j>        d           G d d e'e(                      Z? G d! d"e(          Z@eAd#k    r e/jB                     dS dS )$    Nnjit)types)compile_isolatedFlags)rtsysnrtopt_nrt_pythonnrt)	intrinsicinclude_path)	signature)impl_ret_untracked)irNRT_get_api)EnableNRTStatsMixinTestCasetemp_directoryimport_dynamicskip_if_32bitrun_in_subprocess)
cpu_targetTlinuxzlinux only test)i386x86_64zx86 only testc                       e Zd ZdZd Zd ZdS )Dummyr   c                 @    t          |           xj        dz  c_        d S N   typealiveselfs    4lib/python3.11/site-packages/numba/tests/test_nrt.py__init__zDummy.__init__,   "    T

A    c                 @    t          |           xj        dz  c_        d S r    r"   r%   s    r'   __del__zDummy.__del__/   r)   r*   N)__name__
__module____qualname__r$   r(   r,    r*   r'   r   r   )   s7        E      r*   r   c                       e Zd ZdZdZd ZdS )TestNrtMemInfoNotInitializedzn
    Unit test for checking the use of the NRT fails if the
    initialization sequence has not been run.
    Fc                    dddd}|                                 D ]\  }}	 |                     t                    5 }dt          _        t          t          |          } ||  d d d            n# 1 swxY w Y   d}|                     |t          |j                             dt          _        # dt          _        w xY wd S )Nr0   )r0   r0   )r0   )librarymeminfo_newmeminfo_allocFz'Runtime must be initialized before use.T)	itemsassertRaisesRuntimeErrorr   _initgetattrassertInstr	exception)r&   methodsmethargsraisesfnmsgs          r'   test_init_failz+TestNrtMemInfoNotInitialized.test_init_fail:   s    "*$) 
 "--// 
	# 
	#JD$	#&&|44 "'EK --BBII              
 @c3v'7#8#8999"d""""
	# 
	#s.   B0'A."B0.A2	2B05A2	6-B00B>N)r-   r.   r/   __doc___numba_parallel_test_rE   r0   r*   r'   r2   r2   3   s5          "# # # # #r*   r2   c                   \     e Zd ZdZ fdZd Zd Zd Zd Zd Z	e
d             Zd	 Z xZS )
TestNrtMemInfoz2
    Unit test for core MemInfo functionality
    c                     dt           _        t          j        t          j                   t          t          |                                            d S )Nr   )	r   r$   r   
initializer   target_contextsuperrI   setUpr&   	__class__s    r'   rN   zTestNrtMemInfo.setUpR   s@    2333nd##))+++++r*   c                 F   t                      }|                     t           j        d           d}t          j        ||          }|                     |j        d           ~|                     t           j        d           |                                 |                     |j        d           |                     t           j        d           |                                 |                     |j        d           ~|                     t           j        d           d S )Nr!      J[=    r   )r   assertEqualr$   r   r5   refcountacquirerelease)r&   daddrmis       r'   test_meminfo_refct_1z#TestNrtMemInfo.test_meminfo_refct_1Y   s    GGa(((tQ''a(((a(((


a(((a(((


a(((a(((((r*   c                    t                      }|                     t           j        d           d}t          j        ||          }|                     |j        d           ~|                     t           j        d           t          d          D ]}|                                 |                     |j        d           |                     t           j        d           t          d          D ]}|                                 |                     |j        d           ~|                     t           j        d           d S )Nr!   rR   d   e   r   )	r   rT   r$   r   r5   rU   rangerV   rW   )r&   rX   rY   rZ   ct_s         r'   test_meminfo_refct_2z#TestNrtMemInfo.test_meminfo_refct_2j   s   GGa(((tQ''a(((a(((** 	 	BJJLLLLg...a(((s 	 	AJJLLLLa(((a(((((r*   c                    t                      }|                     t           j        d           d}t          j        ||          }|                     |j        d           t          |          }|                     |j        d           |                     ||j                   |                     |j	                   | 
                    ||j                   |                     |j                   |                     |j        d           |                     |j        d           ~~|                     t           j        d           ~|                     t           j        d           d S )Nr!   rR   r   )r   rT   r$   r   r5   rU   
memoryviewdataassertFalsereadonlyassertIsobj
assertTruec_contiguousitemsizendim)r&   rX   rY   rZ   mviews        r'   test_fake_memoryviewz#TestNrtMemInfo.test_fake_memoryview}   s=   GGa(((tQ''a(((2a(((rw'''(((b%)$$$*++++++Q'''a(((a(((((r*   c                 n   ddl m}m}m}m} t          j        t
          j                  }|j        dz  }t          j
        |d          }|j        } | ||j                   ||dz                      }	t          d          D ]#}
|                     |	j        |
         d           $t          d          D ]}
|
dz   |	j        |
<   t          |          }|                     |j        |           |                     |j                   |                     ||j                   |                     |j                   |                     |j        d           |                     |j        d           ~t          j        ||j        |j        z  |          }~t
          j                            t          j        |j                  dz   |           |dz  }t          d          D ]&}
|                     |	j        |
         |
d	z              '|                     |j         j        |           ~d S )
Nr   c_uint32c_void_pPOINTERcast
   Tsafe   K r!   dtypeshapebufferrS   )ctypesrr   rs   rt   ru   npr{   uint32rl   r   r6   re   r_   rT   contentsrd   nbytesrf   rg   rh   ri   rj   rk   rm   ndarraytestingassert_equalarangesize)r&   rr   rs   rt   ru   r{   bytesizerZ   rY   c_arrirn   arrs                r'   test_memoryviewzTestNrtMemInfo.test_memoryview   s7   <<<<<<<<<<<<##>B& 555wXXbg&&2(>(>??r 	< 	<AU^A.
;;;; r 	& 	&A !AEN12x000(((b%)$$$*++++++Q'''juELEN,J %' ' '

	#( 3 3a 7===q r 	7 	7AU^A.A6666$///CCr*   c                 f   ddl m}m}m}m} t          j        t
          j                  }|j        dz  }t          j
        |d          }|                     |j        d           |j        } | ||           ||dz                      }	t          d          D ]#}
|                     |	j        |
         d           $t          d          D ]}
|
dz   |	j        |
<   t          j        |||j        z  |          }|                     |j        d           ~t
          j                            t          j        |j                  dz   |           |dz  }t          d          D ]&}
|                     |	j        |
         |
d	z              '|                     |j         j        |           ~d S )
Nr   rq   rv   Trw   r!   ry   rz   rS   )r~   rr   rs   rt   ru   r   r{   r   rl   r   r6   rT   rU   re   r_   r   r   r   r   r   r   )r&   rr   rs   rt   ru   r{   r   rZ   rY   r   r   r   s               r'   test_bufferzTestNrtMemInfo.test_buffer   s   <<<<<<<<<<<<##>B& 555a(((wXXd^^WWX]%;%;<<r 	< 	<AU^A.
;;;; r 	& 	&A !AEN1juH,F "$ $ $a(((

	#( 3 3a 7===q r 	7 	7AU^A.A6666$///CCr*   c                 &   t           j        j        dz  dz  }dD ]v}|                     t                    5 }t          j        ||           d d d            n# 1 swxY w Y   |                     d| dt          |j	                             wd S )N   rS   TFrw   zRequested allocation of z bytes failed.)
r   size_tmaxvalr8   MemoryErrorr   r6   r<   r=   r>   )r&   r   predrB   s       r'   test_allocate_invalid_sizez)TestNrtMemInfo.test_allocate_invalid_size   s     |"a'1,! 	1 	1D"";// 56#Dt44445 5 5 5 5 5 5 5 5 5 5 5 5 5 5MMITIIIf.//1 1 1 1	1 	1s   AA	 A	c                     d}dD ]x}|                      t                    5 }t          j        ||           d d d            n# 1 swxY w Y   d| d}|                     |t          |j                             yd S )Nir   rw   z,Cannot allocate a negative number of bytes: .)r8   
ValueErrorr   r6   r<   r=   r>   )r&   r   r   rB   rD   s        r'   test_allocate_negative_sizez*TestNrtMemInfo.test_allocate_negative_size   s     ! 	6 	6D"":.. 5&#Dt44445 5 5 5 5 5 5 5 5 5 5 5 5 5 5HHHHCMM#s6#3445555		6 	6s   AA	A	)r-   r.   r/   rF   rN   r[   rb   ro   r   r   r   r   r   __classcell__rP   s   @r'   rI   rI   M   s         , , , , ,) ) )") ) )&) ) ),$ $ $R  H 1 1 ]16 6 6 6 6 6 6r*   rI   c                       e Zd ZdZd Zd ZdS )TestTracemalloczB
    Test NRT-allocated memory can be tracked by tracemalloc.
    c                 n   	 dd l }n%# t          $ r |                     d           Y nw xY w|                                 	 |                                } |            }|                                }~|                    |d          |                                 S # |                                 w xY w)Nr   ztracemalloc not availablelineno)tracemallocImportErrorskipTeststarttake_snapshot
compare_tostop)r&   funcr   beforeresafters         r'   measure_memory_diffz#TestTracemalloc.measure_memory_diff   s    	7 	7 	7 	7MM566666	7	 ..00F$&&C--//E##FH55Ks    ))AB B4c                 z  	 dt           j        	t          	fd            fd}fd}|j        j        dz   }              |                     |          }|d         }|                     |j                   |                     |j        dz  d	           |j	        d         }| 
                    t          j                            |j                  d
           | 
                    |j        |           |                     |          }|d         }|                     |j        dz             d S )Ni@B c                  .    t          j                   S )z<
            Allocate and return a large array.
            )r   empty)Nr{   s   r'   alloc_nrt_memoryz7TestTracemalloc.test_snapshot.<locals>.alloc_nrt_memory  s    
 8Au%%%r*   c                                    S Nr0   r   s   r'   keep_memoryz2TestTracemalloc.test_snapshot.<locals>.keep_memory  s    ##%%%r*   c                                     d S r   r0   r   s   r'   release_memoryz5TestTracemalloc.test_snapshot.<locals>.release_memory  s    r*   r!   r   g=
ףp=?zpUnexpected allocation overhead encountered. May be due to difference in CPython builds or running under coverage)rD   ztest_nrt.pyg{Gz?)r   int8r   __code__co_firstlinenor   assertGreaterEqualr   
assertLess	tracebackrT   ospathbasenamefilenamer   )
r&   r   r   alloc_linenodiffstatframer   r   r{   s
          @@@r'   test_snapshotzTestTracemalloc.test_snapshot
  s~   		& 	& 	& 	& 	& 
	&	& 	& 	& 	& 	&	 	 	 	 	 #+:Q> 	 ''44Aw	1---	1u9@ 	 	B 	B 	B q!))%.99=III|444 ''77Aw	1t8,,,,,r*   N)r-   r.   r/   rF   r   r   r0   r*   r'   r   r      s<            (- (- (- (- (-r*   r   c                   F    e Zd Zd Zd Zd Zd Zej        d             Z	dS )TestNRTIssuec                 <   t           d             t           fd            t           fd            }d}t          j                            |df          } |||          }|                    ||          }t          j                            ||           dS )zO
        GitHub Issue #1244 https://github.com/numba/numba/issues/1244
        c                 F    | \  }}t          j        |dz  |dz  z             S )NrS   )mathsqrt)vectorxys      r'   calculate_2D_vector_magzNTestNRTIssue.test_issue_with_refct_op_pruning.<locals>.calculate_2D_vector_mag:  s'    DAq9Q!Va1f_---r*   c                     t          j        dt           j                  } |           }| \  }}||z  |d<   ||z  |d<   |S NrS   r{   r   r!   )r   r   float64)r   normalized_vectormagr   r   r   s        r'   normalize_2D_vectorzJTestNRTIssue.test_issue_with_refct_op_pruning.<locals>.normalize_2D_vector@  sW     ""* = = =))&11CDAq#$s7a #$s7a $$r*   c                     t          j        | dft           j                  }t          |           D ]/}||         } |          }|d         ||df<   |d         ||df<   0|S r   )r   r   r   r_   )num_vectorsvectorsnormalized_vectorsr   r   r   r   s         r'   normalize_vectorszHTestNRTIssue.test_issue_with_refct_op_pruning.<locals>.normalize_vectorsL  s    !#;*:"*!M!M!M;'' @ @ $7$7$?$?!+<Q+?"1a4(+<Q+?"1a4((%%r*   rv   rS   N)r   r   randompy_funcr   assert_almost_equal)r&   r   r   test_vectorsgotexpectedr   r   s         @@r'    test_issue_with_refct_op_pruningz-TestNRTIssue.test_issue_with_refct_op_pruning6  s     
	. 	. 
	.
 
		% 		% 		% 		% 
		% 
	& 	& 	& 	& 
	& y''a(899\::$,,[,GG

&&x55555r*   c                 h   d }t          |dt          j        t          j        t          j        t          j        dd          f                    }|                                \  }}|                     |d           |                     |t          j	        dt          j                             d S )Nc                  F    dt          j        dt           j                  fS )Ng        r!   r   )r   zerosint32r0   r*   r'   fz.TestNRTIssue.test_incref_after_cast.<locals>.fd  s    "(33333r*   r0   r!   Cy                r   )
r   r   Tuple
complex128Arrayr   entry_pointassertPreciseEqualr   r   )r&   r   creszr   s        r'   test_incref_after_castz#TestNRTIssue.test_incref_after_casta  s    	4 	4 	4
  2 %U-=-2[a-M-M-/ !0 !0" "
 !!##32&&&RXarx%@%@%@AAAAAr*   c                     t           d             } |            \  }}t          j                            ||           t          j                            |t          j        dt          j                             d S )Nc                      t          j        dt           j                  } t          j        dt           j                  }| |d d          fS )Nrv   r   )r   onesr   )abs     r'   r   z5TestNRTIssue.test_refct_pruning_issue_1511.<locals>.fs  s?    "*---A"*---Aad7Nr*   rv   r   )r   r   r   r   r   r   )r&   r   r   r   s       r'   test_refct_pruning_issue_1511z*TestNRTIssue.test_refct_pruning_issue_1511r  ss    		 	 
	
 qss1

1%%%

272RZ#@#@#@AAAAAr*   c                     t           d             }t          j        g dg          }|                    |dd          } ||dd          }|                     ||           d S )Nc                     t          j        | dk              }t          |d                   dk    rd}d}n|d         d         }|d         d         }|dz
  |z   }|dz
  |z   }||fS )Nr!   r   )r   wherelen)imager   r   next_locy_offsetx_offset
next_loc_x
next_loc_ys           r'   udtz7TestNRTIssue.test_refct_pruning_issue_1526.<locals>.udt~  sy    x
++H8A;1$$#A;q>#A;q>a%8+Ja%8+Jz))r*   )
r!   r   r!   r   r!   r   r   r!   r   r   r!      )r   r   arrayr   rT   )r&   r  r   expectr   s        r'   test_refct_pruning_issue_1526z*TestNRTIssue.test_refct_pruning_issue_1526}  sx    		* 	* 
	* H444566Q1%%c!Qll%%%%%r*   c                 B   ddl m} |                     t          j                   |d             }|                     t          j                   |                      |            |                                           |                     t          j                   d S )Nr   r   c                      dS )N{   r0   r0   r*   r'   fooz8TestNRTIssue.test_no_nrt_on_njit_decoration.<locals>.foo  s    3r*   )numbar   rf   r   r:   rT   r   rj   )r&   r   r
  s      r'   test_no_nrt_on_njit_decorationz+TestNRTIssue.test_no_nrt_on_njit_decoration  s     	 	%%% 
	 	 
	 	%%% 	... 	$$$$$r*   N)
r-   r.   r/   r   r   r   r  r   run_test_in_subprocessr  r0   r*   r'   r   r   5  sv        )6 )6 )6VB B B"	B 	B 	B& & &. $% % %$% % %r*   r   c                   p    e Zd ZdZd Z ej        d          d             Zee	d                         Z
dS )TestRefCtPruninga  
define i32 @"MyFunction"(i8** noalias nocapture %retptr, { i8*, i32 }** noalias nocapture %excinfo, i8* noalias nocapture readnone %env, double %arg.vt.0, double %arg.vt.1, double %arg.vt.2, double %arg.vt.3, double %arg.bounds.0, double %arg.bounds.1, double %arg.bounds.2, double %arg.bounds.3, i8* %arg.xs.0, i8* nocapture readnone %arg.xs.1, i64 %arg.xs.2, i64 %arg.xs.3, double* nocapture readonly %arg.xs.4, i64 %arg.xs.5.0, i64 %arg.xs.6.0, i8* %arg.ys.0, i8* nocapture readnone %arg.ys.1, i64 %arg.ys.2, i64 %arg.ys.3, double* nocapture readonly %arg.ys.4, i64 %arg.ys.5.0, i64 %arg.ys.6.0, i8* %arg.aggs_and_cols.0.0, i8* nocapture readnone %arg.aggs_and_cols.0.1, i64 %arg.aggs_and_cols.0.2, i64 %arg.aggs_and_cols.0.3, i32* nocapture %arg.aggs_and_cols.0.4, i64 %arg.aggs_and_cols.0.5.0, i64 %arg.aggs_and_cols.0.5.1, i64 %arg.aggs_and_cols.0.6.0, i64 %arg.aggs_and_cols.0.6.1) local_unnamed_addr {
entry:
tail call void @NRT_incref(i8* %arg.xs.0)
tail call void @NRT_incref(i8* %arg.ys.0)
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0)
%.251 = icmp sgt i64 %arg.xs.5.0, 0
br i1 %.251, label %B42.preheader, label %B160

B42.preheader:                                    ; preds = %entry
%0 = add i64 %arg.xs.5.0, 1
br label %B42

B42:                                              ; preds = %B40.backedge, %B42.preheader
%lsr.iv3 = phi i64 [ %lsr.iv.next, %B40.backedge ], [ %0, %B42.preheader ]
%lsr.iv1 = phi double* [ %scevgep2, %B40.backedge ], [ %arg.xs.4, %B42.preheader ]
%lsr.iv = phi double* [ %scevgep, %B40.backedge ], [ %arg.ys.4, %B42.preheader ]
%.381 = load double, double* %lsr.iv1, align 8
%.420 = load double, double* %lsr.iv, align 8
%.458 = fcmp ole double %.381, %arg.bounds.1
%not..432 = fcmp oge double %.381, %arg.bounds.0
%"$phi82.1.1" = and i1 %.458, %not..432
br i1 %"$phi82.1.1", label %B84, label %B40.backedge

B84:                                              ; preds = %B42
%.513 = fcmp ole double %.420, %arg.bounds.3
%not..487 = fcmp oge double %.420, %arg.bounds.2
%"$phi106.1.1" = and i1 %.513, %not..487
br i1 %"$phi106.1.1", label %B108.endif.endif.endif, label %B40.backedge

B160:                                             ; preds = %B40.backedge, %entry
tail call void @NRT_decref(i8* %arg.ys.0)
tail call void @NRT_decref(i8* %arg.xs.0)
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0)
store i8* null, i8** %retptr, align 8
ret i32 0

B108.endif.endif.endif:                           ; preds = %B84
%.575 = fmul double %.381, %arg.vt.0
%.583 = fadd double %.575, %arg.vt.1
%.590 = fptosi double %.583 to i64
%.630 = fmul double %.420, %arg.vt.2
%.638 = fadd double %.630, %arg.vt.3
%.645 = fptosi double %.638 to i64
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0)              ; GONE 1
tail call void @NRT_decref(i8* null)                                ; GONE 2
tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 3
%.62.i.i = icmp slt i64 %.645, 0
%.63.i.i = select i1 %.62.i.i, i64 %arg.aggs_and_cols.0.5.0, i64 0
%.64.i.i = add i64 %.63.i.i, %.645
%.65.i.i = icmp slt i64 %.590, 0
%.66.i.i = select i1 %.65.i.i, i64 %arg.aggs_and_cols.0.5.1, i64 0
%.67.i.i = add i64 %.66.i.i, %.590
%.84.i.i = mul i64 %.64.i.i, %arg.aggs_and_cols.0.5.1
%.87.i.i = add i64 %.67.i.i, %.84.i.i
%.88.i.i = getelementptr i32, i32* %arg.aggs_and_cols.0.4, i64 %.87.i.i
%.89.i.i = load i32, i32* %.88.i.i, align 4, !noalias !3
%.99.i.i = add i32 %.89.i.i, 1
store i32 %.99.i.i, i32* %.88.i.i, align 4, !noalias !3
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 4
tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0)              ; GONE 5
br label %B40.backedge

B40.backedge:                                     ; preds = %B108.endif.endif.endif, %B84, %B42
%scevgep = getelementptr double, double* %lsr.iv, i64 1
%scevgep2 = getelementptr double, double* %lsr.iv1, i64 1
%lsr.iv.next = add i64 %lsr.iv3, -1
%.294 = icmp sgt i64 %lsr.iv.next, 1
br i1 %.294, label %B42, label %B160
}
    c                 X   | j         }t          |                                          }d |D             }d |D             }t          j        |          }t          |                                          }d |D             }d |D             }|                     ||           |                     ||           t          |          t          |          z
  }	t          |          t          |          z
  }
|	|
z  }|                     ||	|
z             d                    |          }dD ]-}d	                    |          }| 
                    ||           .|                     t          t          |                                                    t          |                     d S )Nc                     g | ]}d |v |	S 
NRT_increfr0   .0lns     r'   
<listcomp>zDTestRefCtPruning.test_refct_pruning_op_recognize.<locals>.<listcomp>  "    IIIlb6H6H"6H6H6Hr*   c                     g | ]}d |v |	S 
NRT_decrefr0   r  s     r'   r  zDTestRefCtPruning.test_refct_pruning_op_recognize.<locals>.<listcomp>  r  r*   c                     g | ]}d |v |	S r  r0   r  s     r'   r  zDTestRefCtPruning.test_refct_pruning_op_recognize.<locals>.<listcomp>   "    IIIlb6H6H6H6H6Hr*   c                     g | ]}d |v |	S r  r0   r  s     r'   r  zDTestRefCtPruning.test_refct_pruning_op_recognize.<locals>.<listcomp>  r  r*   
)r!   rS            z	; GONE {})sample_llvm_irlist
splitlinesr	   _remove_redundant_nrt_refctassertNotEqualsetrT   joinformatr<   r   )r&   input_irinput_linesbefore_increfsbefore_decrefs	output_iroutput_linesafter_increfsafter_decrefspruned_increfspruned_decrefscombinedpruned_linesr   gones                  r'   test_refct_pruning_op_recognizez0TestRefCtPruning.test_refct_pruning_op_recognize  s   &8..0011II{IIIII{III 6x@@	I002233IIlIIIIIlIII 	NM:::NM:::^,,s=/A/AA^,,s=/A/AA "N2>N#BCCCyy** ! 	. 	.A%%a((DMM$----T,"9"9";";<<==s8}}MMMMMr*   z3Pass removed as it was buggy. Re-enable when fixed.c                    t           d             t           d             t           fd            t          d          fd            }|                    d           t          |                    |j        d                             }t          t          j        d	|                    }|                     t          |          d           d
S )ztestcase from #2350c                 V    t          j        |          s||| fxx         dz  cc<   d S d S r    r   isnanr   r   aggfields       r'   _append_non_nazITestRefCtPruning.test_refct_pruning_with_branches.<locals>._append_non_na  s9    8E?? AqD			Q					 r*   c                     t          j        |          s9t          j        ||| f                   r	|||| f<   d S ||| fxx         |z  cc<   d S d S r   r;  r=  s       r'   _appendzBTestRefCtPruning.test_refct_pruning_with_branches.<locals>._append  se    8E?? '8C1I&& ' %C1III1III&IIIII	' 'r*   c                 @     | |||            | |||           d S r   r0   )r   r   r>  r?  rB  r@  s       r'   appendzATestRefCtPruning.test_refct_pruning_with_branches.<locals>.append&  s5    N1ae,,,GAq#u%%%%%r*   T)no_cpython_wrapperc                     t          | j        d                   D ]-}t          | j        d                   D ]} ||| |           .d S )Nr   r!   )r_   r|   )r   r?  r   jrD  s       r'   extendzATestRefCtPruning.test_refct_pruning_with_branches.<locals>.extend-  se    39Q<(( - -sy|,, - -AF1ae,,,,-- -r*   z(f4[:,::1], f4)r   z!(NRT_incref|NRT_decref)\([^\)]+\)N)
r   compiler=   inspect_llvm
signaturesr$  refinditerrT   r   )r&   rH  llvmirrefopsrB  r@  rD  s       @@@r'    test_refct_pruning_with_branchesz1TestRefCtPruning.test_refct_pruning_with_branches  s    
	 	 
	 
	' 	' 
	' 
	& 	& 	& 	& 	& 
	& 
	&	&	&	- 	- 	- 	- 
'	&	- 	())) V(():1)=>>??bk"FOOPPVa(((((r*   c                 4   t          j                     t          j                     t          j                     t          j                     t
          d             t          dg          fd            }|                      |d          d           dS )ztThe InlineAsm class from llvmlite.ir has no 'name' attr the refcount
        pruning pass should be tolerant to thisc                 j    d }t          t          j        t          j        t          j                  |fS )Nc                    |\  }}t          j        t          j        d          t          j        d          t          j        d          g          }|                    |dd||fdd          }t	          | ||j        |          S )N    zmov $2, $0; imul $1, $0z=&r,r,rasm_mulF)nameside_effect)r   FunctionTypeIntTypeasmr   return_type)cgctxbuildersigrA   arg_0arg_1ftymuls           r'   codegenz>TestRefCtPruning.test_inline_asm.<locals>.bar.<locals>.codegenG  s    !%objnnrz"~~79z"~~7G H Hkk#'@)#(%.y.3 " 5 5 *%#/3OOOr*   )r   r   r   )tyctxr   r   rc  s       r'   barz-TestRefCtPruning.test_inline_asm.<locals>.barE  s3    P P P U[%+u{CCWLLr*   zint32(int32)c                 *    | dz  }  | d          }|S )Nr!   rS   r0   )r   r   re  s     r'   r
  z-TestRefCtPruning.test_inline_asm.<locals>.fooQ  s     FAAq		AHr*   rv      N)llvmrK   initialize_native_targetinitialize_native_asmprinterinitialize_native_asmparserr   r   rT   )r&   r
  re  s     @r'   test_inline_asmz TestRefCtPruning.test_inline_asm;  s    
 	%''')+++(***			M 		M 
		M 
~			 	 	 	 
 		
 	R"%%%%%r*   N)r-   r.   r/   r#  r8  unittestskiprP  
linux_onlyx86_onlyrl  r0   r*   r'   r  r    s        FNPN N N> X]HII") ") JI")H & & X Z& & &r*   r  zcffi requiredc                   @     e Zd ZdZ fdZd Zd Zd Zd Zd Z	 xZ
S )TestNrtExternalCFFIz?Testing the use of externally compiled C code that use NRT
    c                 n    t           j         t          t          |                                            d S r   )r   rL   rM   rr  rN   rO   s    r'   rN   zTestNrtExternalCFFI.setUp^  s/    !!!4((..00000r*   c                    ddl m}  |            }|                    ||t                      g           |                    |           t          d                    |                    }|                    |           t          j	        
                    |           	 t          |          }t          j	                            |           n$# t          j	                            |           w xY w||fS )Nr   FFI)include_dirszcffi_test_{})tmpdir)cffirv  
set_sourcer   cdefr   r*  rI  sysr   rD  r   remove)r&   rV  sourcer{  rv  ffirx  mods           r'   compile_cffi_modulez'TestNrtExternalCFFI.compile_cffi_modulec  s    ceetV<>>2BCCC 5 5d ; ;<<6"""	$ &&CHOOF####CHOOF####Cxs   #C !C3c                     ddl m}  |            }|                    dt          j        d                   } |            }|S )Nr   ru  zvoid* (*)()get_api)ry  rv  ru   r
   	c_helpers)r&   rv  r  nrt_get_apitables        r'   get_nrt_api_tablez%TestNrtExternalCFFI.get_nrt_api_tables  sJ    ceehh}k.CI.NOOr*   c                 B   d                     | j        j                  }d}d}|                     |||          \  }}|                     |j        j        d           |                                 }|j                            |          }|                     |j        j        d           t          |
                    d|                    }t          j        |          }	|                     |	j        d           ~	|                     |j        j        d           d S )	Nz{}_test_manage_memoryaz  
#include <stdio.h>
#include "numba/core/runtime/nrt_external.h"

int status = 0;

void my_dtor(void *ptr) {
    free(ptr);
    status = 0xdead;
}

NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt) {
    void * data = malloc(10);
    NRT_MemInfo *mi = nrt->manage_memory(data, my_dtor);
    nrt->acquire(mi);
    nrt->release(mi);
    status = 0xa110c;
    return mi;
}
        z;
void* test_nrt_api(void *nrt);
extern int status;
        r   i
 r   r!   i  )r*  rP   r-   r  rT   libstatusr  test_nrt_apiintru   r   MemInforU   )
r&   rV  r~  r{  r  r  r  outmi_addrrZ   s
             r'   test_manage_memoryz&TestNrtExternalCFFI.test_manage_memory{  s   &--dn.EFF(
 ++D&$??S+++&&((g""5))111chhx--..[!!a(((00000r*   c                    d                     | j        j                  }d}d}|                     |||          \  }}|                                 }dt          j        t
          j                  j        z  }|j	        
                    ||          }t          |                    d|                    }	t          j        |	          }
|                     |
j        d           |                    |                    d                     |          |
j                            }t          j        dt
          j        |	          }t
          j                            |g d
           d S )Nz{}_test_allocatea7  
#include <stdio.h>
#include "numba/core/runtime/nrt_external.h"

NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt, size_t n) {
    size_t *data = NULL;
    NRT_MemInfo *mi = nrt->allocate(n);
    data = nrt->get_data(mi);
    data[0] = 0xded;
    data[1] = 0xabc;
    data[2] = 0xdef;
    return mi;
}
        z(void* test_nrt_api(void *nrt, size_t n);r   r   r!   z	char [{}])r   )r|   r{   r}   )i  i
  i  )r*  rP   r-   r  r  r   r{   intprl   r  r  r  ru   r   r  rT   rU   r}   re   r   r   r   )r&   rV  r~  r{  r  r  r  numbytesr  r  rZ   r}   r   s                r'   test_allocatez!TestNrtExternalCFFI.test_allocate  s2   !(()@AA :++D&$??S&&((rx((11g""5(33chhx--..[!!a(((CHH[%7%7%A%A27KKLLjt276BBB

%:%:%:;;;;;r*   c                     ddl m} t          d             } |            }t          |                    d|                                                     } |            }|                     ||           d S )Nr   ru  c                      t                      S r   r   r0   r*   r'   r  z6TestNrtExternalCFFI.test_get_api.<locals>.test_nrt_api  s    == r*   r   )ry  rv  r   r  ru   r  rT   )r&   rv  r  r  r  r   s         r'   test_get_apiz TestNrtExternalCFFI.test_get_api  s    		! 	! 
	! ceeSXXh(>(>(@(@AABBlnn%%%%%r*   )r-   r.   r/   rF   rN   r  r  r  r  r  r   r   s   @r'   rr  rr  Z  s         1 1 1 1 1
     '1 '1 '1R< < <@
& 
& 
& 
& 
& 
& 
&r*   rr  c                   D    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )TestNrtStatisticsc                 6    t          j                    | _        d S r   )r
   memsys_stats_enabled_TestNrtStatistics__stats_stater%   s    r'   rN   zTestNrtStatistics.setUp  s    (=??r*   c                 d    | j         rt          j                     d S t          j                     d S r   )r  r
   memsys_enable_statsmemsys_disable_statsr%   s    r'   tearDownzTestNrtStatistics.tearDown  s7     	/+-----,.....r*   c                 r    d}t           j                                        }d|d<   t          ||           d S )Na  if 1:
        from numba import njit
        import numpy as np
        from numba.core.runtime import rtsys, _nrt_python
        from numba.core.registry import cpu_target

        @njit
        def foo():
            return np.arange(10)[0]

        # initialize the NRT before use
        rtsys.initialize(cpu_target.target_context)
        assert _nrt_python.memsys_stats_enabled()
        orig_stats = rtsys.get_allocation_stats()
        foo()
        new_stats = rtsys.get_allocation_stats()
        total_alloc = new_stats.alloc - orig_stats.alloc
        total_free = new_stats.free - orig_stats.free
        total_mi_alloc = new_stats.mi_alloc - orig_stats.mi_alloc
        total_mi_free = new_stats.mi_free - orig_stats.mi_free

        expected = 1
        assert total_alloc == expected
        assert total_free == expected
        assert total_mi_alloc == expected
        assert total_mi_free == expected
        1NUMBA_NRT_STATSenv)r   environcopyr   )r&   srcr  s      r'   test_stats_env_var_explicit_onz0TestNrtStatistics.test_stats_env_var_explicit_on  s@    8 joo!$#3''''''r*   c                 ,    d}t          ||           d S )Na  if 1:
        from numba import njit
        import numpy as np
        from numba.core.runtime import rtsys, _nrt_python

        @njit
        def foo():
            return np.arange(10)[0]

        assert _nrt_python.memsys_stats_enabled() == False
        try:
            rtsys.get_allocation_stats()
        except RuntimeError as e:
            assert "NRT stats are disabled." in str(e)
        r  )r   )r&   r  r  s      r'   check_env_var_offz#TestNrtStatistics.check_env_var_off   s$     	#3''''''r*   c                 v    t           j                                        }d|d<   |                     |           d S )N0r  )r   r  r  r  r&   r  s     r'   test_stats_env_var_explicit_offz1TestNrtStatistics.test_stats_env_var_explicit_off  s8    joo!$s#####r*   c                     t           j                                        }|                    dd            |                     |           d S )Nr  )r   r  r  popr  r  s     r'   test_stats_env_var_default_offz0TestNrtStatistics.test_stats_env_var_default_off  sD     joo!4(((s#####r*   c                    t           d             }t          j                     |                     t          j                               t          d          D ]}t          j                    }t          j                     | 	                    t          j                                |             t          j                     |                     t          j                               t          j                    } |             t          j                    }| 
                    ||           |                     ||           d S )Nc                  d    t          j        d          } t          j        d| d         z            S )Nr   r"  r   )r   r   r   )tmps    r'   r
  z7TestNrtStatistics.test_stats_status_toggle.<locals>.foo"  s'    '!**C9QQZ(((r*   rS   )r   r
   r  rj   r  r_   r   get_allocation_statsr  rf   rT   r   )r&   r
  r   stats_1stats_2stats_3s         r'   test_stats_status_togglez*TestNrtStatistics.test_stats_status_toggle   s)   		) 	) 
	)
 	')))8::;;;q 	. 	.A022G,...[=??@@@CEEE+---OOK<>>???022GCEEE022GWg...OOGW-----	. 	.r*   c                 R   t          j                     |                     t          j                               |                     t
                    5 }t          j                     d d d            n# 1 swxY w Y   |                     dt          |j
                             d S )NNRT stats are disabled.)r
   r  rf   r  r8   r9   r   r  r<   r=   r>   )r&   rB   s     r'   5test_rtsys_stats_query_raises_exception_when_disabledzGTestNrtStatistics.test_rtsys_stats_query_raises_exception_when_disabledD  s     	(***9;;<<<|,, 	)&(((	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	) 	/V5E1F1FGGGGGs   A44A8;A8c                    d}|D ]}t          t          d|           }|                     |          5  t          j                     |                     t          j                               |                     t                    5 } |             d d d            n# 1 swxY w Y   |                     dt          |j
                             d d d            n# 1 swxY w Y   d S )N)allocfreemi_allocmi_freememsys_get_stats_)
stats_funcr  )r;   r
   subTestr  rf   r  r8   r9   r<   r=   r>   )r&   method_variationsr@   r  rB   s        r'   <test_nrt_explicit_stats_query_raises_exception_when_disabledzNTestNrtStatistics.test_nrt_explicit_stats_query_raises_exception_when_disabledP  sx    E% 	P 	PD .H$.H.HIIJ44 P P0222  !A!C!CDDD&&|44 !JLLL! ! ! ! ! ! ! ! ! ! ! ! ! ! !7V=M9N9NOOOP P P P P P P P P P P P P P P	P 	Ps6   AC	B C B$$C'B$(+CC#	&C#	N)r-   r.   r/   rN   r  r  r  r  r  r  r  r  r0   r*   r'   r  r    s        @ @ @/ / / (  (  (D( ( (&$ $ $$ $ $". ". ".H
H 
H 
HP P P P Pr*   r  __main__)Cr   r   platformr|  rL  numpyr   r  r   
numba.corer   numba.core.compilerr   r   numba.core.runtimer   r	   r
   r   numba.core.extendingr   r   numba.core.typingr   numba.core.imputilsr   llvmliter   llvmlite.bindingbindingrh  numba.core.typing.cffi_utilscoretyping
cffi_utilscffi_supportnumba.core.unsafe.nrtr   numba.tests.supportr   r   r   r   r   r   numba.core.registryr   rm  enable_nrt_flagsskipIf
startswithro  machinerp  objectr   r2   rI   r   r   r  
skipUnless	SUPPORTEDrr  r  r-   mainr0   r*   r'   <module>r     s    				  



 				                 7 7 7 7 7 7 7 7            9 8 8 8 8 8 8 8 ' ' ' ' ' ' 2 2 2 2 2 2             3 3 3 3 3 3 3 3 3 3 3 3 - - - - - -4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 + * * * * * 577   X_!8!8!A!AA.0 0
8?+8+--5GG*, ,    F   # # # # #8#4 # # #4e6 e6 e6 e6 e6X& e6 e6 e6P=- =- =- =- =-h' =- =- =-@u% u% u% u% u%8 u% u% u%pj& j& j& j& j&x( j& j& j&Z \+_==s& s& s& s& s&-x s& s& >=s&lKP KP KP KP KP KP KP KP\ zHMOOOOO r*   