aboutsummaryrefslogtreecommitdiff
path: root/py/vm.c
diff options
context:
space:
mode:
authorDamien George <damien@micropython.org>2022-03-16 09:37:58 +1100
committerDamien George <damien@micropython.org>2022-03-28 15:41:38 +1100
commit538c3c0a5540b4018cedd442b585666130fc8def (patch)
treeddf773175e96e85650b3e77a9400ca3e0ba6ab40 /py/vm.c
parent9e3e67b1d8bf0fd5ee612b3c828ae549f76d1407 (diff)
py: Change jump opcodes to emit 1-byte jump offset when possible.
This commit introduces changes: - All jump opcodes are changed to have variable length arguments, of either 1 or 2 bytes (previously they were fixed at 2 bytes). In most cases only 1 byte is needed to encode the short jump offset, saving bytecode size. - The bytecode emitter now selects 1 byte jump arguments when the jump offset is guaranteed to fit in 1 byte. This is achieved by checking if the code size changed during the last pass and, if it did (if it shrank), then requesting that the compiler make another pass to get the correct offsets of the now-smaller code. This can continue multiple times until the code stabilises. The code can only ever shrink so this iteration is guaranteed to complete. In most cases no extra passes are needed, the original 4 passes are enough to get it right by the 4th pass (because the 2nd pass computes roughly the correct labels and the 3rd pass computes the correct size for the jump argument). This change to the jump opcode encoding reduces .mpy files and RAM usage (when bytecode is in RAM) by about 2% on average. The performance of the VM is not impacted, at least within measurment of the performance benchmark suite. Code size is reduced for builds that include a decent amount of frozen bytecode. ARM Cortex-M builds without any frozen code increase by about 350 bytes. Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'py/vm.c')
-rw-r--r--py/vm.c26
1 files changed, 24 insertions, 2 deletions
diff --git a/py/vm.c b/py/vm.c
index 497a56962..990009c00 100644
--- a/py/vm.c
+++ b/py/vm.c
@@ -61,8 +61,30 @@
do { \
unum = (unum << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0)
-#define DECODE_ULABEL size_t ulab = (ip[0] | (ip[1] << 8)); ip += 2
-#define DECODE_SLABEL size_t slab = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2
+
+#define DECODE_ULABEL \
+ size_t ulab; \
+ do { \
+ if (ip[0] & 0x80) { \
+ ulab = ((ip[0] & 0x7f) | (ip[1] << 7)); \
+ ip += 2; \
+ } else { \
+ ulab = ip[0]; \
+ ip += 1; \
+ } \
+ } while (0)
+
+#define DECODE_SLABEL \
+ size_t slab; \
+ do { \
+ if (ip[0] & 0x80) { \
+ slab = ((ip[0] & 0x7f) | (ip[1] << 7)) - 0x4000; \
+ ip += 2; \
+ } else { \
+ slab = ip[0] - 0x40; \
+ ip += 1; \
+ } \
+ } while (0)
#if MICROPY_EMIT_BYTECODE_USES_QSTR_TABLE