Skip to content

Add constant folding#51

Merged
Zaneham merged 4 commits intoZaneham:masterfrom
nataliakokoromyti:add-constfold
Feb 28, 2026
Merged

Add constant folding#51
Zaneham merged 4 commits intoZaneham:masterfrom
nataliakokoromyti:add-constfold

Conversation

@nataliakokoromyti
Copy link
Copy Markdown
Contributor

This PR adds single-pass constant folding for BIR. Folds constant expressions at compile time so 3+4 becomes 7 in the IR instead of an actual add instruction. Handles ints, floats, comparisons, casts, select. One forward pass, DCE cleans up after.

Comment thread src/ir/bir_cfold.c
}

/* Sign-extend an integer from w bits to int64_t. */
static int64_t sign_extend(int64_t val, int w)
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think theres some undefined behaviour here for c99. I think it should be 1ULL in both

Comment thread src/ir/bir_cfold.c
default: return 0;
}

r = mask_to_width(r, rw);
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a is a negative, left shifting it is undefined behaviour in c99. Needs r = (int64_t)((uint64_t)a << (b & (sw - 1)))

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think but happy to discuss other approaches

@Zaneham
Copy link
Copy Markdown
Owner

Zaneham commented Feb 28, 2026

Two more things:

BIR_SDIV / BIR_SREM (the if (b == 0) return 0; guard) -- there's one more edge case here. If sw=64 and a is the most negative 64-bit value and b is -1, the division overflows. Same thing applies to SREM below. Just need a guard to skip folding for that case.

BIR_FPTRUNC (r = (double)(float)r;) -- this always truncates to float32 precision but the target type could be half (f16). Not urgent since constant half expressions are pretty rare, just something to be aware of.

Everything else looks great. No dynamic allocation, deterministic single-pass, correct SSA traversal. Clean work.

Edit: oh, my manners, thank you again!

@nataliakokoromyti
Copy link
Copy Markdown
Contributor Author

thank YOU for the feedback and quick response! love BarraCUDA

Copy link
Copy Markdown
Owner

@Zaneham Zaneham left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved, requested changes have been made, thanks again!

@Zaneham Zaneham merged commit 5898158 into Zaneham:master Feb 28, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants