Source file src/simd/example_amd64_test.go

     1  // Copyright 2026 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  //go:build goexperiment.simdstable && amd64
     6  
     7  package simd_test
     8  
     9  import (
    10  	"fmt"
    11  	"simd"
    12  	"simd/archsimd"
    13  )
    14  
    15  // mulAddPairs multiplies corresponding int16 elements of x and y and adds
    16  // their products into acc, using x86's VPMADDWD (DotProductPairs) when
    17  // available and falling back to portable widening multiplies otherwise.
    18  func mulAddPairs(acc simd.Int32s, x, y simd.Int16s) simd.Int32s {
    19  	switch ax := x.ToArch().(type) {
    20  	case archsimd.Int16x8:
    21  		ay := y.ToArch().(archsimd.Int16x8)
    22  		return acc.Add(simd.Int32sFromArch(ax.DotProductPairs(ay)))
    23  	case archsimd.Int16x16:
    24  		ay := y.ToArch().(archsimd.Int16x16)
    25  		return acc.Add(simd.Int32sFromArch(ax.DotProductPairs(ay)))
    26  	case archsimd.Int16x32:
    27  		ay := y.ToArch().(archsimd.Int16x32)
    28  		return acc.Add(simd.Int32sFromArch(ax.DotProductPairs(ay)))
    29  	default:
    30  		lo := x.ExtendToInt32().Mul(y.ExtendToInt32())
    31  		hi := x.HiToLo().ExtendToInt32().Mul(y.HiToLo().ExtendToInt32())
    32  		return acc.Add(lo).Add(hi)
    33  	}
    34  }
    35  
    36  // dotProduct returns the int32 dot product of equal-length slices xs and ys.
    37  func dotProduct(xs, ys []int16) int32 {
    38  	var acc simd.Int32s
    39  	step := (simd.Int16s{}).Len()
    40  	i := 0
    41  	for ; i+step <= len(xs); i += step {
    42  		x := simd.LoadInt16s(xs[i:])
    43  		y := simd.LoadInt16s(ys[i:])
    44  		acc = mulAddPairs(acc, x, y)
    45  	}
    46  	if i < len(xs) {
    47  		x, _ := simd.LoadInt16sPart(xs[i:])
    48  		y, _ := simd.LoadInt16sPart(ys[i:])
    49  		acc = mulAddPairs(acc, x, y)
    50  	}
    51  	return acc.ReduceSum()
    52  }
    53  
    54  func ExampleInt16s_ToArch() {
    55  	xs := make([]int16, 50)
    56  	ys := make([]int16, 50)
    57  	for i := range xs {
    58  		xs[i] = int16(i + 1)
    59  		ys[i] = 2
    60  	}
    61  	fmt.Println(dotProduct(xs, ys))
    62  	// Output: 2550
    63  }
    64  

View as plain text