Skip to content

cmd/compile: small fixed array [2]uint64 fails scalar replacement of aggregates (SROA) unlike equivalent struct #81192

Closed

Description

@hazyhaar

What version of Go are you using (go version)?

go version go1.27.0 linux/amd64 (and earlier Go versions).

What operating system and processor architecture are you using (go env)?

linux/amd64

What did you do?

We compared the SSA code generation of 128-bit arithmetic across three representations:

  1. Two scalar variables (a0, a1 uint64)
  2. A two-field struct (struct { Lo, Hi uint64 })
  3. A two-element fixed array ([2]uint64)

Reproduction file:

package main

import "math/bits"

// 1. Array representation
//go:noinline
func Add128Array(a, b [2]uint64) [2]uint64 {
	lo, c := bits.Add64(a[0], b[0], 0)
	hi, _ := bits.Add64(a[1], b[1], c)
	return [2]uint64{lo, hi}
}

// 2. Struct representation
type Uint128 struct {
	Lo, Hi uint64
}

//go:noinline
func Add128Struct(a, b Uint128) Uint128 {
	lo, c := bits.Add64(a.Lo, b.Lo, 0)
	hi, _ := bits.Add64(a.Hi, b.Hi, c)
	return Uint128{Lo: lo, Hi: hi}
}

// 3. Scalar representation
//go:noinline
func Add128Scalar(a0, a1, b0, b1 uint64) (uint64, uint64) {
	lo, c := bits.Add64(a0, b0, 0)
	hi, _ := bits.Add64(a1, b1, c)
	return lo, hi
}

func main() {}

What did you see happen?

cmd/compile (go build -gcflags="-S") performs Scalar Replacement of Aggregates (SROA) for Add128Struct and Add128Scalar, generating optimal 7-byte register-only code:

main.Add128Scalar STEXT nosplit size=7 args=0x20 locals=0x0
	ADDQ	CX, AX
	ADCQ	DI, BX
	RET

main.Add128Struct STEXT nosplit size=7 args=0x20 locals=0x0
	ADDQ	CX, AX
	ADCQ	DI, BX
	RET

However, for [2]uint64 in Add128Array, the SSA backend fails to decompose the array into scalar registers. It generates 46 bytes of machine code with stack allocation, stack reads/writes, and zeroing:

main.Add128Array STEXT nosplit size=46 args=0x30 locals=0x0
	LEAQ	main.~r0+40(SP), AX
	MOVUPS	X15, (AX)
	MOVQ	main.a+8(SP), AX
	MOVQ	main.b+24(SP), CX
	MOVQ	main.a+16(SP), DX
	MOVQ	main.b+32(SP), BX
	ADDQ	AX, CX
	MOVQ	CX, main.~r0+40(SP)
	ADCQ	BX, DX
	MOVQ	DX, main.~r0+48(SP)
	RET

When 128-bit operations are chained in loops, this asymmetry causes severe register spilling to the stack for small arrays, expanding the stack frame and emitting dead bounds check branches that are completely absent with structs or scalars.

What did you expect to see?

For small non-escaping fixed arrays (e.g. [2]uint64, [2]uint32, [4]uint32), cmd/compile's SSA pass should perform scalar replacement into GPR registers with the same efficiency as equivalent structs (struct{Lo, Hi uint64}).

Activity

  1. randall77 commented on Aug 28, 2026

    @randall77
    Contributor

    The tricky part of registerizing arrays is what to do about non-constant indexes. That problem cannot happen for structs.

    That said @JunyangShao has a set of CLs that would probably fix this for 1.28.

  2. JunyangShao commented on Aug 28, 2026

    @JunyangShao
    Contributor

    My SROA pass can handle partially, if Add128Array is called with local variables in its caller side, and it's inlined, then SROA can promote them.
    But the function itself won't be SROA-ed, because my SROA currently don't optimize params, and also CanSSA decides to put the 2 arrays in memory already, and I am not sure if it's possible to change the ABI decision at SSA stage.

    Supporting SROA on params is in my plan though, it might not completely move the value to register, but everything following a dominating load can be registerized I think. :D

  3. hazyhaar commented on Aug 28, 2026

    @hazyhaar
    Author

    Hi Junyang,

    Thanks for the clarification on the SROA / SSA pipeline!

    To provide some concrete context on why this matters so much for 128-bit/256-bit arithmetic and crypto kernels (like Poly1305, ChaCha20, AES-OCB), we ran an isolated SSA assembly comparison and micro-benchmark on Go 1.27 (GOEXPERIMENT=simd, AMD64) comparing [2]uint64 vs struct{Lo, Hi uint64} vs discrete scalars.

    1. Disassembly Comparison (go build -gcflags="-S")

    A. Array parameter Add128_Array(a, b [2]uint64) [2]uint64 (46 bytes, 8 stack operations):

    LEAQ    main.~r0+40(SP), AX
    MOVUPS  X15, (AX)
    MOVQ    main.a+8(SP), AX      // Load a[0] from stack
    MOVQ    main.b+24(SP), CX     // Load b[0] from stack
    MOVQ    main.a+16(SP), DX     // Load a[1] from stack
    MOVQ    main.b+32(SP), BX     // Load b[1] from stack
    ADDQ    AX, CX                // Add lo
    MOVQ    CX, main.~r0+40(SP)   // Store lo to stack
    ADCQ    BX, DX                // Add hi with carry
    MOVQ    DX, main.~r0+48(SP)   // Store hi to stack
    RET

    B. Struct parameter Add128_Struct(a, b U128Struct) U128Struct (7 bytes, 0 stack operations):

    ADDQ    CX, AX                // RAX = a.Lo + b.Lo (100% Register ABI)
    ADCQ    DI, BX                // RBX = a.Hi + b.Hi + Carry
    RET

    2. Benchmark Results (i9-14900K, Go 1.27.0):

    Benchmark_Add128_Array_StackSpill-32    420000000    5.61 ns/op   (Stack ABI)
    Benchmark_Add128_Struct_RegABI-32      1000000000    0.61 ns/op   (9.2x faster, 100% Reg ABI)
    Benchmark_Add128_Scalars_RegABI-32     1000000000    0.63 ns/op   (8.9x faster, 100% Reg ABI)
    

    3. Takeaway & Observation on types/size.go:

    • The reason [2]uint64 is sent to stack memory in the first place is that types/size.go:619 assigns the sentinel MaxUint8 to [N>1]T, whereas a struct with <= 4 fields (MaxStruct) is allocated direct GPR registers in abiutils.go.
    • While SROA on PPARAM with a dominating load (CL 743100) will be a massive improvement for loop bodies, treating small fixed-size arrays (<= 4 scalar words, 32 bytes max) identically to equivalent structs in types/size.go and CanSSA would eliminate the caller/callee stack overhead entirely.

    Looking forward to your SROA CL landing!

  4. JunyangShao commented on Aug 29, 2026

    @JunyangShao
    Contributor

    @hazyhaar I think the decision to registerize array params with len > 1 shouldn't be made by SROA, it belongs in the frontend, where CanSSA/param decisions live. This pending CL makes small arrays SSA-able and could be extended to cover params. Note the CL currently excludes params deliberately (decomposing a copy-dominated param pessimizes whole-copies), so the extension probably wants a use-sensitivity check alongside its existing dynamic-index analysis.

    Actually passing arrays params in registers would additionally need an ABIInternal change (the register-assignment algorithm stack-assigns arrays of length > 1) plus matching updates in reflect and the runtime, that's separable, and per the ABI doc's own rationale probably not worth it on its own.

    @randall77 Wdyt? Is that CL a good candidate for the param extension, or should we do it ourselves? Or should we do it at all? :P

  5. randall77 commented on Aug 29, 2026

    @randall77
    Contributor

    I'm not sure if we should change the ABI at this point. It will help cases where we use all constant indexes, sure, but I suspect that's a minority of cases. Otherwise, I think it just makes things worse. And we can't in general tell whether the callee uses constant indexes or not (e.g. for an interface call).

    func f(a [4]int, i int) int {
        return a[i]
    }
    

    This function currently compiles to a single indexed load. If a came in registers, then we need 4 stores + an indexed load (or some mess of conditional moves or masking to simulate indexing).
    Of course, at the call site we would need fewer stores.

    f([4]int{3,4,5,6}, 1)
    

    Currently needs 4 constant stores to set up the array. If we passed in registers, we'd need 4 constant moves.
    So passing in registers seems to me at least a slight pessimism (same number of stores, maybe a few extra reg-reg ops) in the case where indexes aren't constant.

    Putting arrays in registers can also quickly exhaust the set of registers. For f, what if we had only 4 registers? Then i is not in a register anymore.

  6. hazyhaar commented on Aug 29, 2026

    @hazyhaar
    Author

    Thanks @randall77 and @JunyangShao for taking the time to explain the underlying trade-offs.

    It helps me understand much better why general-purpose Go makes this choice around dynamic indexing (a[i]), and why keeping [N>1]T on the stack ABI makes sense at the language scale.

    Looking forward to Junyang's CanSSA / SROA work landing in 1.28. In the meantime, we will continue using dedicated structs (struct { Lo, Hi uint64 }) for our static 128-bit/crypto kernels.

    Appreciate the great discussion, and thanks a lot for 1.27, it's awesome!

  7. JunyangShao commented on Sep 8, 2026

    @JunyangShao
    Contributor

    We will do the SROA passes to optimize local variables, but not yet for params.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

compiler/runtimeIssues related to the Go compiler and/or runtime.

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions