Commit b8c7b236
b8c7b236f234Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 1 file · ~1 modified
Description
perf: constant propagation for simple literal constants
When a constant's initializer is a simple literal (integer, float, string, bool, nil, symbol), inline the literal value at each use site instead of emitting cst_NAME runtime lookup.
N = 100 while i < N # was: while (i < cst_N)
now: while (i < 100)
Enables the C compiler to do further optimizations like loop-unrolling, constant folding in conditions, and dead-code elimination of the cst_N global when it becomes unused.
75/75 tests pass, bootstrap stable.
Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]
Details
- Commit
- b8c7b236f234
- Parent
- d4c69492d081
spinel_codegen.rbmodifiedView file
@@ -733,6 +733,46 @@
733733
-1734734
end735735
736+
# If the constant's initializer is a simple literal, return the737+
# corresponding C expression. Otherwise return "" so callers fall738+
# back to cst_<name> lookup. Enables propagation of:739+
# N = 10 → 10 at use sites740+
# PI = 3.14 → 3.14741+
# GREETING = "hi" → ("\xff" "hi" + 1)742+
# OK = true → TRUE743+
def const_literal_c_value(ci)744+
if ci < 0 || ci >= @const_expr_ids.length745+
return ""746+
end747+
eid = @const_expr_ids[ci]748+
if eid < 0749+
return ""750+
end751+
et = @nd_type[eid]752+
if et == "IntegerNode"753+
return @nd_value[eid].to_s754+
end755+
if et == "FloatNode"756+
return @nd_content[eid]757+
end758+
if et == "StringNode"759+
return c_string_literal(@nd_content[eid])760+
end761+
if et == "TrueNode"762+
return "TRUE"763+
end764+
if et == "FalseNode"765+
return "FALSE"766+
end767+
if et == "NilNode"768+
return "0"769+
end770+
if et == "SymbolNode"771+
return compile_symbol_literal(@nd_content[eid])772+
end773+
""774+
end775+
736776
# Find method in class (search parent chain)737777
def cls_find_method(ci, mname)738778
names = @cls_meth_names[ci].split(";")@@ -10578,6 +10618,11 @@
1057810618
end1057910619
ci = find_const_idx(@nd_name[nid])1058010620
if ci >= 010621+
# Propagate simple literal constants to their use sites.10622+
lv = const_literal_c_value(ci)10623+
if lv != ""10624+
return lv10625+
end1058110626
return "cst_" + @nd_name[nid]1058210627
end1058310628
# Check if inside a module method and constant belongs to that module