Files
avo/examples/sum
Michael McLoughlin 304c7425d2 build: add attributes argument to TEXT
Brings the TEXT() function signature closer to how the directive works
in assembly.

Also update almost all examples to use NOSPLIT.

Closes #11
2019-01-06 20:04:51 -08:00
..
2019-01-06 20:04:51 -08:00
2018-12-27 23:09:44 -08:00
2018-12-12 00:02:22 -08:00
2019-01-06 20:04:51 -08:00

sum

Sum a slice of uint64s.

func main() {
	TEXT("Sum", "func(xs []uint64) uint64")
	Doc("Sum returns the sum of the elements in xs.")
	ptr := Load(Param("xs").Base(), GP64())
	n := Load(Param("xs").Len(), GP64())

	// Initialize sum register to zero.
	s := GP64()
	XORQ(s, s)

	// Loop until zero bytes remain.
	Label("loop")
	CMPQ(n, Imm(0))
	JE(LabelRef("done"))

	// Load from pointer and add to running sum.
	ADDQ(Mem{Base: ptr}, s)

	// Advance pointer, decrement byte count.
	ADDQ(Imm(8), ptr)
	DECQ(n)
	JMP(LabelRef("loop"))

	// Store sum to return value.
	Label("done")
	Store(s, ReturnIndex(0))
	RET()
	Generate()
}