Source file src/cmd/compile/internal/test/stack_test.go

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package test
     6  
     7  import (
     8  	"internal/testenv"
     9  	"testing"
    10  	"unsafe"
    11  )
    12  
    13  // Stack allocation size for variable-sized allocations.
    14  // Matches constant of the same name in ../walk/builtin.go:walkMakeSlice.
    15  const maxStackSize = 32
    16  
    17  //go:noinline
    18  func genericUse[T any](s []T) {
    19  	// Doesn't escape s.
    20  }
    21  
    22  func TestStackAllocation(t *testing.T) {
    23  	testenv.SkipIfOptimizationOff(t)
    24  
    25  	type testCase struct {
    26  		f        func(int)
    27  		elemSize uintptr
    28  	}
    29  
    30  	for _, tc := range []testCase{
    31  		{
    32  			f: func(n int) {
    33  				genericUse(make([]int, n))
    34  			},
    35  			elemSize: unsafe.Sizeof(int(0)),
    36  		},
    37  		{
    38  			f: func(n int) {
    39  				genericUse(make([]*byte, n))
    40  			},
    41  			elemSize: unsafe.Sizeof((*byte)(nil)),
    42  		},
    43  		{
    44  			f: func(n int) {
    45  				genericUse(make([]string, n))
    46  			},
    47  			elemSize: unsafe.Sizeof(""),
    48  		},
    49  	} {
    50  		max := maxStackSize / int(tc.elemSize)
    51  		if n := testing.AllocsPerRun(10, func() {
    52  			tc.f(max)
    53  		}); n != 0 {
    54  			t.Fatalf("unexpected allocation: %f", n)
    55  		}
    56  		if n := testing.AllocsPerRun(10, func() {
    57  			tc.f(max + 1)
    58  		}); n != 1 {
    59  			t.Fatalf("unexpected allocation: %f", n)
    60  		}
    61  	}
    62  }
    63  

View as plain text