8000 py/compile: Add COMP_RETURN_IF_EXPR option to enable return-if-else opt. · micropython/micropython@ae54fbf · GitHub
[go: up one dir, main page]

Skip to content

Commit ae54fbf

Browse files
committed
py/compile: Add COMP_RETURN_IF_EXPR option to enable return-if-else opt.
With this optimisation enabled the compiler optimises the if-else expression within a return statement. The optimisation reduces bytecode size by 2 bytes for each use of such a return-if-else statement. Since such a statement is not often used, and costs bytes for the code, the feature is disabled by default. For example the following code: def f(x): return 1 if x else 2 compiles to this bytecode with the optimisation disabled (left column is bytecode offset in bytes): 00 LOAD_FAST 0 01 POP_JUMP_IF_FALSE 8 04 LOAD_CONST_SMALL_INT 1 05 JUMP 9 08 LOAD_CONST_SMALL_INT 2 09 RETURN_VALUE and to this bytecode with the optimisation enabled: 00 LOAD_FAST 0 01 POP_JUMP_IF_FALSE 6 04 LOAD_CONST_SMALL_INT 1 05 RETURN_VALUE 06 LOAD_CONST_SMALL_INT 2 07 RETURN_VALUE So the JUMP to RETURN_VALUE is optimised and replaced by RETURN_VALUE, saving 2 bytes and making the code a bit faster.
1 parent 40b40ff commit ae54fbf

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

py/compile.c

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -980,7 +980,8 @@ STATIC void compile_return_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
980980
if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
981981
// no argument to 'return', so return None
982982
EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE);
983-
} else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) {
983+
} else if (MICROPY_COMP_RETURN_IF_EXPR
984+
&& MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) {
984985
// special case when returning an if-expression; to match CPython optimisation
985986
mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t*)pns->nodes[0];
986987
mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns_test_if_expr->nodes[1];

py/mpconfig.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,12 @@
353353
#define MICROPY_COMP_TRIPLE_TUPLE_ASSIGN (0)
354354
#endif
355355

356+
// Whether to enable optimisation of: return a if b else c
357+
// Costs about 80 bytes (Thumb2) and saves 2 bytes of bytecode for each use
358+
#ifndef MICROPY_COMP_RETURN_IF_EXPR
359+
#define MICROPY_COMP_RETURN_IF_EXPR (0)
360+
#endif
361+
356362
/*****************************************************************************/
357363
/* Internal debugging stuff */
358364

0 commit comments

Comments
 (0)
0