Page 1 of 1

Does the compiler omit code that will never execute?

Posted: Fri Apr 26, 2019 6:38 am
by rhubarbdog

Code: Select all

import pyb 

DEBUG = const(0)

# some code
if DEBUG:
    print("debug info")
Does the compiler omit the if DEBUG and it's associated block. Making the code leaner and faster?

Re: Does the compiler omit code that will never execute?

Posted: Fri Apr 26, 2019 7:21 am
by Roberthh
It looks like that. If I cross-compile a version with DEBUG being either 0 or 1, the result is different and the difference is for instance the presence of the string "debg info". Interesting!

Re: Does the compiler omit code that will never execute?

Posted: Sat Apr 27, 2019 12:53 pm
by jimmo
Yes, this would trigger this optimisation in compile.c

Code: Select all

STATIC void compile_if_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
    uint l_end = comp_next_label(comp);

    // optimisation: don't emit anything when "if False"
    if (!mp_parse_node_is_const_false(pns->nodes[0])) {
    ...
 }
    
bool mp_parse_node_is_const_false(mp_parse_node_t pn) {
    return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE)
        || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
}