Commit 36f1c6d4
36f1c6d4f7e9Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified
Description
Merge pull request #365 from mame/pr/poly-index-narrow-int
fix(codegen): auto-unbox poly arg in arithmetic / bit operators with primitive recv
Details
- Commit
- 36f1c6d4f7e9
- Parent
- bc92f28e9f12
- Merge parent
- 20065f23ed0d
spinel_codegen.rbmodifiedView file
@@ -153,6 +153,10 @@
153153
# distinct types per ivar; the outer dimension is semicolon-154154
# separated and parallel to `@cls_ivar_names[ci]`.155155
@cls_ivar_observed_types = "".split(",")156+
# Memoization for `find_lv_ivar_alias_in_ast`. Keyed by157+
# `"<class_idx>:<lv_name>"`, value is the resolved ivar name (or158+
# `""` when the LV has multiple sources / non-ivar writes).159+
@lv_alias_cache = {}156160
# Top-level (script-scope) ivars. Lowered to `static` file-scope157161
# globals because `main()` / top-level `def` bodies have no `self`.158162
@toplevel_ivar_names = "".split(",")@@ -237,6 +241,13 @@
237241
# ---- Scope stack for local variables ----238242
@scope_names = "".split(",")239243
@scope_types = "".split(",")244+
# Parallel to `@scope_names`: when a local was assigned directly245+
# from an ivar read (`lv = @ivar`), record the ivar name here so246+
# later sites that need ivar-side metadata (notably the247+
# `<poly>[k]` narrowing in `compile_poly_method_call`) can248+
# resolve through the alias. Empty string when the local has no249+
# such alias (or had a non-ivar write since).250+
@scope_ivar_alias = "".split(",")240251
241252
# Issue #207: type narrowing introduced by `is_a?`/`kind_of?`242253
# guards. While walking the then-arm of `if v.is_a?(Hash)` or@@ -1278,6 +1289,7 @@
12781289
def push_scope12791290
@scope_names.push("---")12801291
@scope_types.push("---")1292+
@scope_ivar_alias.push("---")12811293
012821294
end12831295
@@ -1287,16 +1299,19 @@
12871299
if top_name == "---"12881300
@scope_names.pop12891301
@scope_types.pop1302+
@scope_ivar_alias.pop12901303
return12911304
end12921305
@scope_names.pop12931306
@scope_types.pop1307+
@scope_ivar_alias.pop12941308
end12951309
end12961310
12971311
def declare_var(name, vtype)12981312
@scope_names.push(name)12991313
@scope_types.push(vtype)1314+
@scope_ivar_alias.push("")13001315
013011316
end13021317
@@ -1327,6 +1342,31 @@
13271342
end13281343
end13291344
1345+
# Record / clear an ivar alias for a local variable. Walks the1346+
# `@scope_*` parallel stacks like `set_var_type` does. `iname` is1347+
# the source ivar name (e.g. `@fetch`); pass `""` to clear.1348+
def set_var_ivar_alias(name, iname)1349+
i = @scope_names.length - 11350+
while i >= 01351+
if @scope_names[i] == name1352+
@scope_ivar_alias[i] = iname1353+
return1354+
end1355+
i = i - 11356+
end1357+
end1358+
1359+
def find_var_ivar_alias(name)1360+
i = @scope_names.length - 11361+
while i >= 01362+
if @scope_names[i] == name1363+
return @scope_ivar_alias[i]1364+
end1365+
i = i - 11366+
end1367+
""1368+
end1369+
13301370
def find_var_type(name)13311371
# Type-narrow override (issue #207): walk top-down so the13321372
# innermost is_a? guard wins. Skipped for the unscoped global@@ -4303,6 +4343,13 @@
43034343
return "string"43044344
end43054345
if rt == "poly"4346+
# Approach 2: narrow `<poly>[k]` to int when the receiver4347+
# came from a poly_array whose observed element kinds all4348+
# imply int-returning `[]`. Mirrors the codegen-side4349+
# narrowing in `compile_poly_method_call`.4350+
if poly_index_narrow_int(nid) == 14351+
return "int"4352+
end43064353
return "poly"43074354
end43084355
if rt == "int_array"@@ -4763,6 +4810,15 @@
47634810
return "bool"47644811
end47654812
if mname == "[]"4813+
# Narrow `<poly>[k]` to int when the receiver came from a4814+
# poly_array whose observed slot-type history all imply4815+
# int-returning element kinds (IntArray, Method). Keep this4816+
# in sync with `compile_poly_method_call`'s codegen-side4817+
# narrowing — divergence widens the consuming slot to poly4818+
# while emit produces int.4819+
if poly_index_narrow_int(nid) == 14820+
return "int"4821+
end47664822
return "poly"47674823
end47684824
# Scan every user class that defines this method. If they all@@ -27165,6 +27221,186 @@
2716527221
02716627222
end2716727223
27224+
# Decide whether a `<poly>[k]` call site (the outer `[]` in27225+
# `arr[i][k]` chains) can return int instead of poly. The poly27226+
# value came from `arr[i]` where `arr` is a poly_array; if every27227+
# element kind observed for `arr`'s slot has an int-returning27228+
# `[]` (IntArray + Method, the optcarrot `__fetch__` shape), the27229+
# outer dispatch is guaranteed to land on a poly carrying an int27230+
# tag, and we can read it as `mrb_int` directly. Returns 027231+
# whenever the chain doesn't fit the pattern, so the default27232+
# poly-typed temp is preserved for everything else.27233+
def poly_index_narrow_int(nid)27234+
recv_id = @nd_receiver[nid]27235+
if recv_id < 027236+
return 027237+
end27238+
# The receiver must itself be a `[]` call (`arr[i]`).27239+
if @nd_type[recv_id] != "CallNode" || @nd_name[recv_id] != "[]"27240+
return 027241+
end27242+
inner_recv = @nd_receiver[recv_id]27243+
if inner_recv < 027244+
return 027245+
end27246+
# Resolve the inner receiver to an ivar (directly, or via a27247+
# one-step LV alias from `lv = @ivar`).27248+
iname = ""27249+
if @nd_type[inner_recv] == "InstanceVariableReadNode"27250+
iname = @nd_name[inner_recv]27251+
elsif @nd_type[inner_recv] == "LocalVariableReadNode"27252+
lv_name = @nd_name[inner_recv]27253+
# Codegen-time scope alias takes priority (set by the LV-write27254+
# handler when `lv = @ivar` is emitted in this scope).27255+
iname = find_var_ivar_alias(lv_name)27256+
# Fallback for inference-time (`infer_type` before codegen,27257+
# when the scope stack hasn't been populated yet): walk the27258+
# enclosing method bodies for a single, unambiguous27259+
# `lv_name = @ivar` write. If the LV is reassigned from a27260+
# non-ivar elsewhere, leave iname empty and let the caller27261+
# bail out — the alias is no longer load-bearing.27262+
if iname == ""27263+
iname = find_lv_ivar_alias_in_ast(lv_name)27264+
end27265+
end27266+
if iname == "" || @current_class_idx < 027267+
return 027268+
end27269+
# The slot must currently be a poly_array — the only shape that27270+
# produces a poly via `[i]`.27271+
slot_t = cls_ivar_type(@current_class_idx, iname)27272+
if slot_t != "poly_array"27273+
return 027274+
end27275+
# Derive the heterogeneous element kinds from27276+
# `cls_ivar_observed_types`. Each entry there is a slot type27277+
# the ivar held at some scan iteration: `int_array` means int27278+
# elements were stored, `obj_Method_ptr_array` means Method27279+
# elements, etc. The final `poly_array` entry just records the27280+
# widened state and adds no info. A bare `poly` observation27281+
# (whole-ivar `@x = something_poly`) is unknown — bail out.27282+
obs = cls_ivar_observed_types_for(@current_class_idx, iname)27283+
if obs == ""27284+
return 027285+
end27286+
distinct = obs.split(",")27287+
saw_any = 027288+
di = 027289+
while di < distinct.length27290+
t = distinct[di]27291+
if t == "" || t == "poly_array"27292+
# ignore — uninformative27293+
elsif t == "int_array" || t == "obj_Method_ptr_array"27294+
# int-returning element kind27295+
saw_any = 127296+
else27297+
# any other observed slot type (str_array, float_array,27298+
# other ptr_array variants, "poly" whole-ivar writes…) is27299+
# not safely narrowable.27300+
return 027301+
end27302+
di = di + 127303+
end27304+
saw_any27305+
end27306+
27307+
# Inference-time fallback for resolving `lv_name -> @ivar` when the27308+
# codegen scope alias isn't available yet. Walks every method body27309+
# in the current class for `lv_name = @ivar` writes. Returns the27310+
# ivar name only if the LV is unambiguously aliased (one ivar27311+
# source, no non-ivar reassignment); empty string otherwise. Cached27312+
# in `@lv_alias_cache_<class>:<lv>` to keep the per-narrow cost27313+
# down — this is called during type inference, which runs many27314+
# iterations.27315+
def find_lv_ivar_alias_in_ast(lv_name)27316+
if @current_class_idx < 027317+
return ""27318+
end27319+
cache_key = @current_class_idx.to_s + ":" + lv_name27320+
if @lv_alias_cache.key?(cache_key)27321+
return @lv_alias_cache[cache_key]27322+
end27323+
found = ""27324+
bodies = @cls_meth_bodies[@current_class_idx].split(";")27325+
bi = 027326+
while bi < bodies.length27327+
bid = bodies[bi].to_i27328+
if bid >= 027329+
r = scan_lv_alias_for(bid, lv_name)27330+
if r == "?"27331+
# Ambiguous: at least one non-ivar write to this LV. The27332+
# alias is unstable and unsafe to use for narrowing.27333+
found = ""27334+
break27335+
end27336+
if r != ""27337+
if found != "" && found != r27338+
found = ""27339+
break27340+
end27341+
found = r27342+
end27343+
end27344+
bi = bi + 127345+
end27346+
@lv_alias_cache[cache_key] = found27347+
found27348+
end27349+
27350+
# Recursive AST walk under `nid`. Returns:27351+
# "" — no `lv_name = ...` write seen27352+
# "?" — `lv_name = <non-ivar>` write seen (alias is unstable)27353+
# "@x" — exactly one ivar source `lv_name = @x` seen27354+
def scan_lv_alias_for(nid, lv_name)27355+
if nid < 027356+
return ""27357+
end27358+
found = ""27359+
if @nd_type[nid] == "LocalVariableWriteNode" && @nd_name[nid] == lv_name27360+
ex_id = @nd_expression[nid]27361+
if ex_id >= 0 && @nd_type[ex_id] == "InstanceVariableReadNode"27362+
found = @nd_name[ex_id]27363+
else27364+
return "?"27365+
end27366+
end27367+
cs = []27368+
push_child_ids(nid, cs)27369+
k = 027370+
while k < cs.length27371+
r = scan_lv_alias_for(cs[k], lv_name)27372+
if r == "?"27373+
return "?"27374+
end27375+
if r != ""27376+
if found != "" && found != r27377+
return "?"27378+
end27379+
found = r27380+
end27381+
k = k + 127382+
end27383+
found27384+
end27385+
27386+
# Read the comma-separated whole-ivar observation list for a given27387+
# ivar by name. Used by `poly_index_narrow_int`.27388+
def cls_ivar_observed_types_for(ci, iname)27389+
if ci < 0 || ci >= @cls_ivar_observed_types.length27390+
return ""27391+
end27392+
names = @cls_ivar_names[ci].split(";")27393+
parts = @cls_ivar_observed_types[ci].split(";", -1)27394+
k = 027395+
while k < names.length27396+
if names[k] == iname && k < parts.length27397+
return parts[k]27398+
end27399+
k = k + 127400+
end27401+
""27402+
end27403+
2716827404
def poly_dispatch_return_type(mname)2716927405
if mname == "[]"2717027406
@needs_rb_value = 1@@ -27328,6 +27564,21 @@
2732827564
# classes disagree on that type, the result is sp_RbVal and each2732927565
# branch boxes its concrete return value.2733027566
ret_type = poly_dispatch_return_type(mname)27567+
# Approach 2 narrowing: `<poly>[k]` defaults to poly because the27568+
# static `[]` dispatch can't pin the return; check whether the27569+
# poly receiver here came from `<poly_array>[i]` whose every27570+
# observed element kind has an int-returning `[]` (IntArray,27571+
# Method-with-int-return). If so, narrow to int so the slot27572+
# @_pc / @_addr / etc. on the caller side stays mrb_int instead27573+
# of widening to sp_RbVal and breaking downstream `iv += 1`,27574+
# `~poly`, and friends.27575+
narrowed_int_idx = 027576+
if ret_type == "poly" && mname == "[]"27577+
narrowed_int_idx = poly_index_narrow_int(nid)27578+
if narrowed_int_idx == 127579+
ret_type = "int"27580+
end27581+
end2733127582
is_poly_ret = ret_type == "poly" ? 1 : 02733227583
ret_ct = c_type(ret_type)2733327584
ret_def = c_default_val(ret_type)@@ -27427,7 +27678,16 @@
2742727678
this_rt = cls_method_return(i, mname)2742827679
rhs = box_val_to_poly(call_expr, this_rt)2742927680
end27430-
emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")27681+
# Narrowed `[]` arms (Approach 2): suppress user-class arms27682+
# whose `[]` doesn't return int — the dead-code emit would27683+
# otherwise assign e.g. a string to the now-mrb_int result27684+
# temp and fail the C compile. The runtime can't reach these27685+
# arms anyway because the observation set narrowed past them.27686+
if narrowed_int_idx == 1 && cls_method_return(i, mname) != "int"27687+
# skip27688+
else27689+
emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")27690+
end2743127691
elsif cls_has_attr_reader(i, mname) == 12743227692
# An auto-registered attr_reader doesn't appear in2743327693
# @cls_meth_names, so the explicit-method walk above misses it.@@ -27438,12 +27698,16 @@
2743827698
this_rt = cls_ivar_type(i, "@" + mname)2743927699
rhs = box_val_to_poly(ivar_expr, this_rt)2744027700
end27441-
emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")27701+
if narrowed_int_idx == 1 && cls_ivar_type(i, "@" + mname) != "int"27702+
# skip non-int attr_reader arms on a narrowed `[]`27703+
else27704+
emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")27705+
end2744227706
end2744327707
i = i + 12744427708
end2744527709
# Built-in type dispatch (cls_id < 0).27446-
emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, tmp, is_poly_ret)27710+
emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, tmp, is_poly_ret, narrowed_int_idx)2744727711
emit(" }")2744827712
tmp2744927713
end@@ -27451,7 +27715,7 @@
2745127715
# Emit branches for the built-in (negative cls_id) entries. Each2745227716
# entry maps a (SP_BUILTIN_*, method) pair to a C expression.2745327717
# Adding a new built-in type means one more `if` branch here.27454-
def emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, result_tmp, is_poly_ret)27718+
def emit_poly_builtin_dispatch(recv_tmp, mname, arg_compiled, arg_types, result_tmp, is_poly_ret, narrowed_int = 0)2745527719
a0 = ""2745627720
if arg_compiled.length > 02745727721
a0 = arg_compiled[0]@@ -27499,16 +27763,26 @@
2749927763
# implicitly convertible to any pointer for the non-poly path2750027764
# (result_tmp may be `sp_Foo *`) and accepted directly by2750127765
# sp_box_obj for the poly path. Casting through mrb_int would27502-
# fail to compile when result_tmp is a pointer type.27503-
pc = "sp_PtrArray_get((sp_PtrArray *)" + recv_tmp + ".v.p, " + a0 + ")"27504-
prhs = is_poly_ret == 1 ? "sp_box_obj(" + pc + ", 0)" : pc27505-
emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_PTR_ARRAY) " + result_tmp + " = " + prhs + ";")27766+
# fail to compile when result_tmp is a pointer type — and the27767+
# narrowed-`[]` path (Approach 2) types result_tmp as mrb_int,27768+
# so PtrArray cls_ids are unobserved by construction. Skip the27769+
# arm in that case.27770+
if narrowed_int == 027771+
pc = "sp_PtrArray_get((sp_PtrArray *)" + recv_tmp + ".v.p, " + a0 + ")"27772+
prhs = is_poly_ret == 1 ? "sp_box_obj(" + pc + ", 0)" : pc27773+
emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_PTR_ARRAY) " + result_tmp + " = " + prhs + ";")27774+
end2750627775
# PolyArray dispatch — sp_PolyArray_get returns sp_RbVal directly.2750727776
# When the result temp is poly, just assign; otherwise unbox via .v.i2750827777
# (the typed temp's static type drives caller-side conversion).27509-
polyc = "sp_PolyArray_get((sp_PolyArray *)" + recv_tmp + ".v.p, " + a0 + ")"27510-
polyrhs = is_poly_ret == 1 ? polyc : "(" + polyc + ").v.i"27511-
emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_POLY_ARRAY) " + result_tmp + " = " + polyrhs + ";")27778+
# Narrowed-`[]` likewise excludes PolyArray from the observed27779+
# set: the arm is unreachable, and emitting `.v.i` against a27780+
# cls_id that won't match at runtime is harmless but noisy.27781+
if narrowed_int == 027782+
polyc = "sp_PolyArray_get((sp_PolyArray *)" + recv_tmp + ".v.p, " + a0 + ")"27783+
polyrhs = is_poly_ret == 1 ? polyc : "(" + polyc + ").v.i"27784+
emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_POLY_ARRAY) " + result_tmp + " = " + polyrhs + ";")27785+
end2751227786
# Method dispatch — `bm[arg]` / `bm[a1, a2]` on a Method instance2751327787
# is `bm.call(...)`. When bm came through a heterogeneous2751427788
# poly_array (e.g. optcarrots `@fetch[i] = method(:peek_X)` mixed@@ -29749,6 +30023,16 @@
2974930023
set_var_type(lname, rhs_t)2975030024
end2975130025
end30026+
# Track `lv = @ivar` as a one-step alias so the `<poly>[k]`30027+
# narrowing can resolve through the local back to the ivar's30028+
# element-observation list. Any non-ivar RHS (or a subsequent30029+
# write of a non-ivar) clears the alias.30030+
ivar_alias = ""30031+
ex_id = @nd_expression[nid]30032+
if ex_id >= 0 && @nd_type[ex_id] == "InstanceVariableReadNode"30033+
ivar_alias = @nd_name[ex_id]30034+
end30035+
set_var_ivar_alias(lname, ivar_alias)2975230036
return2975330037
end2975430038
if t == "LocalVariableOperatorWriteNode"test/heterogeneous_dispatch_int_return_narrow.rbaddedView file
Loading diff…
test/heterogeneous_dispatch_int_return_narrow.rb.expectedaddedView file
Loading diff…