Skip to content

cmd/compile, runtime: recognize min/max reduction loops and rewrite them to vectorized kernels (under GOEXPERIMENT=simd) #80857

Closed

Description

@achille-roussel

The compiler performs no auto-vectorization, so element-wise min/max reductions — including slices.Min and slices.Max — compile to scalar loops processing one element per iteration. On amd64 this leaves large factors on the table: a scalar CMOV loop over []uint8 runs at ~1.5 GB/s where AVX-512 reaches ~90 GB/s, and the compiled scalar form of the float min builtin costs ~10 cycles per element.

This issue proposes recognizing min/max reduction loops in walk — in the spirit of the existing memclr (#5373) and map-clearing (#20138) range-idiom optimizations — and rewriting them into calls to vectorized runtime kernels built on simd/archsimd (#73787), gated on GOEXPERIMENT=simd and amd64.

Recognized forms

for i := k; i < len(x); i++ { m = min(m, x[i]) }   // the body of slices.Min/Max
for _, v := range x { m = min(m, v) }
for _, v := range x { if v < m { m = v } }         // and <=, >, >=, either operand order

The indexed form is rewritten to if i < len(x) { m = runtime.kernel(m, x[i:]); i = len(x) }, which is exact for any starting value of i and preserves i after the loop. The rewrite fires both in the generic shape instantiations of slices.Min/Max and when they inline into callers. It is disabled under -N and under -race/-msan/-asan (like the memclr idioms, since it would elide the per-element loads those tools instrument), and never fires when compiling the runtime itself (the kernels' own scalar tails are the recognized form).

Kernels

Seeded reductions (minUint8(m uint8, d []uint8) uint8, etc.) for all integer element types — int/uint/uintptr map to the 64-bit kernels — plus float32/float64. The kernels live in runtime and are declared in _builtin/runtime.go, like the memclr family. AVX-512 and AVX2 tiers with dynamic dispatch via internal/cpu (so the win is independent of GOAMD64), two vectors per iteration, remainders handled by reloading full vectors overlapping already-processed elements (min/max are idempotent). 64-bit AVX2 tiers select with compare+blend (VPMINSQ is AVX-512-only). This requires adding simd/archsimd to the runtime package set in objabi.pkgspecial; the dependency graph in go/build already permits the edge.

Float semantics

The two loop forms differ for floats, so they are handled differently:

  • m = min(m, v) propagates NaN and prefers −0. The kernels reproduce the scalar lowering exactly (two directed compare+blend selects, bit-OR combined; max runs the min kernel in the negated domain, as AMD64.rules does). archsimd's float Min/Max are not used: their NaN behavior is undocumented and operand-order-dependent.
  • if v < m { m = v } skips NaN elements and keeps a NaN accumulator, and a single compare+blend reproduces this — except when the result is zero and the input mixes −0 and +0, where lane-parallel evaluation can return the other sign of zero than the sequential loop (observable via math.Signbit). Following the standard set by cmd/compile: recognize map-clearing range idiom #20138, which excluded non-reflexive key types rather than accept any observable deviation, the comparison form is not rewritten for float elements. Float recognition covers the builtin form only, which keeps the full slices.Min/Max win; the loose comparison forms (v <= m) are likewise not rewritten for floats (they replace the accumulator on a −0/+0 tie).

Performance

Intel Xeon Platinum 8481C (Sapphire Rapids), GOAMD64=v4, 64K elements, vector kernel vs the loop it replaces:

Element type before after speedup
uint8 1.5 GB/s 118.7 GB/s 79x
int16 3.0 GB/s 123.8 GB/s 42x
int64 (= []int) 11.9 GB/s 126.2 GB/s 10.6x
float32 (builtin form) 1.07 GB/s 48.1 GB/s 45x
float64 (builtin form) 2.14 GB/s 48.4 GB/s 23x

The integer kernels approach memory bandwidth; the float kernels are compute-bound by the exact-semantics select sequence (two directed compare+blends plus a bit-OR per vector, versus a single VPMIN for integers). The AVX2 tier, measured on the same machine at the series stage before the AVX-512 commit, reaches 78.9 GB/s (uint8) and 83.2 GB/s (int16). Below one vector chunk the kernels fall back to their scalar loops.

An implementation of all of the above as a CL series is at https://github.com/achille-roussel/go/tree/simd-minmax-idiom.

Activity

  1. randall77 commented on Aug 12, 2026

    @randall77
    Contributor

    It is not clear to me why this should be a compiler optimization instead of just a library (which itself uses archsimd).

    Compiler optimizations are for general code and should apply in lots of different situations that make explicit libraries infeasible. If we're really just implementing min([]T), we should just write a library for that.

  2. achille-roussel commented on Aug 12, 2026

    @achille-roussel
    ContributorAuthor

    You're correct, this can be an optimization in the implementation of slices.Min/Max, it's a smaller scope but would solve the problem as well.

    I don't have a strong opinion, I pattern-matched on the loop optimizations that already exist in the compiler (e.g., zeroing slices or clearing maps), but either way would work.

  3. achille-roussel commented on Aug 13, 2026

    @achille-roussel
    ContributorAuthor

    Exploring the option to do this at the slices package level, I don't think we currently have a way to really implement the optimization in library code yet.

    The closest we can get is a narrow subset of what the proposed change would support, for example:

    func Min[S ~[]E, E cmp.Ordered](x S) E {
    	if len(x) < 1 {
    		panic("slices.Min: empty list")
    	}
    	switch s := any(x).(type) {
    	case []int32:
    		return minInt32(s)
    	case []int64:
    		return minInt64(s)
    	...
    	}
    	m := x[0]
    	for i := 1; i < len(x); i++ {
    		m = min(m, x[i])
    	}
    	return m
    }

    With DCE, most of this code will be removed in the instantiation of the generic function, however, it disables the optimization when used on a types like:

    // neither of those would be optimized
    type Int32Slice []int32 // slices.Min(Int32Slice{0,1,2})
    type Int32 int32 // slices.Min([]Int32{0,1,2})

    Those have a layout compatible with the optimization but wouldn't match the type assertion for []int32.

    Am I missing something?

  4. randall77 commented on Aug 13, 2026

    @randall77
    Contributor

    Something like this works, but is kinda ugly:

    if s, ok := any(x).([]int32); ok {
    	return any(minInt32(s)).(E)
    }
    func minInt32(s []int32) int32
    
  5. achille-roussel commented on Aug 13, 2026

    @achille-roussel
    ContributorAuthor

    Would it? any(x).([]int32) wouldn't pass if E isn't exactly []int32 isn't it?

  6. randall77 commented on Aug 13, 2026

    @randall77
    Contributor

    Would it? any(x).([]int32) wouldn't pass if E isn't exactly []int32 isn't it?

    It would work for named slices (type Name []int32; var s Name; min(s)). It would not work for named elements (type Elem int32; var s []Elem; min(s)).

  7. 11 remaining items

  8. achille-roussel commented on Aug 15, 2026

    @achille-roussel
    ContributorAuthor

    I did more research on the topic and I think we'd need a proposal like #45380 to support implementing this as library code in the slices package.

  9. added
    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.
    on Aug 18, 2026
  10. added this to the Backlog milestone on Aug 18, 2026
  11. randall77 commented on Aug 19, 2026

    @randall77
    Contributor

    We discussed this in triage and we don't think we want to implement this kind of thing inside the compiler. This should be a library of some sort. We already have slices.{Min,Max}, we would welcome optimizations (SIMD?) to those functions.

    We do lower zeroing loops to memclr, but that optimization came before the clear builtin. I don't think we'd allow rewriting loops to memclr if we had to make that decision again today. Especially because it is tricky, see #80519.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions