#! /usr/bin/env perl
# Copyright 2010-2020 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

#
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# March, June 2010
#
# The module implements "4-bit" GCM GHASH function and underlying
# single multiplication operation in GF(2^128). "4-bit" means that
# it uses 256 bytes per-key table [+128 bytes shared table]. GHASH
# function features so called "528B" variant utilizing additional
# 256+16 bytes of per-key storage [+512 bytes shared table].
# Performance results are for this streamed GHASH subroutine and are
# expressed in cycles per processed byte, less is better:
#
#		gcc 3.4.x(*)	assembler
#
# P4		28.6		14.0		+100%
# Opteron	19.3		7.7		+150%
# Core2		17.8		8.1(**)		+120%
# Atom		31.6		16.8		+88%
# VIA Nano	21.8		10.1		+115%
#
# (*)	comparison is not completely fair, because C results are
#	for vanilla "256B" implementation, while assembler results
#	are for "528B";-)
# (**)	it's mystery [to me] why Core2 result is not same as for
#	Opteron;

# May 2010
#
# Add PCLMULQDQ version performing at 2.02 cycles per processed byte.
# See ghash-x86.pl for background information and details about coding
# techniques.
#
# Special thanks to David Woodhouse for providing access to a
# Westmere-based system on behalf of Intel Open Source Technology Centre.

# December 2012
#
# Overhaul: aggregate Karatsuba post-processing, improve ILP in
# reduction_alg9, increase reduction aggregate factor to 4x. As for
# the latter. ghash-x86.pl discusses that it makes lesser sense to
# increase aggregate factor. Then why increase here? Critical path
# consists of 3 independent pclmulqdq instructions, Karatsuba post-
# processing and reduction. "On top" of this we lay down aggregated
# multiplication operations, triplets of independent pclmulqdq's. As
# issue rate for pclmulqdq is limited, it makes lesser sense to
# aggregate more multiplications than it takes to perform remaining
# non-multiplication operations. 2x is near-optimal coefficient for
# contemporary Intel CPUs (therefore modest improvement coefficient),
# but not for Bulldozer. Latter is because logical SIMD operations
# are twice as slow in comparison to Intel, so that critical path is
# longer. A CPU with higher pclmulqdq issue rate would also benefit
# from higher aggregate factor...
#
# Westmere	1.78(+13%)
# Sandy Bridge	1.80(+8%)
# Ivy Bridge	1.80(+7%)
# Haswell	0.55(+93%) (if system doesn't support AVX)
# Broadwell	0.45(+110%)(if system doesn't support AVX)
# Skylake	0.44(+110%)(if system doesn't support AVX)
# Bulldozer	1.49(+27%)
# Silvermont	2.88(+13%)
# Knights L	2.12(-)    (if system doesn't support AVX)
# Goldmont	1.08(+24%)

# March 2013
#
# ... 8x aggregate factor AVX code path is using reduction algorithm
# suggested by Shay Gueron[1]. Even though contemporary AVX-capable
# CPUs such as Sandy and Ivy Bridge can execute it, the code performs
# sub-optimally in comparison to above mentioned version. But thanks
# to Ilya Albrekht and Max Locktyukhin of Intel Corp. we knew that
# it performs in 0.41 cycles per byte on Haswell processor, in
# 0.29 on Broadwell, and in 0.36 on Skylake.
#
# Knights Landing achieves 1.09 cpb.
#
# [1] http://rt.openssl.org/Ticket/Display.html?id=2900&user=guest&pass=guest

$flavour = shift;
$output  = shift;
if ($flavour =~ /\./) { $output = $flavour; undef $flavour; }

$win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/);

$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or
( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or
die "can't locate x86_64-xlate.pl";

if (`$ENV{CC} -Wa,-v -c -o /dev/null -x assembler /dev/null 2>&1`
		=~ /GNU assembler version ([2-9]\.[0-9]+)/) {
	$avx = ($1>=2.20) + ($1>=2.22);
}

if (!$avx && $win64 && ($flavour =~ /nasm/ || $ENV{ASM} =~ /nasm/) &&
	    `nasm -v 2>&1` =~ /NASM version ([2-9]\.[0-9]+)/) {
	$avx = ($1>=2.09) + ($1>=2.10);
}

if (!$avx && $win64 && ($flavour =~ /masm/ || $ENV{ASM} =~ /ml64/) &&
	    `ml64 2>&1` =~ /Version ([0-9]+)\./) {
	$avx = ($1>=10) + ($1>=11);
}

if (!$avx && `$ENV{CC} -v 2>&1` =~ /((?:clang|LLVM) version|.*based on LLVM) ([0-9]+\.[0-9]+)/) {
	$avx = ($2>=3.0) + ($2>3.0);
}

open OUT,"| \"$^X\" \"$xlate\" $flavour \"$output\"";
*STDOUT=*OUT;

$do4xaggr=1;

# common register layout
$nlo="%rax";
$nhi="%rbx";
$Zlo="%r8";
$Zhi="%r9";
$tmp="%r10";
$rem_4bit = "%r11";

$Xi="%rdi";
$Htbl="%rsi";

# per-function register layout
$cnt="%rcx";
$rem="%rdx";

sub LB() { my $r=shift; $r =~ s/%[er]([a-d])x/%\1l/	or
			$r =~ s/%[er]([sd]i)/%\1l/	or
			$r =~ s/%[er](bp)/%\1l/		or
			$r =~ s/%(r[0-9]+)[d]?/%\1b/;   $r; }

sub AUTOLOAD()		# thunk [simplified] 32-bit style perlasm
{ my $opcode = $AUTOLOAD; $opcode =~ s/.*:://;
  my $arg = pop;
    $arg = "\$$arg" if ($arg*1 eq $arg);
    $code .= "\t$opcode\t".join(',',$arg,reverse @_)."\n";
}

{ my $N;
  sub loop() {
  my $inp = shift;

	$N++;
$code.=<<___;
	xor	$nlo,$nlo
	xor	$nhi,$nhi
	mov	`&LB("$Zlo")`,`&LB("$nlo")`
	mov	`&LB("$Zlo")`,`&LB("$nhi")`
	shl	\$4,`&LB("$nlo")`
	mov	\$14,$cnt
	mov	8($Htbl,$nlo),$Zlo
	mov	($Htbl,$nlo),$Zhi
	and	\$0xf0,`&LB("$nhi")`
	mov	$Zlo,$rem
	jmp	.Loop$N

.align	16
.Loop$N:
	shr	\$4,$Zlo
	and	\$0xf,$rem
	mov	$Zhi,$tmp
	mov	($inp,$cnt),`&LB("$nlo")`
	shr	\$4,$Zhi
	xor	8($Htbl,$nhi),$Zlo
	shl	\$60,$tmp
	xor	($Htbl,$nhi),$Zhi
	mov	`&LB("$nlo")`,`&LB("$nhi")`
	xor	($rem_4bit,$rem,8),$Zhi
	mov	$Zlo,$rem
	shl	\$4,`&LB("$nlo")`
	xor	$tmp,$Zlo
	dec	$cnt
	js	.Lbreak$N

	shr	\$4,$Zlo
	and	\$0xf,$rem
	mov	$Zhi,$tmp
	shr	\$4,$Zhi
	xor	8($Htbl,$nlo),$Zlo
	shl	\$60,$tmp
	xor	($Htbl,$nlo),$Zhi
	and	\$0xf0,`&LB("$nhi")`
	xor	($rem_4bit,$rem,8),$Zhi
	mov	$Zlo,$rem
	xor	$tmp,$Zlo
	jmp	.Loop$N

.align	16
.Lbreak$N:
	shr	\$4,$Zlo
	and	\$0xf,$rem
	mov	$Zhi,$tmp
	shr	\$4,$Zhi
	xor	8($Htbl,$nlo),$Zlo
	shl	\$60,$tmp
	xor	($Htbl,$nlo),$Zhi
	and	\$0xf0,`&LB("$nhi")`
	xor	($rem_4bit,$rem,8),$Zhi
	mov	$Zlo,$rem
	xor	$tmp,$Zlo

	shr	\$4,$Zlo
	and	\$0xf,$rem
	mov	$Zhi,$tmp
	shr	\$4,$Zhi
	xor	8($Htbl,$nhi),$Zlo
	shl	\$60,$tmp
	xor	($Htbl,$nhi),$Zhi
	xor	$tmp,$Zlo
	xor	($rem_4bit,$rem,8),$Zhi

	bswap	$Zlo
	bswap	$Zhi
___
}}

$code=<<___;
.text
.extern	OPENSSL_ia32cap_P

.globl	gcm_gmult_4bit
.type	gcm_gmult_4bit,\@function,2
.align	16
gcm_gmult_4bit:
.cfi_startproc
	push	%rbx
.cfi_push	%rbx
	push	%rbp		# %rbp and others are pushed exclusively in
.cfi_push	%rbp
	push	%r12		# order to reuse Win64 exception handler...
.cfi_push	%r12
	push	%r13
.cfi_push	%r13
	push	%r14
.cfi_push	%r14
	push	%r15
.cfi_push	%r15
	sub	\$280,%rsp
.cfi_adjust_cfa_offset	280
.Lgmult_prologue:

	movzb	15($Xi),$Zlo
	lea	.Lrem_4bit(%rip),$rem_4bit
___
	&loop	($Xi);
$code.=<<___;
	mov	$Zlo,8($Xi)
	mov	$Zhi,($Xi)

	lea	280+48(%rsp),%rsi
.cfi_def_cfa	%rsi,8
	mov	-8(%rsi),%rbx
.cfi_restore	%rbx
	lea	(%rsi),%rsp
.cfi_def_cfa_register	%rsp
.Lgmult_epilogue:
	ret
.cfi_endproc
.size	gcm_gmult_4bit,.-gcm_gmult_4bit
___

# per-function register layout
$inp="%rdx";
$len="%rcx";
$rem_8bit=$rem_4bit;

$code.=<<___;
.globl	gcm_ghash_4bit
.type	gcm_ghash_4bit,\@function,4
.align	16
gcm_ghash_4bit:
.cfi_startproc
	push	%rbx
.cfi_push	%rbx
	push	%rbp
.cfi_push	%rbp
	push	%r12
.cfi_push	%r12
	push	%r13
.cfi_push	%r13
	push	%r14
.cfi_push	%r14
	push	%r15
.cfi_push	%r15
	sub	\$280,%rsp
.cfi_adjust_cfa_offset	280
.Lghash_prologue:
	mov	$inp,%r14		# reassign couple of args
	mov	$len,%r15
___
{ my $inp="%r14";
  my $dat="%edx";
  my $len="%r15";
  my @nhi=("%ebx","%ecx");
  my @rem=("%r12","%r13");
  my $Hshr4="%rbp";

	&sub	($Htbl,-128);		# size optimization
	&lea	($Hshr4,"16+128(%rsp)");
	{ my @lo =($nlo,$nhi);
          my @hi =($Zlo,$Zhi);

	  &xor	($dat,$dat);
	  for ($i=0,$j=-2;$i<18;$i++,$j++) {
	    &mov	("$j(%rsp)",&LB($dat))		if ($i>1);
	    &or		($lo[0],$tmp)			if ($i>1);
	    &mov	(&LB($dat),&LB($lo[1]))		if ($i>0 && $i<17);
	    &shr	($lo[1],4)			if ($i>0 && $i<17);
	    &mov	($tmp,$hi[1])			if ($i>0 && $i<17);
	    &shr	($hi[1],4)			if ($i>0 && $i<17);
	    &mov	("8*$j($Hshr4)",$hi[0])		if ($i>1);
	    &mov	($hi[0],"16*$i+0-128($Htbl)")	if ($i<16);
	    &shl	(&LB($dat),4)			if ($i>0 && $i<17);
	    &mov	("8*$j-128($Hshr4)",$lo[0])	if ($i>1);
	    &mov	($lo[0],"16*$i+8-128($Htbl)")	if ($i<16);
	    &shl	($tmp,60)			if ($i>0 && $i<17);

	    push	(@lo,shift(@lo));
	    push	(@hi,shift(@hi));
	  }
	}
	&add	($Htbl,-128);
	&mov	($Zlo,"8($Xi)");
	&mov	($Zhi,"0($Xi)");
	&add	($len,$inp);		# pointer to the end of data
	&lea	($rem_8bit,".Lrem_8bit(%rip)");
	&jmp	(".Louter_loop");

$code.=".align	16\n.Louter_loop:\n";
	&xor	($Zhi,"($inp)");
	&mov	("%rdx","8($inp)");
	&lea	($inp,"16($inp)");
	&xor	("%rdx",$Zlo);
	&mov	("($Xi)",$Zhi);
	&mov	("8($Xi)","%rdx");
	&shr	("%rdx",32);

	&xor	($nlo,$nlo);
	&rol	($dat,8);
	&mov	(&LB($nlo),&LB($dat));
	&movz	($nhi[0],&LB($dat));
	&shl	(&LB($nlo),4);
	&shr	($nhi[0],4);

	for ($j=11,$i=0;$i<15;$i++) {
	    &rol	($dat,8);
	    &xor	($Zlo,"8($Htbl,$nlo)")			if ($i>0);
	    &xor	($Zhi,"($Htbl,$nlo)")			if ($i>0);
	    &mov	($Zlo,"8($Htbl,$nlo)")			if ($i==0);
	    &mov	($Zhi,"($Htbl,$nlo)")			if ($i==0);

	    &mov	(&LB($nlo),&LB($dat));
	    &xor	($Zlo,$tmp)				if ($i>0);
	    &movzw	($rem[1],"($rem_8bit,$rem[1],2)")	if ($i>0);

	    &movz	($nhi[1],&LB($dat));
	    &shl	(&LB($nlo),4);
	    &movzb	($rem[0],"(%rsp,$nhi[0])");

	    &shr	($nhi[1],4)				if ($i<14);
	    &and	($nhi[1],0xf0)				if ($i==14);
	    &shl	($rem[1],48)				if ($i>0);
	    &xor	($rem[0],$Zlo);

	    &mov	($tmp,$Zhi);
	    &xor	($Zhi,$rem[1])				if ($i>0);
	    &shr	($Zlo,8);

	    &movz	($rem[0],&LB($rem[0]));
	    &mov	($dat,"$j($Xi)")			if (--$j%4==0);
	    &shr	($Zhi,8);

	    &xor	($Zlo,"-128($Hshr4,$nhi[0],8)");
	    &shl	($tmp,56);
	    &xor	($Zhi,"($Hshr4,$nhi[0],8)");

	    unshift	(@nhi,pop(@nhi));		# "rotate" registers
	    unshift	(@rem,pop(@rem));
	}
	&movzw	($rem[1],"($rem_8bit,$rem[1],2)");
	&xor	($Zlo,"8($Htbl,$nlo)");
	&xor	($Zhi,"($Htbl,$nlo)");

	&shl	($rem[1],48);
	&xor	($Zlo,$tmp);

	&xor	($Zhi,$rem[1]);
	&movz	($rem[0],&LB($Zlo));
	&shr	($Zlo,4);

	&mov	($tmp,$Zhi);
	&shl	(&LB($rem[0]),4);
	&shr	($Zhi,4);

	&xor	($Zlo,"8($Htbl,$nhi[0])");
	&movzw	($rem[0],"($rem_8bit,$rem[0],2)");
	&shl	($tmp,60);

	&xor	($Zhi,"($Htbl,$nhi[0])");
	&xor	($Zlo,$tmp);
	&shl	($rem[0],48);

	&bswap	($Zlo);
	&xor	($Zhi,$rem[0]);

	&bswap	($Zhi);
	&cmp	($inp,$len);
	&jb	(".Louter_loop");
}
$code.=<<___;
	mov	$Zlo,8($Xi)
	mov	$Zhi,($Xi)

	lea	280+48(%rsp),%rsi
.cfi_def_cfa	%rsi,8
	mov	-48(%rsi),%r15
.cfi_restore	%r15
	mov	-40(%rsi),%r14
.cfi_restore	%r14
	mov	-32(%rsi),%r13
.cfi_restore	%r13
	mov	-24(%rsi),%r12
.cfi_restore	%r12
	mov	-16(%rsi),%rbp
.cfi_restore	%rbp
	mov	-8(%rsi),%rbx
.cfi_restore	%rbx
	lea	0(%rsi),%rsp
.cfi_def_cfa_register	%rsp
.Lghash_epilogue:
	ret
.cfi_endproc
.size	gcm_ghash_4bit,.-gcm_ghash_4bit
___

######################################################################
# PCLMULQDQ version.

@_4args=$win64?	("%rcx","%rdx","%r8", "%r9") :	# Win64 order
		("%rdi","%rsi","%rdx","%rcx");	# Unix order

($Xi,$Xhi)=("%xmm0","%xmm1");	$Hkey="%xmm2";
($T1,$T2,$T3)=("%xmm3","%xmm4","%xmm5");

sub clmul64x64_T2 {	# minimal register pressure
my ($Xhi,$Xi,$Hkey,$HK)=@_;

if (!defined($HK)) {	$HK = $T2;
$code.=<<___;
	movdqa		$Xi,$Xhi		#
	pshufd		\$0b01001110,$Xi,$T1
	pshufd		\$0b01001110,$Hkey,$T2
	pxor		$Xi,$T1			#
	pxor		$Hkey,$T2
___
} else {
$code.=<<___;
	movdqa		$Xi,$Xhi		#
	pshufd		\$0b01001110,$Xi,$T1
	pxor		$Xi,$T1			#
___
}
$code.=<<___;
	pclmulqdq	\$0x00,$Hkey,$Xi	#######
	pclmulqdq	\$0x11,$Hkey,$Xhi	#######
	pclmulqdq	\$0x00,$HK,$T1		#######
	pxor		$Xi,$T1			#
	pxor		$Xhi,$T1		#

	movdqa		$T1,$T2			#
	psrldq		\$8,$T1
	pslldq		\$8,$T2			#
	pxor		$T1,$Xhi
	pxor		$T2,$Xi			#
___
}

sub reduction_alg9 {	# 17/11 times faster than Intel version
my ($Xhi,$Xi) = @_;

$code.=<<___;
	# 1st phase
	movdqa		$Xi,$T2			#
	movdqa		$Xi,$T1
	psllq		\$5,$Xi
	pxor		$Xi,$T1			#
	psllq		\$1,$Xi
	pxor		$T1,$Xi			#
	psllq		\$57,$Xi		#
	movdqa		$Xi,$T1			#
	pslldq		\$8,$Xi
	psrldq		\$8,$T1			#
	pxor		$T2,$Xi
	pxor		$T1,$Xhi		#

	# 2nd phase
	movdqa		$Xi,$T2
	psrlq		\$1,$Xi
	pxor		$T2,$Xhi		#
	pxor		$Xi,$T2
	psrlq		\$5,$Xi
	pxor		$T2,$Xi			#
	psrlq		\$1,$Xi			#
	pxor		$Xhi,$Xi		#
___
}

{ my ($Htbl,$Xip)=@_4args;
  my $HK="%xmm6";

$code.=<<___;
.globl	gcm_init_clmul
.type	gcm_init_clmul,\@abi-omnipotent
.align	16
gcm_init_clmul:
.cfi_startproc
.L_init_clmul:
___
$code.=<<___ if ($win64);
.LSEH_begin_gcm_init_clmul:
	# I can't trust assembler to use specific encoding:-(
	.byte	0x48,0x83,0xec,0x18		#sub	$0x18,%rsp
	.byte	0x0f,0x29,0x34,0x24		#movaps	%xmm6,(%rsp)
___
$code.=<<___;
	movdqu		($Xip),$Hkey
	pshufd		\$0b01001110,$Hkey,$Hkey	# dword swap

	# <<1 twist
	pshufd		\$0b11111111,$Hkey,$T2	# broadcast uppermost dword
	movdqa		$Hkey,$T1
	psllq		\$1,$Hkey
	pxor		$T3,$T3			#
	psrlq		\$63,$T1
	pcmpgtd		$T2,$T3			# broadcast carry bit
	pslldq		\$8,$T1
	por		$T1,$Hkey		# H<<=1

	# magic reduction
	pand		.L0x1c2_polynomial(%rip),$T3
	pxor		$T3,$Hkey		# if(carry) H^=0x1c2_polynomial

	# calculate H^2
	pshufd		\$0b01001110,$Hkey,$HK
	movdqa		$Hkey,$Xi
	pxor		$Hkey,$HK
___
	&clmul64x64_T2	($Xhi,$Xi,$Hkey,$HK);
	&reduction_alg9	($Xhi,$Xi);
$code.=<<___;
	pshufd		\$0b01001110,$Hkey,$T1
	pshufd		\$0b01001110,$Xi,$T2
	pxor		$Hkey,$T1		# Karatsuba pre-processing
	movdqu		$Hkey,0x00($Htbl)	# save H
	pxor		$Xi,$T2			# Karatsuba pre-processing
	movdqu		$Xi,0x10($Htbl)		# save H^2
	palignr		\$8,$T1,$T2		# low part is H.lo^H.hi...
	movdqu		$T2,0x20($Htbl)		# save Karatsuba "salt"
___
if ($do4xaggr) {
	&clmul64x64_T2	($Xhi,$Xi,$Hkey,$HK);	# H^3
	&reduction_alg9	($Xhi,$Xi);
$code.=<<___;
	movdqa		$Xi,$T3
___
	&clmul64x64_T2	($Xhi,$Xi,$Hkey,$HK);	# H^4
	&reduction_alg9	($Xhi,$Xi);
$code.=<<___;
	pshufd		\$0b01001110,$T3,$T1
	pshufd		\$0b01001110,$Xi,$T2
	pxor		$T3,$T1			# Karatsuba pre-processing
	movdqu		$T3,0x30($Htbl)		# save H^3
	pxor		$Xi,$T2			# Karatsuba pre-processing
	movdqu		$Xi,0x40($Htbl)		# save H^4
	palignr		\$8,$T1,$T2		# low part is H^3.lo^H^3.hi...
	movdqu		$T2,0x50($Htbl)		# save Karatsuba "salt"
___
}
$code.=<<___ if ($win64);
	movaps	(%rsp),%xmm6
	lea	0x18(%rsp),%rsp
.LSEH_end_gcm_init_clmul:
___
$code.=<<___;
	ret
.cfi_endproc
.size	gcm_init_clmul,.-gcm_init_clmul
___
}

{ my ($Xip,$Htbl)=@_4args;

$code.=<<___;
.globl	gcm_gmult_clmul
.type	gcm_gmult_clmul,\@abi-omnipotent
.align	16
gcm_gmult_clmul:
.cfi_startproc
.L_gmult_clmul:
	movdqu		($Xip),$Xi
	movdqa		.Lbswap_mask(%rip),$T3
	movdqu		($Htbl),$Hkey
	movdqu		0x20($Htbl),$T2
	pshufb		$T3,$Xi
___
	&clmul64x64_T2	($Xhi,$Xi,$Hkey,$T2);
$code.=<<___ if (0 || (&reduction_alg9($Xhi,$Xi)&&0));
	# experimental alternative. special thing about is that there
	# no dependency between the two multiplications...
	mov		\$`0xE1<<1`,%eax
	mov		\$0xA040608020C0E000,%r10	# ((7..0)Â·0xE0)&0xff
	mov		\$0x07,%r11d
	movq		%rax,$T1
	movq		%r10,$T2
	movq		%r11,$T3		# borrow $T3
	pand		$Xi,$T3
	pshufb		$T3,$T2			# ($Xi&7)Â·0xE0
	movq		%rax,$T3
	pclmulqdq	\$0x00,$Xi,$T1		# Â·(0xE1<<1)
	pxor		$Xi,$T2
	pslldq		\$15,$T2
	paddd		$T2,$T2			# <<(64+56+1)
	pxor		$T2,$Xi
	pclmulqdq	\$0x01,$T3,$Xi
	movdqa		.Lbswap_mask(%rip),$T3	# reload $T3
	psrldq		\$1,$T1
	pxor		$T1,$Xhi
	pslldq		\$7,$Xi
	pxor		$Xhi,$Xi
___
$code.=<<___;
	pshufb		$T3,$Xi
	movdqu		$Xi,($Xip)
	ret
.cfi_endproc
.size	gcm_gmult_clmul,.-gcm_gmult_clmul
___
}

{ my ($Xip,$Htbl,$inp,$len)=@_4args;
  my ($Xln,$Xmn,$Xhn,$Hkey2,$HK) = map("%xmm$_",(3..7));
  my ($T1,$T2,$T3)=map("%xmm$_",(8..10));

$code.=<<___;
.globl	gcm_ghash_clmul
.type	gcm_ghash_clmul,\@abi-omnipotent
.align	32
gcm_ghash_clmul:
.cfi_startproc
.L_ghash_clmul:
___
$code.=<<___ if ($win64);
	lea	-0x88(%rsp),%rax
.LSEH_begin_gcm_ghash_clmul:
	# I can't trust assembler to use specific encoding:-(
	.byte	0x48,0x8d,0x60,0xe0		#lea	-0x20(%rax),%rsp
	.byte	0x0f,0x29,0x70,0xe0		#movaps	%xmm6,-0x20(%rax)
	.byte	0x0f,0x29,0x78,0xf0		#movaps	%xmm7,-0x10(%rax)
	.byte	0x44,0x0f,0x29,0x00		#movaps	%xmm8,0(%rax)
	.byte	0x44,0x0f,0x29,0x48,0x10	#movaps	%xmm9,0x10(%rax)
	.byte	0x44,0x0f,0x29,0x50,0x20	#movaps	%xmm10,0x20(%rax)
	.byte	0x44,0x0f,0x29,0x58,0x30	#movaps	%xmm11,0x30(%rax)
	.byte	0x44,0x0f,0x29,0x60,0x40	#movaps	%xmm12,0x40(%rax)
	.byte	0x44,0x0f,0x29,0x68,0x50	#movaps	%xmm13,0x50(%rax)
	.byte	0x44,0x0f,0x29,0x70,0x60	#movaps	%xmm14,0x60(%rax)
	.byte	0x44,0x0f,0x29,0x78,0x70	#movaps	%xmm15,0x70(%rax)
___
$code.=<<___;
	movdqa		.Lbswap_mask(%rip),$T3

	movdqu		($Xip),$Xi
	movdqu		($Htbl),$Hkey
	movdqu		0x20($Htbl),$HK
	pshufb		$T3,$Xi

	sub		\$0x10,$len
	jz		.Lodd_tail

	movdqu		0x10($Htbl),$Hkey2
___
if ($do4xaggr) {
my ($Xl,$Xm,$Xh,$Hkey3,$Hkey4)=map("%xmm$_",(11..15));

$code.=<<___;
	mov		OPENSSL_ia32cap_P+4(%rip),%eax
	cmp		\$0x30,$len
	jb		.Lskip4x

	and		\$`1<<26|1<<22`,%eax	# isolate MOVBE+XSAVE
	cmp		\$`1<<22`,%eax		# check for MOVBE without XSAVE
	je		.Lskip4x

	sub		\$0x30,$len
	mov		\$0xA040608020C0E000,%rax	# ((7..0)Â·0xE0)&0xff
	movdqu		0x30($Htbl),$Hkey3
	movdqu		0x40($Htbl),$Hkey4

	#######
	# Xi+4 =[(H*Ii+3) + (H^2*Ii+2) + (H^3*Ii+1) + H^4*(Ii+Xi)] mod P
	#
	movdqu		0x30($inp),$Xln
	 movdqu		0x20($inp),$Xl
	pshufb		$T3,$Xln
	 pshufb		$T3,$Xl
	movdqa		$Xln,$Xhn
	pshufd		\$0b01001110,$Xln,$Xmn
	pxor		$Xln,$Xmn
	pclmulqdq	\$0x00,$Hkey,$Xln
	pclmulqdq	\$0x11,$Hkey,$Xhn
	pclmulqdq	\$0x00,$HK,$Xmn

	movdqa		$Xl,$Xh
	pshufd		\$0b01001110,$Xl,$Xm
	pxor		$Xl,$Xm
	pclmulqdq	\$0x00,$Hkey2,$Xl
	pclmulqdq	\$0x11,$Hkey2,$Xh
	pclmulqdq	\$0x10,$HK,$Xm
	xorps		$Xl,$Xln
	xorps		$Xh,$Xhn
	movups		0x50($Htbl),$HK
	xorps		$Xm,$Xmn

	movdqu		0x10($inp),$Xl
	 movdqu		0($inp),$T1
	pshufb		$T3,$Xl
	 pshufb		$T3,$T1
	movdqa		$Xl,$Xh
	pshufd		\$0b01001110,$Xl,$Xm
	 pxor		$T1,$Xi
	pxor		$Xl,$Xm
	pclmulqdq	\$0x00,$Hkey3,$Xl
	 movdqa		$Xi,$Xhi
	 pshufd		\$0b01001110,$Xi,$T1
	 pxor		$Xi,$T1
	pclmulqdq	\$0x11,$Hkey3,$Xh
	pclmulqdq	\$0x00,$HK,$Xm
	xorps		$Xl,$Xln
	xorps		$Xh,$Xhn

	lea	0x40($inp),$inp
	sub	\$0x40,$len
	jc	.Ltail4x

	jmp	.Lmod4_loop
.align	32
.Lmod4_loop:
	pclmulqdq	\$0x00,$Hkey4,$Xi
	xorps		$Xm,$Xmn
	 movdqu		0x30($inp),$Xl
	 pshufb		$T3,$Xl
	pclmulqdq	\$0x11,$Hkey4,$Xhi
	xorps		$Xln,$Xi
	 movdqu		0x20($inp),$Xln
	 movdqa		$Xl,$Xh
	pclmulqdq	\$0x10,$HK,$T1
	 pshufd		\$0b01001110,$Xl,$Xm
	xorps		$Xhn,$Xhi
	 pxor		$Xl,$Xm
	 pshufb		$T3,$Xln
	movups		0x20($Htbl),$HK
	xorps		$Xmn,$T1
	 pclmulqdq	\$0x00,$Hkey,$Xl
	 pshufd		\$0b01001110,$Xln,$Xmn

	pxor		$Xi,$T1			# aggregated Karatsuba post-processing
	 movdqa		$Xln,$Xhn
	pxor		$Xhi,$T1		#
	 pxor		$Xln,$Xmn
	movdqa		$T1,$T2			#
	 pclmulqdq	\$0x11,$Hkey,$Xh
	pslldq		\$8,$T1
	psrldq		\$8,$T2			#
	pxor		$T1,$Xi
	movdqa		.L7_mask(%rip),$T1
	pxor		$T2,$Xhi		#
	movq		%rax,$T2

	pand		$Xi,$T1			# 1st phase
	pshufb		$T1,$T2			#
	pxor		$Xi,$T2			#
	 pclmulqdq	\$0x00,$HK,$Xm
	psllq		\$57,$T2		#
	movdqa		$T2,$T1			#
	pslldq		\$8,$T2
	 pclmulqdq	\$0x00,$Hkey2,$Xln
	psrldq		\$8,$T1			#
	pxor		$T2,$Xi
	pxor		$T1,$Xhi		#
	movdqu		0($inp),$T1

	movdqa		$Xi,$T2			# 2nd phase
	psrlq		\$1,$Xi
	 pclmulqdq	\$0x11,$Hkey2,$Xhn
	 xorps		$Xl,$Xln
	 movdqu		0x10($inp),$Xl
	 pshufb		$T3,$Xl
	 pclmulqdq	\$0x10,$HK,$Xmn
	 xorps		$Xh,$Xhn
	 movups		0x50($Htbl),$HK
	pshufb		$T3,$T1
	pxor		$T2,$Xhi		#
	pxor		$Xi,$T2
	psrlq		\$5,$Xi

	 movdqa		$Xl,$Xh
	 pxor		$Xm,$Xmn
	 pshufd		\$0b01001110,$Xl,$Xm
	pxor		$T2,$Xi			#
	pxor		$T1,$Xhi
	 pxor		$Xl,$Xm
	 pclmulqdq	\$0x00,$Hkey3,$Xl
	psrlq		\$1,$Xi			#
	pxor		$Xhi,$Xi		#
	movdqa		$Xi,$Xhi
	 pclmulqdq	\$0x11,$Hkey3,$Xh
	 xorps		$Xl,$Xln
	pshufd		\$0b01001110,$Xi,$T1
	pxor		$Xi,$T1

	 pclmulqdq	\$0x00,$HK,$Xm
	 xorps		$Xh,$Xhn

	lea	0x40($inp),$inp
	sub	\$0x40,$len
	jnc	.Lmod4_loop

.Ltail4x:
	pclmulqdq	\$0x00,$Hkey4,$Xi
	pclmulqdq	\$0x11,$Hkey4,$Xhi
	pclmulqdq	\$0x10,$HK,$T1
	xorps		$Xm,$Xmn
	xorps		$Xln,$Xi
	xorps		$Xhn,$Xhi
	pxor		$Xi,$Xhi		# aggregated Karatsuba post-processing
	pxor		$Xmn,$T1

	pxor		$Xhi,$T1		#
	pxor		$Xi,$Xhi

	movdqa		$T1,$T2			#
	psrldq		\$8,$T1
	pslldq		\$8,$T2			#
	pxor		$T1,$Xhi
	pxor		$T2,$Xi			#
___
	&reduction_alg9($Xhi,$Xi);
$code.=<<___;
	add	\$0x40,$len
	jz	.Ldone
	movdqu	0x20($Htbl),$HK
	sub	\$0x10,$len
	jz	.Lodd_tail
.Lskip4x:
___
}
$code.=<<___;
	#######
	# Xi+2 =[H*(Ii+1 + Xi+1)] mod P =
	#	[(H*Ii+1) + (H*Xi+1)] mod P =
	#	[(H*Ii+1) + H^2*(Ii+Xi)] mod P
	#
	movdqu		($inp),$T1		# Ii
	movdqu		16($inp),$Xln		# Ii+1
	pshufb		$T3,$T1
	pshufb		$T3,$Xln
	pxor		$T1,$Xi			# Ii+Xi

	movdqa		$Xln,$Xhn
	pshufd		\$0b01001110,$Xln,$Xmn
	pxor		$Xln,$Xmn
	pclmulqdq	\$0x00,$Hkey,$Xln
	pclmulqdq	\$0x11,$Hkey,$Xhn
	pclmulqdq	\$0x00,$HK,$Xmn

	lea		32($inp),$inp		# i+=2
	nop
	sub		\$0x20,$len
	jbe		.Leven_tail
	nop
	jmp		.Lmod_loop

.align	32
.Lmod_loop:
	movdqa		$Xi,$Xhi
	movdqa		$Xmn,$T1
	pshufd		\$0b01001110,$Xi,$Xmn	#
	pxor		$Xi,$Xmn		#

	pclmulqdq	\$0x00,$Hkey2,$Xi
	pclmulqdq	\$0x11,$Hkey2,$Xhi
	pclmulqdq	\$0x10,$HK,$Xmn

	pxor		$Xln,$Xi		# (H*Ii+1) + H^2*(Ii+Xi)
	pxor		$Xhn,$Xhi
	  movdqu	($inp),$T2		# Ii
	pxor		$Xi,$T1			# aggregated Karatsuba post-processing
	  pshufb	$T3,$T2
	  movdqu	16($inp),$Xln		# Ii+1

	pxor		$Xhi,$T1
	  pxor		$T2,$Xhi		# "Ii+Xi", consume early
	pxor		$T1,$Xmn
	 pshufb		$T3,$Xln
	movdqa		$Xmn,$T1		#
	psrldq		\$8,$T1
	pslldq		\$8,$Xmn		#
	pxor		$T1,$Xhi
	pxor		$Xmn,$Xi		#

	movdqa		$Xln,$Xhn		#

	  movdqa	$Xi,$T2			# 1st phase
	  movdqa	$Xi,$T1
	  psllq		\$5,$Xi
	  pxor		$Xi,$T1			#
	pclmulqdq	\$0x00,$Hkey,$Xln	#######
	  psllq		\$1,$Xi
	  pxor		$T1,$Xi			#
	  psllq		\$57,$Xi		#
	  movdqa	$Xi,$T1			#
	  pslldq	\$8,$Xi
	  psrldq	\$8,$T1			#
	  pxor		$T2,$Xi
	pshufd		\$0b01001110,$Xhn,$Xmn
	  pxor		$T1,$Xhi		#
	pxor		$Xhn,$Xmn		#

	  movdqa	$Xi,$T2			# 2nd phase
	  psrlq		\$1,$Xi
	pclmulqdq	\$0x11,$Hkey,$Xhn	#######
	  pxor		$T2,$Xhi		#
	  pxor		$Xi,$T2
	  psrlq		\$5,$Xi
	  pxor		$T2,$Xi			#
	lea		32($inp),$inp
	  psrlq		\$1,$Xi			#
	pclmulqdq	\$0x00,$HK,$Xmn		#######
	  pxor		$Xhi,$Xi		#

	sub		\$0x20,$len
	ja		.Lmod_loop

.Leven_tail:
	 movdqa		$Xi,$Xhi
	 movdqa		$Xmn,$T1
	 pshufd		\$0b01001110,$Xi,$Xmn	#
	 pxor		$Xi,$Xmn		#

	pclmulqdq	\$0x00,$Hkey2,$Xi
	pclmulqdq	\$0x11,$Hkey2,$Xhi
	pclmulqdq	\$0x10,$HK,$Xmn

	pxor		$Xln,$Xi		# (H*Ii+1) + H^2*(Ii+Xi)
	pxor		$Xhn,$Xhi
	pxor		$Xi,$T1
	pxor		$Xhi,$T1
	pxor		$T1,$Xmn
	movdqa		$Xmn,$T1		#
	psrldq		\$8,$T1
	pslldq		\$8,$Xmn		#
	pxor		$T1,$Xhi
	pxor		$Xmn,$Xi		#
___
	&reduction_alg9	($Xhi,$Xi);
$code.=<<___;
	test		$len,$len
	jnz		.Ldone

.Lodd_tail:
	movdqu		($inp),$T1		# Ii
	pshufb		$T3,$T1
	pxor		$T1,$Xi			# Ii+Xi
___
	&clmul64x64_T2	($Xhi,$Xi,$Hkey,$HK);	# H*(Ii+Xi)
	&reduction_alg9	($Xhi,$Xi);
$code.=<<___;
.Ldone:
	pshufb		$T3,$Xi
	movdqu		$Xi,($Xip)
___
$code.=<<___ if ($win64);
	movaps	(%rsp),%xmm6
	movaps	0x10(%rsp),%xmm7
	movaps	0x20(%rsp),%xmm8
	movaps	0x30(%rsp),%xmm9
	movaps	0x40(%rsp),%xmm10
	movaps	0x50(%rsp),%xmm11
	movaps	0x60(%rsp),%xmm12
	movaps	0x70(%rsp),%xmm13
	movaps	0x80(%rsp),%xmm14
	movaps	0x90(%rsp),%xmm15
	lea	0xa8(%rsp),%rsp
.LSEH_end_gcm_ghash_clmul:
___
$code.=<<___;
	ret
.cfi_endproc
.size	gcm_ghash_clmul,.-gcm_ghash_clmul
___
}

$code.=<<___;
.globl	gcm_init_avx
.type	gcm_init_avx,\@abi-omnipotent
.align	32
gcm_init_avx:
.cfi_startproc
___
if ($avx) {
my ($Htbl,$Xip)=@_4args;
my $HK="%xmm6";

$code.=<<___ if ($win64);
.LSEH_begin_gcm_init_avx:
	# I can't trust assembler to use specific encoding:-(
	.byte	0x48,0x83,0xec,0x18		#sub	$0x18,%rsp
	.byte	0x0f,0x29,0x34,0x24		#movaps	%xmm6,(%rsp)
___
$code.=<<___;
	vzeroupper

	vmovdqu		($Xip),$Hkey
	vpshufd		\$0b01001110,$Hkey,$Hkey	# dword swap

	# <<1 twist
	vpshufd		\$0b11111111,$Hkey,$T2	# broadcast uppermost dword
	vpsrlq		\$63,$Hkey,$T1
	vpsllq		\$1,$Hkey,$Hkey
	vpxor		$T3,$T3,$T3		#
	vpcmpgtd	$T2,$T3,$T3		# broadcast carry bit
	vpslldq		\$8,$T1,$T1
	vpor		$T1,$Hkey,$Hkey		# H<<=1

	# magic reduction
	vpand		.L0x1c2_polynomial(%rip),$T3,$T3
	vpxor		$T3,$Hkey,$Hkey		# if(carry) H^=0x1c2_polynomial

	vpunpckhqdq	$Hkey,$Hkey,$HK
	vmovdqa		$Hkey,$Xi
	vpxor		$Hkey,$HK,$HK
	mov		\$4,%r10		# up to H^8
	jmp		.Linit_start_avx
___

sub clmul64x64_avx {
my ($Xhi,$Xi,$Hkey,$HK)=@_;

if (!defined($HK)) {	$HK = $T2;
$code.=<<___;
	vpunpckhqdq	$Xi,$Xi,$T1
	vpunpckhqdq	$Hkey,$Hkey,$T2
	vpxor		$Xi,$T1,$T1		#
	vpxor		$Hkey,$T2,$T2
___
} else {
$code.=<<___;
	vpunpckhqdq	$Xi,$Xi,$T1
	vpxor		$Xi,$T1,$T1		#
___
}
$code.=<<___;
	vpclmulqdq	\$0x11,$Hkey,$Xi,$Xhi	#######
	vpclmulqdq	\$0x00,$Hkey,$Xi,$Xi	#######
	vpclmulqdq	\$0x00,$HK,$T1,$T1	#######
	vpxor		$Xi,$Xhi,$T2		#
	vpxor		$T2,$T1,$T1		#

	vpslldq		\$8,$T1,$T2		#
	vpsrldq		\$8,$T1,$T1
	vpxor		$T2,$Xi,$Xi		#
	vpxor		$T1,$Xhi,$Xhi
___
}

sub reduction_avx {
my ($Xhi,$Xi) = @_;

$code.=<<___;
	vpsllq		\$57,$Xi,$T1		# 1st phase
	vpsllq		\$62,$Xi,$T2
	vpxor		$T1,$T2,$T2		#
	vpsllq		\$63,$Xi,$T1
	vpxor		$T1,$T2,$T2		#
	vpslldq		\$8,$T2,$T1		#
	vpsrldq		\$8,$T2,$T2
	vpxor		$T1,$Xi,$Xi		#
	vpxor		$T2,$Xhi,$Xhi

	vpsrlq		\$1,$Xi,$T2		# 2nd phase
	vpxor		$Xi,$Xhi,$Xhi
	vpxor		$T2,$Xi,$Xi		#
	vpsrlq		\$5,$T2,$T2
	vpxor		$T2,$Xi,$Xi		#
	vpsrlq		\$1,$Xi,$Xi		#
	vpxor		$Xhi,$Xi,$Xi		#
___
}

$code.=<<___;
.align	32
.Linit_loop_avx:
	vpalignr	\$8,$T1,$T2,$T3		# low part is H.lo^H.hi...
	vmovdqu		$T3,-0x10($Htbl)	# save Karatsuba "salt"
___
	&clmul64x64_avx	($Xhi,$Xi,$Hkey,$HK);	# calculate H^3,5,7
	&reduction_avx	($Xhi,$Xi);
$code.=<<___;
.Linit_start_avx:
	vmovdqa		$Xi,$T3
___
	&clmul64x64_avx	($Xhi,$Xi,$Hkey,$HK);	# calculate H^2,4,6,8
	&reduction_avx	($Xhi,$Xi);
$code.=<<___;
	vpshufd		\$0b01001110,$T3,$T1
	vpshufd		\$0b01001110,$Xi,$T2
	vpxor		$T3,$T1,$T1		# Karatsuba pre-processing
	vmovdqu		$T3,0x00($Htbl)		# save H^1,3,5,7
	vpxor		$Xi,$T2,$T2		# Karatsuba pre-processing
	vmovdqu		$Xi,0x10($Htbl)		# save H^2,4,6,8
	lea		0x30($Htbl),$Htbl
	sub		\$1,%r10
	jnz		.Linit_loop_avx

	vpalignr	\$8,$T2,$T1,$T3		# last "salt" is flipped
	vmovdqu		$T3,-0x10($Htbl)

	vzeroupper
___
$code.=<<___ if ($win64);
	movaps	(%rsp),%xmm6
	lea	0x18(%rsp),%rsp
.LSEH_end_gcm_init_avx:
___
$code.=<<___;
	ret
.cfi_endproc
.size	gcm_init_avx,.-gcm_init_avx
___
} else {
$code.=<<___;
	jmp	.L_init_clmul
.cfi_endproc
.size	gcm_init_avx,.-gcm_init_avx
___
}

$code.=<<___;
.globl	gcm_gmult_avx
.type	gcm_gmult_avx,\@abi-omnipotent
.align	32
gcm_gmult_avx:
.cfi_startproc
	jmp	.L_gmult_clmul
.cfi_endproc
.size	gcm_gmult_avx,.-gcm_gmult_avx
___

$code.=<<___;
.globl	gcm_ghash_avx
.type	gcm_ghash_avx,\@abi-omnipotent
.align	32
gcm_ghash_avx:
.cfi_startproc
___
if ($avx) {
my ($Xip,$Htbl,$inp,$len)=@_4args;
my ($Xlo,$Xhi,$Xmi,
    $Zlo,$Zhi,$Zmi,
    $Hkey,$HK,$T1,$T2,
    $Xi,$Xo,$Tred,$bswap,$Ii,$Ij) = map("%xmm$_",(0..15));

$code.=<<___ if ($win64);
	lea	-0x88(%rsp),%rax
.LSEH_begin_gcm_ghash_avx:
	# I can't trust assembler to use specific encoding:-(
	.byte	0x48,0x8d,0x60,0xe0		#lea	-0x20(%rax),%rsp
	.byte	0x0f,0x29,0x70,0xe0		#movaps	%xmm6,-0x20(%rax)
	.byte	0x0f,0x29,0x78,0xf0		#movaps	%xmm7,-0x10(%rax)
	.byte	0x44,0x0f,0x29,0x00		#movaps	%xmm8,0(%rax)
	.byte	0x44,0x0f,0x29,0x48,0x10	#movaps	%xmm9,0x10(%rax)
	.byte	0x44,0x0f,0x29,0x50,0x20	#movaps	%xmm10,0x20(%rax)
	.byte	0x44,0x0f,0x29,0x58,0x30	#movaps	%xmm11,0x30(%rax)
	.byte	0x44,0x0f,0x29,0x60,0x40	#movaps	%xmm12,0x40(%rax)
	.byte	0x44,0x0f,0x29,0x68,0x50	#movaps	%xmm13,0x50(%rax)
	.byte	0x44,0x0f,0x29,0x70,0x60	#movaps	%xmm14,0x60(%rax)
	.byte	0x44,0x0f,0x29,0x78,0x70	#movaps	%xmm15,0x70(%rax)
___
$code.=<<___;
	vzeroupper

	vmovdqu		($Xip),$Xi		# load $Xi
	lea		.L0x1c2_polynomial(%rip),%r10
	lea		0x40($Htbl),$Htbl	# size optimization
	vmovdqu		.Lbswap_mask(%rip),$bswap
	vpshufb		$bswap,$Xi,$Xi
	cmp		\$0x80,$len
	jb		.Lshort_avx
	sub		\$0x80,$len

	vmovdqu		0x70($inp),$Ii		# I[7]
	vmovdqu		0x00-0x40($Htbl),$Hkey	# $Hkey^1
	vpshufb		$bswap,$Ii,$Ii
	vmovdqu		0x20-0x40($Htbl),$HK

	vpunpckhqdq	$Ii,$Ii,$T2
	 vmovdqu	0x60($inp),$Ij		# I[6]
	vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	vpxor		$Ii,$T2,$T2
	 vpshufb	$bswap,$Ij,$Ij
	vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	 vmovdqu	0x10-0x40($Htbl),$Hkey	# $Hkey^2
	 vpunpckhqdq	$Ij,$Ij,$T1
	 vmovdqu	0x50($inp),$Ii		# I[5]
	vpclmulqdq	\$0x00,$HK,$T2,$Xmi
	 vpxor		$Ij,$T1,$T1

	 vpshufb	$bswap,$Ii,$Ii
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Zlo
	 vpunpckhqdq	$Ii,$Ii,$T2
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Zhi
	 vmovdqu	0x30-0x40($Htbl),$Hkey	# $Hkey^3
	 vpxor		$Ii,$T2,$T2
	 vmovdqu	0x40($inp),$Ij		# I[4]
	vpclmulqdq	\$0x10,$HK,$T1,$Zmi
	 vmovdqu	0x50-0x40($Htbl),$HK

	 vpshufb	$bswap,$Ij,$Ij
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	vpxor		$Xhi,$Zhi,$Zhi
	 vpunpckhqdq	$Ij,$Ij,$T1
	vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	 vmovdqu	0x40-0x40($Htbl),$Hkey	# $Hkey^4
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T2,$Xmi
	 vpxor		$Ij,$T1,$T1

	 vmovdqu	0x30($inp),$Ii		# I[3]
	vpxor		$Zlo,$Xlo,$Xlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Zlo
	vpxor		$Zhi,$Xhi,$Xhi
	 vpshufb	$bswap,$Ii,$Ii
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Zhi
	 vmovdqu	0x60-0x40($Htbl),$Hkey	# $Hkey^5
	vpxor		$Zmi,$Xmi,$Xmi
	 vpunpckhqdq	$Ii,$Ii,$T2
	vpclmulqdq	\$0x10,$HK,$T1,$Zmi
	 vmovdqu	0x80-0x40($Htbl),$HK
	 vpxor		$Ii,$T2,$T2

	 vmovdqu	0x20($inp),$Ij		# I[2]
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	vpxor		$Xhi,$Zhi,$Zhi
	 vpshufb	$bswap,$Ij,$Ij
	vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	 vmovdqu	0x70-0x40($Htbl),$Hkey	# $Hkey^6
	vpxor		$Xmi,$Zmi,$Zmi
	 vpunpckhqdq	$Ij,$Ij,$T1
	vpclmulqdq	\$0x00,$HK,$T2,$Xmi
	 vpxor		$Ij,$T1,$T1

	 vmovdqu	0x10($inp),$Ii		# I[1]
	vpxor		$Zlo,$Xlo,$Xlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Zlo
	vpxor		$Zhi,$Xhi,$Xhi
	 vpshufb	$bswap,$Ii,$Ii
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Zhi
	 vmovdqu	0x90-0x40($Htbl),$Hkey	# $Hkey^7
	vpxor		$Zmi,$Xmi,$Xmi
	 vpunpckhqdq	$Ii,$Ii,$T2
	vpclmulqdq	\$0x10,$HK,$T1,$Zmi
	 vmovdqu	0xb0-0x40($Htbl),$HK
	 vpxor		$Ii,$T2,$T2

	 vmovdqu	($inp),$Ij		# I[0]
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	vpxor		$Xhi,$Zhi,$Zhi
	 vpshufb	$bswap,$Ij,$Ij
	vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	 vmovdqu	0xa0-0x40($Htbl),$Hkey	# $Hkey^8
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x10,$HK,$T2,$Xmi

	lea		0x80($inp),$inp
	cmp		\$0x80,$len
	jb		.Ltail_avx

	vpxor		$Xi,$Ij,$Ij		# accumulate $Xi
	sub		\$0x80,$len
	jmp		.Loop8x_avx

.align	32
.Loop8x_avx:
	vpunpckhqdq	$Ij,$Ij,$T1
	 vmovdqu	0x70($inp),$Ii		# I[7]
	vpxor		$Xlo,$Zlo,$Zlo
	vpxor		$Ij,$T1,$T1
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xi
	 vpshufb	$bswap,$Ii,$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xo
	 vmovdqu	0x00-0x40($Htbl),$Hkey	# $Hkey^1
	 vpunpckhqdq	$Ii,$Ii,$T2
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Tred
	 vmovdqu	0x20-0x40($Htbl),$HK
	 vpxor		$Ii,$T2,$T2

	  vmovdqu	0x60($inp),$Ij		# I[6]
	 vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	vpxor		$Zlo,$Xi,$Xi		# collect result
	  vpshufb	$bswap,$Ij,$Ij
	 vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	vxorps		$Zhi,$Xo,$Xo
	  vmovdqu	0x10-0x40($Htbl),$Hkey	# $Hkey^2
	 vpunpckhqdq	$Ij,$Ij,$T1
	 vpclmulqdq	\$0x00,$HK,  $T2,$Xmi
	vpxor		$Zmi,$Tred,$Tred
	 vxorps		$Ij,$T1,$T1

	  vmovdqu	0x50($inp),$Ii		# I[5]
	vpxor		$Xi,$Tred,$Tred		# aggregated Karatsuba post-processing
	 vpclmulqdq	\$0x00,$Hkey,$Ij,$Zlo
	vpxor		$Xo,$Tred,$Tred
	vpslldq		\$8,$Tred,$T2
	 vpxor		$Xlo,$Zlo,$Zlo
	 vpclmulqdq	\$0x11,$Hkey,$Ij,$Zhi
	vpsrldq		\$8,$Tred,$Tred
	vpxor		$T2, $Xi, $Xi
	  vmovdqu	0x30-0x40($Htbl),$Hkey	# $Hkey^3
	  vpshufb	$bswap,$Ii,$Ii
	vxorps		$Tred,$Xo, $Xo
	 vpxor		$Xhi,$Zhi,$Zhi
	 vpunpckhqdq	$Ii,$Ii,$T2
	 vpclmulqdq	\$0x10,$HK,  $T1,$Zmi
	  vmovdqu	0x50-0x40($Htbl),$HK
	 vpxor		$Ii,$T2,$T2
	 vpxor		$Xmi,$Zmi,$Zmi

	  vmovdqu	0x40($inp),$Ij		# I[4]
	vpalignr	\$8,$Xi,$Xi,$Tred	# 1st phase
	 vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	  vpshufb	$bswap,$Ij,$Ij
	 vpxor		$Zlo,$Xlo,$Xlo
	 vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	  vmovdqu	0x40-0x40($Htbl),$Hkey	# $Hkey^4
	 vpunpckhqdq	$Ij,$Ij,$T1
	 vpxor		$Zhi,$Xhi,$Xhi
	 vpclmulqdq	\$0x00,$HK,  $T2,$Xmi
	 vxorps		$Ij,$T1,$T1
	 vpxor		$Zmi,$Xmi,$Xmi

	  vmovdqu	0x30($inp),$Ii		# I[3]
	vpclmulqdq	\$0x10,(%r10),$Xi,$Xi
	 vpclmulqdq	\$0x00,$Hkey,$Ij,$Zlo
	  vpshufb	$bswap,$Ii,$Ii
	 vpxor		$Xlo,$Zlo,$Zlo
	 vpclmulqdq	\$0x11,$Hkey,$Ij,$Zhi
	  vmovdqu	0x60-0x40($Htbl),$Hkey	# $Hkey^5
	 vpunpckhqdq	$Ii,$Ii,$T2
	 vpxor		$Xhi,$Zhi,$Zhi
	 vpclmulqdq	\$0x10,$HK,  $T1,$Zmi
	  vmovdqu	0x80-0x40($Htbl),$HK
	 vpxor		$Ii,$T2,$T2
	 vpxor		$Xmi,$Zmi,$Zmi

	  vmovdqu	0x20($inp),$Ij		# I[2]
	 vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	  vpshufb	$bswap,$Ij,$Ij
	 vpxor		$Zlo,$Xlo,$Xlo
	 vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	  vmovdqu	0x70-0x40($Htbl),$Hkey	# $Hkey^6
	 vpunpckhqdq	$Ij,$Ij,$T1
	 vpxor		$Zhi,$Xhi,$Xhi
	 vpclmulqdq	\$0x00,$HK,  $T2,$Xmi
	 vpxor		$Ij,$T1,$T1
	 vpxor		$Zmi,$Xmi,$Xmi
	vxorps		$Tred,$Xi,$Xi

	  vmovdqu	0x10($inp),$Ii		# I[1]
	vpalignr	\$8,$Xi,$Xi,$Tred	# 2nd phase
	 vpclmulqdq	\$0x00,$Hkey,$Ij,$Zlo
	  vpshufb	$bswap,$Ii,$Ii
	 vpxor		$Xlo,$Zlo,$Zlo
	 vpclmulqdq	\$0x11,$Hkey,$Ij,$Zhi
	  vmovdqu	0x90-0x40($Htbl),$Hkey	# $Hkey^7
	vpclmulqdq	\$0x10,(%r10),$Xi,$Xi
	vxorps		$Xo,$Tred,$Tred
	 vpunpckhqdq	$Ii,$Ii,$T2
	 vpxor		$Xhi,$Zhi,$Zhi
	 vpclmulqdq	\$0x10,$HK,  $T1,$Zmi
	  vmovdqu	0xb0-0x40($Htbl),$HK
	 vpxor		$Ii,$T2,$T2
	 vpxor		$Xmi,$Zmi,$Zmi

	  vmovdqu	($inp),$Ij		# I[0]
	 vpclmulqdq	\$0x00,$Hkey,$Ii,$Xlo
	  vpshufb	$bswap,$Ij,$Ij
	 vpclmulqdq	\$0x11,$Hkey,$Ii,$Xhi
	  vmovdqu	0xa0-0x40($Htbl),$Hkey	# $Hkey^8
	vpxor		$Tred,$Ij,$Ij
	 vpclmulqdq	\$0x10,$HK,  $T2,$Xmi
	vpxor		$Xi,$Ij,$Ij		# accumulate $Xi

	lea		0x80($inp),$inp
	sub		\$0x80,$len
	jnc		.Loop8x_avx

	add		\$0x80,$len
	jmp		.Ltail_no_xor_avx

.align	32
.Lshort_avx:
	vmovdqu		-0x10($inp,$len),$Ii	# very last word
	lea		($inp,$len),$inp
	vmovdqu		0x00-0x40($Htbl),$Hkey	# $Hkey^1
	vmovdqu		0x20-0x40($Htbl),$HK
	vpshufb		$bswap,$Ii,$Ij

	vmovdqa		$Xlo,$Zlo		# subtle way to zero $Zlo,
	vmovdqa		$Xhi,$Zhi		# $Zhi and
	vmovdqa		$Xmi,$Zmi		# $Zmi
	sub		\$0x10,$len
	jz		.Ltail_avx

	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	 vmovdqu	-0x20($inp),$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vmovdqu		0x10-0x40($Htbl),$Hkey	# $Hkey^2
	 vpshufb	$bswap,$Ii,$Ij
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi
	vpsrldq		\$8,$HK,$HK
	sub		\$0x10,$len
	jz		.Ltail_avx

	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	 vmovdqu	-0x30($inp),$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vmovdqu		0x30-0x40($Htbl),$Hkey	# $Hkey^3
	 vpshufb	$bswap,$Ii,$Ij
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi
	vmovdqu		0x50-0x40($Htbl),$HK
	sub		\$0x10,$len
	jz		.Ltail_avx

	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	 vmovdqu	-0x40($inp),$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vmovdqu		0x40-0x40($Htbl),$Hkey	# $Hkey^4
	 vpshufb	$bswap,$Ii,$Ij
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi
	vpsrldq		\$8,$HK,$HK
	sub		\$0x10,$len
	jz		.Ltail_avx

	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	 vmovdqu	-0x50($inp),$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vmovdqu		0x60-0x40($Htbl),$Hkey	# $Hkey^5
	 vpshufb	$bswap,$Ii,$Ij
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi
	vmovdqu		0x80-0x40($Htbl),$HK
	sub		\$0x10,$len
	jz		.Ltail_avx

	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	 vmovdqu	-0x60($inp),$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vmovdqu		0x70-0x40($Htbl),$Hkey	# $Hkey^6
	 vpshufb	$bswap,$Ii,$Ij
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi
	vpsrldq		\$8,$HK,$HK
	sub		\$0x10,$len
	jz		.Ltail_avx

	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	 vmovdqu	-0x70($inp),$Ii
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vmovdqu		0x90-0x40($Htbl),$Hkey	# $Hkey^7
	 vpshufb	$bswap,$Ii,$Ij
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi
	vmovq		0xb8-0x40($Htbl),$HK
	sub		\$0x10,$len
	jmp		.Ltail_avx

.align	32
.Ltail_avx:
	vpxor		$Xi,$Ij,$Ij		# accumulate $Xi
.Ltail_no_xor_avx:
	vpunpckhqdq	$Ij,$Ij,$T1
	vpxor		$Xlo,$Zlo,$Zlo
	vpclmulqdq	\$0x00,$Hkey,$Ij,$Xlo
	vpxor		$Ij,$T1,$T1
	vpxor		$Xhi,$Zhi,$Zhi
	vpclmulqdq	\$0x11,$Hkey,$Ij,$Xhi
	vpxor		$Xmi,$Zmi,$Zmi
	vpclmulqdq	\$0x00,$HK,$T1,$Xmi

	vmovdqu		(%r10),$Tred

	vpxor		$Xlo,$Zlo,$Xi
	vpxor		$Xhi,$Zhi,$Xo
	vpxor		$Xmi,$Zmi,$Zmi

	vpxor		$Xi, $Zmi,$Zmi		# aggregated Karatsuba post-processing
	vpxor		$Xo, $Zmi,$Zmi
	vpslldq		\$8, $Zmi,$T2
	vpsrldq		\$8, $Zmi,$Zmi
	vpxor		$T2, $Xi, $Xi
	vpxor		$Zmi,$Xo, $Xo

	vpclmulqdq	\$0x10,$Tred,$Xi,$T2	# 1st phase
	vpalignr	\$8,$Xi,$Xi,$Xi
	vpxor		$T2,$Xi,$Xi

	vpclmulqdq	\$0x10,$Tred,$Xi,$T2	# 2nd phase
	vpalignr	\$8,$Xi,$Xi,$Xi
	vpxor		$Xo,$Xi,$Xi
	vpxor		$T2,$Xi,$Xi

	cmp		\$0,$len
	jne		.Lshort_avx

	vpshufb		$bswap,$Xi,$Xi
	vmovdqu		$Xi,($Xip)
	vzeroupper
___
$code.=<<___ if ($win64);
	movaps	(%rsp),%xmm6
	movaps	0x10(%rsp),%xmm7
	movaps	0x20(%rsp),%xmm8
	movaps	0x30(%rsp),%xmm9
	movaps	0x40(%rsp),%xmm10
	movaps	0x50(%rsp),%xmm11
	movaps	0x60(%rsp),%xmm12
	movaps	0x70(%rsp),%xmm13
	movaps	0x80(%rsp),%xmm14
	movaps	0x90(%rsp),%xmm15
	lea	0xa8(%rsp),%rsp
.LSEH_end_gcm_ghash_avx:
___
$code.=<<___;
	ret
.cfi_endproc
.size	gcm_ghash_avx,.-gcm_ghash_avx
___
} else {
$code.=<<___;
	jmp	.L_ghash_clmul
.cfi_endproc
.size	gcm_ghash_avx,.-gcm_ghash_avx
___
}

$code.=<<___;
.align	64
.Lbswap_mask:
	.byte	15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0
.L0x1c2_polynomial:
	.byte	1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xc2
.L7_mask:
	.long	7,0,7,0
.L7_mask_poly:
	.long	7,0,`0xE1<<1`,0
.align	64
.type	.Lrem_4bit,\@object
.Lrem_4bit:
	.long	0,`0x0000<<16`,0,`0x1C20<<16`,0,`0x3840<<16`,0,`0x2460<<16`
	.long	0,`0x7080<<16`,0,`0x6CA0<<16`,0,`0x48C0<<16`,0,`0x54E0<<16`
	.long	0,`0xE100<<16`,0,`0xFD20<<16`,0,`0xD940<<16`,0,`0xC560<<16`
	.long	0,`0x9180<<16`,0,`0x8DA0<<16`,0,`0xA9C0<<16`,0,`0xB5E0<<16`
.type	.Lrem_8bit,\@object
.Lrem_8bit:
	.value	0x0000,0x01C2,0x0384,0x0246,0x0708,0x06CA,0x048C,0x054E
	.value	0x0E10,0x0FD2,0x0D94,0x0C56,0x0918,0x08DA,0x0A9C,0x0B5E
	.value	0x1C20,0x1DE2,0x1FA4,0x1E66,0x1B28,0x1AEA,0x18AC,0x196E
	.value	0x1230,0x13F2,0x11B4,0x1076,0x1538,0x14FA,0x16BC,0x177E
	.value	0x3840,0x3982,0x3BC4,0x3A06,0x3F48,0x3E8A,0x3CCC,0x3D0E
	.value	0x3650,0x3792,0x35D4,0x3416,0x3158,0x309A,0x32DC,0x331E
	.value	0x2460,0x25A2,0x27E4,0x2626,0x2368,0x22AA,0x20EC,0x212E
	.value	0x2A70,0x2BB2,0x29F4,0x2836,0x2D78,0x2CBA,0x2EFC,0x2F3E
	.value	0x7080,0x7142,0x7304,0x72C6,0x7788,0x764A,0x740C,0x75CE
	.value	0x7E90,0x7F52,0x7D14,0x7CD6,0x7998,0x785A,0x7A1C,0x7BDE
	.value	0x6CA0,0x6D62,0x6F24,0x6EE6,0x6BA8,0x6A6A,0x682C,0x69EE
	.value	0x62B0,0x6372,0x6134,0x60F6,0x65B8,0x647A,0x663C,0x67FE
	.value	0x48C0,0x4902,0x4B44,0x4A86,0x4FC8,0x4E0A,0x4C4C,0x4D8E
	.value	0x46D0,0x4712,0x4554,0x4496,0x41D8,0x401A,0x425C,0x439E
	.value	0x54E0,0x5522,0x5764,0x56A6,0x53E8,0x522A,0x506C,0x51AE
	.value	0x5AF0,0x5B32,0x5974,0x58B6,0x5DF8,0x5C3A,0x5E7C,0x5FBE
	.value	0xE100,0xE0C2,0xE284,0xE346,0xE608,0xE7CA,0xE58C,0xE44E
	.value	0xEF10,0xEED2,0xEC94,0xED56,0xE818,0xE9DA,0xEB9C,0xEA5E
	.value	0xFD20,0xFCE2,0xFEA4,0xFF66,0xFA28,0xFBEA,0xF9AC,0xF86E
	.value	0xF330,0xF2F2,0xF0B4,0xF176,0xF438,0xF5FA,0xF7BC,0xF67E
	.value	0xD940,0xD882,0xDAC4,0xDB06,0xDE48,0xDF8A,0xDDCC,0xDC0E
	.value	0xD750,0xD692,0xD4D4,0xD516,0xD058,0xD19A,0xD3DC,0xD21E
	.value	0xC560,0xC4A2,0xC6E4,0xC726,0xC268,0xC3AA,0xC1EC,0xC02E
	.value	0xCB70,0xCAB2,0xC8F4,0xC936,0xCC78,0xCDBA,0xCFFC,0xCE3E
	.value	0x9180,0x9042,0x9204,0x93C6,0x9688,0x974A,0x950C,0x94CE
	.value	0x9F90,0x9E52,0x9C14,0x9DD6,0x9898,0x995A,0x9B1C,0x9ADE
	.value	0x8DA0,0x8C62,0x8E24,0x8FE6,0x8AA8,0x8B6A,0x892C,0x88EE
	.value	0x83B0,0x8272,0x8034,0x81F6,0x84B8,0x857A,0x873C,0x86FE
	.value	0xA9C0,0xA802,0xAA44,0xAB86,0xAEC8,0xAF0A,0xAD4C,0xAC8E
	.value	0xA7D0,0xA612,0xA454,0xA596,0xA0D8,0xA11A,0xA35C,0xA29E
	.value	0xB5E0,0xB422,0xB664,0xB7A6,0xB2E8,0xB32A,0xB16C,0xB0AE
	.value	0xBBF0,0xBA32,0xB874,0xB9B6,0xBCF8,0xBD3A,0xBF7C,0xBEBE

.asciz	"GHASH for x86_64, CRYPTOGAMS by <appro\@openssl.org>"
.align	64
___

# EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame,
#		CONTEXT *context,DISPATCHER_CONTEXT *disp)
if ($win64) {
$rec="%rcx";
$frame="%rdx";
$context="%r8";
$disp="%r9";

$code.=<<___;
.extern	__imp_RtlVirtualUnwind
.type	se_handler,\@abi-omnipotent
.align	16
se_handler:
	push	%rsi
	push	%rdi
	push	%rbx
	push	%rbp
	push	%r12
	push	%r13
	push	%r14
	push	%r15
	pushfq
	sub	\$64,%rsp

	mov	120($context),%rax	# pull context->Rax
	mov	248($context),%rbx	# pull context->Rip

	mov	8($disp),%rsi		# disp->ImageBase
	mov	56($disp),%r11		# disp->HandlerData

	mov	0(%r11),%r10d		# HandlerData[0]
	lea	(%rsi,%r10),%r10	# prologue label
	cmp	%r10,%rbx		# context->Rip<prologue label
	jb	.Lin_prologue

	mov	152($context),%rax	# pull context->Rsp

	mov	4(%r11),%r10d		# HandlerData[1]
	lea	(%rsi,%r10),%r10	# epilogue label
	cmp	%r10,%rbx		# context->Rip>=epilogue label
	jae	.Lin_prologue

	lea	48+280(%rax),%rax	# adjust "rsp"

	mov	-8(%rax),%rbx
	mov	-16(%rax),%rbp
	mov	-24(%rax),%r12
	mov	-32(%rax),%r13
	mov	-40(%rax),%r14
	mov	-48(%rax),%r15
	mov	%rbx,144($context)	# restore context->Rbx
	mov	%rbp,160($context)	# restore context->Rbp
	mov	%r12,216($context)	# restore context->R12
	mov	%r13,224($context)	# restore context->R13
	mov	%r14,232($context)	# restore context->R14
	mov	%r15,240($context)	# restore context->R15

.Lin_prologue:
	mov	8(%rax),%rdi
	mov	16(%rax),%rsi
	mov	%rax,152($context)	# restore context->Rsp
	mov	%rsi,168($context)	# restore context->Rsi
	mov	%rdi,176($context)	# restore context->Rdi

	mov	40($disp),%rdi		# disp->ContextRecord
	mov	$context,%rsi		# context
	mov	\$`1232/8`,%ecx		# sizeof(CONTEXT)
	.long	0xa548f3fc		# cld; rep movsq

	mov	$disp,%rsi
	xor	%rcx,%rcx		# arg1, UNW_FLAG_NHANDLER
	mov	8(%rsi),%rdx		# arg2, disp->ImageBase
	mov	0(%rsi),%r8		# arg3, disp->ControlPc
	mov	16(%rsi),%r9		# arg4, disp->FunctionEntry
	mov	40(%rsi),%r10		# disp->ContextRecord
	lea	56(%rsi),%r11		# &disp->HandlerData
	lea	24(%rsi),%r12		# &disp->EstablisherFrame
	mov	%r10,32(%rsp)		# arg5
	mov	%r11,40(%rsp)		# arg6
	mov	%r12,48(%rsp)		# arg7
	mov	%rcx,56(%rsp)		# arg8, (NULL)
	call	*__imp_RtlVirtualUnwind(%rip)

	mov	\$1,%eax		# ExceptionContinueSearch
	add	\$64,%rsp
	popfq
	pop	%r15
	pop	%r14
	pop	%r13
	pop	%r12
	pop	%rbp
	pop	%rbx
	pop	%rdi
	pop	%rsi
	ret
.size	se_handler,.-se_handler

.section	.pdata
.align	4
	.rva	.LSEH_begin_gcm_gmult_4bit
	.rva	.LSEH_end_gcm_gmult_4bit
	.rva	.LSEH_info_gcm_gmult_4bit

	.rva	.LSEH_begin_gcm_ghash_4bit
	.rva	.LSEH_end_gcm_ghash_4bit
	.rva	.LSEH_info_gcm_ghash_4bit

	.rva	.LSEH_begin_gcm_init_clmul
	.rva	.LSEH_end_gcm_init_clmul
	.rva	.LSEH_info_gcm_init_clmul

	.rva	.LSEH_begin_gcm_ghash_clmul
	.rva	.LSEH_end_gcm_ghash_clmul
	.rva	.LSEH_info_gcm_ghash_clmul
___
$code.=<<___	if ($avx);
	.rva	.LSEH_begin_gcm_init_avx
	.rva	.LSEH_end_gcm_init_avx
	.rva	.LSEH_info_gcm_init_clmul

	.rva	.LSEH_begin_gcm_ghash_avx
	.rva	.LSEH_end_gcm_ghash_avx
	.rva	.LSEH_info_gcm_ghash_clmul
___
$code.=<<___;
.section	.xdata
.align	8
.LSEH_info_gcm_gmult_4bit:
	.byte	9,0,0,0
	.rva	se_handler
	.rva	.Lgmult_prologue,.Lgmult_epilogue	# HandlerData
.LSEH_info_gcm_ghash_4bit:
	.byte	9,0,0,0
	.rva	se_handler
	.rva	.Lghash_prologue,.Lghash_epilogue	# HandlerData
.LSEH_info_gcm_init_clmul:
	.byte	0x01,0x08,0x03,0x00
	.byte	0x08,0x68,0x00,0x00	#movaps	0x00(rsp),xmm6
	.byte	0x04,0x22,0x00,0x00	#sub	rsp,0x18
.LSEH_info_gcm_ghash_clmul:
	.byte	0x01,0x33,0x16,0x00
	.byte	0x33,0xf8,0x09,0x00	#movaps 0x90(rsp),xmm15
	.byte	0x2e,0xe8,0x08,0x00	#movaps 0x80(rsp),xmm14
	.byte	0x29,0xd8,0x07,0x00	#movaps 0x70(rsp),xmm13
	.byte	0x24,0xc8,0x06,0x00	#movaps 0x60(rsp),xmm12
	.byte	0x1f,0xb8,0x05,0x00	#movaps 0x50(rsp),xmm11
	.byte	0x1a,0xa8,0x04,0x00	#movaps 0x40(rsp),xmm10
	.byte	0x15,0x98,0x03,0x00	#movaps 0x30(rsp),xmm9
	.byte	0x10,0x88,0x02,0x00	#movaps 0x20(rsp),xmm8
	.byte	0x0c,0x78,0x01,0x00	#movaps 0x10(rsp),xmm7
	.byte	0x08,0x68,0x00,0x00	#movaps 0x00(rsp),xmm6
	.byte	0x04,0x01,0x15,0x00	#sub	rsp,0xa8
___
}

$code =~ s/\`([^\`]*)\`/eval($1)/gem;

print $code;

close STDOUT or die "error closing STDOUT: $!";


#! /usr/bin/env perl
# Copyright 2014-2020 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

#
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# GHASH for for PowerISA v2.07.
#
# July 2014
#
# Accurate performance measurements are problematic, because it's
# always virtualized setup with possibly throttled processor.
# Relative comparison is therefore more informative. This initial
# version is ~2.1x slower than hardware-assisted AES-128-CTR, ~12x
# faster than "4-bit" integer-only compiler-generated 64-bit code.
# "Initial version" means that there is room for further improvement.

# May 2016
#
# 2x aggregated reduction improves performance by 50% (resulting
# performance on POWER8 is 1 cycle per processed byte), and 4x
# aggregated reduction - by 170% or 2.7x (resulting in 0.55 cpb).
# POWER9 delivers 0.51 cpb.

$flavour=shift;
$output =shift;

if ($flavour =~ /64/) {
	$SIZE_T=8;
	$LRSAVE=2*$SIZE_T;
	$STU="stdu";
	$POP="ld";
	$PUSH="std";
	$UCMP="cmpld";
	$SHRI="srdi";
} elsif ($flavour =~ /32/) {
	$SIZE_T=4;
	$LRSAVE=$SIZE_T;
	$STU="stwu";
	$POP="lwz";
	$PUSH="stw";
	$UCMP="cmplw";
	$SHRI="srwi";
} else { die "nonsense $flavour"; }

$sp="r1";
$FRAME=6*$SIZE_T+13*16;	# 13*16 is for v20-v31 offload

$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
( $xlate="${dir}ppc-xlate.pl" and -f $xlate ) or
( $xlate="${dir}../../perlasm/ppc-xlate.pl" and -f $xlate) or
die "can't locate ppc-xlate.pl";

open STDOUT,"| $^X $xlate $flavour $output" || die "can't call $xlate: $!";

my ($Xip,$Htbl,$inp,$len)=map("r$_",(3..6));	# argument block

my ($Xl,$Xm,$Xh,$IN)=map("v$_",(0..3));
my ($zero,$t0,$t1,$t2,$xC2,$H,$Hh,$Hl,$lemask)=map("v$_",(4..12));
my ($Xl1,$Xm1,$Xh1,$IN1,$H2,$H2h,$H2l)=map("v$_",(13..19));
my $vrsave="r12";

$code=<<___;
.machine	"any"

.text

.globl	.gcm_init_p8
.align	5
.gcm_init_p8:
	li		r0,-4096
	li		r8,0x10
	mfspr		$vrsave,256
	li		r9,0x20
	mtspr		256,r0
	li		r10,0x30
	lvx_u		$H,0,r4			# load H

	vspltisb	$xC2,-16		# 0xf0
	vspltisb	$t0,1			# one
	vaddubm		$xC2,$xC2,$xC2		# 0xe0
	vxor		$zero,$zero,$zero
	vor		$xC2,$xC2,$t0		# 0xe1
	vsldoi		$xC2,$xC2,$zero,15	# 0xe1...
	vsldoi		$t1,$zero,$t0,1		# ...1
	vaddubm		$xC2,$xC2,$xC2		# 0xc2...
	vspltisb	$t2,7
	vor		$xC2,$xC2,$t1		# 0xc2....01
	vspltb		$t1,$H,0		# most significant byte
	vsl		$H,$H,$t0		# H<<=1
	vsrab		$t1,$t1,$t2		# broadcast carry bit
	vand		$t1,$t1,$xC2
	vxor		$IN,$H,$t1		# twisted H

	vsldoi		$H,$IN,$IN,8		# twist even more ...
	vsldoi		$xC2,$zero,$xC2,8	# 0xc2.0
	vsldoi		$Hl,$zero,$H,8		# ... and split
	vsldoi		$Hh,$H,$zero,8

	stvx_u		$xC2,0,r3		# save pre-computed table
	stvx_u		$Hl,r8,r3
	li		r8,0x40
	stvx_u		$H, r9,r3
	li		r9,0x50
	stvx_u		$Hh,r10,r3
	li		r10,0x60

	vpmsumd		$Xl,$IN,$Hl		# H.loÂ·H.lo
	vpmsumd		$Xm,$IN,$H		# H.hiÂ·H.lo+H.loÂ·H.hi
	vpmsumd		$Xh,$IN,$Hh		# H.hiÂ·H.hi

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1

	vsldoi		$Xl,$Xl,$Xl,8
	vxor		$Xl,$Xl,$t2

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	vpmsumd		$Xl,$Xl,$xC2
	vxor		$t1,$t1,$Xh
	vxor		$IN1,$Xl,$t1

	vsldoi		$H2,$IN1,$IN1,8
	vsldoi		$H2l,$zero,$H2,8
	vsldoi		$H2h,$H2,$zero,8

	stvx_u		$H2l,r8,r3		# save H^2
	li		r8,0x70
	stvx_u		$H2,r9,r3
	li		r9,0x80
	stvx_u		$H2h,r10,r3
	li		r10,0x90
___
{
my ($t4,$t5,$t6) = ($Hl,$H,$Hh);
$code.=<<___;
	vpmsumd		$Xl,$IN,$H2l		# H.loÂ·H^2.lo
	 vpmsumd	$Xl1,$IN1,$H2l		# H^2.loÂ·H^2.lo
	vpmsumd		$Xm,$IN,$H2		# H.hiÂ·H^2.lo+H.loÂ·H^2.hi
	 vpmsumd	$Xm1,$IN1,$H2		# H^2.hiÂ·H^2.lo+H^2.loÂ·H^2.hi
	vpmsumd		$Xh,$IN,$H2h		# H.hiÂ·H^2.hi
	 vpmsumd	$Xh1,$IN1,$H2h		# H^2.hiÂ·H^2.hi

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase
	 vpmsumd	$t6,$Xl1,$xC2		# 1st reduction phase

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	 vsldoi		$t4,$Xm1,$zero,8
	 vsldoi		$t5,$zero,$Xm1,8
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1
	 vxor		$Xl1,$Xl1,$t4
	 vxor		$Xh1,$Xh1,$t5

	vsldoi		$Xl,$Xl,$Xl,8
	 vsldoi		$Xl1,$Xl1,$Xl1,8
	vxor		$Xl,$Xl,$t2
	 vxor		$Xl1,$Xl1,$t6

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	 vsldoi		$t5,$Xl1,$Xl1,8		# 2nd reduction phase
	vpmsumd		$Xl,$Xl,$xC2
	 vpmsumd	$Xl1,$Xl1,$xC2
	vxor		$t1,$t1,$Xh
	 vxor		$t5,$t5,$Xh1
	vxor		$Xl,$Xl,$t1
	 vxor		$Xl1,$Xl1,$t5

	vsldoi		$H,$Xl,$Xl,8
	 vsldoi		$H2,$Xl1,$Xl1,8
	vsldoi		$Hl,$zero,$H,8
	vsldoi		$Hh,$H,$zero,8
	 vsldoi		$H2l,$zero,$H2,8
	 vsldoi		$H2h,$H2,$zero,8

	stvx_u		$Hl,r8,r3		# save H^3
	li		r8,0xa0
	stvx_u		$H,r9,r3
	li		r9,0xb0
	stvx_u		$Hh,r10,r3
	li		r10,0xc0
	 stvx_u		$H2l,r8,r3		# save H^4
	 stvx_u		$H2,r9,r3
	 stvx_u		$H2h,r10,r3

	mtspr		256,$vrsave
	blr
	.long		0
	.byte		0,12,0x14,0,0,0,2,0
	.long		0
.size	.gcm_init_p8,.-.gcm_init_p8
___
}
$code.=<<___;
.globl	.gcm_gmult_p8
.align	5
.gcm_gmult_p8:
	lis		r0,0xfff8
	li		r8,0x10
	mfspr		$vrsave,256
	li		r9,0x20
	mtspr		256,r0
	li		r10,0x30
	lvx_u		$IN,0,$Xip		# load Xi

	lvx_u		$Hl,r8,$Htbl		# load pre-computed table
	 le?lvsl	$lemask,r0,r0
	lvx_u		$H, r9,$Htbl
	 le?vspltisb	$t0,0x07
	lvx_u		$Hh,r10,$Htbl
	 le?vxor	$lemask,$lemask,$t0
	lvx_u		$xC2,0,$Htbl
	 le?vperm	$IN,$IN,$IN,$lemask
	vxor		$zero,$zero,$zero

	vpmsumd		$Xl,$IN,$Hl		# H.loÂ·Xi.lo
	vpmsumd		$Xm,$IN,$H		# H.hiÂ·Xi.lo+H.loÂ·Xi.hi
	vpmsumd		$Xh,$IN,$Hh		# H.hiÂ·Xi.hi

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1

	vsldoi		$Xl,$Xl,$Xl,8
	vxor		$Xl,$Xl,$t2

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	vpmsumd		$Xl,$Xl,$xC2
	vxor		$t1,$t1,$Xh
	vxor		$Xl,$Xl,$t1

	le?vperm	$Xl,$Xl,$Xl,$lemask
	stvx_u		$Xl,0,$Xip		# write out Xi

	mtspr		256,$vrsave
	blr
	.long		0
	.byte		0,12,0x14,0,0,0,2,0
	.long		0
.size	.gcm_gmult_p8,.-.gcm_gmult_p8

.globl	.gcm_ghash_p8
.align	5
.gcm_ghash_p8:
	li		r0,-4096
	li		r8,0x10
	mfspr		$vrsave,256
	li		r9,0x20
	mtspr		256,r0
	li		r10,0x30
	lvx_u		$Xl,0,$Xip		# load Xi

	lvx_u		$Hl,r8,$Htbl		# load pre-computed table
	li		r8,0x40
	 le?lvsl	$lemask,r0,r0
	lvx_u		$H, r9,$Htbl
	li		r9,0x50
	 le?vspltisb	$t0,0x07
	lvx_u		$Hh,r10,$Htbl
	li		r10,0x60
	 le?vxor	$lemask,$lemask,$t0
	lvx_u		$xC2,0,$Htbl
	 le?vperm	$Xl,$Xl,$Xl,$lemask
	vxor		$zero,$zero,$zero

	${UCMP}i	$len,64
	bge		Lgcm_ghash_p8_4x

	lvx_u		$IN,0,$inp
	addi		$inp,$inp,16
	subic.		$len,$len,16
	 le?vperm	$IN,$IN,$IN,$lemask
	vxor		$IN,$IN,$Xl
	beq		Lshort

	lvx_u		$H2l,r8,$Htbl		# load H^2
	li		r8,16
	lvx_u		$H2, r9,$Htbl
	add		r9,$inp,$len		# end of input
	lvx_u		$H2h,r10,$Htbl
	be?b		Loop_2x

.align	5
Loop_2x:
	lvx_u		$IN1,0,$inp
	le?vperm	$IN1,$IN1,$IN1,$lemask

	 subic		$len,$len,32
	vpmsumd		$Xl,$IN,$H2l		# H^2.loÂ·Xi.lo
	 vpmsumd	$Xl1,$IN1,$Hl		# H.loÂ·Xi+1.lo
	 subfe		r0,r0,r0		# borrow?-1:0
	vpmsumd		$Xm,$IN,$H2		# H^2.hiÂ·Xi.lo+H^2.loÂ·Xi.hi
	 vpmsumd	$Xm1,$IN1,$H		# H.hiÂ·Xi+1.lo+H.loÂ·Xi+1.hi
	 and		r0,r0,$len
	vpmsumd		$Xh,$IN,$H2h		# H^2.hiÂ·Xi.hi
	 vpmsumd	$Xh1,$IN1,$Hh		# H.hiÂ·Xi+1.hi
	 add		$inp,$inp,r0

	vxor		$Xl,$Xl,$Xl1
	vxor		$Xm,$Xm,$Xm1

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	 vxor		$Xh,$Xh,$Xh1
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1

	vsldoi		$Xl,$Xl,$Xl,8
	vxor		$Xl,$Xl,$t2
	 lvx_u		$IN,r8,$inp
	 addi		$inp,$inp,32

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	vpmsumd		$Xl,$Xl,$xC2
	 le?vperm	$IN,$IN,$IN,$lemask
	vxor		$t1,$t1,$Xh
	vxor		$IN,$IN,$t1
	vxor		$IN,$IN,$Xl
	$UCMP		r9,$inp
	bgt		Loop_2x			# done yet?

	cmplwi		$len,0
	bne		Leven

Lshort:
	vpmsumd		$Xl,$IN,$Hl		# H.loÂ·Xi.lo
	vpmsumd		$Xm,$IN,$H		# H.hiÂ·Xi.lo+H.loÂ·Xi.hi
	vpmsumd		$Xh,$IN,$Hh		# H.hiÂ·Xi.hi

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1

	vsldoi		$Xl,$Xl,$Xl,8
	vxor		$Xl,$Xl,$t2

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	vpmsumd		$Xl,$Xl,$xC2
	vxor		$t1,$t1,$Xh

Leven:
	vxor		$Xl,$Xl,$t1
	le?vperm	$Xl,$Xl,$Xl,$lemask
	stvx_u		$Xl,0,$Xip		# write out Xi

	mtspr		256,$vrsave
	blr
	.long		0
	.byte		0,12,0x14,0,0,0,4,0
	.long		0
___
{
my ($Xl3,$Xm2,$IN2,$H3l,$H3,$H3h,
    $Xh3,$Xm3,$IN3,$H4l,$H4,$H4h) = map("v$_",(20..31));
my $IN0=$IN;
my ($H21l,$H21h,$loperm,$hiperm) = ($Hl,$Hh,$H2l,$H2h);

$code.=<<___;
.align	5
.gcm_ghash_p8_4x:
Lgcm_ghash_p8_4x:
	$STU		$sp,-$FRAME($sp)
	li		r10,`15+6*$SIZE_T`
	li		r11,`31+6*$SIZE_T`
	stvx		v20,r10,$sp
	addi		r10,r10,32
	stvx		v21,r11,$sp
	addi		r11,r11,32
	stvx		v22,r10,$sp
	addi		r10,r10,32
	stvx		v23,r11,$sp
	addi		r11,r11,32
	stvx		v24,r10,$sp
	addi		r10,r10,32
	stvx		v25,r11,$sp
	addi		r11,r11,32
	stvx		v26,r10,$sp
	addi		r10,r10,32
	stvx		v27,r11,$sp
	addi		r11,r11,32
	stvx		v28,r10,$sp
	addi		r10,r10,32
	stvx		v29,r11,$sp
	addi		r11,r11,32
	stvx		v30,r10,$sp
	li		r10,0x60
	stvx		v31,r11,$sp
	li		r0,-1
	stw		$vrsave,`$FRAME-4`($sp)	# save vrsave
	mtspr		256,r0			# preserve all AltiVec registers

	lvsl		$t0,0,r8		# 0x0001..0e0f
	#lvx_u		$H2l,r8,$Htbl		# load H^2
	li		r8,0x70
	lvx_u		$H2, r9,$Htbl
	li		r9,0x80
	vspltisb	$t1,8			# 0x0808..0808
	#lvx_u		$H2h,r10,$Htbl
	li		r10,0x90
	lvx_u		$H3l,r8,$Htbl		# load H^3
	li		r8,0xa0
	lvx_u		$H3, r9,$Htbl
	li		r9,0xb0
	lvx_u		$H3h,r10,$Htbl
	li		r10,0xc0
	lvx_u		$H4l,r8,$Htbl		# load H^4
	li		r8,0x10
	lvx_u		$H4, r9,$Htbl
	li		r9,0x20
	lvx_u		$H4h,r10,$Htbl
	li		r10,0x30

	vsldoi		$t2,$zero,$t1,8		# 0x0000..0808
	vaddubm		$hiperm,$t0,$t2		# 0x0001..1617
	vaddubm		$loperm,$t1,$hiperm	# 0x0809..1e1f

	$SHRI		$len,$len,4		# this allows to use sign bit
						# as carry
	lvx_u		$IN0,0,$inp		# load input
	lvx_u		$IN1,r8,$inp
	subic.		$len,$len,8
	lvx_u		$IN2,r9,$inp
	lvx_u		$IN3,r10,$inp
	addi		$inp,$inp,0x40
	le?vperm	$IN0,$IN0,$IN0,$lemask
	le?vperm	$IN1,$IN1,$IN1,$lemask
	le?vperm	$IN2,$IN2,$IN2,$lemask
	le?vperm	$IN3,$IN3,$IN3,$lemask

	vxor		$Xh,$IN0,$Xl

	 vpmsumd	$Xl1,$IN1,$H3l
	 vpmsumd	$Xm1,$IN1,$H3
	 vpmsumd	$Xh1,$IN1,$H3h

	 vperm		$H21l,$H2,$H,$hiperm
	 vperm		$t0,$IN2,$IN3,$loperm
	 vperm		$H21h,$H2,$H,$loperm
	 vperm		$t1,$IN2,$IN3,$hiperm
	 vpmsumd	$Xm2,$IN2,$H2		# H^2.loÂ·Xi+2.hi+H^2.hiÂ·Xi+2.lo
	 vpmsumd	$Xl3,$t0,$H21l		# H^2.loÂ·Xi+2.lo+H.loÂ·Xi+3.lo
	 vpmsumd	$Xm3,$IN3,$H		# H.hiÂ·Xi+3.lo  +H.loÂ·Xi+3.hi
	 vpmsumd	$Xh3,$t1,$H21h		# H^2.hiÂ·Xi+2.hi+H.hiÂ·Xi+3.hi

	 vxor		$Xm2,$Xm2,$Xm1
	 vxor		$Xl3,$Xl3,$Xl1
	 vxor		$Xm3,$Xm3,$Xm2
	 vxor		$Xh3,$Xh3,$Xh1

	blt		Ltail_4x

Loop_4x:
	lvx_u		$IN0,0,$inp
	lvx_u		$IN1,r8,$inp
	subic.		$len,$len,4
	lvx_u		$IN2,r9,$inp
	lvx_u		$IN3,r10,$inp
	addi		$inp,$inp,0x40
	le?vperm	$IN1,$IN1,$IN1,$lemask
	le?vperm	$IN2,$IN2,$IN2,$lemask
	le?vperm	$IN3,$IN3,$IN3,$lemask
	le?vperm	$IN0,$IN0,$IN0,$lemask

	vpmsumd		$Xl,$Xh,$H4l		# H^4.loÂ·Xi.lo
	vpmsumd		$Xm,$Xh,$H4		# H^4.hiÂ·Xi.lo+H^4.loÂ·Xi.hi
	vpmsumd		$Xh,$Xh,$H4h		# H^4.hiÂ·Xi.hi
	 vpmsumd	$Xl1,$IN1,$H3l
	 vpmsumd	$Xm1,$IN1,$H3
	 vpmsumd	$Xh1,$IN1,$H3h

	vxor		$Xl,$Xl,$Xl3
	vxor		$Xm,$Xm,$Xm3
	vxor		$Xh,$Xh,$Xh3
	 vperm		$t0,$IN2,$IN3,$loperm
	 vperm		$t1,$IN2,$IN3,$hiperm

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase
	 vpmsumd	$Xl3,$t0,$H21l		# H.loÂ·Xi+3.lo  +H^2.loÂ·Xi+2.lo
	 vpmsumd	$Xh3,$t1,$H21h		# H.hiÂ·Xi+3.hi  +H^2.hiÂ·Xi+2.hi

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1

	vsldoi		$Xl,$Xl,$Xl,8
	vxor		$Xl,$Xl,$t2

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	 vpmsumd	$Xm2,$IN2,$H2		# H^2.hiÂ·Xi+2.lo+H^2.loÂ·Xi+2.hi
	 vpmsumd	$Xm3,$IN3,$H		# H.hiÂ·Xi+3.lo  +H.loÂ·Xi+3.hi
	vpmsumd		$Xl,$Xl,$xC2

	 vxor		$Xl3,$Xl3,$Xl1
	 vxor		$Xh3,$Xh3,$Xh1
	vxor		$Xh,$Xh,$IN0
	 vxor		$Xm2,$Xm2,$Xm1
	vxor		$Xh,$Xh,$t1
	 vxor		$Xm3,$Xm3,$Xm2
	vxor		$Xh,$Xh,$Xl
	bge		Loop_4x

Ltail_4x:
	vpmsumd		$Xl,$Xh,$H4l		# H^4.loÂ·Xi.lo
	vpmsumd		$Xm,$Xh,$H4		# H^4.hiÂ·Xi.lo+H^4.loÂ·Xi.hi
	vpmsumd		$Xh,$Xh,$H4h		# H^4.hiÂ·Xi.hi

	vxor		$Xl,$Xl,$Xl3
	vxor		$Xm,$Xm,$Xm3

	vpmsumd		$t2,$Xl,$xC2		# 1st reduction phase

	vsldoi		$t0,$Xm,$zero,8
	vsldoi		$t1,$zero,$Xm,8
	 vxor		$Xh,$Xh,$Xh3
	vxor		$Xl,$Xl,$t0
	vxor		$Xh,$Xh,$t1

	vsldoi		$Xl,$Xl,$Xl,8
	vxor		$Xl,$Xl,$t2

	vsldoi		$t1,$Xl,$Xl,8		# 2nd reduction phase
	vpmsumd		$Xl,$Xl,$xC2
	vxor		$t1,$t1,$Xh
	vxor		$Xl,$Xl,$t1

	addic.		$len,$len,4
	beq		Ldone_4x

	lvx_u		$IN0,0,$inp
	${UCMP}i	$len,2
	li		$len,-4
	blt		Lone
	lvx_u		$IN1,r8,$inp
	beq		Ltwo

Lthree:
	lvx_u		$IN2,r9,$inp
	le?vperm	$IN0,$IN0,$IN0,$lemask
	le?vperm	$IN1,$IN1,$IN1,$lemask
	le?vperm	$IN2,$IN2,$IN2,$lemask

	vxor		$Xh,$IN0,$Xl
	vmr		$H4l,$H3l
	vmr		$H4, $H3
	vmr		$H4h,$H3h

	vperm		$t0,$IN1,$IN2,$loperm
	vperm		$t1,$IN1,$IN2,$hiperm
	vpmsumd		$Xm2,$IN1,$H2		# H^2.loÂ·Xi+1.hi+H^2.hiÂ·Xi+1.lo
	vpmsumd		$Xm3,$IN2,$H		# H.hiÂ·Xi+2.lo  +H.loÂ·Xi+2.hi
	vpmsumd		$Xl3,$t0,$H21l		# H^2.loÂ·Xi+1.lo+H.loÂ·Xi+2.lo
	vpmsumd		$Xh3,$t1,$H21h		# H^2.hiÂ·Xi+1.hi+H.hiÂ·Xi+2.hi

	vxor		$Xm3,$Xm3,$Xm2
	b		Ltail_4x

.align	4
Ltwo:
	le?vperm	$IN0,$IN0,$IN0,$lemask
	le?vperm	$IN1,$IN1,$IN1,$lemask

	vxor		$Xh,$IN0,$Xl
	vperm		$t0,$zero,$IN1,$loperm
	vperm		$t1,$zero,$IN1,$hiperm

	vsldoi		$H4l,$zero,$H2,8
	vmr		$H4, $H2
	vsldoi		$H4h,$H2,$zero,8

	vpmsumd		$Xl3,$t0, $H21l		# H.loÂ·Xi+1.lo
	vpmsumd		$Xm3,$IN1,$H		# H.hiÂ·Xi+1.lo+H.loÂ·Xi+2.hi
	vpmsumd		$Xh3,$t1, $H21h		# H.hiÂ·Xi+1.hi

	b		Ltail_4x

.align	4
Lone:
	le?vperm	$IN0,$IN0,$IN0,$lemask

	vsldoi		$H4l,$zero,$H,8
	vmr		$H4, $H
	vsldoi		$H4h,$H,$zero,8

	vxor		$Xh,$IN0,$Xl
	vxor		$Xl3,$Xl3,$Xl3
	vxor		$Xm3,$Xm3,$Xm3
	vxor		$Xh3,$Xh3,$Xh3

	b		Ltail_4x

Ldone_4x:
	le?vperm	$Xl,$Xl,$Xl,$lemask
	stvx_u		$Xl,0,$Xip		# write out Xi

	li		r10,`15+6*$SIZE_T`
	li		r11,`31+6*$SIZE_T`
	mtspr		256,$vrsave
	lvx		v20,r10,$sp
	addi		r10,r10,32
	lvx		v21,r11,$sp
	addi		r11,r11,32
	lvx		v22,r10,$sp
	addi		r10,r10,32
	lvx		v23,r11,$sp
	addi		r11,r11,32
	lvx		v24,r10,$sp
	addi		r10,r10,32
	lvx		v25,r11,$sp
	addi		r11,r11,32
	lvx		v26,r10,$sp
	addi		r10,r10,32
	lvx		v27,r11,$sp
	addi		r11,r11,32
	lvx		v28,r10,$sp
	addi		r10,r10,32
	lvx		v29,r11,$sp
	addi		r11,r11,32
	lvx		v30,r10,$sp
	lvx		v31,r11,$sp
	addi		$sp,$sp,$FRAME
	blr
	.long		0
	.byte		0,12,0x04,0,0x80,0,4,0
	.long		0
___
}
$code.=<<___;
.size	.gcm_ghash_p8,.-.gcm_ghash_p8

.asciz  "GHASH for PowerISA 2.07, CRYPTOGAMS by <appro\@openssl.org>"
.align  2
___

foreach (split("\n",$code)) {
	s/\`([^\`]*)\`/eval $1/geo;

	if ($flavour =~ /le$/o) {	# little-endian
	    s/le\?//o		or
	    s/be\?/#be#/o;
	} else {
	    s/le\?/#le#/o	or
	    s/be\?//o;
	}
	print $_,"\n";
}

close STDOUT or die "error closing STDOUT: $!"; # enforce flush


#! /usr/bin/env perl
# Copyright 2014-2020 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

#
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# GHASH for ARMv8 Crypto Extension, 64-bit polynomial multiplication.
#
# June 2014
#
# Initial version was developed in tight cooperation with Ard
# Biesheuvel of Linaro from bits-n-pieces from other assembly modules.
# Just like aesv8-armx.pl this module supports both AArch32 and
# AArch64 execution modes.
#
# July 2014
#
# Implement 2x aggregated reduction [see ghash-x86.pl for background
# information].
#
# November 2017
#
# AArch64 register bank to "accommodate" 4x aggregated reduction and
# improve performance by 20-70% depending on processor.
#
# Current performance in cycles per processed byte:
#
#		64-bit PMULL	32-bit PMULL	32-bit NEON(*)
# Apple A7	0.58		0.92		5.62
# Cortex-A53	0.85		1.01		8.39
# Cortex-A57	0.73		1.17		7.61
# Denver	0.51		0.65		6.02
# Mongoose	0.65		1.10		8.06
# Kryo		0.76		1.16		8.00
#
# (*)	presented for reference/comparison purposes;

$flavour = shift;
$output  = shift;

$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or
( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or
die "can't locate arm-xlate.pl";

open OUT,"| \"$^X\" $xlate $flavour $output";
*STDOUT=*OUT;

$Xi="x0";	# argument block
$Htbl="x1";
$inp="x2";
$len="x3";

$inc="x12";

{
my ($Xl,$Xm,$Xh,$IN)=map("q$_",(0..3));
my ($t0,$t1,$t2,$xC2,$H,$Hhl,$H2)=map("q$_",(8..14));

$code=<<___;
#include "arm_arch.h"

#if __ARM_MAX_ARCH__>=7
.text
___
$code.=".arch	armv8-a+crypto\n"	if ($flavour =~ /64/);
$code.=<<___				if ($flavour !~ /64/);
.fpu	neon
.code	32
#undef	__thumb2__
___

################################################################################
# void gcm_init_v8(u128 Htable[16],const u64 H[2]);
#
# input:	128-bit H - secret parameter E(K,0^128)
# output:	precomputed table filled with degrees of twisted H;
#		H is twisted to handle reverse bitness of GHASH;
#		only few of 16 slots of Htable[16] are used;
#		data is opaque to outside world (which allows to
#		optimize the code independently);
#
$code.=<<___;
.global	gcm_init_v8
.type	gcm_init_v8,%function
.align	4
gcm_init_v8:
	vld1.64		{$t1},[x1]		@ load input H
	vmov.i8		$xC2,#0xe1
	vshl.i64	$xC2,$xC2,#57		@ 0xc2.0
	vext.8		$IN,$t1,$t1,#8
	vshr.u64	$t2,$xC2,#63
	vdup.32		$t1,${t1}[1]
	vext.8		$t0,$t2,$xC2,#8		@ t0=0xc2....01
	vshr.u64	$t2,$IN,#63
	vshr.s32	$t1,$t1,#31		@ broadcast carry bit
	vand		$t2,$t2,$t0
	vshl.i64	$IN,$IN,#1
	vext.8		$t2,$t2,$t2,#8
	vand		$t0,$t0,$t1
	vorr		$IN,$IN,$t2		@ H<<<=1
	veor		$H,$IN,$t0		@ twisted H
	vst1.64		{$H},[x0],#16		@ store Htable[0]

	@ calculate H^2
	vext.8		$t0,$H,$H,#8		@ Karatsuba pre-processing
	vpmull.p64	$Xl,$H,$H
	veor		$t0,$t0,$H
	vpmull2.p64	$Xh,$H,$H
	vpmull.p64	$Xm,$t0,$t0

	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	veor		$Xm,$Xm,$t2
	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase

	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	veor		$Xl,$Xm,$t2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	veor		$H2,$Xl,$t2

	vext.8		$t1,$H2,$H2,#8		@ Karatsuba pre-processing
	veor		$t1,$t1,$H2
	vext.8		$Hhl,$t0,$t1,#8		@ pack Karatsuba pre-processed
	vst1.64		{$Hhl-$H2},[x0],#32	@ store Htable[1..2]
___
if ($flavour =~ /64/) {
my ($t3,$Yl,$Ym,$Yh) = map("q$_",(4..7));

$code.=<<___;
	@ calculate H^3 and H^4
	vpmull.p64	$Xl,$H, $H2
	 vpmull.p64	$Yl,$H2,$H2
	vpmull2.p64	$Xh,$H, $H2
	 vpmull2.p64	$Yh,$H2,$H2
	vpmull.p64	$Xm,$t0,$t1
	 vpmull.p64	$Ym,$t1,$t1

	vext.8		$t0,$Xl,$Xh,#8		@ Karatsuba post-processing
	 vext.8		$t1,$Yl,$Yh,#8
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t0
	 veor		$t3,$Yl,$Yh
	 veor		$Ym,$Ym,$t1
	veor		$Xm,$Xm,$t2
	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase
	 veor		$Ym,$Ym,$t3
	 vpmull.p64	$t3,$Yl,$xC2

	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	 vmov		$Yh#lo,$Ym#hi
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	 vmov		$Ym#hi,$Yl#lo
	veor		$Xl,$Xm,$t2
	 veor		$Yl,$Ym,$t3

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase
	 vext.8		$t3,$Yl,$Yl,#8
	vpmull.p64	$Xl,$Xl,$xC2
	 vpmull.p64	$Yl,$Yl,$xC2
	veor		$t2,$t2,$Xh
	 veor		$t3,$t3,$Yh
	veor		$H, $Xl,$t2		@ H^3
	 veor		$H2,$Yl,$t3		@ H^4

	vext.8		$t0,$H, $H,#8		@ Karatsuba pre-processing
	 vext.8		$t1,$H2,$H2,#8
	veor		$t0,$t0,$H
	 veor		$t1,$t1,$H2
	vext.8		$Hhl,$t0,$t1,#8		@ pack Karatsuba pre-processed
	vst1.64		{$H-$H2},[x0]		@ store Htable[3..5]
___
}
$code.=<<___;
	ret
.size	gcm_init_v8,.-gcm_init_v8
___
################################################################################
# void gcm_gmult_v8(u64 Xi[2],const u128 Htable[16]);
#
# input:	Xi - current hash value;
#		Htable - table precomputed in gcm_init_v8;
# output:	Xi - next hash value Xi;
#
$code.=<<___;
.global	gcm_gmult_v8
.type	gcm_gmult_v8,%function
.align	4
gcm_gmult_v8:
	vld1.64		{$t1},[$Xi]		@ load Xi
	vmov.i8		$xC2,#0xe1
	vld1.64		{$H-$Hhl},[$Htbl]	@ load twisted H, ...
	vshl.u64	$xC2,$xC2,#57
#ifndef __ARMEB__
	vrev64.8	$t1,$t1
#endif
	vext.8		$IN,$t1,$t1,#8

	vpmull.p64	$Xl,$H,$IN		@ H.loÂ·Xi.lo
	veor		$t1,$t1,$IN		@ Karatsuba pre-processing
	vpmull2.p64	$Xh,$H,$IN		@ H.hiÂ·Xi.hi
	vpmull.p64	$Xm,$Hhl,$t1		@ (H.lo+H.hi)Â·(Xi.lo+Xi.hi)

	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	veor		$Xm,$Xm,$t2
	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction

	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	veor		$Xl,$Xm,$t2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	veor		$Xl,$Xl,$t2

#ifndef __ARMEB__
	vrev64.8	$Xl,$Xl
#endif
	vext.8		$Xl,$Xl,$Xl,#8
	vst1.64		{$Xl},[$Xi]		@ write out Xi

	ret
.size	gcm_gmult_v8,.-gcm_gmult_v8
___
################################################################################
# void gcm_ghash_v8(u64 Xi[2],const u128 Htable[16],const u8 *inp,size_t len);
#
# input:	table precomputed in gcm_init_v8;
#		current hash value Xi;
#		pointer to input data;
#		length of input data in bytes, but divisible by block size;
# output:	next hash value Xi;
#
$code.=<<___;
.global	gcm_ghash_v8
.type	gcm_ghash_v8,%function
.align	4
gcm_ghash_v8:
___
$code.=<<___	if ($flavour =~ /64/);
	cmp		$len,#64
	b.hs		.Lgcm_ghash_v8_4x
___
$code.=<<___		if ($flavour !~ /64/);
	vstmdb		sp!,{d8-d15}		@ 32-bit ABI says so
___
$code.=<<___;
	vld1.64		{$Xl},[$Xi]		@ load [rotated] Xi
						@ "[rotated]" means that
						@ loaded value would have
						@ to be rotated in order to
						@ make it appear as in
						@ algorithm specification
	subs		$len,$len,#32		@ see if $len is 32 or larger
	mov		$inc,#16		@ $inc is used as post-
						@ increment for input pointer;
						@ as loop is modulo-scheduled
						@ $inc is zeroed just in time
						@ to preclude overstepping
						@ inp[len], which means that
						@ last block[s] are actually
						@ loaded twice, but last
						@ copy is not processed
	vld1.64		{$H-$Hhl},[$Htbl],#32	@ load twisted H, ..., H^2
	vmov.i8		$xC2,#0xe1
	vld1.64		{$H2},[$Htbl]
	cclr		$inc,eq			@ is it time to zero $inc?
	vext.8		$Xl,$Xl,$Xl,#8		@ rotate Xi
	vld1.64		{$t0},[$inp],#16	@ load [rotated] I[0]
	vshl.u64	$xC2,$xC2,#57		@ compose 0xc2.0 constant
#ifndef __ARMEB__
	vrev64.8	$t0,$t0
	vrev64.8	$Xl,$Xl
#endif
	vext.8		$IN,$t0,$t0,#8		@ rotate I[0]
	b.lo		.Lodd_tail_v8		@ $len was less than 32
___
{ my ($Xln,$Xmn,$Xhn,$In) = map("q$_",(4..7));
	#######
	# Xi+2 =[H*(Ii+1 + Xi+1)] mod P =
	#	[(H*Ii+1) + (H*Xi+1)] mod P =
	#	[(H*Ii+1) + H^2*(Ii+Xi)] mod P
	#
$code.=<<___;
	vld1.64		{$t1},[$inp],$inc	@ load [rotated] I[1]
#ifndef __ARMEB__
	vrev64.8	$t1,$t1
#endif
	vext.8		$In,$t1,$t1,#8
	veor		$IN,$IN,$Xl		@ I[i]^=Xi
	vpmull.p64	$Xln,$H,$In		@ HÂ·Ii+1
	veor		$t1,$t1,$In		@ Karatsuba pre-processing
	vpmull2.p64	$Xhn,$H,$In
	b		.Loop_mod2x_v8

.align	4
.Loop_mod2x_v8:
	vext.8		$t2,$IN,$IN,#8
	subs		$len,$len,#32		@ is there more data?
	vpmull.p64	$Xl,$H2,$IN		@ H^2.loÂ·Xi.lo
	cclr		$inc,lo			@ is it time to zero $inc?

	 vpmull.p64	$Xmn,$Hhl,$t1
	veor		$t2,$t2,$IN		@ Karatsuba pre-processing
	vpmull2.p64	$Xh,$H2,$IN		@ H^2.hiÂ·Xi.hi
	veor		$Xl,$Xl,$Xln		@ accumulate
	vpmull2.p64	$Xm,$Hhl,$t2		@ (H^2.lo+H^2.hi)Â·(Xi.lo+Xi.hi)
	 vld1.64	{$t0},[$inp],$inc	@ load [rotated] I[i+2]

	veor		$Xh,$Xh,$Xhn
	 cclr		$inc,eq			@ is it time to zero $inc?
	veor		$Xm,$Xm,$Xmn

	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	 vld1.64	{$t1},[$inp],$inc	@ load [rotated] I[i+3]
#ifndef __ARMEB__
	 vrev64.8	$t0,$t0
#endif
	veor		$Xm,$Xm,$t2
	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction

#ifndef __ARMEB__
	 vrev64.8	$t1,$t1
#endif
	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	 vext.8		$In,$t1,$t1,#8
	 vext.8		$IN,$t0,$t0,#8
	veor		$Xl,$Xm,$t2
	 vpmull.p64	$Xln,$H,$In		@ HÂ·Ii+1
	veor		$IN,$IN,$Xh		@ accumulate $IN early

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$IN,$IN,$t2
	 veor		$t1,$t1,$In		@ Karatsuba pre-processing
	veor		$IN,$IN,$Xl
	 vpmull2.p64	$Xhn,$H,$In
	b.hs		.Loop_mod2x_v8		@ there was at least 32 more bytes

	veor		$Xh,$Xh,$t2
	vext.8		$IN,$t0,$t0,#8		@ re-construct $IN
	adds		$len,$len,#32		@ re-construct $len
	veor		$Xl,$Xl,$Xh		@ re-construct $Xl
	b.eq		.Ldone_v8		@ is $len zero?
___
}
$code.=<<___;
.Lodd_tail_v8:
	vext.8		$t2,$Xl,$Xl,#8
	veor		$IN,$IN,$Xl		@ inp^=Xi
	veor		$t1,$t0,$t2		@ $t1 is rotated inp^Xi

	vpmull.p64	$Xl,$H,$IN		@ H.loÂ·Xi.lo
	veor		$t1,$t1,$IN		@ Karatsuba pre-processing
	vpmull2.p64	$Xh,$H,$IN		@ H.hiÂ·Xi.hi
	vpmull.p64	$Xm,$Hhl,$t1		@ (H.lo+H.hi)Â·(Xi.lo+Xi.hi)

	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	veor		$Xm,$Xm,$t2
	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction

	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	veor		$Xl,$Xm,$t2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	veor		$Xl,$Xl,$t2

.Ldone_v8:
#ifndef __ARMEB__
	vrev64.8	$Xl,$Xl
#endif
	vext.8		$Xl,$Xl,$Xl,#8
	vst1.64		{$Xl},[$Xi]		@ write out Xi

___
$code.=<<___		if ($flavour !~ /64/);
	vldmia		sp!,{d8-d15}		@ 32-bit ABI says so
___
$code.=<<___;
	ret
.size	gcm_ghash_v8,.-gcm_ghash_v8
___

if ($flavour =~ /64/) {				# 4x subroutine
my ($I0,$j1,$j2,$j3,
    $I1,$I2,$I3,$H3,$H34,$H4,$Yl,$Ym,$Yh) = map("q$_",(4..7,15..23));

$code.=<<___;
.type	gcm_ghash_v8_4x,%function
.align	4
gcm_ghash_v8_4x:
.Lgcm_ghash_v8_4x:
	vld1.64		{$Xl},[$Xi]		@ load [rotated] Xi
	vld1.64		{$H-$H2},[$Htbl],#48	@ load twisted H, ..., H^2
	vmov.i8		$xC2,#0xe1
	vld1.64		{$H3-$H4},[$Htbl]	@ load twisted H^3, ..., H^4
	vshl.u64	$xC2,$xC2,#57		@ compose 0xc2.0 constant

	vld1.64		{$I0-$j3},[$inp],#64
#ifndef __ARMEB__
	vrev64.8	$Xl,$Xl
	vrev64.8	$j1,$j1
	vrev64.8	$j2,$j2
	vrev64.8	$j3,$j3
	vrev64.8	$I0,$I0
#endif
	vext.8		$I3,$j3,$j3,#8
	vext.8		$I2,$j2,$j2,#8
	vext.8		$I1,$j1,$j1,#8

	vpmull.p64	$Yl,$H,$I3		@ HÂ·Ii+3
	veor		$j3,$j3,$I3
	vpmull2.p64	$Yh,$H,$I3
	vpmull.p64	$Ym,$Hhl,$j3

	vpmull.p64	$t0,$H2,$I2		@ H^2Â·Ii+2
	veor		$j2,$j2,$I2
	vpmull2.p64	$I2,$H2,$I2
	vpmull2.p64	$j2,$Hhl,$j2

	veor		$Yl,$Yl,$t0
	veor		$Yh,$Yh,$I2
	veor		$Ym,$Ym,$j2

	vpmull.p64	$j3,$H3,$I1		@ H^3Â·Ii+1
	veor		$j1,$j1,$I1
	vpmull2.p64	$I1,$H3,$I1
	vpmull.p64	$j1,$H34,$j1

	veor		$Yl,$Yl,$j3
	veor		$Yh,$Yh,$I1
	veor		$Ym,$Ym,$j1

	subs		$len,$len,#128
	b.lo		.Ltail4x

	b		.Loop4x

.align	4
.Loop4x:
	veor		$t0,$I0,$Xl
	 vld1.64	{$I0-$j3},[$inp],#64
	vext.8		$IN,$t0,$t0,#8
#ifndef __ARMEB__
	 vrev64.8	$j1,$j1
	 vrev64.8	$j2,$j2
	 vrev64.8	$j3,$j3
	 vrev64.8	$I0,$I0
#endif

	vpmull.p64	$Xl,$H4,$IN		@ H^4Â·(Xi+Ii)
	veor		$t0,$t0,$IN
	vpmull2.p64	$Xh,$H4,$IN
	 vext.8		$I3,$j3,$j3,#8
	vpmull2.p64	$Xm,$H34,$t0

	veor		$Xl,$Xl,$Yl
	veor		$Xh,$Xh,$Yh
	 vext.8		$I2,$j2,$j2,#8
	veor		$Xm,$Xm,$Ym
	 vext.8		$I1,$j1,$j1,#8

	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	 vpmull.p64	$Yl,$H,$I3		@ HÂ·Ii+3
	 veor		$j3,$j3,$I3
	veor		$Xm,$Xm,$t1
	 vpmull2.p64	$Yh,$H,$I3
	veor		$Xm,$Xm,$t2
	 vpmull.p64	$Ym,$Hhl,$j3

	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction
	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	 vpmull.p64	$t0,$H2,$I2		@ H^2Â·Ii+2
	 veor		$j2,$j2,$I2
	 vpmull2.p64	$I2,$H2,$I2
	veor		$Xl,$Xm,$t2
	 vpmull2.p64	$j2,$Hhl,$j2

	 veor		$Yl,$Yl,$t0
	 veor		$Yh,$Yh,$I2
	 veor		$Ym,$Ym,$j2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	 vpmull.p64	$j3,$H3,$I1		@ H^3Â·Ii+1
	 veor		$j1,$j1,$I1
	veor		$t2,$t2,$Xh
	 vpmull2.p64	$I1,$H3,$I1
	 vpmull.p64	$j1,$H34,$j1

	veor		$Xl,$Xl,$t2
	 veor		$Yl,$Yl,$j3
	 veor		$Yh,$Yh,$I1
	vext.8		$Xl,$Xl,$Xl,#8
	 veor		$Ym,$Ym,$j1

	subs		$len,$len,#64
	b.hs		.Loop4x

.Ltail4x:
	veor		$t0,$I0,$Xl
	vext.8		$IN,$t0,$t0,#8

	vpmull.p64	$Xl,$H4,$IN		@ H^4Â·(Xi+Ii)
	veor		$t0,$t0,$IN
	vpmull2.p64	$Xh,$H4,$IN
	vpmull2.p64	$Xm,$H34,$t0

	veor		$Xl,$Xl,$Yl
	veor		$Xh,$Xh,$Yh
	veor		$Xm,$Xm,$Ym

	adds		$len,$len,#64
	b.eq		.Ldone4x

	cmp		$len,#32
	b.lo		.Lone
	b.eq		.Ltwo
.Lthree:
	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	 vld1.64	{$I0-$j2},[$inp]
	veor		$Xm,$Xm,$t2
#ifndef	__ARMEB__
	 vrev64.8	$j1,$j1
	 vrev64.8	$j2,$j2
	 vrev64.8	$I0,$I0
#endif

	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction
	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	 vext.8		$I2,$j2,$j2,#8
	 vext.8		$I1,$j1,$j1,#8
	veor		$Xl,$Xm,$t2

	 vpmull.p64	$Yl,$H,$I2		@ HÂ·Ii+2
	 veor		$j2,$j2,$I2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	 vpmull2.p64	$Yh,$H,$I2
	 vpmull.p64	$Ym,$Hhl,$j2
	veor		$Xl,$Xl,$t2
	 vpmull.p64	$j3,$H2,$I1		@ H^2Â·Ii+1
	 veor		$j1,$j1,$I1
	vext.8		$Xl,$Xl,$Xl,#8

	 vpmull2.p64	$I1,$H2,$I1
	veor		$t0,$I0,$Xl
	 vpmull2.p64	$j1,$Hhl,$j1
	vext.8		$IN,$t0,$t0,#8

	 veor		$Yl,$Yl,$j3
	 veor		$Yh,$Yh,$I1
	 veor		$Ym,$Ym,$j1

	vpmull.p64	$Xl,$H3,$IN		@ H^3Â·(Xi+Ii)
	veor		$t0,$t0,$IN
	vpmull2.p64	$Xh,$H3,$IN
	vpmull.p64	$Xm,$H34,$t0

	veor		$Xl,$Xl,$Yl
	veor		$Xh,$Xh,$Yh
	veor		$Xm,$Xm,$Ym
	b		.Ldone4x

.align	4
.Ltwo:
	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	 vld1.64	{$I0-$j1},[$inp]
	veor		$Xm,$Xm,$t2
#ifndef	__ARMEB__
	 vrev64.8	$j1,$j1
	 vrev64.8	$I0,$I0
#endif

	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction
	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	 vext.8		$I1,$j1,$j1,#8
	veor		$Xl,$Xm,$t2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	veor		$Xl,$Xl,$t2
	vext.8		$Xl,$Xl,$Xl,#8

	 vpmull.p64	$Yl,$H,$I1		@ HÂ·Ii+1
	 veor		$j1,$j1,$I1

	veor		$t0,$I0,$Xl
	vext.8		$IN,$t0,$t0,#8

	 vpmull2.p64	$Yh,$H,$I1
	 vpmull.p64	$Ym,$Hhl,$j1

	vpmull.p64	$Xl,$H2,$IN		@ H^2Â·(Xi+Ii)
	veor		$t0,$t0,$IN
	vpmull2.p64	$Xh,$H2,$IN
	vpmull2.p64	$Xm,$Hhl,$t0

	veor		$Xl,$Xl,$Yl
	veor		$Xh,$Xh,$Yh
	veor		$Xm,$Xm,$Ym
	b		.Ldone4x

.align	4
.Lone:
	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	 vld1.64	{$I0},[$inp]
	veor		$Xm,$Xm,$t2
#ifndef	__ARMEB__
	 vrev64.8	$I0,$I0
#endif

	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction
	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	veor		$Xl,$Xm,$t2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	veor		$Xl,$Xl,$t2
	vext.8		$Xl,$Xl,$Xl,#8

	veor		$t0,$I0,$Xl
	vext.8		$IN,$t0,$t0,#8

	vpmull.p64	$Xl,$H,$IN
	veor		$t0,$t0,$IN
	vpmull2.p64	$Xh,$H,$IN
	vpmull.p64	$Xm,$Hhl,$t0

.Ldone4x:
	vext.8		$t1,$Xl,$Xh,#8		@ Karatsuba post-processing
	veor		$t2,$Xl,$Xh
	veor		$Xm,$Xm,$t1
	veor		$Xm,$Xm,$t2

	vpmull.p64	$t2,$Xl,$xC2		@ 1st phase of reduction
	vmov		$Xh#lo,$Xm#hi		@ Xh|Xm - 256-bit result
	vmov		$Xm#hi,$Xl#lo		@ Xm is rotated Xl
	veor		$Xl,$Xm,$t2

	vext.8		$t2,$Xl,$Xl,#8		@ 2nd phase of reduction
	vpmull.p64	$Xl,$Xl,$xC2
	veor		$t2,$t2,$Xh
	veor		$Xl,$Xl,$t2
	vext.8		$Xl,$Xl,$Xl,#8

#ifndef __ARMEB__
	vrev64.8	$Xl,$Xl
#endif
	vst1.64		{$Xl},[$Xi]		@ write out Xi

	ret
.size	gcm_ghash_v8_4x,.-gcm_ghash_v8_4x
___

}
}

$code.=<<___;
.asciz  "GHASH for ARMv8, CRYPTOGAMS by <appro\@openssl.org>"
.align  2
#endif
___

if ($flavour =~ /64/) {			######## 64-bit code
    sub unvmov {
	my $arg=shift;

	$arg =~ m/q([0-9]+)#(lo|hi),\s*q([0-9]+)#(lo|hi)/o &&
	sprintf	"ins	v%d.d[%d],v%d.d[%d]",$1<8?$1:$1+8,($2 eq "lo")?0:1,
					     $3<8?$3:$3+8,($4 eq "lo")?0:1;
    }
    foreach(split("\n",$code)) {
	s/cclr\s+([wx])([^,]+),\s*([a-z]+)/csel	$1$2,$1zr,$1$2,$3/o	or
	s/vmov\.i8/movi/o		or	# fix up legacy mnemonics
	s/vmov\s+(.*)/unvmov($1)/geo	or
	s/vext\.8/ext/o			or
	s/vshr\.s/sshr\.s/o		or
	s/vshr/ushr/o			or
	s/^(\s+)v/$1/o			or	# strip off v prefix
	s/\bbx\s+lr\b/ret/o;

	s/\bq([0-9]+)\b/"v".($1<8?$1:$1+8).".16b"/geo;	# old->new registers
	s/@\s/\/\//o;				# old->new style commentary

	# fix up remaining legacy suffixes
	s/\.[ui]?8(\s)/$1/o;
	s/\.[uis]?32//o and s/\.16b/\.4s/go;
	m/\.p64/o and s/\.16b/\.1q/o;		# 1st pmull argument
	m/l\.p64/o and s/\.16b/\.1d/go;		# 2nd and 3rd pmull arguments
	s/\.[uisp]?64//o and s/\.16b/\.2d/go;
	s/\.[42]([sd])\[([0-3])\]/\.$1\[$2\]/o;

	print $_,"\n";
    }
} else {				######## 32-bit code
    sub unvdup32 {
	my $arg=shift;

	$arg =~ m/q([0-9]+),\s*q([0-9]+)\[([0-3])\]/o &&
	sprintf	"vdup.32	q%d,d%d[%d]",$1,2*$2+($3>>1),$3&1;
    }
    sub unvpmullp64 {
	my ($mnemonic,$arg)=@_;

	if ($arg =~ m/q([0-9]+),\s*q([0-9]+),\s*q([0-9]+)/o) {
	    my $word = 0xf2a00e00|(($1&7)<<13)|(($1&8)<<19)
				 |(($2&7)<<17)|(($2&8)<<4)
				 |(($3&7)<<1) |(($3&8)<<2);
	    $word |= 0x00010001	 if ($mnemonic =~ "2");
	    # since ARMv7 instructions are always encoded little-endian.
	    # correct solution is to use .inst directive, but older
	    # assemblers don't implement it:-(
	    sprintf ".byte\t0x%02x,0x%02x,0x%02x,0x%02x\t@ %s %s",
			$word&0xff,($word>>8)&0xff,
			($word>>16)&0xff,($word>>24)&0xff,
			$mnemonic,$arg;
	}
    }

    foreach(split("\n",$code)) {
	s/\b[wx]([0-9]+)\b/r$1/go;		# new->old registers
	s/\bv([0-9])\.[12468]+[bsd]\b/q$1/go;	# new->old registers
	s/\/\/\s?/@ /o;				# new->old style commentary

	# fix up remaining new-style suffixes
	s/\],#[0-9]+/]!/o;

	s/cclr\s+([^,]+),\s*([a-z]+)/mov$2	$1,#0/o			or
	s/vdup\.32\s+(.*)/unvdup32($1)/geo				or
	s/v?(pmull2?)\.p64\s+(.*)/unvpmullp64($1,$2)/geo		or
	s/\bq([0-9]+)#(lo|hi)/sprintf "d%d",2*$1+($2 eq "hi")/geo	or
	s/^(\s+)b\./$1b/o						or
	s/^(\s+)ret/$1bx\tlr/o;

	print $_,"\n";
    }
}

close STDOUT or die "error closing STDOUT: $!"; # enforce flush


#! /usr/bin/env perl
# Copyright 2000-2019 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

use Getopt::Std;

our($opt_n);
getopts('n');

# Output year depends on the year of the script and the input file.
my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900;
my $iYEAR = [localtime([stat($ARGV[0])]->[9])]->[5] + 1900;
$YEAR = $iYEAR if $iYEAR > $YEAR;
$iYEAR = [localtime([stat($ARGV[1])]->[9])]->[5] + 1900;
$YEAR = $iYEAR if $iYEAR > $YEAR;

open (NUMIN,"$ARGV[1]") || die "Can't open number file $ARGV[1]";
$max_nid=0;
$o=0;
while(<NUMIN>)
	{
	s|\R$||;
	$o++;
	s/#.*$//;
	next if /^\s*$/;
	$_ = 'X'.$_;
	($Cname,$mynum) = split;
	$Cname =~ s/^X//;
	if (defined($nidn{$mynum}))
		{ die "$ARGV[1]:$o:There's already an object with NID ",$mynum," on line ",$order{$mynum},"\n"; }
	if (defined($nid{$Cname}))
		{ die "$ARGV[1]:$o:There's already an object with name ",$Cname," on line ",$order{$nid{$Cname}},"\n"; }
	$nid{$Cname} = $mynum;
	$nidn{$mynum} = $Cname;
	$order{$mynum} = $o;
	$max_nid = $mynum if $mynum > $max_nid;
	}
close NUMIN;

open (IN,"$ARGV[0]") || die "Can't open input file $ARGV[0]";
$Cname="";
$o=0;
while (<IN>)
	{
	s|\R$||;
	$o++;
        if (/^!module\s+(.*)$/)
		{
		$module = $1."-";
		$module =~ s/\./_/g;
		$module =~ s/-/_/g;
		}
        if (/^!global$/)
		{ $module = ""; }
	if (/^!Cname\s+(.*)$/)
		{ $Cname = $1; }
	if (/^!Alias\s+(.+?)\s+(.*)$/)
		{
		$Cname = $module.$1;
		$myoid = $2;
		$myoid = &process_oid($myoid);
		$Cname =~ s/-/_/g;
		$ordern{$o} = $Cname;
		$order{$Cname} = $o;
		$obj{$Cname} = $myoid;
		$_ = "";
		$Cname = "";
		}
	s/!.*$//;
	s/#.*$//;
	next if /^\s*$/;
	($myoid,$mysn,$myln) = split ':';
	$mysn =~ s/^\s*//;
	$mysn =~ s/\s*$//;
	$myln =~ s/^\s*//;
	$myln =~ s/\s*$//;
	$myoid =~ s/^\s*//;
	$myoid =~ s/\s*$//;
	if ($myoid ne "")
		{
		$myoid = &process_oid($myoid);
		}

	if ($Cname eq "" && ($myln =~ /^[_A-Za-z][\w.-]*$/ ))
		{
		$Cname = $myln;
		$Cname =~ s/\./_/g;
		$Cname =~ s/-/_/g;
		if ($Cname ne "" && defined($ln{$module.$Cname}))
			{ die "objects.txt:$o:There's already an object with long name ",$ln{$module.$Cname}," on line ",$order{$module.$Cname},"\n"; }
		}
	if ($Cname eq "")
		{
		$Cname = $mysn;
		$Cname =~ s/-/_/g;
		if ($Cname ne "" && defined($sn{$module.$Cname}))
			{ die "objects.txt:$o:There's already an object with short name ",$sn{$module.$Cname}," on line ",$order{$module.$Cname},"\n"; }
		}
	if ($Cname eq "")
		{
		$Cname = $myln;
		$Cname =~ s/-/_/g;
		$Cname =~ s/\./_/g;
		$Cname =~ s/ /_/g;
		if ($Cname ne "" && defined($ln{$module.$Cname}))
			{ die "objects.txt:$o:There's already an object with long name ",$ln{$module.$Cname}," on line ",$order{$module.$Cname},"\n"; }
		}
	$Cname =~ s/\./_/g;
	$Cname =~ s/-/_/g;
	$Cname = $module.$Cname;
	$ordern{$o} = $Cname;
	$order{$Cname} = $o;
	$sn{$Cname} = $mysn;
	$ln{$Cname} = $myln;
	$obj{$Cname} = $myoid;
	if (!defined($nid{$Cname}))
		{
		$max_nid++;
		$nid{$Cname} = $max_nid;
		$nidn{$max_nid} = $Cname;
print STDERR "Added OID $Cname\n";
		}
	$Cname="";
	}
close IN;

if ( $opt_n ) {
    foreach (sort { $a <=> $b } keys %nidn)
            {
            print $nidn{$_},"\t\t",$_,"\n";
            }
    exit;
}

print <<"EOF";
/*
 * WARNING: do not edit!
 * Generated by crypto/objects/objects.pl
 *
 * Copyright 2000-$YEAR The OpenSSL Project Authors. All Rights Reserved.
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

#define SN_undef                        "UNDEF"
#define LN_undef                        "undefined"
#define NID_undef                       0
#define OBJ_undef                       0L
EOF

sub expand
	{
	my $string = shift;

	1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;

	return $string;
	}

foreach (sort { $a <=> $b } keys %ordern)
	{
	$Cname=$ordern{$_};
	print "\n";
	print expand("#define SN_$Cname\t\t\"$sn{$Cname}\"\n") if $sn{$Cname} ne "";
	print expand("#define LN_$Cname\t\t\"$ln{$Cname}\"\n") if $ln{$Cname} ne "";
	print expand("#define NID_$Cname\t\t$nid{$Cname}\n") if $nid{$Cname} ne "";
	print expand("#define OBJ_$Cname\t\t$obj{$Cname}\n") if $obj{$Cname} ne "";
	}

sub process_oid
	{
	local($oid)=@_;
	local(@a,$oid_pref);

	@a = split(/\s+/,$myoid);
	$pref_oid = "";
	$pref_sep = "";
	if (!($a[0] =~ /^[0-9]+$/))
		{
		$a[0] =~ s/-/_/g;
		if (!defined($obj{$a[0]}))
			{ die "$ARGV[0]:$o:Undefined identifier ",$a[0],"\n"; }
		$pref_oid = "OBJ_" . $a[0];
		$pref_sep = ",";
		shift @a;
		}
	$oids = join('L,',@a) . "L";
	if ($oids ne "L")
		{
		$oids = $pref_oid . $pref_sep . $oids;
		}
	else
		{
		$oids = $pref_oid;
		}
	return($oids);
	}


#! /usr/bin/env perl
# Copyright 1998-2019 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

use strict;

my %xref_tbl;
my %oid_tbl;

my ($mac_file, $xref_file) = @ARGV;

# Output year depends on the year of the script and the input file.
my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900;
my $iYEAR = [localtime([stat($mac_file)]->[9])]->[5] + 1900;
$YEAR = $iYEAR if $iYEAR > $YEAR;
$iYEAR = [localtime([stat($xref_file)]->[9])]->[5] + 1900;
$YEAR = $iYEAR if $iYEAR > $YEAR;

open(IN, $mac_file) || die "Can't open $mac_file, $!\n";

# Read in OID nid values for a lookup table.

while (<IN>)
	{
	s|\R$||;                # Better chomp
	my ($name, $num) = /^(\S+)\s+(\S+)$/;
	$oid_tbl{$name} = $num;
	}
close IN;

open(IN, $xref_file) || die "Can't open $xref_file, $!\n";

my $ln = 1;

while (<IN>)
	{
	s|\R$||;                # Better chomp
	s/#.*$//;
	next if (/^\S*$/);
	my ($xr, $p1, $p2) = /^(\S+)\s+(\S+)\s+(\S+)/;
	check_oid($xr);
	check_oid($p1);
	check_oid($p2);
	$xref_tbl{$xr} = [$p1, $p2, $ln];
	}

my @xrkeys = keys %xref_tbl;

my @srt1 = sort { $oid_tbl{$a} <=> $oid_tbl{$b}} @xrkeys;

my $i;
for($i = 0; $i <= $#srt1; $i++)
	{
	$xref_tbl{$srt1[$i]}[2] = $i;
	}

my @srt2 = sort
	{
	my$ap1 = $oid_tbl{$xref_tbl{$a}[0]};
	my$bp1 = $oid_tbl{$xref_tbl{$b}[0]};
	return $ap1 - $bp1 if ($ap1 != $bp1);
	my$ap2 = $oid_tbl{$xref_tbl{$a}[1]};
	my$bp2 = $oid_tbl{$xref_tbl{$b}[1]};

	return $ap2 - $bp2;
	} @xrkeys;

my $pname = $0;
$pname =~ s|.*/||;

print <<EOF;
/*
 * WARNING: do not edit!
 * Generated by $pname
 *
 * Copyright 1998-$YEAR The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

typedef struct {
    int sign_id;
    int hash_id;
    int pkey_id;
} nid_triple;

DEFINE_STACK_OF(nid_triple)

static const nid_triple sigoid_srt[] = {
EOF

foreach (@srt1)
	{
	my $xr = $_;
	my ($p1, $p2) = @{$xref_tbl{$_}};
	my $o1 = "    {NID_$xr, NID_$p1,";
	my $o2 = "NID_$p2},";
        if (length("$o1 $o2") < 78)
		{
		print "$o1 $o2\n";
		}
	else
		{
		print "$o1\n     $o2\n";
		}
        }

print "};";
print <<EOF;

static const nid_triple *const sigoid_srt_xref[] = {
EOF

foreach (@srt2)
	{
	my ($p1, $p2, $x) = @{$xref_tbl{$_}};
	# If digest or signature algorithm is "undef" then the algorithm
	# needs special handling and is excluded from the cross reference table.
	next if $p1 eq "undef" || $p2 eq "undef";
	print "    \&sigoid_srt\[$x\],\n";
	}

print "};\n";

sub check_oid
	{
	my ($chk) = @_;
	if (!exists $oid_tbl{$chk})
		{
		die "Can't find \"$chk\"\n";
		}
	}


#! /usr/bin/env perl
# Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

use integer;
use strict;
use warnings;

# Generate the DER encoding for the given OID.
sub der_it
{
    # Prologue
    my ($v) = @_;
    my @a = split(/\s+/, $v);
    my $ret = pack("C*", $a[0] * 40 + $a[1]);
    shift @a;
    shift @a;

    # Loop over rest of bytes; or in 0x80 for multi-byte numbers.
    my $t;
    foreach (@a) {
        my @r = ();
        $t = 0;
        while ($_ >= 128) {
            my $x = $_ % 128;
            $_ /= 128;
            push(@r, ($t++ ? 0x80 : 0) | $x);
        }
        push(@r, ($t++ ? 0x80 : 0) | $_);
        $ret .= pack("C*", reverse(@r));
    }
    return $ret;
}

# Output year depends on the year of the script and the input file.
my $YEAR = [localtime([stat($0)]->[9])]->[5] + 1900;
my $iYEAR = [localtime([stat($ARGV[0])]->[9])]->[5] + 1900;
$YEAR = $iYEAR if $iYEAR > $YEAR;

# Read input, parse all #define's into OID name and value.
# Populate %ln and %sn with long and short names (%dupln and %dupsn)
# are used to watch for duplicates.  Also %nid and %obj get the
# NID and OBJ entries.
my %ln;
my %sn;
my %dupln;
my %dupsn;
my %nid;
my %obj;
my %objd;
open(IN, "$ARGV[0]") || die "Can't open input file $ARGV[0], $!";
while (<IN>) {
    next unless /^\#define\s+(\S+)\s+(.*)$/;
    my $v = $1;
    my $d = $2;
    $d =~ s/^\"//;
    $d =~ s/\"$//;
    if ($v =~ /^SN_(.*)$/) {
        if (defined $dupsn{$d}) {
            print "WARNING: Duplicate short name \"$d\"\n";
        } else {
            $dupsn{$d} = 1;
        }
        $sn{$1} = $d;
    }
    elsif ($v =~ /^LN_(.*)$/) {
        if (defined $dupln{$d}) {
            print "WARNING: Duplicate long name \"$d\"\n";
        } else {
            $dupln{$d} = 1;
        }
        $ln{$1} = $d;
    }
    elsif ($v =~ /^NID_(.*)$/) {
        $nid{$d} = $1;
    }
    elsif ($v =~ /^OBJ_(.*)$/) {
        $obj{$1} = $v;
        $objd{$v} = $d;
    }
}
close IN;

# For every value in %obj, recursively expand OBJ_xxx values.  That is:
#     #define OBJ_iso 1L
#     #define OBJ_identified_organization OBJ_iso,3L
# Modify %objd values in-place.  Create an %objn array that has
my $changed;
do {
    $changed = 0;
    foreach my $k (keys %objd) {
        $changed = 1 if $objd{$k} =~ s/(OBJ_[^,]+),/$objd{$1},/;
    }
} while ($changed);

my @a = sort { $a <=> $b } keys %nid;
my $n = $a[$#a] + 1;
my @lvalues = ();
my $lvalues = 0;

# Scan all defined objects, building up the @out array.
# %obj_der holds the DER encoding as an array of bytes, and %obj_len
# holds the length in bytes.
my @out;
my %obj_der;
my %obj_len;
for (my $i = 0; $i < $n; $i++) {
    if (!defined $nid{$i}) {
        push(@out, "    { NULL, NULL, NID_undef },\n");
        next;
    }

    my $sn = defined $sn{$nid{$i}} ? "$sn{$nid{$i}}" : "NULL";
    my $ln = defined $ln{$nid{$i}} ? "$ln{$nid{$i}}" : "NULL";
    if ($sn eq "NULL") {
        $sn = $ln;
        $sn{$nid{$i}} = $ln;
    }
    if ($ln eq "NULL") {
        $ln = $sn;
        $ln{$nid{$i}} = $sn;
    }

    my $out = "    {\"$sn\", \"$ln\", NID_$nid{$i}";
    if (defined $obj{$nid{$i}} && $objd{$obj{$nid{$i}}} =~ /,/) {
        my $v = $objd{$obj{$nid{$i}}};
        $v =~ s/L//g;
        $v =~ s/,/ /g;
        my $r = &der_it($v);
        my $z = "";
        my $length = 0;
        # Format using fixed-with because we use strcmp later.
        foreach (unpack("C*",$r)) {
            $z .= sprintf("0x%02X,", $_);
            $length++;
        }
        $obj_der{$obj{$nid{$i}}} = $z;
        $obj_len{$obj{$nid{$i}}} = $length;

        push(@lvalues,
            sprintf("    %-45s  /* [%5d] %s */\n",
                $z, $lvalues, $obj{$nid{$i}}));
        $out .= ", $length, &so[$lvalues]";
        $lvalues += $length;
    }
    $out .= "},\n";
    push(@out, $out);
}

# Finally ready to generate the output.
print <<"EOF";
/*
 * WARNING: do not edit!
 * Generated by crypto/objects/obj_dat.pl
 *
 * Copyright 1995-$YEAR The OpenSSL Project Authors. All Rights Reserved.
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

EOF

print "/* Serialized OID's */\n";
printf "static const unsigned char so[%d] = {\n", $lvalues + 1;
print @lvalues;
print "};\n\n";

printf "#define NUM_NID %d\n", $n;
printf "static const ASN1_OBJECT nid_objs[NUM_NID] = {\n";
print @out;
print  "};\n\n";

{
    no warnings "uninitialized";
    @a = grep(defined $sn{$nid{$_}}, 0 .. $n);
}
printf "#define NUM_SN %d\n", $#a + 1;
printf "static const unsigned int sn_objs[NUM_SN] = {\n";
foreach (sort { $sn{$nid{$a}} cmp $sn{$nid{$b}} } @a) {
    printf "    %4d,    /* \"$sn{$nid{$_}}\" */\n", $_;
}
print  "};\n\n";

{
    no warnings "uninitialized";
    @a = grep(defined $ln{$nid{$_}}, 0 .. $n);
}
printf "#define NUM_LN %d\n", $#a + 1;
printf "static const unsigned int ln_objs[NUM_LN] = {\n";
foreach (sort { $ln{$nid{$a}} cmp $ln{$nid{$b}} } @a) {
    printf "    %4d,    /* \"$ln{$nid{$_}}\" */\n", $_;
}
print  "};\n\n";

{
    no warnings "uninitialized";
    @a = grep(defined $obj{$nid{$_}}, 0 .. $n);
}
printf "#define NUM_OBJ %d\n", $#a + 1;
printf "static const unsigned int obj_objs[NUM_OBJ] = {\n";

# Compare DER; prefer shorter; if some length, use the "smaller" encoding.
sub obj_cmp
{
    no warnings "uninitialized";
    my $A = $obj_len{$obj{$nid{$a}}};
    my $B = $obj_len{$obj{$nid{$b}}};
    my $r = $A - $B;
    return $r if $r != 0;

    $A = $obj_der{$obj{$nid{$a}}};
    $B = $obj_der{$obj{$nid{$b}}};
    return $A cmp $B;
}
foreach (sort obj_cmp @a) {
    my $m = $obj{$nid{$_}};
    my $v = $objd{$m};
    $v =~ s/L//g;
    $v =~ s/,/ /g;
    printf "    %4d,    /* %-32s %s */\n", $_, $m, $v;
}
print  "};\n";


#! /usr/bin/env perl
# Copyright 2015-2020 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License").  You may not use
# this file except in compliance with the License.  You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html

use strict;

my $flavour = shift;
my $output = shift;
open STDOUT,">$output" || die "can't open $output: $!";

$flavour = "linux32" if (!$flavour or $flavour eq "void");

my %GLOBALS;
my $dotinlocallabels=($flavour=~/linux/)?1:0;

################################################################
# directives which need special treatment on different platforms
################################################################
my $arch = sub {
    if ($flavour =~ /linux/)	{ ".arch\t".join(',',@_); }
    else			{ ""; }
};
my $fpu = sub {
    if ($flavour =~ /linux/)	{ ".fpu\t".join(',',@_); }
    else			{ ""; }
};
my $hidden = sub {
    if ($flavour =~ /ios/)	{ ".private_extern\t".join(',',@_); }
    else			{ ".hidden\t".join(',',@_); }
};
my $comm = sub {
    my @args = split(/,\s*/,shift);
    my $name = @args[0];
    my $global = \$GLOBALS{$name};
    my $ret;

    if ($flavour =~ /ios32/)	{
	$ret = ".comm\t_$name,@args[1]\n";
	$ret .= ".non_lazy_symbol_pointer\n";
	$ret .= "$name:\n";
	$ret .= ".indirect_symbol\t_$name\n";
	$ret .= ".long\t0";
	$name = "_$name";
    } else			{ $ret = ".comm\t".join(',',@args); }

    $$global = $name;
    $ret;
};
my $globl = sub {
    my $name = shift;
    my $global = \$GLOBALS{$name};
    my $ret;

    SWITCH: for ($flavour) {
	/ios/		&& do { $name = "_$name";
				last;
			      };
    }

    $ret = ".globl	$name" if (!$ret);
    $$global = $name;
    $ret;
};
my $global = $globl;
my $extern = sub {
    &$globl(@_);
    return;	# return nothing
};
my $type = sub {
    if ($flavour =~ /linux/)	{ ".type\t".join(',',@_); }
    elsif ($flavour =~ /ios32/)	{ if (join(',',@_) =~ /(\w+),%function/) {
					"#ifdef __thumb2__\n".
					".thumb_func	$1\n".
					"#endif";
				  }
			        }
    else			{ ""; }
};
my $size = sub {
    if ($flavour =~ /linux/)	{ ".size\t".join(',',@_); }
    else			{ ""; }
};
my $inst = sub {
    if ($flavour =~ /linux/)    { ".inst\t".join(',',@_); }
    else                        { ".long\t".join(',',@_); }
};
my $asciz = sub {
    my $line = join(",",@_);
    if ($line =~ /^"(.*)"$/)
    {	".byte	" . join(",",unpack("C*",$1),0) . "\n.align	2";	}
    else
    {	"";	}
};

sub range {
  my ($r,$sfx,$start,$end) = @_;

    join(",",map("$r$_$sfx",($start..$end)));
}

sub expand_line {
  my $line = shift;
  my @ret = ();

    pos($line)=0;

    while ($line =~ m/\G[^@\/\{\"]*/g) {
	if ($line =~ m/\G(@|\/\/|$)/gc) {
	    last;
	}
	elsif ($line =~ m/\G\{/gc) {
	    my $saved_pos = pos($line);
	    $line =~ s/\G([rdqv])([0-9]+)([^\-]*)\-\1([0-9]+)\3/range($1,$3,$2,$4)/e;
	    pos($line) = $saved_pos;
	    $line =~ m/\G[^\}]*\}/g;
	}
	elsif ($line =~ m/\G\"/gc) {
	    $line =~ m/\G[^\"]*\"/g;
	}
    }

    $line =~ s/\b(\w+)/$GLOBALS{$1} or $1/ge;

    return $line;
}

while(my $line=<>) {

    if ($line =~ m/^\s*(#|@|\/\/)/)	{ print $line; next; }

    $line =~ s|/\*.*\*/||;	# get rid of C-style comments...
    $line =~ s|^\s+||;		# ... and skip white spaces in beginning...
    $line =~ s|\s+$||;		# ... and at the end

    {
	$line =~ s|[\b\.]L(\w{2,})|L$1|g;	# common denominator for Locallabel
	$line =~ s|\bL(\w{2,})|\.L$1|g	if ($dotinlocallabels);
    }

    {
	$line =~ s|(^[\.\w]+)\:\s*||;
	my $label = $1;
	if ($label) {
	    printf "%s:",($GLOBALS{$label} or $label);
	}
    }

    if ($line !~ m/^[#@]/) {
	$line =~ s|^\s*(\.?)(\S+)\s*||;
	my $c = $1; $c = "\t" if ($c eq "");
	my $mnemonic = $2;
	my $opcode;
	if ($mnemonic =~ m/([^\.]+)\.([^\.]+)/) {
	    $opcode = eval("\$$1_$2");
	} else {
	    $opcode = eval("\$$mnemonic");
	}

	my $arg=expand_line($line);

	if (ref($opcode) eq 'CODE') {
		$line = &$opcode($arg);
	} elsif ($mnemonic)         {
		$line = $c.$mnemonic;
		$line.= "\t$arg" if ($arg ne "");
	}
    }

    print $line if ($line);
    print "\n";
}

close STDOUT or die "error closing STDOUT: $!";