Does the compiler omit code that will never execute?

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
rhubarbdog
Posts: 166
Joined: Tue Nov 07, 2017 11:45 pm

Does the compiler omit code that will never execute?

Post by rhubarbdog » Fri Apr 26, 2019 6:38 am

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?

User avatar
Roberthh
Posts: 2277
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

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

Post by Roberthh » Fri Apr 26, 2019 7:21 am

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!

User avatar
jimmo
Posts: 2061
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

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

Post by jimmo » Sat Apr 27, 2019 12:53 pm

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);
}

Post Reply