dino icon indicating copy to clipboard operation
dino copied to clipboard

Short-circuit evaluation

Open sunjay opened this issue 6 years ago • 1 comments

This applies to the boolean && and || operators. We need to make sure all of our code generation adequately short-circuits, only executing the right-hand side if the left is true for && or false for ||.

This has to work even for weird code like:

if true || (if true { foo(); false } else { false }) { ... }

Here, foo should never execute because the left branch is true and foo may have side effects.

Arbitrarily nested boolean expressions should work correctly.

sunjay avatar Oct 16 '19 21:10 sunjay

When lowering nir::BoolOr and nir::BoolAnd, we should create cgenir that uses C goto statements to implement the short-circuiting semantics.

This pseudo-code represents approximately what we're going for:

    bool result;

    // ...generated code for lhs of || operator...
    if (coerce_bool(lhs_result)) goto store_true;

    // ...generated code for rhs of || operator...
    if (coerce_bool(rhs_result)) goto store_true;

    // if neither are true
    goto store_false;

store_true:
    result = true;
store_false:
    result = false;

sunjay avatar Jun 24 '20 21:06 sunjay