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 by
157+ # `"<class_idx>:<lv_name>"`, value is the resolved ivar name (or
158+ # `""` when the LV has multiple sources / non-ivar writes).
159+ @lv_alias_cache = {}
156160 # Top-level (script-scope) ivars. Lowered to `static` file-scope
157161 # 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 directly
245+ # from an ivar read (`lv = @ivar`), record the ivar name here so
246+ # later sites that need ivar-side metadata (notably the
247+ # `<poly>[k]` narrowing in `compile_poly_method_call`) can
248+ # resolve through the alias. Empty string when the local has no
249+ # 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_scope
12791290 @scope_names.push("---")
12801291 @scope_types.push("---")
1292+ @scope_ivar_alias.push("---")
12811293 0
12821294 end
12831295
@@ -1287,16 +1299,19 @@
12871299 if top_name == "---"
12881300 @scope_names.pop
12891301 @scope_types.pop
1302+ @scope_ivar_alias.pop
12901303 return
12911304 end
12921305 @scope_names.pop
12931306 @scope_types.pop
1307+ @scope_ivar_alias.pop
12941308 end
12951309 end
12961310
12971311 def declare_var(name, vtype)
12981312 @scope_names.push(name)
12991313 @scope_types.push(vtype)
1314+ @scope_ivar_alias.push("")
13001315 0
13011316 end
13021317
@@ -1327,6 +1342,31 @@
13271342 end
13281343 end
13291344
1345+ # Record / clear an ivar alias for a local variable. Walks the
1346+ # `@scope_*` parallel stacks like `set_var_type` does. `iname` is
1347+ # the source ivar name (e.g. `@fetch`); pass `""` to clear.
1348+ def set_var_ivar_alias(name, iname)
1349+ i = @scope_names.length - 1
1350+ while i >= 0
1351+ if @scope_names[i] == name
1352+ @scope_ivar_alias[i] = iname
1353+ return
1354+ end
1355+ i = i - 1
1356+ end
1357+ end
1358+
1359+ def find_var_ivar_alias(name)
1360+ i = @scope_names.length - 1
1361+ while i >= 0
1362+ if @scope_names[i] == name
1363+ return @scope_ivar_alias[i]
1364+ end
1365+ i = i - 1
1366+ end
1367+ ""
1368+ end
1369+
13301370 def find_var_type(name)
13311371 # Type-narrow override (issue #207): walk top-down so the
13321372 # innermost is_a? guard wins. Skipped for the unscoped global
@@ -4303,6 +4343,13 @@
43034343 return "string"
43044344 end
43054345 if rt == "poly"
4346+ # Approach 2: narrow `<poly>[k]` to int when the receiver
4347+ # came from a poly_array whose observed element kinds all
4348+ # imply int-returning `[]`. Mirrors the codegen-side
4349+ # narrowing in `compile_poly_method_call`.
4350+ if poly_index_narrow_int(nid) == 1
4351+ return "int"
4352+ end
43064353 return "poly"
43074354 end
43084355 if rt == "int_array"
@@ -4763,6 +4810,15 @@
47634810 return "bool"
47644811 end
47654812 if mname == "[]"
4813+ # Narrow `<poly>[k]` to int when the receiver came from a
4814+ # poly_array whose observed slot-type history all imply
4815+ # int-returning element kinds (IntArray, Method). Keep this
4816+ # in sync with `compile_poly_method_call`'s codegen-side
4817+ # narrowing — divergence widens the consuming slot to poly
4818+ # while emit produces int.
4819+ if poly_index_narrow_int(nid) == 1
4820+ return "int"
4821+ end
47664822 return "poly"
47674823 end
47684824 # Scan every user class that defines this method. If they all
@@ -27165,6 +27221,186 @@
2716527221 0
2716627222 end
2716727223
27224+ # Decide whether a `<poly>[k]` call site (the outer `[]` in
27225+ # `arr[i][k]` chains) can return int instead of poly. The poly
27226+ # value came from `arr[i]` where `arr` is a poly_array; if every
27227+ # element kind observed for `arr`'s slot has an int-returning
27228+ # `[]` (IntArray + Method, the optcarrot `__fetch__` shape), the
27229+ # outer dispatch is guaranteed to land on a poly carrying an int
27230+ # tag, and we can read it as `mrb_int` directly. Returns 0
27231+ # whenever the chain doesn't fit the pattern, so the default
27232+ # 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 < 0
27236+ return 0
27237+ end
27238+ # The receiver must itself be a `[]` call (`arr[i]`).
27239+ if @nd_type[recv_id] != "CallNode" || @nd_name[recv_id] != "[]"
27240+ return 0
27241+ end
27242+ inner_recv = @nd_receiver[recv_id]
27243+ if inner_recv < 0
27244+ return 0
27245+ end
27246+ # Resolve the inner receiver to an ivar (directly, or via a
27247+ # 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-write
27254+ # 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 the
27258+ # enclosing method bodies for a single, unambiguous
27259+ # `lv_name = @ivar` write. If the LV is reassigned from a
27260+ # non-ivar elsewhere, leave iname empty and let the caller
27261+ # bail out — the alias is no longer load-bearing.
27262+ if iname == ""
27263+ iname = find_lv_ivar_alias_in_ast(lv_name)
27264+ end
27265+ end
27266+ if iname == "" || @current_class_idx < 0
27267+ return 0
27268+ end
27269+ # The slot must currently be a poly_array — the only shape that
27270+ # produces a poly via `[i]`.
27271+ slot_t = cls_ivar_type(@current_class_idx, iname)
27272+ if slot_t != "poly_array"
27273+ return 0
27274+ end
27275+ # Derive the heterogeneous element kinds from
27276+ # `cls_ivar_observed_types`. Each entry there is a slot type
27277+ # the ivar held at some scan iteration: `int_array` means int
27278+ # elements were stored, `obj_Method_ptr_array` means Method
27279+ # elements, etc. The final `poly_array` entry just records the
27280+ # widened state and adds no info. A bare `poly` observation
27281+ # (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 0
27285+ end
27286+ distinct = obs.split(",")
27287+ saw_any = 0
27288+ di = 0
27289+ while di < distinct.length
27290+ t = distinct[di]
27291+ if t == "" || t == "poly_array"
27292+ # ignore — uninformative
27293+ elsif t == "int_array" || t == "obj_Method_ptr_array"
27294+ # int-returning element kind
27295+ saw_any = 1
27296+ else
27297+ # any other observed slot type (str_array, float_array,
27298+ # other ptr_array variants, "poly" whole-ivar writes…) is
27299+ # not safely narrowable.
27300+ return 0
27301+ end
27302+ di = di + 1
27303+ end
27304+ saw_any
27305+ end
27306+
27307+ # Inference-time fallback for resolving `lv_name -> @ivar` when the
27308+ # codegen scope alias isn't available yet. Walks every method body
27309+ # in the current class for `lv_name = @ivar` writes. Returns the
27310+ # ivar name only if the LV is unambiguously aliased (one ivar
27311+ # source, no non-ivar reassignment); empty string otherwise. Cached
27312+ # in `@lv_alias_cache_<class>:<lv>` to keep the per-narrow cost
27313+ # down — this is called during type inference, which runs many
27314+ # iterations.
27315+ def find_lv_ivar_alias_in_ast(lv_name)
27316+ if @current_class_idx < 0
27317+ return ""
27318+ end
27319+ cache_key = @current_class_idx.to_s + ":" + lv_name
27320+ if @lv_alias_cache.key?(cache_key)
27321+ return @lv_alias_cache[cache_key]
27322+ end
27323+ found = ""
27324+ bodies = @cls_meth_bodies[@current_class_idx].split(";")
27325+ bi = 0
27326+ while bi < bodies.length
27327+ bid = bodies[bi].to_i
27328+ if bid >= 0
27329+ r = scan_lv_alias_for(bid, lv_name)
27330+ if r == "?"
27331+ # Ambiguous: at least one non-ivar write to this LV. The
27332+ # alias is unstable and unsafe to use for narrowing.
27333+ found = ""
27334+ break
27335+ end
27336+ if r != ""
27337+ if found != "" && found != r
27338+ found = ""
27339+ break
27340+ end
27341+ found = r
27342+ end
27343+ end
27344+ bi = bi + 1
27345+ end
27346+ @lv_alias_cache[cache_key] = found
27347+ found
27348+ end
27349+
27350+ # Recursive AST walk under `nid`. Returns:
27351+ # "" — no `lv_name = ...` write seen
27352+ # "?" — `lv_name = <non-ivar>` write seen (alias is unstable)
27353+ # "@x" — exactly one ivar source `lv_name = @x` seen
27354+ def scan_lv_alias_for(nid, lv_name)
27355+ if nid < 0
27356+ return ""
27357+ end
27358+ found = ""
27359+ if @nd_type[nid] == "LocalVariableWriteNode" && @nd_name[nid] == lv_name
27360+ ex_id = @nd_expression[nid]
27361+ if ex_id >= 0 && @nd_type[ex_id] == "InstanceVariableReadNode"
27362+ found = @nd_name[ex_id]
27363+ else
27364+ return "?"
27365+ end
27366+ end
27367+ cs = []
27368+ push_child_ids(nid, cs)
27369+ k = 0
27370+ while k < cs.length
27371+ r = scan_lv_alias_for(cs[k], lv_name)
27372+ if r == "?"
27373+ return "?"
27374+ end
27375+ if r != ""
27376+ if found != "" && found != r
27377+ return "?"
27378+ end
27379+ found = r
27380+ end
27381+ k = k + 1
27382+ end
27383+ found
27384+ end
27385+
27386+ # Read the comma-separated whole-ivar observation list for a given
27387+ # 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.length
27390+ return ""
27391+ end
27392+ names = @cls_ivar_names[ci].split(";")
27393+ parts = @cls_ivar_observed_types[ci].split(";", -1)
27394+ k = 0
27395+ while k < names.length
27396+ if names[k] == iname && k < parts.length
27397+ return parts[k]
27398+ end
27399+ k = k + 1
27400+ end
27401+ ""
27402+ end
27403+
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 each
2732927565 # branch boxes its concrete return value.
2733027566 ret_type = poly_dispatch_return_type(mname)
27567+ # Approach 2 narrowing: `<poly>[k]` defaults to poly because the
27568+ # static `[]` dispatch can't pin the return; check whether the
27569+ # poly receiver here came from `<poly_array>[i]` whose every
27570+ # observed element kind has an int-returning `[]` (IntArray,
27571+ # Method-with-int-return). If so, narrow to int so the slot
27572+ # @_pc / @_addr / etc. on the caller side stays mrb_int instead
27573+ # of widening to sp_RbVal and breaking downstream `iv += 1`,
27574+ # `~poly`, and friends.
27575+ narrowed_int_idx = 0
27576+ if ret_type == "poly" && mname == "[]"
27577+ narrowed_int_idx = poly_index_narrow_int(nid)
27578+ if narrowed_int_idx == 1
27579+ ret_type = "int"
27580+ end
27581+ end
2733127582 is_poly_ret = ret_type == "poly" ? 1 : 0
2733227583 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 end
27430- emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27681+ # Narrowed `[]` arms (Approach 2): suppress user-class arms
27682+ # whose `[]` doesn't return int — the dead-code emit would
27683+ # otherwise assign e.g. a string to the now-mrb_int result
27684+ # temp and fail the C compile. The runtime can't reach these
27685+ # arms anyway because the observation set narrowed past them.
27686+ if narrowed_int_idx == 1 && cls_method_return(i, mname) != "int"
27687+ # skip
27688+ else
27689+ emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27690+ end
2743127691 elsif cls_has_attr_reader(i, mname) == 1
2743227692 # An auto-registered attr_reader doesn't appear in
2743327693 # @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 end
27441- 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+ else
27704+ emit(" if (" + recv_tmp + ".cls_id == " + i.to_s + ") " + tmp + " = " + rhs + ";")
27705+ end
2744227706 end
2744327707 i = i + 1
2744427708 end
2744527709 # 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 tmp
2744927713 end
@@ -27451,7 +27715,7 @@
2745127715 # Emit branches for the built-in (negative cls_id) entries. Each
2745227716 # 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 > 0
2745727721 a0 = arg_compiled[0]
@@ -27499,16 +27763,26 @@
2749927763 # implicitly convertible to any pointer for the non-poly path
2750027764 # (result_tmp may be `sp_Foo *`) and accepted directly by
2750127765 # sp_box_obj for the poly path. Casting through mrb_int would
27502- # 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)" : pc
27505- 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 the
27767+ # narrowed-`[]` path (Approach 2) types result_tmp as mrb_int,
27768+ # so PtrArray cls_ids are unobserved by construction. Skip the
27769+ # arm in that case.
27770+ if narrowed_int == 0
27771+ pc = "sp_PtrArray_get((sp_PtrArray *)" + recv_tmp + ".v.p, " + a0 + ")"
27772+ prhs = is_poly_ret == 1 ? "sp_box_obj(" + pc + ", 0)" : pc
27773+ emit(" if (" + recv_tmp + ".cls_id == SP_BUILTIN_PTR_ARRAY) " + result_tmp + " = " + prhs + ";")
27774+ end
2750627775 # PolyArray dispatch — sp_PolyArray_get returns sp_RbVal directly.
2750727776 # When the result temp is poly, just assign; otherwise unbox via .v.i
2750827777 # (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 observed
27779+ # set: the arm is unreachable, and emitting `.v.i` against a
27780+ # cls_id that won't match at runtime is harmless but noisy.
27781+ if narrowed_int == 0
27782+ 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+ end
2751227786 # Method dispatch — `bm[arg]` / `bm[a1, a2]` on a Method instance
2751327787 # is `bm.call(...)`. When bm came through a heterogeneous
2751427788 # poly_array (e.g. optcarrots `@fetch[i] = method(:peek_X)` mixed
@@ -29749,6 +30023,16 @@
2974930023 set_var_type(lname, rhs_t)
2975030024 end
2975130025 end
30026+ # Track `lv = @ivar` as a one-step alias so the `<poly>[k]`
30027+ # narrowing can resolve through the local back to the ivar's
30028+ # element-observation list. Any non-ivar RHS (or a subsequent
30029+ # 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+ end
30035+ set_var_ivar_alias(lname, ivar_alias)
2975230036 return
2975330037 end
2975430038 if t == "LocalVariableOperatorWriteNode"