Python Bytecode

Michael Hudson mwh at python.net
Wed Aug 21 13:03:04 CEST 2002


Christos "TZOTZIOY" Georgiou <DLNXPEGFQVEB at spammotel.com> writes:

> As Tim, Neal and Michael have also noticed, there are two cases
> (shortcut 'and' - 'or' comparisons and multiple comparisons, eg. 0<x<10)
> where the TOS value must not be popped.
> There are two quick-and-dirty ways to overcome this possibility, both
> introducing new opcodes (affecting opcodes.h, ceval.c, compile.c):
> 
> 1: introduce JUMP_IF_FALSE_POP and JUMP_IF_TRUE_POP (both doing a test
> and then a pop).  They can be used in the following compile.c functions:
> com_list_if, com_assert_stmt, com_if_stmt, com_while_stmt,
> com_try_except.  The relevant POP_TOP's can be safely removed then, and
> so can two JUMP_FORWARD's.

This is indeed the easy option.

> 2: change JUMP_IF_FALSE and JUMP_IF_TRUE to always pop (and remove all
> JUMP_IF related POP_TOP's), but then you introduce two opcodes:
> STORE_TRUE and STORE_FALSE (STORE_TRUE would PUSH(Py_True);
> Py_INCREF(Py_True); and samewise STORE_FALSE), which should be inserted
> at the end of com_test and com_and_test respectively.
> The slightly more tough point here is com_comparison, where if you reach
> the "if (anchor)" point, instead of ROT_TWO and then POP_TOP, you must
> POP_TOP and then PUSH_FALSE (since you get to that point *always* after
> a JUMP_IF_FALSE) to let the False value pass through to the next opcode.

Err, don't really follow that (but didn't try too hard).

Can't you get the same effect by selectively emitting a DUP_TOP before
the JUMP_IF_* opcodes?  This may be hard to graft into the way the
compiler currently works, I guess.

> I agree (without any thorough scientific backing :) that the savings
> should not be that great; I'll give it (method 2) a try though, and
> report back... won't make any promises :)

Look forward to seeing it!

> PS An opcode optimizing pass would be interesting... 

There are a couple of these around, you know -- one in bytecodehacks,
one by Skip Montanaro, but both are somewhat out of date wrt modern
Python.

Cheers,
M.

-- 
  ZAPHOD:  You know what I'm thinking?
    FORD:  No.
  ZAPHOD:  Neither do I.  Frightening isn't it?
                   -- The Hitch-Hikers Guide to the Galaxy, Episode 11



More information about the Python-list mailing list