dnl  AMD64 mpn_addsubmul_1msb0, R = Au - Bv, u,v < 2^63.

dnl  Copyright 2021 Free Software Foundation, Inc.

dnl  This file is part of the GNU MP Library.
dnl
dnl  The GNU MP Library is free software; you can redistribute it and/or modify
dnl  it under the terms of either:
dnl
dnl    * the GNU Lesser General Public License as published by the Free
dnl      Software Foundation; either version 3 of the License, or (at your
dnl      option) any later version.
dnl
dnl  or
dnl
dnl    * the GNU General Public License as published by the Free Software
dnl      Foundation; either version 2 of the License, or (at your option) any
dnl      later version.
dnl
dnl  or both in parallel, as here.
dnl
dnl  The GNU MP Library is distributed in the hope that it will be useful, but
dnl  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
dnl  for more details.
dnl
dnl  You should have received copies of the GNU General Public License and the
dnl  GNU Lesser General Public License along with the GNU MP Library.  If not,
dnl  see https://www.gnu.org/licenses/.

include(`../config.m4')

C INPUT PARAMETERS
define(`rp',	`%rdi')
define(`ap',	`%rsi')
define(`bp_param', `%rdx')
define(`n',	`%rcx')
define(`u0',	`%r8')
define(`v0',	`%r9')

define(`bp', `%rbp')

define(`c0', `%rax')	C c0 and c1 alternate as carry limbs
define(`c1', `%rbx')	C c0 is also the return value.
define(`l0', `%r10')
define(`l1', `%r11')
define(`hi', `%r12')

undefine(`mulx', `adcx', `adox')

ASM_START()
	TEXT
	ALIGN(16)
PROLOGUE(mpn_addaddmul_1msb0)

	push	%rbx
	push	%rbp
	push	%r12

	lea	(ap,n,8), ap
	lea	(bp_param,n,8), bp
	lea	(rp,n,8), rp
	neg	n

	xor	c0, c0		C Also clears CF and OF
	test	$1, n
	jz	L(top)

	mov	(ap, n, 8), %rdx
	mulx	u0, l0, hi
	mov	(bp, n, 8), %rdx
	mulx	v0, l1, c0
	adox	hi, c0		C No carry out
	adc	l0, l1
	mov	l1, (rp, n, 8)

	C This and below uses of inc instruction clears OF, except if
	C the increment is from 2^63-1 to 2^63. It seems fairly safe
	C to assume that limb size is < 2^63, and then overflow can't
	C happen.
	inc	n
	jz	L(end)

L(top):
	mov	(ap, n, 8), %rdx
	mulx	u0, l0, hi
	mov	(bp, n, 8), %rdx
	mulx	v0, l1, c1
	adox	c0, l0
	adox	hi, c1
	adc	l0, l1
	mov	l1, (rp, n, 8)

	inc	n
	mov	(ap, n, 8), %rdx
	mulx	u0, l0, hi
	mov	(bp, n, 8), %rdx
	mulx	v0, l1, c0
	adox	c1, l0
	adox	hi, c0
	adc	l0, l1
	mov	l1, (rp, n, 8)
	inc	n

	jnz	L(top)

L(end):
	adc	$0, c0

	pop	%r12
	pop	%rbp
	pop	%rbx
	ret
EPILOGUE()
