
    9j
                       d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
mZmZmZmZ ddlmZmZmZmZ ddlmZ ddlmZmZmZmZ ddlmZ erdd	lmZ  ej>                  d
       G d d             Z  ej>                  d
       G d d             Z!ejD                  dk\  rdejB                  de!fdZ#n4ejD                  dk\  rdejB                  de!fdZ#ndejB                  de!fdZ# G d d      Z$ejD                  dk\  r	de%de&fdZ'n ejD                  dk\  r	de%de&fdZ'nde%de&fdZ'de$ddde%de(dz  d edz  d!e!dz  de!f
d"Z)d!e!de!fd#Z*d!e!de&fd$Z+dd%ed&e&de!fd'Z,de-e!   fd(Z.de!fd)Z/d*e(de-e!   fd+Z0d,e!e-e!   z  de-e!   fd-Z1d,e!e-e!   z  de-e!   fd.Z2d/e(d0e&de-e!   fd1Z3	 dd2e&d0e&d3e&de-e!   fd4Z4d/e(de-e!   fd5Z5de%de!fd6Z6d!e!de!fd7Z7d*e(de-e!   fd8Z8	 dd9e(dz  d:e(dz  d;e&de-e!   fd<Z9de(de-e!   fd=Z:d>e(de-e!   fd?Z;d@ede-e!   fdAZ<de!fdBZ=d*e(de!fdCZ>dDe(de?e-e(   e
e(e(gdf   e
e(gdf   f   fdEZ@d*e(de-e(   fdFZAejD                  dk\  r$dDe(de?e-e(   e
ej                  dz  e(gdf   f   fdGZC ej>                  d
       G dH dI             ZDd*e(de-e(   fdJZEdKee(   de(fdLZFdMe-eD   ddfdNZGdOeHde-eD   fdPZIdMe-eD   deHfdQZJdRe-e!   dSe(de?eHeHf   fdTZKdUeLe(e!f   dVe(de!dz  fdWZMdRee!   ddfdXZN eOej                        ZQdYe!ddfdZZRdRe-e!   d[e(de!fd\ZSdRe-e!   ddfd]ZTd^eHdRe-e!   ddfd_ZUdRe-e!   de-eD   fd`ZVdMe-e    daeLe!e(f   ddfdbZWdRe-e!   ddfdcZXdRe-e!   ddfddZYdRe-e!   ddfdeZZdfe!dge-e!   de-e!   fdhZ[dRe-e!   de-e!   fdiZ\dRe-e!   ddfdjZ]dRe-e!   ddfdkZ^dldmdndodpZ_dRe-e!   ddfdqZ`dRe-e!   ddfdrZadRe-e!   ddfdsZbdtej                  dRe-e!   ddfduZddRe-e!   de(fdvZedwe!de(fdxZfdRee!   ddfdyZgdRee!   ddfdzZhd{eHde%fd|Zidtej                  ddfd}Zj eOej                        Zl eOej                        Zn eOej                        Zp eOej                        Zrd~eLe%ef   d%ede(fdZs	 ddRe-e!   d~eLe%ef   de
def   dz  ddfdZtdRe-e!   ddfdZuej                  de-e%   fd       Zw	 ddtej                  de
e-e!   eLe%ef   ged   f   de&de?ej                  ed   f   fdZxdRe-e!   de-e%   d~eLe%ef   de?e-e!   ej                  f   fdZydRee!   deddfdZzddtej                  de&de-e!   fdZ{dRee!   de-e!   fdZ|ej                  	 ddtej                  de&dee!   fd       Z} ej                         Zdde%de&de%fdZdtej                  de&fdZ	 	 	 dde
def   deeef   dz  de&de&de-e!   f
dZy)a  
This module provides utilities for analyzing, transforming and manipulating Python bytecode.
It includes functionality for:
- Converting between different bytecode formats and versions
- Virtualizing jumps and managing jump targets
- Handling exception tables and their entries
- Managing instruction offsets and extended arguments
- Providing a clean API for bytecode modification and transformation
- Supporting Python version-specific bytecode features
- Generating bytecode from template functions

The module is designed to work across different Python versions (3.7+) and handles
version-specific bytecode differences transparently.
    N)CallableIterableIteratorMappingSequence)AnycastOptionalTYPE_CHECKING   )config)get_indexofpropagate_line_numsremove_extra_line_numsstacksize_analysis)is_safe_constant)DynamoTracerOutputT)slotsc                   \    e Zd ZU ded<   ded<   ded<   eed<   eed<   defdZd	edefd
Z	y)InstructionExnTabEntryInstructionstartendtargetdepthlastireturnc                     d| j                   j                          d| j                  j                          d| j                  j                          d| j                   d| j
                   dS )NzInstructionExnTabEntry(start=z, end=z	, target=z, depth=z, lasti=))r   short_inst_reprr   r   r   r   selfs    e/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/torch/_dynamo/bytecode_transformation.py__repr__zInstructionExnTabEntry.__repr__1   sl    +DJJ,F,F,H+I J88++-. /kk1134 5ZZLA7	
    oc                 (   t        |t              sy| j                  |j                  u xrh | j                  |j                  u xrN | j                  |j                  u xr4 | j
                  |j
                  k(  xr | j                  |j                  k(  S NF)
isinstancer   r   r   r   r   r   )r"   r&   s     r#   __eq__zInstructionExnTabEntry.__eq__9   s}    !34JJ!''! &AEE!&qxx'& 

agg%& 

agg%	
r%   N)
__name__
__module____qualname____annotations__intboolstrr$   objectr*    r%   r#   r   r   )   s=    	JK
# 
	
 	
4 	
r%   r   c                       e Zd ZU dZeed<   eed<   edz  ed<   eed<   dZedz  ed<   dZ	edz  ed<   d	Z
eed
<   dZed   ed<   dZed    ed<   dZedz  ed<   dZedz  ed<   defdZdedefdZdefdZddZy)r   z$A mutable version of dis.InstructionopcodeopnameNargargvaloffsetstarts_lineFis_jump_targetzdis.Positions	positionsr   exn_tab_entryargreprr   c                     t        |       S Nidr!   s    r#   __hash__zInstruction.__hash__W   s    $xr%   otherc                 0    t        |       t        |      k(  S r@   rA   r"   rD   s     r#   r*   zInstruction.__eq__Z   s    $x2e9$$r%   c                 <    d| j                    d| j                   dS )NzInstruction(opname=z	, offset=r   )r6   r9   r!   s    r#   r    zInstruction.short_inst_repr]   s    $T[[M4;;-qIIr%   c                 H    |j                   | _         |j                  | _        y r@   )r:   r<   rF   s     r#   copy_positionszInstruction.copy_positions`   s     ,,r%   )rD   r   r   N)r+   r,   r-   __doc__r/   r.   r1   r   r9   r:   r;   r0   r<   r
   r   r=   r   r>   rC   r2   r*   r    rI   r3   r%   r#   r   r   E   s    .KK	tOKFC$J"Kt" ND +/Ix(/&*FH]#*37M)D07GS4Z# %F %t %J J)r%   r         ir   c           
          t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                        S r@   )	r   r5   r6   r7   r8   r9   line_numberr;   r<   rN   s    r#   convert_instructionrR   g   I    HHHHEEHHHHMMKK	
 		
r%   rL      c           
          t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                        S r@   )	r   r5   r6   r7   r8   r9   r:   r;   r<   rQ   s    r#   rR   rR   u   rS   r%   c           
          t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                  d       S r@   )r   r5   r6   r7   r8   r9   r:   r;   rQ   s    r#   rR   rR      sE    HHHHEEHHHHMM	
 		
r%   c                       e Zd ZdefdZy)_NotProvidedr   c                      y)NrY   r3   r!   s    r#   r$   z_NotProvided.__repr__   s    r%   N)r+   r,   r-   r1   r$   r3   r%   r#   rY   rY      s    # r%   rY   rL      namec                 
    | dv S )N)	LOAD_ATTRLOAD_GLOBALLOAD_SUPER_ATTRr3   r]   s    r#   inst_has_op_bitsrc      s    FFFr%   c                     | dk(  S )Nr`   r3   rb   s    r#   rc   rc      s    }$$r%   c                      yr(   r3   rb   s    r#   rc   rc      s    r%   )r7   r8   r   r7   r8   r   c                    t        |       r|t        d      |%d}n"|du|t        uz   |duz   }|dkD  rt        d      |t        |t              st        d      t        t        j                  |    | |||      S )a  
    At most one of `arg`, `argval`, and `target` can be not None/_NotProvided.
    This is to prevent ambiguity, e.g. does
        create_instruction("LOAD_CONST", 5)
    mean load the constant at co_consts[5], or load the constant 5?

    If `arg` is not provided, it will be computed during assembly from
    `argval` or `target`.

    Bits in the args of instructions LOAD_GLOBAL, LOAD_ATTR (3.12+), and LOAD_SUPER_ATTR
    modify the behavior of the instruction. In this case, we allow both `arg`
    and `argval` to be set. The value of `arg` here is expected to be the value of
    the op bits and the true value of `arg` will be computed during assembly.
    If `arg` is not set, the bits are assumed to be 0.
    Nz*target cannot be specified for instructionr   r   z@only one of arg, argval, and target can be not None/_NotProvidedz#instruction arg must be int or None)r5   r6   r7   r8   r   )rc   RuntimeErrorrY   r)   r/   r   disopmap)r]   r7   r8   r   cnts        r#   create_instructionrk      s    0 KLL;C$6#=>&PTBTU7R  z#s3@AAyytVF r%   c                 J    t         j                  dk\  rdnd}t        ||       S )NrT   JUMP_FORWARDJUMP_ABSOLUTEr   sysversion_infork   )r   insts     r#   create_jump_absolutert      s#     --8>oDd622r%   c                     | j                   dv S )N)rm   rn   )r6   ro   s    r#   is_jump_absoluterv      s    =====r%   valcheckedc                 J    |rt        |       s
J d|         t        d|       S )z
    In general we should only create `LOAD_CONST` for immutable objects, but
    sometimes it's convenient _and safe_ for Dynamo create `LOAD_CONST` for
    mutable objects. In such cases, use `checked=False`.
    zunsafe constant 
LOAD_CONSTr8   )r   rk   )rw   rx   s     r#   create_load_constr|      s/     $>(8&>>$l377r%   c                  >    ddl m}  t        d|       t        d      gS )a  
    Create instructions that trigger the bytecode debugger to stop.

    Usage:
        codegen.extend_output(create_breakpoint())

    When the bytecode debugger is active, execution will pause at this point.
    At runtime, these instructions have no effect on program state.
    r   BREAKPOINT_MARKERrz   r{   POP_TOP)bytecode_debuggerr   rk   r~   s    r#   create_breakpointr      s&     5 	<0AB9% r%   c                  X    t         j                  dk\  rt        dd      S t        d      S )NrT   COPYr   r7   DUP_TOPrp   r3   r%   r#   create_dup_topr      s(    
7"!&a00i((r%   nc                     | dk  rg S t         j                  dk\  r&t        | dd      D cg c]  }t        d|       c}S | dk  rt        dg d| d	z
     z         gS t        d
|       gS c c}w )a  
    Returns a "simple" sequence of instructions that rotates TOS to the n-th
    position in the stack. For Python < 3.11, returns a single ROT_*
    instruction. If no such instruction exists, an error is raised and the
    caller is expected to generate an equivalent sequence of instructions.
    For Python >= 3.11, any rotation can be expressed as a simple sequence of
    swaps.
    r   rT   SWAPr      ROT_)TWOTHREEFOUR   ROT_N)rq   rr   rangerk   )r   rN   s     r#   create_rot_nr      s|     	Av	
7" <AAr?Ka"6q1KKAv"6,DQU,K#KLMMwA.//	 Ls   A+inst_or_instsc                    t        | t              r| gnt        | t              sJ | dt        dt        ffd}dt        ddffd}t
        j                  dk\  r;t        d   j                        r |d      s
 |d       S t        d      gz   S t
        j                  d	k\  r_t        d   j                        r |d      s
 |d       S d
   j                  dk(  r |d
      s
 |d
       S t        d      gz   S t
        j                  dk\  r9t        d
   j                        r |d
      s
 |d
       S t        d      gz   S )a  
    Appends or prepends a PUSH_NULL instruction to `inst_or_insts`,
    depending on Python version. Used when you know that
    `inst_or_insts` generates a callable that will be called.

    NOTE: Assumes `inst_or_insts` is a single instruction or sequence of
    instructions that pushes exactly 1 object to the stack that is to
    be called. It is important that you include ALL instructions that
    construct the callable - not just the first instruction/a prefix.

    Will attempt to use the NULL push bit for instructions
    with such bits (LOAD_GLOBAL 3.11+, LOAD_ATTR 3.12+, LOAD_SUPER_ATTR).
    In this case, instructions WILL be modified.
    idxr   c                 P    |    j                   J |    j                   dz  dk(  S Nr   r   r   instss    r#   inst_has_bit_setz'add_push_null.<locals>.inst_has_bit_set*  s/    Sz~~)))Sz~~!Q&&r%   Nc                 X    |    j                   J |    xj                   dz  c_         y r   r   r   s    r#   set_inst_bitz#add_push_null.<locals>.set_inst_bit.  s)    Sz~~)))c
!r%   rK   r   	PUSH_NULLr[   r   r`   rT   )
r)   r   listr/   r0   rq   rr   rc   r6   rk   )r   r   r   r   s      @r#   add_push_nullr     su   " --$1?-...'c 'd '# $  7"E"I,,-6Fr6J & L# /<==E" L! 
		W	$ E"I,,-6Fr6J L 1X__-6Fq6IO L (45=E L 
		W	$E!HOO,5Ea5HO L (45=ELr%   c                    t        | t              r| g}nt        | t              sJ | }t        j                  dk  r|S t        j                  dk\  rdnd}||   j
                  dk(  r@||   j                  J ||   j                  dz  dk(  r||   xj                  dz  c_        |S t        j                  dk\  r|t        d      gz   }|S t        d      g|z   }|S )zLike add_push_null, but the low bit of LOAD_ATTR/LOAD_SUPER_ATTR
    is not set, due to an expected CALL_FUNCTION_EX instruction.
    rT   rK   r   r   r`   r   r   )r)   r   r   rq   rr   r6   r7   rk   )r   r   r   s      r#   add_push_null_call_function_exr   N  s     --$1?-...
'!  G+"CSzM)Sz~~))):>>A"#JNNaNL
7"+K899 L $K01E9Lr%   nargs	push_nullc                    t         j                  dk\  rg }|rQ|j                  t        d             t         j                  dk\  r| dz   n| dz   }|j	                  t        |             t         j                  dk  r|j                  t        d|              |j                  t        d	|              |S t        d
|       gS )aS  
    Creates a sequence of instructions that makes a function call.

    `push_null` is used in Python 3.11+ only. It is used in codegen when
    a function call is intended to be made with the NULL + fn convention,
    and we know that the NULL has not been pushed yet. We will push a
    NULL and rotate it to the correct position immediately before making
    the function call.

    `push_null` should be True if no NULL is pushed for the callable.
    Conversely, `push_null` should be False if a NULL was pushed for the callable.
    Prefer using `push_null=False` when possible since we will not need to rotate
    NULL to the right place, which is less efficient.

    Generally, you should codegen a function by using `add_push_null` then
    `create_call_function` with `push_null=False`.

    Example of when to set push_null False:

    insts = [
        create_instruction("LOAD_GLOBAL", argval="torch"),
        create_instruction("LOAD_ATTR", argval="nn"),
        create_instruction("LOAD_ATTR", argval="functional"),
        create_instruction("LOAD_ATTR", argval="relu"),
    ]
    insts = add_push_null(insts)
    insts.append(create_instruction("LOAD_FAST", argval="x"))
    insts.extend(create_call_function(1, False))

    Example of when to set push_null True:

    insts = [create_instruction("LOAD_FAST", x)]
    for should_wrap, wrapper_name in wrappers:
        if should_wrap:
            insts.extend([
                create_instruction("LOAD_GLOBAL", argval="wrapper1"),
                create_instruction("SWAP", arg=2),
                *create_call_function(1, True),
            )
    rT   r   rK   r   r   r[   PRECALLr   CALLCALL_FUNCTION)rq   rr   appendrk   extendr   )r   r   outputrotss       r#   create_call_functionr   l  s    R 7"MM,[9: # 0 0G ;519DMM,t,-g%MM,YEBC(U;<E:;;r%   
has_kwargsignore_314_kwargs_pushc                    t         j                  dk\  rg }t         j                  dk\  r | s|s|j                  t        d             d} |rc|j                  t        d             t         j                  dk\  rt	        |       dz   nt	        |       dz   }|j                  t        |             |j                  t        dt	        |       	             |S t        dt	        |       	      gS )
a(  
    Assumes that in 3.14+, if has_kwargs=False, there is NOT a NULL
    on the TOS for the kwargs. This utility function will add a PUSH_NULL.

    If the caller has already pushed a NULL for the kwargs, then set ignore_314_kwargs_push=True
    so we don't push another NULL for the kwargs.
    rT   rL      r   TrK   r   rL   CALL_FUNCTION_EXr   )rq   rr   r   rk   r/   r   r   )r   r   r   r   r   s        r#   create_call_function_exr     s     7"'*MM,[9:JMM,[9:
 ##w. J!#_q( 
 MM,t,-();ZQR1s:GHHr%   c                     t         j                  dk\  rt        d|       gS t         j                  dk\  rt        d|       t        d|       gS t        d|       gS )Nr[   r   r   rT   r   CALL_METHODrp   )r   s    r#   create_call_methodr     s^    
7""6u566
7"ye4v51
 	
 }%899r%   c                 ^    t         j                  dk\  rt        dd|       S t        d|       S )Nr[   r_   r   )r7   r8   LOAD_METHODr{   rp   rb   s    r#   create_load_methodr     s,    
7"!+1TBBmD99r%   c                 J    t         j                  dk\  rdnd}t        ||       S )NrT   BEFORE_WITH
SETUP_WITHro   rp   )r   r6   s     r#   create_setup_withr     s#    !..'9]|FfV44r%   c                    t         j                  dk\  rt        d|       gS | dk(  rg S | dk(  rt        d      gS | dk(  rt        d      t        d      gS 	 t        d	| dz
        t        d
      t        dd      t               t        d      t        d
      t        d      t        dd      t        d      t        d
      t	        d      gt        d      t        d      t        d| dz
        S )NrT   r   r   r   r   ROT_TWOrL   	ROT_THREE
BUILD_LISTr   rz   r   r{   STORE_SUBSCRreverser   r   UNPACK_SEQUENCE)rq   rr   rk   create_binary_subscrr   r   r   s    r#   create_swapr     s   
7""6q122Av		
a"9-..	
a";/1CI1NOO& 	<QU39%<3;'9%;'<3>*9%9% 
A	 	9% 	,!a%8 r%   r   r   storec                 Z   t         j                  dk\  r.|rt        d      n	t               }t	        t        | |            |gS t         j                  dk\  r&|rdnd}t	        |       t	        |      t        |      gS |rdnd}t	        |       t	        |      t        dd	      t        |      gS )
zQ
    BINARY_SLICE and STORE_SLICE (if `set` is True) for all Python versions
    r   r   r[   STORE_SLICEBINARY_SLICEBINARY_SUBSCRBUILD_SLICEr   r   )rq   rr   rk   r   r|   slice)r   r   r   subscr_inst	inst_names        r#   create_binary_slicer   
  s     7"27~.=Q=S 	 eE3/0
 	
 
		W	$%*M	e$c"y)
 	
 ',N	e$c"}!4y)	
 	
r%   c                     t         j                  dk\  rt        d|       gS | dk(  rt        d      gS g t        |       t	               t        | dz         t        d      S )NrT   r   r   r   r   r   )rq   rr   rk   r   r   rQ   s    r#   create_copyr   )  sw    
7""6q122Av"9-..	Q 
QU	 
Q	 r%   r   c                     g t        t        dt                    t        | t        j
                  dk\  rdndz         t        dd      t        d      S )Nrz   r{   rT   r   r   Fr   )r   rk   printr   rq   rr   r   )r   s    r#   create_print_on_stackr   =  sb    	),uE	F	U3#3#3w#>aAF	G 
a	' 	9%	 r%   valuec                     g t        t        dt                    t        d|       t        dd      t        d      S )Nrz   r{   r   Fr   )r   rk   r   r   )r   s    r#   create_print_valuer   G  sP    	),uE	F<6 
a	' 	9%	 r%   c                  X    t         j                  dk  rt        d      S t        dd      S )Nr   r   	BINARY_OP   r   rp   r3   r%   r#   r   r   P  s(    
'!!/22kr22r%   c                 b    t         j                  dk\  r| dk(  rt        d      S t        d|       S )Nr   r   r3   BUILD_TUPLEr   )rq   rr   r|   rk   r   s    r#   create_build_tupler   W  s.    
7"qAv $$m33r%   first_linenoc                     t         j                  dd dk(  sJ g | dddt        dt        ddffdd	t        d
t        ddffd}dt        ddffd}||fS )z
    Used to create typing.CodeType.co_linetable
    See https://github.com/python/cpython/blob/main/Objects/lnotab_notes.txt
    This is the internal format of the line number table for Python 3.10
    Nr   )rL   
   r   byteno_deltalineno_deltar   c                     | dk7  s|dk7  ret        dt        | d            }t        dt        |d            }|dk7  s|dk7  sJ | |z  } ||z  }j                  ||dz  f       | dk7  r^|dk7  rdy y )Nr      i      )maxminr   )r   r   byte_offsetline_offset	linetables       r#   _updatez!linetable_writer.<locals>._updatek  s    a<1#4a\3!78KdCc$:;K!#{a'777K'LK'Lk;+=>? a<1#4r%   
lineno_new
byteno_newc                 4    |z
  }| |       | z
  | y r@   r3   )r   r   r   r   bytenolinenor   s      r#   updatez linetable_writer.<locals>.updatet  s+    !F*l+!F*r%   total_bytesc                      | z
         y r@   r3   )r   r   r   r   s    r#   r   zlinetable_writer.<locals>.end|  s    f$l3r%   )rq   rr   r/   )r   r   r   r   r   r   r   r   s      @@@@@r#   linetable_writerr   ]  s     BQ7***IFLF@c @ @ @3 C D  4 4 4 fc!!r%   c                     | dk\  sJ | dz  g}| dz  } | dkD  r,|dxx   dz  cc<   |j                  | dz         | dz  } | dkD  r,|S )z~
    6-bit chunk encoding of an unsigned integer
    See https://github.com/python/cpython/blob/3.11/Objects/locations.md
    r   ?      r   @   )r   )r   bs     r#   encode_varintr     s`    
 6M6	
RA!GA
a%	"	R	a a% Hr%   c                     t         j                  dk\  sJ g | dt        j                  dz  dt        ddffd}|fS )z
        Used to create typing.CodeType.co_linetable
        See https://github.com/python/cpython/blob/3.11/Objects/locations.md
        This is the internal format of the line number table for Python 3.11
        rT   r<   N	inst_sizer   c                       r j                   nd }dt        dt        dd f fd}|d}n|z
  }||dkD  r ||d       |dz  }|dkD  r |||       y )Ndeltasizer   c                    d|cxk  rdk  sJ  J d}r~j                   rj                  fj                  Zj                  Nj	                  d|z   dz
         j                  j                   z
  j                  dz   j                  dz   f}nj	                  d|z   dz
         | dk  r
|  dz  dz  } n| dz  } j                  t        |              |D ]  }j                  t        |              y )Nr      r3      r      )r   
end_lineno
col_offsetend_col_offsetr   r   r   )r  r  other_varintsr   r   r<   s       r#   r   z5linetable_311_writer.<locals>.update.<locals>._update  s   4}1}$}$} 24!((4!,,8!,,8!00<$$\D%81%<= ",,y/?/??!,,q0!0014%M $$\D%81%<=19$f]a/EaKE  u!56& 7A$$]1%567r%   r   r  )r   r/   )r<   r  r   r   r   r   r   s   `    r#   r   z$linetable_311_writer.<locals>.update  sx    -6))DJ7s 7# 7$ 7@ ! )F2#a-a(Q	 a- L),r%   )rq   rr   rh   	Positionsr/   )r   r   r   r   s     @@r#   linetable_311_writerr    sT     7***	,	-cmmd2 ,	-s ,	-t ,	-\ &  r%   c                   @    e Zd ZU eed<   eed<   eed<   eed<   eed<   y)ExceptionTableEntryr   r   r   r   r   N)r+   r,   r-   r/   r.   r0   r3   r%   r#   r  r    s    J	HKJKr%   r  c                     | dk\  sJ | dz  g}| dz  } | dkD  r|j                  | dz         | dz  } | dkD  r|j                          t        t        |      dz
        D ]  }||xx   dz  cc<    |S )zR
    Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse.
    r   r   r   r   r   )r   r   r   len)r   r   rN   s      r#   encode_exception_table_varintr    s     6M6	
RA!GA
a%	R	a a% IIK3q6A: 	!
Hr%   
bytes_iterc                 l    t        |       }|dz  }|dz  r|dz  }t        |       }||dz  z  }|dz  r|S )z5
    Inverse of `encode_exception_table_varint`.
    r   r   r   )next)r  r   rw   s      r#   decode_exception_table_varintr    sN     	ZA
b&C
b&	q2v b& Jr%   tabc                    t        t        |       dz
        D ]j  }| |   j                  | |   j                  k  rH| |   j                  | |dz      j                  k  r&| |dz      j                  | |dz      j                  k  rjJ  y)z
    Verifies that a list of ExceptionTableEntries will make a well-formed
    jump table: entries are non-empty, sorted, and do not overlap.
    r   N)r   r  r   r   )r  rN   s     r#   check_exception_tabler    s    
 3s8a<  
FLLCFJJ&A

SQZ---AE
  CAJNN2	
3
r%   exntabc           	      6   t        |       }g }	 	 t        |      dz  }t        |      dz  }||z   dz
  }t        |      dz  }t        |      }|dz	  }t        |dz        }	|j                  t	        |||||	             o# t
        $ r t        |       |cY S w xY w)z
    Parse the exception table according to
    https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt
    r   r   )iterr  r0   r   r  StopIterationr  )
r  exntab_iterr  r   lengthr   r   dlr   r   s
             r#   parse_exception_tabler"    s    
 v,K
C1+>BE2;?!CF&.1$C2;?!CF.{;B!GEaLEJJ*5#vueLM   c"
s   A0A? ?BBc                    g }| D ]  }t        |j                  dz        }|dxx   dz  cc<   |j                  |       |j                  |j                  z
  dz   }|j                  t        |dz               |j                  t        |j                  dz               |j
                  dz  |j                  z   }|j                  t        |              t        |      S )zd
    Inverse of parse_exception_table - encodes list of exception
    table entries into bytes.
    r   r      r   )r  r   r   r   r   r   r   bytes)r  r   entryfirst_entryr   r!  s         r#   assemble_exception_tabler(    s    
 	A 43EKK14DEA& 	U[[(1,	.v{;<	.u||q/@ABkkQ%++-	.r234 8Or%   instructionsfirstlinenoc                 F   g }t         j                  dk\  rt        |      \  }}d}t        |       D ]  \  }}|j                  dk(  r=d}|dz  }dD ]0  }	| ||	z      j                  dk7  s| ||	z      j
                  |_         n nt        |      dz  |z   }d} ||j
                  |       d}|j                  xs d}
|j                  |j                  |
dz  f       t        t        |      dz  dz
        D ]  }|j                  d         nt        |      \  }}}| D ]Z  }|j                   ||j                  t        |             |j                  xs d}
|j                  |j                  |
dz  f       \  |t        |             t        |      t        |      fS )	z)Do the opposite of dis.get_instructions()rT   r   EXTENDED_ARGr   r   r   rL   r   r   )r   r   )rq   rr   r  	enumerater6   r<   instruction_sizer7   r   r5   r   r   r:   r  r%  )r)  r*  codelnotabupdate_linenonum_extrN   rs   r  jr7   _r   s                r#   assembler6  +  s   D
7" 4[ A . 	$GAt{{n,	1" A#AE*11^C)5a!e)<)F)F
 -T2a7'A	$..)4G((-aCKKcDj12+D1Q6:; $F#$!	$& &6k%B"s  	3D+d..D	:((-aCKKcDj12		3 	CI;f%%r%   offset_to_instr9   c                 l    dD ]/  }| ||z      j                   t        j                  k7  s'| ||z      c S  y)zU
    Get the instruction located at a given offset, accounting for EXTENDED_ARGs
    )r   r   r   r   Nr5   rh   r,  )r7  r9   r   s      r#   _get_instruction_by_offsetr:  Q  sD      .&1*%,,0@0@@!&1*--. r%   c                    | D ci c]  }|j                   |j                   | }}| D ]V  }|j                  t        j                  v s|j                  t        j                  v s<t        ||j                        |_        X yc c}w )z9Replace jump targets with pointers to make editing easierN)r9   r5   rh   hasjabshasjrelr:  r8   r   )r)  rs   jump_targetss      r#   virtualize_jumpsr?  ]  sy     '3"dkk6MTL   P;;#++%)C4\4;;ODKP	s
   BBinstructionc                    t         j                  dk  rt        d      d| j                  v r"| j                  j	                  dd      | _        n;d| j                  v r"| j                  j	                  dd      | _        nt        d      t        j                  | j                     | _        | j                  t        v sJ y )NrT   z+Cannot flip jump direction in Python < 3.11FORWARDBACKWARDz-Instruction is not a forward or backward jump)
rq   rr   rg   r6   replaceAttributeErrorrh   ri   r5   
_REL_JUMPS)r@  s    r#   flip_jump_directionrG  k  s    
'!HIIK&&&(//77	:N	{))	)(//77
INLMM;#5#56K+++r%   r   c                     | |   }dD ]5  }||k\  r,| ||z
     j                   t        j                  k(  r	| ||z
     }4 |S  |S )zp
    i.e. get the first EXTENDED_ARG instruction (if any) when targeting
    instructions[idx] with a jump.
    r-  r9  )r)  r   r   r9   s       r#   _get_instruction_frontrI  x  s]    
 #F &=\#,7>>#BRBRR!#,/FM
 Mr%   c           	         t        t        j                        j                  t        t        j                              }| D ]  }|j
                  |v s|j
                  t        j                  vs/|j                  "|j                  j                  |j                  J |j                  j                  |j                  k  r9t        j                  dk  rt        d      d|j                  v st        |       t        j                  dk\  sd|j                  v st        |        t        |        t        |       }| D ]/  }|j
                  |v s|j                  J t        | ||j                           }|j
                  t        j                  v rJt        j                  dk  r,|j                  J t!        |j                  dz        |_        nvt        d      |j                  |j                  J t%        t!        |j                  |j                  z
  t'        |      z
              |_        |xj"                  dz  c_        |j                  |_        d|j                   |_        2 y)	zJFill in args for virtualized jump target after instructions may have movedNrT   z*Got negative jump offset for Python < 3.11rB  rC  r   z+Python 3.11+ should not have absolute jumpszto )setrh   r<  unionr=  r5   r   r9   rq   rr   rg   r6   rG  update_offsetsr   rI  r/   r7   absr/  r8   r>   )r)  jumpsrs   indexofr   s        r#   devirtualize_jumpsrQ    s   ""3s{{#34E  2;;%{{#++-KK+**6/0 ;;%%3'''1*+WXX DKK/+D1 ''72zT[[7P+D1#2( < ,'G  1;;%;;***+L'$++:NOF{{ckk)##g- "==444"6==1#45DH&'TUU }}0T[[5LLL36Ft6LLM Q --DK 0DL+1r%   exn_tab_bytesc                 B  	
 t        |       }|D ci c]  }t        t        |j                        | c}	t	        	j                               
dt        |      	 dt        t        t        f   f	
fd} |       \  }}|D ]  }|j                  J |j                  |j                  kD  r$ |       \  }}|j                  |j                  kD  r$|j                  |j                  k\  sht        j                  |      |_         yc c}w # t        $ r Y yw xY w)zDReplace exception table entries with pointers to make editing easierr   r   c                  v   t              } t              k  r8   | j                  k  r&dz  t              k  r   | j                  k  r&dkD  sJ dz
     }t        t	        | j
                        t	        |      t	        | j                        | j                  | j                        }| |fS )Nr   r   )	r  r  r   r   r:  r   r   r   r   )r&  
end_offset
inst_entryend_offset_idxexn_tab_iterr7  offsetss      r#   stepz(virtualize_exception_table.<locals>.step  s    &E W-'.2IUYY2V!# W-'.2IUYY2V "A%%% !!34J/*>5;;G*>:F*>5<<HJ *$$r%   N)r"  r	   r/   r9   sortedkeysr  tupler  r   r   r   copyr=   r  )rR  r)  exn_tabrs   rZ  r&  rV  rW  rX  r7  rY  s          @@@@r#   virtualize_exception_tabler`    s	    $M2G?KLtd3,d2LN^((*+GN=L 	%e/1GGH 	% 	%, !Fz  	;D;;***++		)$(F!z ++		){{ekk)%)YYz%:"	;; MF  s$   "D A5D D 0D 	DDc           	      0   i t        |       }| D ]  }|j                  st        | ||j                  j                           j                  }|J t        t        |j                  j                  j                        t        |j                  j                        z   dz
  }|J t        | ||j                  j                           j                  }|J ||f}||j                  j                  |j                  j                  f}|v r
|   |k(  sJ ||<    t        j                         d       }dg g dfd}	|D ]  }r&d   d   |d   k  r |	        rd   d   |d   k  rrod   d   |d   cxk  r|d   cxk  rd   d   k  sJ  J t        d   d         }
|
|d   k  r(j                  t!        |
|d   dz
  gd              |d   j                  |        r
 |	        r
t#               S )	zMCompute exception table in list format from instructions with exn_tab_entriesr   c                     | d   | d    fS Nr   r   r3   ts    r#   <lambda>z)compute_exception_table.<locals>.<lambda>  s    1!u r%   keyr   c                      rQj                         } | d   k  r8j                  t        t        | d         | d   g|            | d   dz   yyy)zT
        Pop the key_stack and append an exception table entry if possible.
        r   r   r   N)popr   r  r   )rh  exn_dictr_  	key_stacknextis    r#   rj  z$compute_exception_table.<locals>.pop  se    
 --/CA'CFE(:CFSXc]S A
	  r%   r   r   )r   N)r   r=   rI  r   r9   r	   r/   r   r/  r   r   r   r[  r\  r   r   r  r  )r)  rP  rs   r   r   r   rh  rw   keys_sortedrj  leftrk  r_  rl  rm  s              @@@@r#   compute_exception_tablerp    sh    >@H,'G  *gd&8&8&>&>?f  $$$ S$,,00778"4#5#5#9#9:; 
 ?"?+gd&8&8&?&?@f  %%%#,C4--33T5G5G5M5MNCh}+++HSM- < .EFKE')I)+G# #  IbM!,s1v5E IbM!,s1v5R=#s1vKQK9R=;KKKKKKuimA./Dc!f}'c!fqjS8IbM;RS FE  '"Nr%   rP  c                 *   g }| D ]  }||j                      ||j                     f}|r/|d   d   |d   k  r!|j                          |r|d   d   |d   k  r!|r(|d   d   |d   cxk  r|d   cxk  r|d   d   k  sJ  J |j                  |        y)z
    Checks `tab` is a properly sorted list of nested InstructionExnTabEntry's,
    i.e. no entries partially overlap.
    "Properly sorted" means entries are sorted by increasing starts, then
    decreasing ends.
    r   r   r   N)r   r   rj  r   )r  rP  entry_stackr&  rh  s        r#   !check_inst_exn_tab_entries_nestedrs  4  s     *,K  u{{#WUYY%78k"oa03q69OO k"oa03q69r?1%QO3q6O[_Q=OOOOOO3 r%   c                    t        |       }i }| D ]h  }|j                  s||j                  j                     ||j                  j                     f}||v r|j                  ||   k(  sJ |j                  ||<   j t	        |j                         d       D cg c]  }||   	 }}t        ||       |D ]M  }t        ||j                     ||j                     dz         D ]  }t        j                  |      | |   _        ! O yc c}w )z~
    Copies exception table entries to all instructions in an entry's range.
    Supports nested exception table entries.
    c                     | d   | d    fS rc  r3   rd  s    r#   rf  z2propagate_inst_exn_table_entries.<locals>.<lambda>X  s    adQqTE] r%   rg  r   N)	r   r=   r   r   r[  r\  rs  r   r^  )r)  rP  entriesrs   rh  sorted_entriesr&  rN   s           r#    propagate_inst_exn_table_entriesrx  G  s   
 ,'G=?G .**001**../C g~))WS\999--GCL. !'w||~;R SN  &ng>   =wu{{+WUYY-?!-CD 	=A,0IIe,<LO)	==s   Dc                    t        |       }t               }t        |       D ]  \  }}|j                  st        j
                  dk\  sJ t        |j                        |vsJ |j                  t        |j                               |j                  }|j                  |v sJ |j                  |v sJ |j                  |v sJ ||j                     |cxk  r||j                     k  rJ  J  y)aJ  
    Checks that exn_tab_entries of instructions are valid.
    An entry's start, end, and target must be in instructions.
    Instructions with an exn_tab_entry are located within
    the entry's start and end instructions.
    Instructions do not share exn_tab_entries.

    Implicitly checks for no duplicate instructions.
    rT   N)r   rK  r.  r=   rq   rr   rB   addr   r   r   )r)  rP  exn_tab_entry_setrN   rs   r&  s         r#    check_inst_exn_tab_entries_validr|  b  s     ,'G\* 	C4##w...d(()1BBBB!!"T%7%7"89&&E;;')))99'''<<7***5;;'1B		0BBBBBB	Cr%   c                 p    | D cg c]"  }|j                   t        j                  k7  s!|$ c}| d d  y c c}w r@   r9  )r)  rN   s     r#   strip_extended_argsr~  z  s*    ".OQ!((c>N>N2NqOLOOs   "33old_inst	new_instsc                    | j                   r:| j                   j                  | u r"t        |      dkD  r|d   | j                   _        |dd  D ]7  }t        j                  | j                         |_         | j                  |_        9 |d   j
                  | _        |d   j                  | _        |d   j                  | _        |d   j                  | _        |d   j                  | _	        | g|dd  z   S )Nr   r   r   )
r=   r   r  r^  r<   r5   r6   r7   r8   r   )r  r  rs   s      r#   overwrite_instructionr    s    
 	""&&(2	NQ%.r]"!" ,!YYx'='=>!++,  l))HOl))HOQ<##HLl))HOl))HO:	!"%%r%   c                     t         j                  dk  sJ ddd}| D ]G  }|j                  |v s||j                     |_        t        j                  |j                     |_        I | S )zFLOAD_METHOD puts a NULL on the stack which causes issues, so remove itrT   r_   r   )r   r   )rq   rr   r6   rh   ri   r5   )r)  rewritesrs   s      r#   remove_load_call_methodr    sg    g%%%*?KH 1;;(""4;;/DK))DKK0DK1 r%   c                    g }| D ]  }d|j                   v rt        dt        d|j                   v             }|j                  |_        t
        j                  dk  r(t        d|j                   v rdnd|j                  	      }nt        d
|j                  	      }t        dd       ||g}|j                  t        ||             |j                  |        || d d  y )N_NONEIS_OPNOTr   r[   rB  POP_JUMP_FORWARD_IF_TRUEPOP_JUMP_BACKWARD_IF_TRUEro   POP_JUMP_IF_TRUErz   r{   )r6   rk   r/   r7   r8   rq   rr   r   r   r  r   )r)  r  rs   is_opjump_opreplace_instss         r#   remove_jump_if_noner    s    I #dkk!&wC8L4MNE 99EL'), %3 38;; --?T #<=M
 24GHT"3#4  LOr%   c                 X   g }| D ]  }|j                  |       |j                  dv s$t        j                  dk\  r|j                  dk(  rt	               }n%t        |j                  j                  dd            }|j                  r)|j                  j                  |u r||j                  _        t        j                  |j                        |_        |j                  |_
        t        j                  d   |_        d|_        d|_        d|_        |j                  |         || d d  y )N)r   r   r   r   SLICESUBSCRr   r   )r   r6   rq   rr   r   rk   rD  r=   r   r^  r<   rh   ri   r5   r7   r8   )r)  r  rs   r   s       r#   remove_binary_store_slicer    s    I *;;997*t{{n/L2401D1DWh1WX!!d&8&8&<&<&D)4""&(,		$2D2D(EK%$(NNK!))M2DK'DKDHDK[)#*$  LOr%   )	LOAD_FASTr  )LOAD_FAST_BORROWr  )
STORE_FASTr  )r  r  )LOAD_FAST_LOAD_FAST!LOAD_FAST_BORROW_LOAD_FAST_BORROWSTORE_FAST_STORE_FASTSTORE_FAST_LOAD_FASTc                    g }| D ]  }|j                   t        v r[t        |j                      \  }}|j                  \  }}t        ||      t        ||      g}|j	                  t        ||             p|j                  |        || d d  y )Nr{   )r6   FUSED_INSTSr8   rk   r   r  r   )r)  r  rs   inst0inst1argval0argval1r  s           r#   remove_fused_load_storer    s    I #;;+%&t{{3LE5#{{GW #59"59M 24GHT"#  LOr%   c                     g }| D ]k  }d|j                   v rJt        dd      t        |j                   |j                        g}|j                  t	        ||             [|j                  |       m || d d  y )NRETURNNOPGRAPH_BREAK_IF_LEAFr{   )r6   rk   r8   r   r  r   )r)  r  rs   r  s       r#   $add_graph_break_if_leaf_instructionsr    sw    I #t{{""51FG"4;;t{{CM 24GHT"#  LOr%   c                    g }t        j                  |       D ]$  \  }}|j                  dk(  r|j                  dk(  r|j                  j	                  d      rt        t        |             D ]  }| |   j                  |u r
|| |   _        | |   j                  s.| |   j                  j                  |u r|| |   j                  _	        | |   j                  j                  |u r|| |   j                  _
        | |   j                  j                  |u s|| |   j                  _         |j                  |       ' |j                  | d          || d d  y )Nr  r  r  r   )	itertoolspairwiser6   r8   
startswithr   r  r   r=   r   r   r   )r)  r  rs   	next_instrN   s        r#   'remove_graph_break_if_leaf_instructionsr    sH   I$--l; #iKK5 44  ++H5 3|,- I?))T1-6LO*?00 $A44::dB>GQ55;#A4488D@<EQ559#A44;;tC?HQ55<I T")#* \"%&LOr%   r0  c                 x   | j                   xs d| j                  xs dz   }t        | j                        syg }t	        |      D ]m  \  }}|j                  |       |j                  dk(  s(|j                  dk(  s8||dz      }|j                  dk(  sPt        j                  dk\  r|j                  dk(  sYt        j                  d	k\  r"t        j                  dk  r|j                  d
k(  s$t        j                  d	k  s|j                  dk(  sd|v sJ |j                  t        dd             | j                  d   }||v r|j                  t        d|             n|j                  t        d|             d|_        d|_        |j                  d
k(  sX||dz      }d|_        d|_        p ||dd y)z3convert super() with no args into explicit arg formr3   Nr`   superr   r   r[   r   rT   r   r   	__class__
LOAD_DEREFr{   r  r   )co_cellvarsco_freevarsr  co_varnamesr.  r   r6   r8   r7   rq   rr   rk   )	r0  r)  cell_and_freer   r   rs   rm  	first_var	call_insts	            r#   explicit_superr    s   %%+0@0@0FBGMt F|, )	Td;;-'DKK7,B q)EyyA~!!W,1G$$/((72	1$$w.5<<?3R"m3330kRS ,,Q/	-MM"4\)"TUMM"4["ST	 <<9, ,S1W 5I$%IM'(I$5)8 LOr%   c                    g dt         ddffd}| D ]  }|j                  t        j                  k(  r	d|_        na|j                  r|j                  dkD  r |d       j                  t        d|j                  d	z	  
             j                  t        d|j                  dz	  
             j                  t        d|j                  dz	  
             n|j                  rj|j                  dkD  r[ |d       j                  t        d|j                  dz	  
             j                  t        d|j                  dz	  
             nL|j                  r@|j                  dkD  r1 |d       j                  t        d|j                  dz	  
             j                  |        t              t        |       z
  }|dk\  sJ | dd |S )z,Fill in correct argvals for EXTENDED_ARG opsr   r   Nc                     t        |       D ]6  }sd   j                  t        j                  k(  s'j	                          8 y )Nr   )r   r5   rh   r,  rj  )r   r5  r   s     r#   maybe_pop_nz&fix_extended_args.<locals>.maybe_pop_nI  s9    q 	A&*++s/?/??

	r%   r   i rL   r,     r      r  i  r   r   r   )r/   r5   rh   r,  r7   r   rk   r  )r)  r  rs   addedr   s       @r#   fix_extended_argsr  E  sr    "Fs t 
  ;;#***DHXX$((X-NMM,^RPQMM,^RPQMM,^QOPXX$((V+NMM,^RPQMM,^QOPXX$((T/NMM,^QOPd!$ K#l++EA::LOLr%   rs   c                     dd l }t        j                  dk\  r=d|j                  j                  j
                  j                  | j                     dz   z  S y)Nr   rT   r   r   )torchrq   rr   _C_dynamo
eval_framepy_opcode_cachesr5   )rs   r  s     r#   r/  r/  f  sF    
7"EHH$$//@@MPQQRRr%   c                 T    d}| D ]!  }|j                   |k(  sJ |t        |      z  }# y Nr   r9   r/  r)  r9   rs   s      r#   check_offsetsr  n  s8    F ){{f$$$"4(()r%   c                 @    d}| D ]  }||_         |t        |      z  } y r  r  r  s      r#   rM  rM  u  s-    F )"4(()r%   argsc            	      N   t        t        t        t        |                   }|gt	        |       z   t        | d   | d         D cg c]  \  }}t        ||k7         c}}gz   D cg c]  }dj                  d |D               }}ddj                  |      z   S c c}}w c c}w )Nr    c              3   $   K   | ]  }|d  
 yw)03Nr3   ).0xs     r#   	<genexpr>zdebug_bytes.<locals>.<genexpr>  s     (qAb6(s   zbytes mismatch

)r   r   mapr  r   zipr/   join)r  indexar   r7   results         r#   debug_bytesr  }  s    #c#tn%&E 7
t*$'R$r($;<DAqCQK<
=> 	(C((F  		& 111 =	s   B'B"c                     t        | d d      \  }}| j                  |j                  k(  s%J t        | j                  |j                               y)z<Make sure our assembler produces same bytes as we start withc                      y r@   r3   )r  ys     r#   rf  zdebug_checks.<locals>.<lambda>  s    r%   T)safeN)transform_code_objectco_coder  )r0  doder5  s      r#   debug_checksr    s?    #D*;$GGD!<<4<<'PT\\4<<)PP'r%   code_optionsc                 |    t        | d         D ]  \  }}||u s|c S  | dxx   |fz  cc<   t        | d         dz
  S )N	co_constsr   )r.  r  )r  rw   rN   vs       r#   get_const_indexr    sV    ,{34 1
 !8H #'|K()A--r%   varname_from_oparg.c                 @
   	
 t        d         D ci c]  \  }}||
 c}}dt        dt        ffd}t        j                  dk  rO|J t        d         D ci c]  \  }}||
 c}}t        d   d   z         D ci c]  \  }}||
 c}}	njt        |      sJ i }t        j                         D ]  }	  ||      }|||<    d   D ci c]  }|||   
 c}d   d   z   D ci c]  }|||   
 c}	t        t                     D ]  
dt        f
 fd	} 
   j                  d
k(  r 
   j                  t        usJ t        j                  dk\  rS 
   j                  J  | 
   j                        dz  t!        t         
   j                        dz  z    
   _         | 
   j                         
   _         
   j                  dk(  r 
   j                  t        usJ t        j                  dk\  rT 
   j                  J  | 
   j                        dz  t!        t         
   j                        dz  z    
   _        N | 
   j                         
   _        m 
   j                  dk(  rn 
   j                  J  
   j                  t        usJ  | 
   j                        dz  t!        t         
   j                        dz  z   dz    
   _         
   j                  t"        v rt        j                  dk\  sJ t%         
   j                  t&              sJ t         
   j                        dk(  sJ t'        	fd 
   j                  D              }|d   dz  |d   dz  z    
   _         
   j(                  t*        v re |       st        j                  dk\  r- 
   j                  vr	 
   j                      
   _         
   j                      
   _        
 
   j(                  t,        v r( |       s( | 
   j                         
   _        G 
   j(                  t.        v r% |       se	 
   j                      
   _         
   j(                  t0        v s 
   j                  t3         
   j                        }|dk\  sJ | 
   _         y c c}}w c c}}w c c}}w # t        $ r Y  >w xY wc c}w c c}w )Nco_namesr]   r   c                     	 |    }|S # t         $ r= t              x}| <   g d   | d<   t        d         t              k(  sJ Y |S w xY w)Nr  )KeyErrorr  )r]   r   r  namess     r#   get_name_indexz fix_vars.<locals>.get_name_index  su    	?+C 
  	? #E
*C%+'Hj)A'H4'HL$|J/0CJ>>>
	?s   
 AAArT   r  r  r  c                  .        j                   t        uS r@   )r8   rY   )rN   r)  s   r#   should_compute_argz$fix_vars.<locals>.should_compute_arg  s    ?))==r%   r`   r   r   r_   r[   ra   rK   c              3   :   K   | ]  }|v r|   n|     y wr@   r3   )r  r]   	freenamesvarnamess     r#   r  zfix_vars.<locals>.<genexpr>  s-       #'("2	$Gs   r   r      )r.  r1   r/   rq   rr   callabler  count
IndexErrorr   r  r0   r6   r8   rY   r7   r	   r  r)   r]  r5   	HAS_LOCALHAS_NAMEHAS_FREE	HAS_CONSTr  )r)  r  r  r   r]   r  allnamesr  	arg_tupler  rN   r  r  s   ``       @@@@r#   fix_varsr     sM    )2,z2J(KL93T3YLES S  '!!)))/8m9T/UV)#tD#IV ']+l=.II
T #I
	 *+++??$ 	C)#.!$	 6B-5PQTD(4.(Q %]3l=6QQ
 (4. 
	 3|$% C*	>D 	> ?!!]2?))===7*#A**666'5l1o6L6L'MQR'Rl1o112Q6'Q# '5\!_5K5K&LQ#!_##{2?))===7*#A**666'5l1o6L6L'MQR'Rl1o112Q6'Q# '5\!_5K5K&LQ#!_##'88?&&222?))===  Q 6 671<\!_001A57 O
 !_##{2##w...l1o44e<<<|A--.!333 (O22 I $-Q<1#419J"KLO!_##y0!#$$/$Q..h> +4LO4J4J*KLO'*2<?3I3I*JLO'!_##x/!#&4\!_5K5K&LQ#!_##x/!#&/Q0F0F&GQ#!_##y0 A""*%lLO4J4JKaxx&)Q#GC*G M W
  Q
s/   S3$S9S?TT8T	TTc                     | D ]t  }|j                   t        us|j                  t        v s7|j                  t        v s%|j                  t
        v s|j                  t        v s_|j                  dvsnd |_        v y )N)r`   r_   ra   )	r8   rY   r5   r  r  r  r  r6   r7   )r)  rs   s     r#   clear_instruction_argsr    sc      KK|+y(;;(*;;(*;;)+#RRDHr%   c                  N   dg} | j                  d       | j                  g d       t        j                  dk\  r| j                  d       | j                  d       | j                  d       t        j                  dk\  r| j                  d       | j                  d	d
g       | S )Nco_argcountco_posonlyargcount)
co_kwonlyargcount
co_nlocalsco_stacksizeco_flagsr  r  r  r  co_filenameco_namerT   co_qualnameco_firstlinenoco_linetableco_exceptiontabler  r  )r   r   rq   rr   )r\  s    r#   get_code_keysr  &  s    
 ?DKK$%KK	
 7"M"KK !KK
7"'(KK	
 Kr%   transformationsr   r  c                     t               }|D ci c]  }|t        | |       }}t        |d         |d   k(  sJ t        | |      }t	        |        |||      }t        |||      \  }}	|	|fS c c}w )Nr  r  )r  getattrr  cleaned_instructionsr   clean_and_assemble_instructions)
r0  r  r  r\  kr  r)  tracer_outputr5  bytecodes
             r#   r  r  K  s     ?D156AAwtQ''6L6|M*+|L/IIII'd3L%#L,?M1,lSKAx]"" 7s   A/r\  c                    t        |        t        |        t        |d         |d<   d }t        j                  dk\  r/t        j                  |D cg c]  }||   	 c} }|j                  }t        | ||       d}|r-t        |        t        |        t        t        |             }|r-t        |        t        | |d         \  }}||d<   ||d<   t        |       |d	<   t!        |      d
hz
  t!        |j#                               d
hz
  k(  sJ t        j                  dk\  rt%        t'        |             |d<   | t        j                  |D cg c]  }||   	 c} fS c c}w c c}w )Nr  r  rT   )r  Tr  r  r  r  r  r  )r  r|  r  rq   rr   typesCodeType_varname_from_opargr   rM  rQ  r0   r  r   r6  r   rK  r\  r(  rp  )	r)  r\  r  r  r  tmp_codedirtyr  r1  s	            r#   r  r  _  sy    ,L9$\2!$\-%@!AL
7">>T#BLO#BC%99\<<NOE
|$<(&|45	  <(l;K.LMHf#)L &L#5l#CL t9,--\5F5F5H1IM 2    7",D#L1-
() 4)Ha,q/)HIII3 $C2 *Is   EE#
constsc                 Z    | D ]&  }|j                   dk(  s||j                     |_        ( y )NKW_NAMES)r6   r7   r8   )r)  r  rs   s      r#   populate_kw_names_argvalr"    s-     +;;*$ *DK+r%   c                 0    t        | |      }t        |      S r@   )_cached_cleaned_instructions_clone_instructionsr0  r  r)  s      r#   r  r    s    /d;L |,,r%   c                 V   | D cg c]  }t        |j                  |j                  |j                  |j                  |j
                  |j                  |j                  |j                  |j                  |j                  |j                         }}t        t        | |            }d |d <   |D ]t  }||j                     |_	        |j                  x}s&t        ||j                     ||j                      ||j                     |j"                  |j$                        |_
        v |S c c}w r@   )r   r5   r6   r7   r8   r9   r:   r;   r<   r   r=   r>   dictr  r   r   r   r   r   )r)  rN   copiedremapr&  s        r#   r%  r%    s
   "   	HHHHEEHHHHMMKKHHOOII	
F " \6*+EE$K 	?OO#5#4ekk"eii ell#AO	 M?s   B
D&c                    t        t        t        t        j                  |                   }t        |       t        |       t        j                  dk\  r,t        || j                         t        | j                  |       t        |       t        |       |st        j                  dk  rt        |       t        j                  dk  rt!        | |       t        j                  dk\  rGt#        |       t        j                  dk\  rt%        |       t        j                  dk\  rt'        |       t(        j*                  rt-        |       t        j                  dk\  rt/        |       t1        |       |S )NrT   r[   rK   )r   r  rR   rh   get_instructionsr   r  rq   rr   r"  r  r`  r  r?  r~  r  r  r  r  r  r   &debug_force_graph_break_on_leaf_returnr  rM  rQ  r&  s      r#   r$  r$    s    /1E1Ed1KLML%,
7" t~~>"4#9#9<H\"%g%#L1g%4.w&-7*),77*'5880>
7"|$<(r%   	with_uuidc                     |  dt        t               }|r*|dt        j                          j	                  dd      z  }|S )Nr5  -)r  _unique_id_counteruuiduuid4rD  )r]   r.  rets      r#   	unique_idr5    sE    F!D+,-
.C4::<.!))#s33Jr%   c                 *    d}| j                   |z  dkD  S )N    r   )r	  )r0  co_generators     r#   is_generatorr9    s    LMML(A--r%   fnvarname_mapnoreturnnoprefixc                    t        | j                        }t        |       |r,t        |      D ]  \  }}|j                  dk(  s||dz   d } n |D ]6  }d|_        d|_        |s|j                  |v s#||j                     |_        8 |rt        j                  dk\  rvg }|D ]m  }|j                  dk(  rKt        j                  d   |_        d|_        |j                  |       |j                  t        d             ]|j                  |       o |}g }|D ]#  }|j                  dk(  s|j                  |       % t        |      dk(  r|d   |d	   u r|j!                  d	       |S t        |      dkD  r|d	   |d	   u rOd
|d	   _        t        j                  d
   |d	   _        d|d	   _        t$        |d	   _        |j!                  d	       n|j                  t        d
             |D ]e  }t'        |d	         }	|	j                  |_        |	j                  |_        |	j"                  |_        |	j                  |_        |	j(                  |_        g |S )a  Generates bytecode from a template function `fn` for use in
    dynamo bytecode generation.

    For example, we can generate Python-version-independent bytecode
    for looping through a dictionary and copying the values to a new dictionary.

    def template(d1, d2):
        for k, v in d1.items():
            d2[k] = v


    or a try block:

    def template():
        try:
            dummy1
        except:
            dummy2
            raise
        dummy3

    Args:
        fn: a function template to generate bytecode from
        varname_map: a mapping of `fn`'s varnames to new names. This
            map will be applied to the generated bytecode's varnames.
            For example, local variables in `fn` can be replaced with
            new names that are generated by `OutputGraph.new_var`.
        noreturn: remove all RETURN_* bytecodes and replace them with a jump
            to the end of the bytecode. NOTE: any items pushed to the stack
            for return WILL remain on the stack! Append a POP_TOP if you don't want
            that item to be present.
        noprefix: remove prefix bytecodes (all bytecode before the first RESUME, inclusive).
    RESUMEr   Nr[   RETURN_CONSTrz   RETURN_VALUEr   r   r  )r  __code__r  r.  r6   r:   r<   r8   rq   rr   rh   ri   r5   r   rk   r  rj  r7   rY   rt   r   )
r:  r;  r<  r=  r   rN   rs   r  returns	jump_insts
             r#   bytecode_from_templaterE    sN   N !-E5! ' 	GAt{{h&a!eg	
  3  4;;+5%dkk2DK3 w&I +;;.0"%))L"9DK".DK$$T*$$%7%GH$$T*+ E  	%D{{n,t$	% w<1uRy!8IIbM0 L/ \A RyGBK'#(b	 #&99U#3b	  $b	#/b	 B/67   / 1r;	'..'..$=='..'../ Lr%   )T)Fr@   )NTT)rJ   r^  dataclassesrh   	functoolsr  rq   r  r2  collections.abcr   r   r   r   r   typingr   r	   r
   r    r   bytecode_analysisr   r   r   r   utilsr   output_graphr   	dataclassr   r   rr   rR   rY   r1   r0   rc   r/   rk   rt   rv   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%  r"  r(  r6  r(  r:  r?  rK  r=  rF  rG  rI  rQ  r`  rp  rs  rx  r|  r~  r  r  r  r  r  r  r  r  r  r  r  r/  r  rM  r  r  haslocalr  hasnamer  hasfreer  hasconstr  r  r   r  	lru_cacher  r  r  r"  r  r%  r$  r  r1  r5  r9  rE  r3   r%   r#   <module>rT     s
     
   
   K K 5 5   $ 0 T"
 
 #
6 T") ) #)> w

s 

; 

 	 

s 

; 



s 

; 

 
 wGs Gt G 	 %s %t %
s t  %!%'
' 
t' $J	'
 $' 'V3 3 3
>[ >T >83 8 8 84, $) )0C 0D- 0.8k!228	+8vk!22	+<4< 4< 4<k9J 4<p GLII!%I?CI	+ID:c :d;&7 ::S :[ :5k 5k 5
+3 +4, +^ 7<
:
$J
/3
	+
>3 4, ( k): c d;&7 3k 34# 4+ 4""""
49hSz4/0(C5$;2GGH""JS T#Y  w:!:!	tCy(CMMD$8##>#DEE	F:!z T"  #S T#Y  
hsm 
 


t$78 

T 

% D1D,E ,$':";  $#&4, #&3 #&5PUCV #&L	k)*	47	4	P8K#8 PT P 

,[ 
,T 
,k):   21T+%6 214 21j))(,[(9)	)XJ{#J	
JZ 	$	% 04[#5E0F 	 &=43D = =6C43D C C0Pd;&7 PD P&&&*;&7&	+&.${*; [@Q  d;&7  D  > D,=  $  0 6)Q97	 ${*;    & tK7H  T   ${:K  PT  6# #tK7H #T #LD$5 # B; 3 ) 5 )$ ))+!6 )4 )	2u 	2 	2Qu~~ Q$ Q 	s{{s{{		.$sCx. 	.s 	.s 	. 59l*{#l*sCx.l* !c*T1l* 
	l*^k): t " !tCy ! !R #
..#	k	DcN+X6J-KK#
 # 5>>8$899:#($J{#$J+/9$JDHcN$J
4enn,-$JN+8K+@ +# +RV +-u~~ -T -d;FW -"h{&; "[@Q "J ',
.. $k > %Y__& C D S .u~~ .$ . -1	gcgc"T)g g 	g
 
+gr%   