# Design: read-only []byte(s) arguments and single-type interface receivers (/docs/experiments/frontend/design-roconv)

Status: revision 2, after the backend critique (see the end). Both parts are opt-in switches, default off, until conformance, fuzz and perfcmp pass.

## Problem [#problem]

Release builds allocate more than go in the json and fmt rows of the bench. Callgrind counts (release, escape set on, linux/amd64): jsonenc 10.58 M allocations against go's 2.12 M, fmtlog 13.5 M against 9.0 M. Two causes this design covers:

1. []byte(s) conversions passed to a function that only reads them. gc converts them without a copy. marmot calls rawbyteslice. Jsonenc: 3.1 M in makeStringArshaler (jsonwire.AppendQuote(b, []byte(s), &mo.Flags)) and 1.0 M in (*encoderState).WriteToken. Fmtlog: h.Write([]byte(msg)), 1.5 M.
2. Interface method calls whose receiver has one known dynamic type. Fmtlog does h := fnv.New64a(). h.Write(...). New64a always returns *sum64a, so gc devirtualizes the call. The escape analysis of marmot treats every invoke as "may keep its arguments". So []byte\{'\n'\} and []byte(msg) go to the heap. These are 2 of the 3 extra allocations per line.

## What gc does [#what-gc-does]

- Escape analysis records, per parameter, whether the callee may write through it ("mutates"), besides whether it escapes. A []byte(s) whose result never escapes and is never written aliases the string (no copy). This works across packages through export data.
- Devirtualization: the dynamic type of an interface value can be statically known, for example after inlining a constructor that returns a concrete type. Then the call becomes a direct call, and escape analysis uses the concrete method.

## Part A: read-only parameter summaries (MARMOT_ROCONV) [#part-a-read-only-parameter-summaries-marmot_roconv]

A summary bit per parameter of slice type: "the callee never writes the elements". paramWritten(fn, i) is true when any of these reach the parameter or a value derived from it. Derived values are a Slice of it, a Phi, a ChangeType, a field of a struct holding it and an element address:
- Store to an IndexAddr of it.
- copy(dst, ...) with dst derived from it.
- append(x, ...) with x derived from it (append writes into x's array when cap allows).
- Passing it to a call: a static callee with paramWritten true for that position, any invoke, or a call through a func value. Also a builtin other than len, cap, copy (as source) and print, or a body-less function (asm, linkname, runtime).
- Conversion to unsafe.Pointer, or unsafe.SliceData / unsafe.Slice / unsafe.String on it.
- Storing it anywhere (Store of the slice value itself, MakeInterface, MakeClosure binding, channel send, map update, return): conservatively written, because the holder may write later. (Escaping covers most of these, this keeps the rule closed.)
- Recursion and unknown code: written.

Use: readOnlyBytes(v) (ops.go) accepts len, cap and element loads. It also accepts an argument position of a static call or a devirtualized call (Part B). There the callee must have paramWritten false, and the parameter must not escape (paramEscapes false, existing summary). Then the conversion aliases the string bytes with cap = len, as today.

Cross-package: the tag word of esctags.go (one bit per parameter for escape, one for to-result) gets a third bit per parameter, "written". Separate compilation: a package compiled before its callees reads the tag from the callee's export record. Absent tag = written.

Why cap = len is not enough on its own: append(b[:0], ...) in the callee writes into the array regardless of len. The append rule above is what protects it.

Soundness: string bytes may sit in read-only memory, so a missed write is a crash (SIGSEGV), not a silent wrong answer. The summary must stay conservative on every unknown.

## Part B: single-type interface receivers (MARMOT_DEVIRT1) [#part-b-single-type-interface-receivers-marmot_devirt1]

dynType(v) returns T when v (an interface value) is:
- MakeInterface of a value of concrete type T, or
- the result of a static call whose callee returns an interface made from type T on every return. That is a MakeInterface with X of type T, or a nested static call with dynType T. Or
- ChangeInterface or Phi of values that all have dynType T. Nil interfaces: a return of a nil interface makes the result "T or nil". The call then needs a nil check, which panics exactly as the invoke would (nil method value panic).

Uses:
1. Escape analysis: callLeaksF for an invoke with dynType(recv) = T uses the summary of the method of T (prog.MethodValue of its method set). returnedClosure does the same for func values today.
2. Code: emit a direct call to T's method (with the receiver extracted from the interface data word), guarded by the nil check only. The existing devirtualize() (calls.go) keeps its itab-compare form for the other cases.

Cross-package: the constructor (fnv.New64a) lives in another package. The tag gets one more field per function: the returned dynamic type (a type descriptor symbol name), or none. Absent = unknown.

Reflection and plugins: the dynamic type comes from the SSA of the constructor, which is the code that runs. No closed-world assumption.

## Tests [#tests]

- tests/run/opt/roconv: callees that write through the slice must each keep the copy. The program checks that the string is unchanged. The writes are a direct store, a copy into it and an append into a reslice. Others are a pass to a writer, a store in a global and a conversion to unsafe.Pointer. read-only callees (range, index read, bytes.Equal, hash.Write) must not copy (allocation report).
- tests/run/opt/devirt1: constructors returning one type, two types, a nil on one path, a reassigned variable, a type from another package. Output as go.
- Unit tests for paramWritten and dynType in the style of TestMayPanic.
- The allocation report (MARMOT_ALLOC_REPORT) shows the fmtlog and jsonenc sites as stack/alias.

## Measurement plan [#measurement-plan]

Callgrind allocation counts and instructions (load-independent) for jsonenc, jsondec, fmtlog, regexpbench. Then conformance and fuzz with the switches forced on. Then perfcmp -b-env. Expected: jsonenc -4.1 M allocations (39% of its total), fmtlog -2 per line (-3.0 M, 22%).

## Open questions for the critic [#open-questions-for-the-critic]

1. Does the backend devirtualize any of these already after inlining (release builds use the go dialect)? If so, Part B code generation is redundant and only the escape side matters.
2. Is a string's data ever in a writable page that another goroutine expects unchanged in a way the read-only rule misses (string(b) temporaries, tempString)? Part A must not apply to a []byte(s) of a temporary string view.
3. Tag format: one more bit per parameter and one type name per function. Any constraint from the backend's import of summaries (WPO)?

## Revision 2 (backend critique, 2026-11-18) [#revision-2-backend-critique-2026-11-18]

Backend reviewed revision 1: both parts sound once these gaps are closed. Each is now a rule of the design.

Part A (MARMOT_ROCONV):
1. Derived pointers: SliceToArrayPointer ((*[N]byte)(b)) and every IndexAddr or FieldAddr result count as derived values. A derived pointer may only feed loads. Passing it to a call or storing it counts as written.
2. go g(b) and defer g(b) count as written (the goroutine outlives the call, the deferred call runs through a func value).
3. Only bodies that link count. These count as written: body-less functions, linkname push and pull targets, assembly replacements, and functions that the C runtime or a lib/src override provides. Tags come from the bodies that link (the merged GOROOT with MARMOT_LIBSRC). A body swapped at link time must never get a read-only tag.
4. Temporary string views (tempString) never reach Part A. They allow only map keys and comparisons in one block. So a []byte(s) use makes the view a copy. STACKCONV frame buffers stay valid (the parameter does not escape). Unit test: string(b) then []byte(s) passed to a read-only callee copies or aliases correctly.
5. Generic callees: one summary per instance. Shape-typed bodies, if any, count as written.

Part B (MARMOT_DEVIRT1):
6. The nil check tests the type word (itab), not the data word. A non-nil interface that holds a nil *T calls the method. Only a nil interface panics.
7. The callee is the method the itab would hold: T's method for a value T (the call gets a copy of *data, the wrapper's summary applies), *T's for a pointer.
8. DynType is unknown for type parameters, interfaces loaded from memory, recover() results and constructors reached through a linkname. A Phi with a nil constant gives "T or nil".
9. The backend's GoDevirt (-release) sees only itabs visible in the same function and runs before inlining, so it misses fnv.New64a. Escape is decided before LLVM could make the call direct. So the escape side of Part B is needed in every mode. The direct call helps dev and -O 2 and costs nothing at -release.

Cross-package and keys:
10. The written bit and the returned type go into EscTags.Hash, so importTagsKey moves the keys of importers when a callee changes. Test: change a callee from read-only to writing, rebuild the importer incrementally, check it copies again. MARMOT_ROCONV and MARMOT_DEVIRT1 are codegen switches: TestCodegenSwitchesInKeys covers them. They stay out of noCodeEffect.
11. An aliased []byte(s) stays a plain (ptr, len, cap = len) value in the go dialect. No op exists that the backend could treat as owning or freeing it. Check: the lifetime pass (MARMOT_LIFETIME region frees) never frees the string's bytes through the alias. Test with MARMOT_LIFETIME=all.

Plan: Part A first (it covers jsonenc's 4.1 M allocations alone), then Part B. Each part lands opt-in with its tests, then conformance and fuzz with the switch on, then perfcmp -b-env.