FFmpeg x86汇编优化一--x86inc.asm分析

    在我的印象中,有几个版本的FFmpeg中有Intrinsic优化的指令集代码。可能是由于纯汇编的性能和灵活性,随着版本的迭代,现在优化代码已经逐渐替换成了纯汇编代码。FFmpeg中的纯汇编代码使用了nasm汇编语法格式,且使用了x264工程中的两个汇编源文件“x86inc.asm”和“x86util.asm”。其中“x86inc.asm”中对寄存器、堆栈和函数调用等做了一个跨平台的约定。本文将主要对“x86inc.asm”文件中的部分代码进行详细的解释说明。

1.  CPU Flags

CPU Flags部分主要根据CPU Feature定义了一些CPU Flags的宏,提供了两个CPU Flags的校验宏并提供了一个初始化的宏。如下所示,根据CPU Feature定义了一系列的CPU Flags,从中可以看出,更高层次的CPU Flags包含了低层次的CPU Flags,比如,如果CPU支持cpuflags_mmx2,那么该CPU也支持cpuflags_mmx。lzcnt和aligned不属于指令集,所以他们与mmx和sse等不一定有包含关系。

; cpuflags

%assign cpuflags_mmx      (1<<0)												;0x0000 0001
%assign cpuflags_mmx2     (1<<1) | cpuflags_mmx									;0x0000 0003
%assign cpuflags_3dnow    (1<<2) | cpuflags_mmx									;0x0000 0007
%assign cpuflags_3dnowext (1<<3) | cpuflags_3dnow								;0x0000 000f
%assign cpuflags_sse      (1<<4) | cpuflags_mmx2								;0x0000 001f
%assign cpuflags_sse2     (1<<5) | cpuflags_sse									;0x0000 003f
%assign cpuflags_sse2slow (1<<6) | cpuflags_sse2								;0x0000 007f
%assign cpuflags_sse3     (1<<7) | cpuflags_sse2								;0x0000 00ff
%assign cpuflags_ssse3    (1<<8) | cpuflags_sse3								;0x0000 01ff
%assign cpuflags_sse4     (1<<9) | cpuflags_ssse3								;0x0000 03ff
%assign cpuflags_sse42    (1<<10)| cpuflags_sse4								;0x0000 07ff
%assign cpuflags_avx      (1<<11)| cpuflags_sse42								;0x0000 0fff
%assign cpuflags_xop      (1<<12)| cpuflags_avx									;0x0000 1fff
%assign cpuflags_fma4     (1<<13)| cpuflags_avx									;0x0000 3fff
%assign cpuflags_fma3     (1<<14)| cpuflags_avx									;0x0000 7fff
%assign cpuflags_avx2     (1<<15)| cpuflags_fma3								;0x0000 ffff

%assign cpuflags_cache32  (1<<16)												;0x0001 0000
%assign cpuflags_cache64  (1<<17)												;0x0002 0000
%assign cpuflags_slowctz  (1<<18)												;0x0004 0000
%assign cpuflags_lzcnt    (1<<19)												;0x0008 0000
%assign cpuflags_aligned  (1<<20) ; not a cpu feature, but a function variant	;0x0010 0000
%assign cpuflags_atom     (1<<21)												;0x0020 0000
%assign cpuflags_bmi1     (1<<22)|cpuflags_lzcnt								;0x0048 0000
%assign cpuflags_bmi2     (1<<23)|cpuflags_bmi1									;0x00c8 0000
%assign cpuflags_aesni    (1<<24)|cpuflags_sse42								;0x0100 07ff


宏cpuflag和notcpuflag主要用于判断是否支持或者不支持某个指令集。假设当前的CPU Feature可以支持到sse,那么我们可以定义cpuflags=cpuflags_sse,那么cpuflag(mmx) =(((((cpuflags_sse & (cpuflags_mmx)) ^ (cpuflags_mmx)) -1) >> 31) & 1)=(((((0x003f & (0x0001)) ^ (0x0001)) - 1) >>31) & 1)=(((((0x0001) ^ (0x0001)) - 1) >> 31) & 1)=(((0 - 1)>> 31) & 1) = 1,结果为真;cpuflag(avx2) =(((((cpuflags_sse& (cpuflags_avx2)) ^ (cpuflags_avx2)) - 1) >> 31) & 1)=(((((0x0000003f & (0x0000 ffff)) ^ (0x0000 ffff)) - 1) >> 31) & 1)=(((((0x0000003f) ^ (0x0000 ffff)) - 1) >> 31) & 1)=(((0x0000 ffc0 - 1) >>31) & 1) = (((0x0000 ffc0 - 1) >> 31) & 1) = 0,结果为假。notcpuflag与cpuflag宏的真假性相反。

 

; Returns a boolean value expressing whether or not the specified cpuflag is enabled.
%define    cpuflag(x) (((((cpuflags & (cpuflags_ %+ x)) ^ (cpuflags_ %+ x)) - 1) >> 31) & 1)
%define notcpuflag(x) (cpuflag(x) ^ 1)

INIT_CPUFLAGS宏主要用于定义优化函数后缀,判断是否支持avx,以及根据CPU Feature对一些指令用宏的方式进行替换。如果调用了INIT_CPUFLAGS mmx, sse, avx,那么,最终的cpuname为mmx_sse_avx,如果调用的是INIT_CPUFLAGS sse,则最终的cpuname为sse,该cpuname在接下来会赋值通过宏定义“%xdefine SUFFIX _ %+ cpuname”作为优化函数的后缀。同时,如果支持avx会将变量avx_enabled置为1,avx_enabled变量和后面的__emulate_avx有关,该变量涉及到是否要通过模拟的方式实现avx指令。

; Takes an arbitrary number of cpuflags from the above list.
; All subsequent functions (up to the next INIT_CPUFLAGS) is built for the specified cpu.
; You shouldn't need to invoke this macro directly, it's a subroutine for INIT_MMX &co.
%macro INIT_CPUFLAGS 0-*
    %xdefine SUFFIX
    %undef cpuname
    %assign cpuflags 0

    %if %0 >= 1												;参数个数
        %rep %0
			;如果调用了INIT_CPUFLAGS mmx, sse, avx,那么,最终的cpuname为
			;mmx_sse_avx,如果调用的是INIT_CPUFLAGS sse,则最终的cpuname为sse
            %ifdef cpuname
                %xdefine cpuname cpuname %+ _%1				
            %else
                %xdefine cpuname %1							;定义cpuname
            %endif
            %assign cpuflags cpuflags | cpuflags_%1			;cpuflags赋值
            %rotate 1										;循环移动宏参数
        %endrep
        %xdefine SUFFIX _ %+ cpuname						;定义函数后缀

        %if cpuflag(avx)									;是否支持avx
            %assign avx_enabled 1
        %endif
		;mmsize==16表示xmm(sse),mmsize==32表示ymm(avx)
        %if (mmsize == 16 && notcpuflag(sse2)) || (mmsize == 32 && notcpuflag(avx2))
            %define mova movaps
            %define movu movups
            %define movnta movntps
        %endif
        %if cpuflag(aligned)								;是否支持aligned特性
            %define movu mova
        %elif cpuflag(sse3) && notcpuflag(ssse3)
            %define movu lddqu								;对齐指令
        %endif
    %endif
	;Always use long nops (reduces 0x90 spam in disassembly on x86_32)
    %if ARCH_X86_64 || cpuflag(sse2)
        CPUNOP amdnop										;AMD K10 guidelines, using long NOPs
    %else
        CPUNOP basicnop										;Long NOPs not used
    %endif
%endmacro


2.  寄存器

由于32位的程序参数都是通过堆栈传递,64位的参数一部分通过寄存器传递一部分通过堆栈传递;且Win64和Linux64对寄存器传递参数的规定又有差异,所以,x86inc.asm文件通过将寄存器重新定义为宏以实现跨平台使用寄存器的目的。对寄存器重新定义主要涉及通过寄存器和矢量寄存器,通用寄存器主要是为了屏蔽32位程序和64为程序的差异,而矢量寄存器重定义主要是为了弥合使用MMX、XMM和YMM寄存器之间的差异。

2.1.通用寄存器

下面列出了32位系统和64位系统的通用寄存器。

;x86_32和x86_64通用寄存器列表
;8位				16位			32位			64位	
;原	 新增		原	新增		原	新增		扩展 新增
;al	---	r8b		ax	r8w			eax	r8d			rax	 r8
;cl		r9b		cx	r9w			ecx	r9d			rcx	 r9
;dl		r10b	dx	r10w		edx	r10d		rdx	 r10
;bl		r11b	bx	r11w		ebx	r11d		rbx	 r11
;ah	spl	r12b	sp	r12w		esp	r12d		rsp	 r12
;ch	bpl	r13b	bp	r13w		ebp	r13d		rbp	 r13
;dh	sil	r14b	si	r14w		esi	r14d		rsi	 r14
;bh	dil	r15b	di	r15w		edi	r15d		rdi	 r15


根据需要访问的寄存器大小q(四字)、d(双字)、w(字)、h(半字)、b(字节)对32位和64位下的寄存器进行定义。

%macro DECLARE_REG_SIZE 3
    %define r%1q r%1			;raxq = rax
    %define e%1q r%1			;eaxq = rax
    %define r%1d e%1			;raxd = eax
    %define e%1d e%1			;eaxd = eax
    %define r%1w %1				;raxw = ax
    %define e%1w %1				;eaxw = ax
    %define r%1h %3				;raxh = ah
    %define e%1h %3				;eaxh = ah
    %define r%1b %2				;raxb = al
    %define e%1b %2				;eaxb = al
    %if ARCH_X86_64 == 0		;32位CPU
        %define r%1 e%1			;rax = eax
    %endif
%endmacro


在汇编代码中不是直接通过rax和eax等来访问寄存器,而是通过r0q和r0d等来访问rax和eax。为了统一访问各寄存器,“x86inc.asm”文件在DECLARE_REG_SIZE宏的基础上,又定义了DECLARE_REG宏,进一步将寄存器的名字以数字的方式来表达,就类似于ARM中的寄存器r0~r15。在下面的代码中我们以“DECLARE_REG 0, eax, 4”为例进行了讲解,其中,第一个寄存器对应的栈的位置“r0m = [rstk + stack_offset + 4]”从4开始,而不是从0开始,主要是考虑了在32位程序下,需要保持4个字节的返回地址。下面会有详细解释。

; registers:
; rN and rNq are the native-size register holding function argument N
; rNd, rNw, rNb are dword, word, and byte size
; rNh is the high 8 bits of the word size
; rNm is the original location of arg N (a register or on the stack), dword
; rNmp is native size

%macro DECLARE_REG 2-3							;以32位的“DECLARE_REG 0, eax, 4”为例
    %define r%1q %2								;r0q = eax
    %define r%1d %2d							;r0d = eaxd = eax
    %define r%1w %2w							;r0w = eaxw = ax
    %define r%1b %2b							;r0b = eaxb = al
    %define r%1h %2h							;r0h = eaxh = ah
    %define %2q %2								;reaxq = eax
    %if %0 == 2									;64位两个参数,以“DECLARE_REG 0,  rcx”为例
        %define r%1m  %2d						;r0m = rcxd = ecx
        %define r%1mp %2						;r0mp = rcx
    %elif ARCH_X86_64 ; memory					;64位三个参数,以“DECLARE_REG 5,  R11, 48”为例
        %define r%1m [rstk + stack_offset + %3]	;r5m = [rstk + stack_offset + 48]
        %define r%1mp qword r %+ %1 %+ m		;r5mp = qword r5m
    %else										;32位,继续以“DECLARE_REG 0, eax, 4”为例
        %define r%1m [rstk + stack_offset + %3]	;r0m = [rstk + stack_offset + 4]
        %define r%1mp dword r %+ %1 %+ m		;r0mp = dword r0m
    %endif
    %define r%1  %2								;r0 = eax
%endmacro


由于32位只有6个可随意使用的通用寄存器,这里将r7~r14声明在栈上,接着上面“r6m= [rstk + stack_offset + 28]”,那么“r7m = [rstk + stack_offset + 32]”,其余依次类推。

;由于32位只有6个可随意使用的通用寄存器,这里将r7~r14声明在栈上,
;接着上面r6m = [rstk + stack_offset + 28],那么,...
%macro DECLARE_ARG 1-*
    %rep %0
        %define r%1m [rstk + stack_offset + 4*%1 + 4]	;r7m = [rstk + stack_offset + 32]
        %define r%1mp dword r%1m						;r7mp = dword r7m 
        %rotate 1
    %endrep
%endmacro


2.2.矢量寄存器

矢量寄存器主要是通过INIT_MMX、INIT_XMM和INIT_YMM三个宏来定义,这三个宏的定义方式非常相似,下面以INIT_MMX为例。从中可以看出:INIT_MMX主要完成了和MMX相关的环境变量的设置,寄存器的定义和调用了INIT_CPUFLAGS。需要注意的是:INIT_MMXsse2,会将寄存器定义为mmx的寄存器,但是会将指令和函数后缀设置为sse。

;INIT_MMX sse2,会将寄存器定义为mmx的寄存器,
;但是会将指令和函数后缀设置为sse.
%macro INIT_MMX 0-1+								;初始化mmx相关
    %assign avx_enabled 0							;不支持avx
    %define RESET_MM_PERMUTATION INIT_MMX %1		;定义宏RESET_MM_PERMUTATION,使其等价于INIT_MMX %1
    %define mmsize 8								;寄存器字节数,8字节
    %define num_mmregs 8							;寄存器个数,8个mmx寄存器,mm0~mm7
    %define mova movq
    %define movu movq
    %define movh movd
    %define movnta movntq
    %assign %%i 0
    %rep 8
        CAT_XDEFINE m, %%i, mm %+ %%i				;m0=mm0 ~ m7=mm7
        CAT_XDEFINE nnmm, %%i, %%i					;nnmm0=0
        %assign %%i %%i+1
    %endrep
    %rep 8
        CAT_UNDEF m, %%i							;取消mmx不支持寄存器的定义
        CAT_UNDEF nnmm, %%i
        %assign %%i %%i+1
    %endrep
    INIT_CPUFLAGS %1								;初始化cpu flags
%endmacro


3.  栈分配

由于在纯汇编代码中,可能会用到一些分配在当前栈上的局部变量等,所以在汇编代码的开始时候需要通过stack_size变量声明需要的栈空间大小,由于Win64中存在32字节的shadowspace将会使得Win64的栈空间分配复杂化。

3.1.常规栈分配

常规的栈的分配主要通过SETUP_STACK_POINTER宏和ALLOC_STACK宏实现,当要求的栈对齐方式大于已知的栈对齐方式(32位4字节对齐,64位16字节对齐)时,需要用一个寄存器来保持原始栈的位置,同时,在64位程序下,最好保证包含参数的寄存器不要被额外使用,比如Win64下需要4个寄存器保存输入参数,可能还需要一个额外的寄存器保持栈地址,在Linux64下需要6个寄存器保存参数,同时rax还要保存一个隐含的参数,可能还需要一个寄存器保存栈地址,所以在Win64下寄存器可能需要5个,在Linux64下可能需要8个。

%macro SETUP_STACK_POINTER 1
    %ifnum %1
        %if %1 != 0 && required_stack_alignment > STACK_ALIGNMENT
            %if %1 > 0
                %assign regs_used (regs_used + 1)			;加1,在ALLOC_STACK中需要一个寄存器保存原始堆栈位置
            %endif
            %if ARCH_X86_64 && regs_used < 5 + UNIX64 * 3
                ; Ensure that we don't clobber any registers containing arguments. For UNIX64 we also preserve r6 (rax)
                ; since it's used as a hidden argument in vararg functions to specify the number of vector registers used.
                %assign regs_used 5 + UNIX64 * 3
            %endif
        %endif
    %endif
%endmacro


ALLOC_STACK宏主要根据申请的stack_size和需要使用的XMM寄存器的个数和返回地址所需的空间,保留所需的栈大小,以方便该函数使用。在ALLOC_STACK中主要是要考虑到Win64中有32字节的shadow space,这32字节的shadow space由被调用者使用,因此在“x86inc.asm”中将该32字节的空间用来保存XMM6和XMM7,因此,如果某个汇编函数使用了多于8个的XMM寄存器,那么需要在栈上分配额外的空间来保持XMM寄存器的内容。在计算stack_size_padded变量的时候使用了“((-%%pad-stack_offset-gprsize) &(STACK_ALIGNMENT-1))”,这条语句是为了将栈按照STACK_ALIGNMENT对齐。假设(-%%pad-stack_offset-gprsize)=-50,STACK_ALIGNMENT=16,那么((-%%pad-stack_offset-gprsize) &(STACK_ALIGNMENT-1)) =(-50) & 15 = 11001110 & 00001111 = 00001110=14,表明:如果要使栈达到16字节对齐,还需要额外补充14个字节。

%macro ALLOC_STACK 1-2 0 ; stack_size, n_xmm_regs (for win64 only)
    %ifnum %1													;栈大小参数存在
        %if %1 != 0
            %assign %%pad 0
            %assign stack_size %1
            %if stack_size < 0
                %assign stack_size -stack_size
            %endif
            %if WIN64											;Win64存在32字节的shadow space
                %assign %%pad %%pad + 32 ; shadow space
                %if mmsize != 8									;sse或者avx
                    %assign xmm_regs_used %2					;需要使用多少个xmm寄存器
                    %if xmm_regs_used > 8						;每个xmm寄存器需要16字节(128位),保存在栈上
                        %assign %%pad %%pad + (xmm_regs_used-8)*16 ; callee-saved xmm registers
                    %endif
                %endif
            %endif
            %if required_stack_alignment <= STACK_ALIGNMENT		;在64位条件下,使用指令集优化,该条件一定满足
                ; maintain the current stack alignment			;堆栈对齐
				;stack_offset主要是因为通用寄存器压栈导致的当前栈地址和返回地址之间的偏移
				;pad主要是xmm寄存器和shadow space所需的栈空间大小,gprsize是栈的变化量
				;((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))是为了保证对齐,所需的额外的空间大小
				;假设(-%%pad-stack_offset-gprsize)=-50,STACK_ALIGNMENT=16,那么((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))
				;=(-50) & 15 = 11001110 & 00001111 = 00001110=14,表明:如果要栈达到16字节对齐,还需要额外补充14个字节 
                %assign stack_size_padded stack_size + %%pad + ((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1)) ;最终所需的栈空间大小(16字节对齐)
                SUB rsp, stack_size_padded						;留出栈空间						
            %else
                %assign %%reg_num (regs_used - 1)				;在SETUP_STACK_POINTER多准备了一个寄存器,这里使用这个寄存器保存rsp
                %xdefine rstk r %+ %%reg_num					;rstk used when greater alignment than the known stack alignment is required
                ; align stack, and save original stack location directly above
                ; it, i.e. in [rsp+stack_size_padded], so we can restore the
                ; stack in a single instruction (i.e. mov rsp, rstk or mov
                ; rsp, [rsp+stack_size_padded])
                %if %1 < 0 ; need to store rsp on stack
                    %xdefine rstkm [rsp + stack_size + %%pad]
                    %assign %%pad %%pad + gprsize				;如果存放在堆栈上,那么堆栈的大小需要增加gprsize,以便存放rsp的值
                %else ; can keep rsp in rstk during whole function
                    %xdefine rstkm rstk
                %endif
				;按照required_stack_alignment对齐
                %assign stack_size_padded stack_size + ((%%pad + required_stack_alignment-1) & ~(required_stack_alignment-1))
				;copy of the original stack pointer, used when greater alignment than the known stack alignment is required
				;rstk在这里为“r %+ %%reg_num”
                mov rstk, rsp									;保存原始rsp到rstk									
                and rsp, ~(required_stack_alignment-1)			;这里rsp required_stack_alignment字节对齐后,rsp的值可能小于等于原始rsp,因为栈地址是向低增长的
                sub rsp, stack_size_padded						;栈空间
                movifnidn rstkm, rstk
            %endif
            WIN64_PUSH_XMM
        %endif
    %endif
%endmacro


3.2.Win64栈分配

在Win64条件下,需要保存XMM寄存器,主要通过宏WIN64_PUSH_XMM来实现。

%macro WIN64_PUSH_XMM 0
    ; Use the shadow space to store XMM6 and XMM7, the rest needs stack space allocated.
    %if xmm_regs_used > 6
		;rstk中表示原始的rsp,这里要加8,是因为shadow space处于高地址,而return address处于
		;低地址;在保存xmm寄存器的时候,返回地址已经压栈(64位条件下返回地址压栈需要8字节),
		;stack_offset表示栈空间大小,所以“rstk + stack_offset +  8”表示正好大于返回地址
		;8个字节的位置,也就是32字节shadow space区域
        movaps [rstk + stack_offset +  8], xmm6
    %endif
    %if xmm_regs_used > 7
        movaps [rstk + stack_offset + 24], xmm7		;xmm6为
    %endif
    %if xmm_regs_used > 8
        %assign %%i 8
        %rep xmm_regs_used-8
			;这里加32是为了在汇编函数中调用下一个汇编函数时,分配的32字节的shadow space
            movaps [rsp + (%%i-8)*16 + stack_size + 32], xmm %+ %%i;
            %assign %%i %%i+1
        %endrep
    %endif
%endmacro


汇编函数中多申请的32字节的shadow space是为了在汇编函数里再调用其他汇编函数时使用。而当前函数的shadow space是其对应的调用者申请的。其原理如下图1所示,假设有一个C语言函数C1调用一个汇编函数A1,那么汇编函数A1所需的32字节的shadow space是由C1函数负者分配的,而如果汇编函数A1再调用另一个汇编函数A2,那么汇编函数A2所需的shadow space由汇编函数A1负责申请。所以在图1中XMM6和XMM7存在在C1函数分配的32字节的shadowspace中,而XMM8~XMM15要存放在“rsp +stack_size + 32”位置开始的地方,其中的“32”字节A1汇编函数为A2汇编函数预留的shadow space。

图1. WIN64 call convention

4.  函数声明和调用

函数的声明和调用主要涉及到“global”和“call”指令,在“x86inc.asm”中主要是通过宏“cglobal”和宏“call”实现。“cglobal”主要用于声明汇编函数,主要用于完成函数名重整(比如函数名是否需要添加下划线,是否需要包含_sse、_sse2等后缀等等),寄存器保存(汇编函数需要使用的寄存器需要提前保存,防止被篡改等),堆栈申请(汇编代码需要额外使用的栈等,XMM寄存器保存等)和一些变量的初始化等等;“call”主要用于在汇编函数中调用其他汇编函数,主要添加函数后缀(如_sse、_sse2等)。

5.  模拟AVX指令

在纯汇编中,常常可能会用到AVX指令,而当前的CPU Feature可能又不支持AVX,这时“x86inc.asm”文件中通过了其他的指令来模拟AVX指令。主要使用了两个区别,第一、以及AVX指令和非AVX指令多了一个前缀“v”,比如“addpd”和“vaddpd”指令;第二、涉及到三操作和四操作数的AVX指令时,先将其中一个参数移动其他寄存器后再进行操作。该操作主要通过AVX_INSTR宏和RUN_AVX_INSTR宏实现。

       AVX_INSTR宏主要是将对于的非AVX指令也定义为一个宏,“fnord”这个参数主要用来判断指令所需的参数的个数。

;%1 == instruction
;%2 == minimal instruction set
;%3 == 1 if float, 0 if int
;%4 == 1 if 4-operand emulation, 0 if 3-operand emulation, 255 otherwise (no emulation)
;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
%macro AVX_INSTR 1-5 fnord, 0, 255, 0
    %macro %1 1-10 fnord, fnord, fnord, fnord, %1, %2, %3, %4, %5	;将AVX指令定义为宏
        %ifidn %2, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1					;%6表示上面的%1,%1表示第一个fnord
        %elifidn %3, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2
        %elifidn %4, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3
        %elifidn %5, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4
        %else
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4, %5
        %endif
    %endmacro
%endmacro



附:x86inc.asm代码全部分析

;*****************************************************************************
;* x86inc.asm: x264asm abstraction layer
;*****************************************************************************
;* Copyright (C) 2005-2016 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;*          Anton Mitrofanov <BugMaster@narod.ru>
;*          Fiona Glaser <fiona@x264.com>
;*          Henrik Gramner <henrik@gramner.com>
;*
;* Permission to use, copy, modify, and/or distribute this software for any
;* purpose with or without fee is hereby granted, provided that the above
;* copyright notice and this permission notice appear in all copies.
;*
;* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
;* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
;* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
;* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
;* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
;* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
;*****************************************************************************

; This is a header file for the x264ASM assembly language, which uses
; NASM/YASM syntax combined with a large number of macros to provide easy
; abstraction between different calling conventions (x86_32, win64, linux64).
; It also has various other useful features to simplify writing the kind of
; DSP functions that are most often used in x264.

; Unlike the rest of x264, this file is available under an ISC license, as it
; has significant usefulness outside of x264 and we want it to be available
; to the largest audience possible.  Of course, if you modify it for your own
; purposes to add a new feature, we strongly encourage contributing a patch
; as this feature might be useful for others as well.  Send patches or ideas
; to x264-devel@videolan.org .

%ifndef private_prefix
    %define private_prefix x264
%endif

%ifndef public_prefix
    %define public_prefix private_prefix
%endif

%if HAVE_ALIGNED_STACK
    %define STACK_ALIGNMENT 16
%endif
%ifndef STACK_ALIGNMENT
    %if ARCH_X86_64
        %define STACK_ALIGNMENT 16					;16字节对齐
    %else	
        %define STACK_ALIGNMENT 4					;4字节对齐
    %endif
%endif

%define WIN64  0
%define UNIX64 0
%if ARCH_X86_64
    %ifidn __OUTPUT_FORMAT__,win32
        %define WIN64  1
    %elifidn __OUTPUT_FORMAT__,win64
        %define WIN64  1
    %elifidn __OUTPUT_FORMAT__,x64
        %define WIN64  1
    %else
        %define UNIX64 1
    %endif
%endif

%define FORMAT_ELF 0
%ifidn __OUTPUT_FORMAT__,elf
    %define FORMAT_ELF 1
%elifidn __OUTPUT_FORMAT__,elf32
    %define FORMAT_ELF 1
%elifidn __OUTPUT_FORMAT__,elf64
    %define FORMAT_ELF 1
%endif

%ifdef PREFIX
    %define mangle(x) _ %+ x
%else
    %define mangle(x) x
%endif

; aout does not support align=
; NOTE: This section is out of sync with x264, in order to
; keep supporting OS/2.
%macro SECTION_RODATA 0-1 16
    %ifidn __OUTPUT_FORMAT__,aout
        section .text
    %else
        SECTION .rodata align=%1
    %endif
%endmacro

%if WIN64
    %define PIC
%elif ARCH_X86_64 == 0
; x86_32 doesn't require PIC.
; Some distros prefer shared objects to be PIC, but nothing breaks if
; the code contains a few textrels, so we'll skip that complexity.
    %undef PIC
%endif
%ifdef PIC
    default rel
%endif

%macro CPUNOP 1
    %if HAVE_CPUNOP
        CPU %1
    %endif
%endmacro

; Macros to eliminate most code duplication between x86_32 and x86_64:
; Currently this works only for leaf functions which load all their arguments
; into registers at the start, and make no other use of the stack. Luckily that
; covers most of x264's asm.

; PROLOGUE:
; %1 = number of arguments. loads them from stack if needed.
; %2 = number of registers used. pushes callee-saved regs if needed.
; %3 = number of xmm registers used. pushes callee-saved xmm regs if needed.
; %4 = (optional) stack size to be allocated. The stack will be aligned before
;      allocating the specified stack size. If the required stack alignment is
;      larger than the known stack alignment the stack will be manually aligned
;      and an extra register will be allocated to hold the original stack
;      pointer (to not invalidate r0m etc.). To prevent the use of an extra
;      register as stack pointer, request a negative stack size.
; %4+/%5+ = list of names to define to registers
; PROLOGUE can also be invoked by adding the same options to cglobal

; e.g.
; cglobal foo, 2,3,7,0x40, dst, src, tmp
; declares a function (foo) that automatically loads two arguments (dst and
; src) into registers, uses one additional register (tmp) plus 7 vector
; registers (m0-m6) and allocates 0x40 bytes of stack space.

; TODO Some functions can use some args directly from the stack. If they're the
; last args then you can just not declare them, but if they're in the middle
; we need more flexible macro.

; RET:
; Pops anything that was pushed by PROLOGUE, and returns.

; REP_RET:
; Use this instead of RET if it's a branch target.




;x86_32和x86_64通用寄存器列表
;8位				16位			32位			64位	
;原	 新增		原	新增		原	新增		扩展 新增
;al	---	r8b		ax	r8w			eax	r8d			rax	 r8
;cl		r9b		cx	r9w			ecx	r9d			rcx	 r9
;dl		r10b	dx	r10w		edx	r10d		rdx	 r10
;bl		r11b	bx	r11w		ebx	r11d		rbx	 r11
;ah	spl	r12b	sp	r12w		esp	r12d		rsp	 r12
;ch	bpl	r13b	bp	r13w		ebp	r13d		rbp	 r13
;dh	sil	r14b	si	r14w		esi	r14d		rsi	 r14
;bh	dil	r15b	di	r15w		edi	r15d		rdi	 r15


; registers:
; rN and rNq are the native-size register holding function argument N
; rNd, rNw, rNb are dword, word, and byte size
; rNh is the high 8 bits of the word size
; rNm is the original location of arg N (a register or on the stack), dword
; rNmp is native size

%macro DECLARE_REG 2-3							;以32位的“DECLARE_REG 0, eax, 4”为例
    %define r%1q %2								;r0q = eax
    %define r%1d %2d							;r0d = eaxd = eax
    %define r%1w %2w							;r0w = eaxw = ax
    %define r%1b %2b							;r0b = eaxb = al
    %define r%1h %2h							;r0h = eaxh = ah
    %define %2q %2								;reaxq = eax
    %if %0 == 2									;64位两个参数,以“DECLARE_REG 0,  rcx”为例
        %define r%1m  %2d						;r0m = rcxd = ecx
        %define r%1mp %2						;r0mp = rcx
    %elif ARCH_X86_64 ; memory					;64位三个参数,以“DECLARE_REG 5,  R11, 48”为例
        %define r%1m [rstk + stack_offset + %3]	;r5m = [rstk + stack_offset + 48]
        %define r%1mp qword r %+ %1 %+ m		;r5mp = qword r5m
    %else										;32位,继续以“DECLARE_REG 0, eax, 4”为例
        %define r%1m [rstk + stack_offset + %3]	;r0m = [rstk + stack_offset + 4]
        %define r%1mp dword r %+ %1 %+ m		;r0mp = dword r0m
    %endif
    %define r%1  %2								;r0 = eax
%endmacro

%macro DECLARE_REG_SIZE 3
    %define r%1q r%1			;raxq = rax
    %define e%1q r%1			;eaxq = rax
    %define r%1d e%1			;raxd = eax
    %define e%1d e%1			;eaxd = eax
    %define r%1w %1				;raxw = ax
    %define e%1w %1				;eaxw = ax
    %define r%1h %3				;raxh = ah
    %define e%1h %3				;eaxh = ah
    %define r%1b %2				;raxb = al
    %define e%1b %2				;eaxb = al
    %if ARCH_X86_64 == 0		;32位CPU
        %define r%1 e%1			;rax = eax
    %endif
%endmacro

DECLARE_REG_SIZE ax, al, ah
DECLARE_REG_SIZE bx, bl, bh
DECLARE_REG_SIZE cx, cl, ch
DECLARE_REG_SIZE dx, dl, dh
DECLARE_REG_SIZE si, sil, null
DECLARE_REG_SIZE di, dil, null
DECLARE_REG_SIZE bp, bpl, null

; t# defines for when per-arch register allocation is more complex than just function arguments
;DECLARE_REG_TMP,寄存器别名,比如如下例子
;%if ARCH_X86_32
;DECLARE_REG_TMP 3	;t0 = r0
;%else
;DECLARE_REG_TMP 7	;t0 = r7
;%endif
%macro DECLARE_REG_TMP 1-*
    %assign %%i 0
    %rep %0
        CAT_XDEFINE t, %%i, r%1
        %assign %%i %%i+1
        %rotate 1
    %endrep
%endmacro

%macro DECLARE_REG_TMP_SIZE 0-*
    %rep %0
        %define t%1q t%1 %+ q	;t0q = t0q
        %define t%1d t%1 %+ d	;t0d = t0d
        %define t%1w t%1 %+ w	;t0w = t0w
        %define t%1h t%1 %+ h	;t0h = t0h
        %define t%1b t%1 %+ b	;t0b = t0b
        %rotate 1
    %endrep
%endmacro

DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14

%if ARCH_X86_64
    %define gprsize 8	;堆栈每次出栈和入栈的变化值
%else
    %define gprsize 4	;64位时堆栈每次按8字节变化,32位按4字节变化
%endif

%macro PUSH 1
    push %1
    %ifidn rstk, rsp
        %assign stack_offset stack_offset+gprsize
    %endif
%endmacro

%macro POP 1
    pop %1
    %ifidn rstk, rsp
        %assign stack_offset stack_offset-gprsize
    %endif
%endmacro

%macro PUSH_IF_USED 1-*
    %rep %0
        %if %1 < regs_used
            PUSH r%1
        %endif
        %rotate 1
    %endrep
%endmacro

%macro POP_IF_USED 1-*
    %rep %0
        %if %1 < regs_used
            pop r%1
        %endif
        %rotate 1
    %endrep
%endmacro

%macro LOAD_IF_USED 1-*
    %rep %0
        %if %1 < num_args
            mov r%1, r %+ %1 %+ mp
        %endif
        %rotate 1
    %endrep
%endmacro

%macro SUB 2
    sub %1, %2
    %ifidn %1, rstk
        %assign stack_offset stack_offset+(%2)
    %endif
%endmacro

%macro ADD 2
    add %1, %2
    %ifidn %1, rstk
        %assign stack_offset stack_offset-(%2)
    %endif
%endmacro

%macro movifnidn 2	;不同就赋值
    %ifnidn %1, %2
        mov %1, %2
    %endif
%endmacro

%macro movsxdifnidn 2
    %ifnidn %1, %2
        movsxd %1, %2
    %endif
%endmacro

%macro ASSERT 1
    %if (%1) == 0
        %error assertion ``%1'' failed
    %endif
%endmacro

%macro DEFINE_ARGS 0-*
    %ifdef n_arg_names
        %assign %%i 0
        %rep n_arg_names						;取消arg_name0, arg_name1等的定义
            CAT_UNDEF arg_name %+ %%i, q		;arg_name0q = ttq
            CAT_UNDEF arg_name %+ %%i, d		;arg_name0d = ttd
            CAT_UNDEF arg_name %+ %%i, w		;arg_name0w = ttw
            CAT_UNDEF arg_name %+ %%i, h		;arg_name0h = tth
            CAT_UNDEF arg_name %+ %%i, b		;arg_name0b = ttb
            CAT_UNDEF arg_name %+ %%i, m		;arg_name0m = ttm
            CAT_UNDEF arg_name %+ %%i, mp		;arg_name0mp = ttmp
            CAT_UNDEF arg_name, %%i
            %assign %%i %%i+1
        %endrep
    %endif

    %xdefine %%stack_offset stack_offset
    %undef stack_offset ; so that the current value of stack_offset doesn't get baked in by xdefine
    %assign %%i 0
    %rep %0										;假设该函数传入了2个参数,分别是tt和zz
        %xdefine %1q r %+ %%i %+ q				;ttq = r0q
        %xdefine %1d r %+ %%i %+ d				;ttd = r0d
        %xdefine %1w r %+ %%i %+ w				;ttw = r0w
        %xdefine %1h r %+ %%i %+ h				;tth = r0h
        %xdefine %1b r %+ %%i %+ b				;ttb = r0b
        %xdefine %1m r %+ %%i %+ m				;ttm = r0m
        %xdefine %1mp r %+ %%i %+ mp			;ttmp = r0mp
        CAT_XDEFINE arg_name, %%i, %1			;arg_name0 = tt
        %assign %%i %%i+1
        %rotate 1
    %endrep
    %xdefine stack_offset %%stack_offset
    %assign n_arg_names %0						;n_arg_names = 2
%endmacro

%define required_stack_alignment ((mmsize + 15) & ~15)

%macro ALLOC_STACK 1-2 0 ; stack_size, n_xmm_regs (for win64 only)
    %ifnum %1													;栈大小参数存在
        %if %1 != 0
            %assign %%pad 0
            %assign stack_size %1
            %if stack_size < 0
                %assign stack_size -stack_size
            %endif
            %if WIN64											;Win64存在32字节的shadow space
                %assign %%pad %%pad + 32 ; shadow space
                %if mmsize != 8									;sse或者avx
                    %assign xmm_regs_used %2					;需要使用多少个xmm寄存器
                    %if xmm_regs_used > 8						;每个xmm寄存器需要16字节(128位),保存在栈上
                        %assign %%pad %%pad + (xmm_regs_used-8)*16 ; callee-saved xmm registers
                    %endif
                %endif
            %endif
            %if required_stack_alignment <= STACK_ALIGNMENT		;在64位条件下,使用指令集优化,该条件一定满足
                ; maintain the current stack alignment			;堆栈对齐
				;stack_offset主要是因为通用寄存器压栈导致的当前栈地址和返回地址之间的偏移
				;pad主要是xmm寄存器和shadow space所需的栈空间大小,gprsize是栈的变化量
				;((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))是为了保证对齐,所需的额外的空间大小
				;假设(-%%pad-stack_offset-gprsize)=-50,STACK_ALIGNMENT=16,那么((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))
				;=(-50) & 15 = 11001110 & 00001111 = 00001110=14,表明:如果要栈达到16字节对齐,还需要额外补充14个字节 
                %assign stack_size_padded stack_size + %%pad + ((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1)) ;最终所需的栈空间大小(16字节对齐)
                SUB rsp, stack_size_padded						;留出栈空间						
            %else
                %assign %%reg_num (regs_used - 1)				;在SETUP_STACK_POINTER多准备了一个寄存器,这里使用这个寄存器保存rsp
                %xdefine rstk r %+ %%reg_num					;rstk used when greater alignment than the known stack alignment is required
                ; align stack, and save original stack location directly above
                ; it, i.e. in [rsp+stack_size_padded], so we can restore the
                ; stack in a single instruction (i.e. mov rsp, rstk or mov
                ; rsp, [rsp+stack_size_padded])
                %if %1 < 0 ; need to store rsp on stack
                    %xdefine rstkm [rsp + stack_size + %%pad]
                    %assign %%pad %%pad + gprsize				;如果存放在堆栈上,那么堆栈的大小需要增加gprsize,以便存放rsp的值
                %else ; can keep rsp in rstk during whole function
                    %xdefine rstkm rstk
                %endif
				;按照required_stack_alignment对齐
                %assign stack_size_padded stack_size + ((%%pad + required_stack_alignment-1) & ~(required_stack_alignment-1))
				;copy of the original stack pointer, used when greater alignment than the known stack alignment is required
				;rstk在这里为“r %+ %%reg_num”
                mov rstk, rsp									;保存原始rsp到rstk									
                and rsp, ~(required_stack_alignment-1)			;这里rsp required_stack_alignment字节对齐后,rsp的值可能小于等于原始rsp,因为栈地址是向低增长的
                sub rsp, stack_size_padded						;栈空间
                movifnidn rstkm, rstk
            %endif
            WIN64_PUSH_XMM
        %endif
    %endif
%endmacro

%macro SETUP_STACK_POINTER 1
    %ifnum %1
        %if %1 != 0 && required_stack_alignment > STACK_ALIGNMENT
            %if %1 > 0
                %assign regs_used (regs_used + 1)			;加1,在ALLOC_STACK中需要一个寄存器保存原始堆栈位置
            %endif
            %if ARCH_X86_64 && regs_used < 5 + UNIX64 * 3
                ; Ensure that we don't clobber any registers containing arguments. For UNIX64 we also preserve r6 (rax)
                ; since it's used as a hidden argument in vararg functions to specify the number of vector registers used.
                %assign regs_used 5 + UNIX64 * 3
            %endif
        %endif
    %endif
%endmacro

%macro DEFINE_ARGS_INTERNAL 3+
    %ifnum %2				;PROLOGUE宏包含stack_size参数
        DEFINE_ARGS %3		;函数参数包含在%3中
    %elif %1 == 4			;PROLOGUE宏未包含stack_size,且只有一个参数
        DEFINE_ARGS %2		;函数参数包含在%2中
    %elif %1 > 4			;PROLOGUE宏未包含stack_size,且有多个参数
        DEFINE_ARGS %2, %3
    %endif
%endmacro

%if WIN64 ; Windows x64 ;=================================================

DECLARE_REG 0,  rcx
DECLARE_REG 1,  rdx
DECLARE_REG 2,  R8
DECLARE_REG 3,  R9
DECLARE_REG 4,  R10, 40
DECLARE_REG 5,  R11, 48
DECLARE_REG 6,  rax, 56
DECLARE_REG 7,  rdi, 64
DECLARE_REG 8,  rsi, 72
DECLARE_REG 9,  rbx, 80
DECLARE_REG 10, rbp, 88
DECLARE_REG 11, R12, 96
DECLARE_REG 12, R13, 104
DECLARE_REG 13, R14, 112
DECLARE_REG 14, R15, 120

%macro PROLOGUE 2-5+ 0 ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
    %assign num_args %1
    %assign regs_used %2
    ASSERT regs_used >= num_args
    SETUP_STACK_POINTER %4
    ASSERT regs_used <= 15
    PUSH_IF_USED 7, 8, 9, 10, 11, 12, 13, 14	;RAX,RCX,RDX,R8,R9,R10,R11是“易挥发”的,不用特别保护,其余寄存器需要保护。
    ALLOC_STACK %4, %3
    %if mmsize != 8 && stack_size == 0
        WIN64_SPILL_XMM %3
    %endif
    LOAD_IF_USED 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
    DEFINE_ARGS_INTERNAL %0, %4, %5
%endmacro

%macro WIN64_PUSH_XMM 0
    ; Use the shadow space to store XMM6 and XMM7, the rest needs stack space allocated.
    %if xmm_regs_used > 6
		;rstk中表示原始的rsp,这里要加8,是因为shadow space处于高地址,而return address处于
		;低地址;在保存xmm寄存器的时候,返回地址已经压栈(64位条件下返回地址压栈需要8字节),
		;stack_offset表示栈空间大小,所以“rstk + stack_offset +  8”表示正好大于返回地址
		;8个字节的位置,也就是32字节shadow space区域
        movaps [rstk + stack_offset +  8], xmm6
    %endif
    %if xmm_regs_used > 7
        movaps [rstk + stack_offset + 24], xmm7		;xmm6为
    %endif
    %if xmm_regs_used > 8
        %assign %%i 8
        %rep xmm_regs_used-8
			;这里加32是为了在汇编函数中调用下一个汇编函数时,分配的32字节的shadow space
            movaps [rsp + (%%i-8)*16 + stack_size + 32], xmm %+ %%i;
            %assign %%i %%i+1
        %endrep
    %endif
%endmacro

%macro WIN64_SPILL_XMM 1	;在ALLOC_STACK调用没有对堆栈产生影响时调用该函数,也就是mmsize != 8 && stack_size == 0时调用
    %assign xmm_regs_used %1
    ASSERT xmm_regs_used <= 16
    %if xmm_regs_used > 8
        ; Allocate stack space for callee-saved xmm registers plus shadow space and align the stack.
        %assign %%pad (xmm_regs_used-8)*16 + 32;
        %assign stack_size_padded %%pad + ((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))
        SUB rsp, stack_size_padded
    %endif
    WIN64_PUSH_XMM
%endmacro

%macro WIN64_RESTORE_XMM_INTERNAL 1
    %assign %%pad_size 0
    %if xmm_regs_used > 8
        %assign %%i xmm_regs_used
        %rep xmm_regs_used-8
            %assign %%i %%i-1
			;%1在该文件中是rsp,这里是在从堆栈中恢复xmm寄存器的内容
            movaps xmm %+ %%i, [%1 + (%%i-8)*16 + stack_size + 32];
        %endrep
    %endif
    %if stack_size_padded > 0
        %if stack_size > 0 && required_stack_alignment > STACK_ALIGNMENT
            mov rsp, rstkm
        %else  ;(stack_size <= 0) || (required_stack_alignment <= STACK_ALIGNMENT)
            add %1, stack_size_padded
            %assign %%pad_size stack_size_padded
        %endif
    %endif
    %if xmm_regs_used > 7	;恢复xmm7
        movaps xmm7, [%1 + stack_offset - %%pad_size + 24]
    %endif
    %if xmm_regs_used > 6	;恢复xmm6
        movaps xmm6, [%1 + stack_offset - %%pad_size +  8]
    %endif
%endmacro

%macro WIN64_RESTORE_XMM 1
    WIN64_RESTORE_XMM_INTERNAL %1
    %assign stack_offset (stack_offset-stack_size_padded)
    %assign xmm_regs_used 0
%endmacro

%define has_epilogue regs_used > 7 || xmm_regs_used > 6 || mmsize == 32 || stack_size > 0

%macro RET 0
    WIN64_RESTORE_XMM_INTERNAL rsp
    POP_IF_USED 14, 13, 12, 11, 10, 9, 8, 7
    %if mmsize == 32
        vzeroupper		;ymm寄存器全部置为0
    %endif
    AUTO_REP_RET
%endmacro

%elif ARCH_X86_64 ; *nix x64 ;=============================================

DECLARE_REG 0,  rdi
DECLARE_REG 1,  rsi
DECLARE_REG 2,  rdx
DECLARE_REG 3,  rcx
DECLARE_REG 4,  R8
DECLARE_REG 5,  R9
DECLARE_REG 6,  rax, 8
DECLARE_REG 7,  R10, 16
DECLARE_REG 8,  R11, 24
DECLARE_REG 9,  rbx, 32
DECLARE_REG 10, rbp, 40
DECLARE_REG 11, R12, 48
DECLARE_REG 12, R13, 56
DECLARE_REG 13, R14, 64
DECLARE_REG 14, R15, 72

%macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
    %assign num_args %1
    %assign regs_used %2
    ASSERT regs_used >= num_args
    SETUP_STACK_POINTER %4
    ASSERT regs_used <= 15
    PUSH_IF_USED 9, 10, 11, 12, 13, 14
    ALLOC_STACK %4
    LOAD_IF_USED 6, 7, 8, 9, 10, 11, 12, 13, 14
    DEFINE_ARGS_INTERNAL %0, %4, %5
%endmacro

%define has_epilogue regs_used > 9 || mmsize == 32 || stack_size > 0

%macro RET 0
    %if stack_size_padded > 0
        %if required_stack_alignment > STACK_ALIGNMENT
            mov rsp, rstkm
        %else
            add rsp, stack_size_padded
        %endif
    %endif
    POP_IF_USED 14, 13, 12, 11, 10, 9
    %if mmsize == 32
        vzeroupper
    %endif
    AUTO_REP_RET
%endmacro

%else ; X86_32 ;==============================================================

DECLARE_REG 0, eax, 4
DECLARE_REG 1, ecx, 8
DECLARE_REG 2, edx, 12
DECLARE_REG 3, ebx, 16
DECLARE_REG 4, esi, 20
DECLARE_REG 5, edi, 24
DECLARE_REG 6, ebp, 28
%define rsp esp

;由于32位只有6个可随意使用的通用寄存器,这里将r7~r14声明在栈上,
;接着上面r6m = [rstk + stack_offset + 28],那么,...
%macro DECLARE_ARG 1-*
    %rep %0
        %define r%1m [rstk + stack_offset + 4*%1 + 4]	;r7m = [rstk + stack_offset + 32]
        %define r%1mp dword r%1m						;r7mp = dword r7m 
        %rotate 1
    %endrep
%endmacro

DECLARE_ARG 7, 8, 9, 10, 11, 12, 13, 14

%macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
    %assign num_args %1
    %assign regs_used %2
    ASSERT regs_used >= num_args
    %if num_args > 7
        %assign num_args 7
    %endif
    %if regs_used > 7
        %assign regs_used 7
    %endif
    SETUP_STACK_POINTER %4
    ASSERT regs_used <= 7
	;这里之所以将3、4、5和6寄存器保存起来,是因为在x86_32环境下0,1和2对应的寄存器
	;分别对应的是eax,ecx和edx,它们3个易挥发的寄存器操作前不用保护.
    PUSH_IF_USED 3, 4, 5, 6
    ALLOC_STACK %4
	;将堆栈中的数据拷贝到寄存器中
    LOAD_IF_USED 0, 1, 2, 3, 4, 5, 6
    DEFINE_ARGS_INTERNAL %0, %4, %5
%endmacro

%define has_epilogue regs_used > 3 || mmsize == 32 || stack_size > 0

%macro RET 0
    %if stack_size_padded > 0
        %if required_stack_alignment > STACK_ALIGNMENT
            mov rsp, rstkm
        %else
            add rsp, stack_size_padded
        %endif
    %endif
    POP_IF_USED 6, 5, 4, 3
    %if mmsize == 32
        vzeroupper
    %endif
    AUTO_REP_RET
%endmacro

%endif ;======================================================================

%if WIN64 == 0
    %macro WIN64_SPILL_XMM 1
    %endmacro
    %macro WIN64_RESTORE_XMM 1
    %endmacro
    %macro WIN64_PUSH_XMM 0
    %endmacro
%endif

; On AMD cpus <=K10, an ordinary ret is slow if it immediately follows either
; a branch or a branch target. So switch to a 2-byte form of ret in that case.
; We can automatically detect "follows a branch", but not a branch target.
; (SSSE3 is a sufficient condition to know that your cpu doesn't have this problem.)
%macro REP_RET 0
    %if has_epilogue
        RET
    %else
        rep ret
    %endif
    annotate_function_size
%endmacro

;'$'和'$$',它们允许引用当前指令的地址。
;'$'计算得到它本身所在源代码行的开始处的地址;
;所以你可以简单地写这样的代码'jmp $'来表示无限循环。
;'$$'计算当前段开始处的地址,所以你可以通过($-$$)找出你当前在段内的偏移。
%define last_branch_adr $$
%macro AUTO_REP_RET 0
    %if notcpuflag(ssse3)
        times ((last_branch_adr-$)>>31)+1 rep ; times 1 iff $ == last_branch_adr.
    %endif
    ret
    annotate_function_size
%endmacro

%macro BRANCH_INSTR 0-*
    %rep %0
        %macro %1 1-2 %1
            %2 %1
            %if notcpuflag(ssse3)
                %%branch_instr equ $
                %xdefine last_branch_adr %%branch_instr
            %endif
        %endmacro
        %rotate 1
    %endrep
%endmacro

BRANCH_INSTR jz, je, jnz, jne, jl, jle, jnl, jnle, jg, jge, jng, jnge, ja, jae, jna, jnae, jb, jbe, jnb, jnbe, jc, jnc, js, jns, jo, jno, jp, jnp

%macro TAIL_CALL 2 ; callee, is_nonadjacent
    %if has_epilogue
        call %1
        RET
    %elif %2
        jmp %1
    %endif
    annotate_function_size
%endmacro

;=============================================================================
; arch-independent part
;=============================================================================

%assign function_align 16

; Begin a function.
; Applies any symbol mangling needed for C linkage, and sets up a define such that
; subsequent uses of the function name automatically refer to the mangled version.
; Appends cpuflags to the function name if cpuflags has been specified.
; The "" empty default parameter is a workaround for nasm, which fails if SUFFIX
; is empty and we call cglobal_internal with just %1 %+ SUFFIX (without %2).
%macro cglobal 1-2+ "" ; name, [PROLOGUE args]
    cglobal_internal 1, %1 %+ SUFFIX, %2
%endmacro
%macro cvisible 1-2+ "" ; name, [PROLOGUE args]
    cglobal_internal 0, %1 %+ SUFFIX, %2
%endmacro
%macro cglobal_internal 2-3+
    annotate_function_size
    %if %1
        %xdefine %%FUNCTION_PREFIX private_prefix
        %xdefine %%VISIBILITY hidden
    %else
        %xdefine %%FUNCTION_PREFIX public_prefix
        %xdefine %%VISIBILITY
    %endif
    %ifndef cglobaled_%2
        %xdefine %2 mangle(%%FUNCTION_PREFIX %+ _ %+ %2)
        %xdefine %2.skip_prologue %2 %+ .skip_prologue
        CAT_XDEFINE cglobaled_, %2, 1
    %endif
    %xdefine current_function %2
    %xdefine current_function_section __SECT__
    %if FORMAT_ELF
        global %2:function %%VISIBILITY
    %else
        global %2
    %endif
    align function_align
    %2:
    RESET_MM_PERMUTATION        ; needed for x86-64, also makes disassembly somewhat nicer,初始化各寄存器的名字
    %xdefine rstk rsp           ; copy of the original stack pointer, used when greater alignment than the known stack alignment is required
    %assign stack_offset 0      ; stack pointer offset relative to the return address
    %assign stack_size 0        ; amount of stack space that can be freely used inside a function
    %assign stack_size_padded 0 ; total amount of allocated stack space, including space for callee-saved xmm registers on WIN64 and alignment padding
    %assign xmm_regs_used 0     ; number of XMM registers requested, used for dealing with callee-saved registers on WIN64
    %ifnidn %3, ""
        PROLOGUE %3
    %endif
%endmacro

%macro cextern 1
    %xdefine %1 mangle(private_prefix %+ _ %+ %1)
    CAT_XDEFINE cglobaled_, %1, 1
    extern %1
%endmacro

; like cextern, but without the prefix
%macro cextern_naked 1
    %ifdef PREFIX
        %xdefine %1 mangle(%1)
    %endif
    CAT_XDEFINE cglobaled_, %1, 1
    extern %1
%endmacro

%macro const 1-2+
    %xdefine %1 mangle(private_prefix %+ _ %+ %1)
    %if FORMAT_ELF
        global %1:data hidden
    %else
        global %1
    %endif
    %1: %2
%endmacro

; This is needed for ELF, otherwise the GNU linker assumes the stack is executable by default.
%if FORMAT_ELF
    [SECTION .note.GNU-stack noalloc noexec nowrite progbits]
%endif

; Tell debuggers how large the function was.
; This may be invoked multiple times per function; we rely on later instances overriding earlier ones.
; This is invoked by RET and similar macros, and also cglobal does it for the previous function,
; but if the last function in a source file doesn't use any of the standard macros for its epilogue,
; then its size might be unspecified.
%macro annotate_function_size 0
    %ifdef __YASM_VER__
        %ifdef current_function
            %if FORMAT_ELF
                current_function_section
                %%ecf equ $
                size current_function %%ecf - current_function
                __SECT__
            %endif
        %endif
    %endif
%endmacro

; cpuflags

%assign cpuflags_mmx      (1<<0)												;0x0000 0001
%assign cpuflags_mmx2     (1<<1) | cpuflags_mmx									;0x0000 0003
%assign cpuflags_3dnow    (1<<2) | cpuflags_mmx									;0x0000 0007
%assign cpuflags_3dnowext (1<<3) | cpuflags_3dnow								;0x0000 000f
%assign cpuflags_sse      (1<<4) | cpuflags_mmx2								;0x0000 001f
%assign cpuflags_sse2     (1<<5) | cpuflags_sse									;0x0000 003f
%assign cpuflags_sse2slow (1<<6) | cpuflags_sse2								;0x0000 007f
%assign cpuflags_sse3     (1<<7) | cpuflags_sse2								;0x0000 00ff
%assign cpuflags_ssse3    (1<<8) | cpuflags_sse3								;0x0000 01ff
%assign cpuflags_sse4     (1<<9) | cpuflags_ssse3								;0x0000 03ff
%assign cpuflags_sse42    (1<<10)| cpuflags_sse4								;0x0000 07ff
%assign cpuflags_avx      (1<<11)| cpuflags_sse42								;0x0000 0fff
%assign cpuflags_xop      (1<<12)| cpuflags_avx									;0x0000 1fff
%assign cpuflags_fma4     (1<<13)| cpuflags_avx									;0x0000 3fff
%assign cpuflags_fma3     (1<<14)| cpuflags_avx									;0x0000 7fff
%assign cpuflags_avx2     (1<<15)| cpuflags_fma3								;0x0000 ffff

%assign cpuflags_cache32  (1<<16)												;0x0001 0000
%assign cpuflags_cache64  (1<<17)												;0x0002 0000
%assign cpuflags_slowctz  (1<<18)												;0x0004 0000
%assign cpuflags_lzcnt    (1<<19)												;0x0008 0000
%assign cpuflags_aligned  (1<<20) ; not a cpu feature, but a function variant	;0x0010 0000
%assign cpuflags_atom     (1<<21)												;0x0020 0000
%assign cpuflags_bmi1     (1<<22)|cpuflags_lzcnt								;0x0048 0000
%assign cpuflags_bmi2     (1<<23)|cpuflags_bmi1									;0x00c8 0000
%assign cpuflags_aesni    (1<<24)|cpuflags_sse42								;0x0100 07ff

; Returns a boolean value expressing whether or not the specified cpuflag is enabled.
%define    cpuflag(x) (((((cpuflags & (cpuflags_ %+ x)) ^ (cpuflags_ %+ x)) - 1) >> 31) & 1)
%define notcpuflag(x) (cpuflag(x) ^ 1)

;假设cpuflags=cpuflags_sse,那么cpuflag(mmx) 
;=(((((cpuflags_sse & (cpuflags_mmx)) ^ (cpuflags_mmx)) - 1) >> 31) & 1)
;=(((((0x003f & (0x0001)) ^ (0x0001)) - 1) >> 31) & 1)
;=(((((0x0001) ^ (0x0001)) - 1) >> 31) & 1)=(((0 - 1) >> 31) & 1) = 1,结果为真;
;假设cpuflags=cpuflags_sse,那么cpuflag(avx2) 
;=(((((cpuflags_sse & (cpuflags_avx2)) ^ (cpuflags_avx2)) - 1) >> 31) & 1)
;=(((((0x0000003f & (0x0000ffff)) ^ (0x0000ffff)) - 1) >> 31) & 1)
;=(((((0x0000003f) ^ (0x0000ffff)) - 1) >> 31) & 1)=(((0x0000ffc0 - 1) >> 31) & 1) = 0,结果为假。


; Takes an arbitrary number of cpuflags from the above list.
; All subsequent functions (up to the next INIT_CPUFLAGS) is built for the specified cpu.
; You shouldn't need to invoke this macro directly, it's a subroutine for INIT_MMX &co.
%macro INIT_CPUFLAGS 0-*
    %xdefine SUFFIX
    %undef cpuname
    %assign cpuflags 0

    %if %0 >= 1												;参数个数
        %rep %0
			;如果调用了INIT_CPUFLAGS mmx, sse, avx,那么,最终的cpuname为
			;mmx_sse_avx,如果调用的是INIT_CPUFLAGS sse,则最终的cpuname为sse
            %ifdef cpuname
                %xdefine cpuname cpuname %+ _%1				
            %else
                %xdefine cpuname %1							;定义cpuname
            %endif
            %assign cpuflags cpuflags | cpuflags_%1			;cpuflags赋值
            %rotate 1										;循环移动宏参数
        %endrep
        %xdefine SUFFIX _ %+ cpuname						;定义函数后缀

        %if cpuflag(avx)									;是否支持avx
            %assign avx_enabled 1
        %endif
		;mmsize==16表示xmm(sse),mmsize==32表示ymm(avx)
        %if (mmsize == 16 && notcpuflag(sse2)) || (mmsize == 32 && notcpuflag(avx2))
            %define mova movaps
            %define movu movups
            %define movnta movntps
        %endif
        %if cpuflag(aligned)								;是否支持aligned特性
            %define movu mova
        %elif cpuflag(sse3) && notcpuflag(ssse3)
            %define movu lddqu								;对齐指令
        %endif
    %endif
	;Always use long nops (reduces 0x90 spam in disassembly on x86_32)
    %if ARCH_X86_64 || cpuflag(sse2)
        CPUNOP amdnop										;AMD K10 guidelines, using long NOPs
    %else
        CPUNOP basicnop										;Long NOPs not used
    %endif
%endmacro

; Merge mmx and sse*
; m# is a simd register of the currently selected size
; xm# is the corresponding xmm register if mmsize >= 16, otherwise the same as m#
; ym# is the corresponding ymm register if mmsize >= 32, otherwise the same as m#
; (All 3 remain in sync through SWAP.)

%macro CAT_XDEFINE 3
    %xdefine %1%2 %3
%endmacro

%macro CAT_UNDEF 2
    %undef %1%2
%endmacro

;INIT_MMX sse2,会将寄存器定义为mmx的寄存器,
;但是会将指令和函数后缀设置为sse.
%macro INIT_MMX 0-1+								;初始化mmx相关
    %assign avx_enabled 0							;不支持avx
    %define RESET_MM_PERMUTATION INIT_MMX %1		;定义宏RESET_MM_PERMUTATION,使其等价于INIT_MMX %1
    %define mmsize 8								;寄存器字节数,8字节
    %define num_mmregs 8							;寄存器个数,8个mmx寄存器,mm0~mm7
    %define mova movq
    %define movu movq
    %define movh movd
    %define movnta movntq
    %assign %%i 0
    %rep 8
        CAT_XDEFINE m, %%i, mm %+ %%i				;m0=mm0 ~ m7=mm7
        CAT_XDEFINE nnmm, %%i, %%i					;nnmm0=0
        %assign %%i %%i+1
    %endrep
    %rep 8
        CAT_UNDEF m, %%i							;取消mmx不支持寄存器的定义
        CAT_UNDEF nnmm, %%i
        %assign %%i %%i+1
    %endrep
    INIT_CPUFLAGS %1								;初始化cpu flags
%endmacro

%macro INIT_XMM 0-1+								;avx不支持
    %assign avx_enabled 0
    %define RESET_MM_PERMUTATION INIT_XMM %1		;定义宏RESET_MM_PERMUTATION,使其等价于INIT_XMM %1
    %define mmsize 16								;寄存器为16字节
    %define num_mmregs 8							;8个xmm寄存器xmm0~xmm7
    %if ARCH_X86_64
        %define num_mmregs 16						;64位CPU增加到16个寄存器
    %endif
    %define mova movdqa
    %define movu movdqu
    %define movh movq
    %define movnta movntdq
    %assign %%i 0
    %rep num_mmregs
        CAT_XDEFINE m, %%i, xmm %+ %%i				;m0=xmm0 ~ m7=xmm7/m0=xmm0 ~ m15=xmm15
        CAT_XDEFINE nnxmm, %%i, %%i
        %assign %%i %%i+1
    %endrep
    INIT_CPUFLAGS %1								;初始化cpu flags
%endmacro

%macro INIT_YMM 0-1+
    %assign avx_enabled 1							;avx支持
    %define RESET_MM_PERMUTATION INIT_YMM %1		;定义宏RESET_MM_PERMUTATION,使其等价于INIT_YMM %1
    %define mmsize 32								;32字节
    %define num_mmregs 8							;32位CPU有8个ymm寄存器
    %if ARCH_X86_64
        %define num_mmregs 16						;64位CPU增加到16个ymm寄存器
    %endif
    %define mova movdqa
    %define movu movdqu
    %undef movh
    %define movnta movntdq
    %assign %%i 0
    %rep num_mmregs
        CAT_XDEFINE m, %%i, ymm %+ %%i				;m0=ymm0 ~ m7=ymm7/m0=ymm0 ~ m15=ymm15
        CAT_XDEFINE nnymm, %%i, %%i
        %assign %%i %%i+1
    %endrep
    INIT_CPUFLAGS %1								;初始化cpu flags
%endmacro

INIT_XMM

%macro DECLARE_MMCAST 1								
    %define  mmmm%1   mm%1							;mmmm0	= mm0
    %define  mmxmm%1  mm%1							;mmxmm0 = mm0
    %define  mmymm%1  mm%1							;mmymm0 = mm0
    %define xmmmm%1   mm%1							;xmmmm0 = mm0
    %define xmmxmm%1 xmm%1							;xmmxmm0 = xmm0
    %define xmmymm%1 xmm%1							;xmmymm0 = xmm0
    %define ymmmm%1   mm%1							;ymmmm0  = mm0
    %define ymmxmm%1 xmm%1							;ymmxmm0 = xmm0
    %define ymmymm%1 ymm%1							;ymmymm0 = ymm0
    %define xm%1 xmm %+ m%1							;xm0     = xmmm0
    %define ym%1 ymm %+ m%1							;ym0     = ymmm0
%endmacro

%assign i 0
%rep 16
    DECLARE_MMCAST i
    %assign i i+1
%endrep

; I often want to use macros that permute their arguments. e.g. there's no
; efficient way to implement butterfly or transpose or dct without swapping some
; arguments.
;
; I would like to not have to manually keep track of the permutations:
; If I insert a permutation in the middle of a function, it should automatically
; change everything that follows. For more complex macros I may also have multiple
; implementations, e.g. the SSE2 and SSSE3 versions may have different permutations.
;
; Hence these macros. Insert a PERMUTE or some SWAPs at the end of a macro that
; permutes its arguments. It's equivalent to exchanging the contents of the
; registers, except that this way you exchange the register names instead, so it
; doesn't cost any cycles.

%macro PERMUTE 2-* ; takes a list of pairs to swap
    %rep %0/2
        %xdefine %%tmp%2 m%2
        %rotate 2
    %endrep
    %rep %0/2
        %xdefine m%1 %%tmp%2
        CAT_XDEFINE nn, m%1, %1
        %rotate 2
    %endrep
%endmacro

%macro SWAP 2+ ; swaps a single chain (sometimes more concise than pairs)
    %ifnum %1 ; SWAP 0, 1, ...
        SWAP_INTERNAL_NUM %1, %2
    %else ; SWAP m0, m1, ...
        SWAP_INTERNAL_NAME %1, %2
    %endif
%endmacro

%macro SWAP_INTERNAL_NUM 2-*
    %rep %0-1					;交换寄存器的名字
        %xdefine %%tmp m%1
        %xdefine m%1 m%2
        %xdefine m%2 %%tmp
        CAT_XDEFINE nn, m%1, %1
        CAT_XDEFINE nn, m%2, %2
        %rotate 1
    %endrep
%endmacro

%macro SWAP_INTERNAL_NAME 2-*
    %xdefine %%args nn %+ %1
    %rep %0-1
        %xdefine %%args %%args, nn %+ %2
        %rotate 1
    %endrep
    SWAP_INTERNAL_NUM %%args
%endmacro

; If SAVE_MM_PERMUTATION is placed at the end of a function, then any later
; calls to that function will automatically load the permutation, so values can
; be returned in mmregs.
%macro SAVE_MM_PERMUTATION 0-1
    %if %0
        %xdefine %%f %1_m
    %else
        %xdefine %%f current_function %+ _m
    %endif
    %assign %%i 0
    %rep num_mmregs	;保存寄存器current_function_m0 = m0
        CAT_XDEFINE %%f, %%i, m %+ %%i
        %assign %%i %%i+1
    %endrep
%endmacro

%macro LOAD_MM_PERMUTATION 1 ; name to load from
    %ifdef %1_m0	;如果已经定义过current_function_m0,则加载其余的寄存器
        %assign %%i 0
        %rep num_mmregs
            CAT_XDEFINE m, %%i, %1_m %+ %%i
            CAT_XDEFINE nn, m %+ %%i, %%i
            %assign %%i %%i+1
        %endrep
    %endif
%endmacro

; Append cpuflags to the callee's name iff the appended name is known and the plain name isn't
%macro call 1						;定义call宏
    call_internal %1 %+ SUFFIX, %1	
%endmacro
%macro call_internal 2
    %xdefine %%i %2
    %ifndef cglobaled_%2			;如果cglobaled_xxx_cpuflags(cpuflags这里用mmx,sse,avx等替换)这个函数还没被定义
        %ifdef cglobaled_%1			
            %xdefine %%i %1
        %endif
    %endif
    call %%i						;调用带cpuflags的函数
    LOAD_MM_PERMUTATION %%i
%endmacro

; Substitutions that reduce instruction size but are functionally equivalent
%macro add 2
    %ifnum %2
        %if %2==128
            sub %1, -128
        %else
            add %1, %2
        %endif
    %else
        add %1, %2
    %endif
%endmacro

%macro sub 2
    %ifnum %2
        %if %2==128
            add %1, -128
        %else
            sub %1, %2
        %endif
    %else
        sub %1, %2
    %endif
%endmacro

;=============================================================================
; AVX abstraction layer
;=============================================================================

%assign i 0
%rep 16
    %if i < 8
        CAT_XDEFINE sizeofmm, i, 8			;sizeofmm0	= 8
    %endif
    CAT_XDEFINE sizeofxmm, i, 16			;sizeofxmm0 = 16
    CAT_XDEFINE sizeofymm, i, 32			;sizeofymm0 = 32
    %assign i i+1
%endrep
%undef i

%macro CHECK_AVX_INSTR_EMU 3-*
    %xdefine %%opcode %1					;{%1 %6, %7, %8, %9}/{%1 %6, %7, %8}
    %xdefine %%dst %2						;%6目的操作数
    %rep %0-2								;__src2, %9
        %ifidn %%dst, %3					;目的操作数和第二及第三源操作数相同,则不支持
            %error non-avx emulation of ``%%opcode'' is not supported
        %endif
        %rotate 1
    %endrep
%endmacro

;%1 == instruction
;%2 == minimal instruction set
;%3 == 1 if float, 0 if int
;%4 == 1 if 4-operand emulation, 0 if 3-operand emulation, 255 otherwise (no emulation)
;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
;%6+: operands
%macro RUN_AVX_INSTR 6-9+
    %ifnum sizeof%7
        %assign __sizeofreg sizeof%7
    %elifnum sizeof%6
        %assign __sizeofreg sizeof%6
    %else
        %assign __sizeofreg mmsize
    %endif
    %assign __emulate_avx 0
    %if avx_enabled && __sizeofreg >= 16
        %xdefine __instr v%1				;如果支持avx,且寄存器大于16字节,则在指令前加v,将其变成avx指令
    %else
        %xdefine __instr %1
        %if %0 >= 8+%4						;%4表示为3操作数指令或者4操作数指令
            %assign __emulate_avx 1			;如果参数个数大于等于指令所支持的参数个数,则模拟avx指令
        %endif
    %endif
    %ifnidn %2, fnord
        %ifdef cpuname
            %if notcpuflag(%2)	;不支持对应的指令集
                %error use of ``%1'' %2 instruction in cpuname function: current_function
            %elif cpuflags_%2 < cpuflags_sse && notcpuflag(sse2) && __sizeofreg > 8
                %error use of ``%1'' sse2 instruction in cpuname function: current_function
            %endif
        %endif
    %endif

    %if __emulate_avx
        %xdefine __src1 %7					;模拟avx指令,则%7表示第一个操作数,%8表示第二个操作数
        %xdefine __src2 %8
        %if %5 && %4 == 0					;commutative不关心源操作数的顺序,%4==0表示模拟3操作数
            %ifnidn %6, %7					;目的操作数%6,和第一个源操作%7不同
                %ifidn %6, %8				;目的操作数和第二源操作数相同
                    %xdefine __src1 %8		;交换第一和第二源操作数顺序
                    %xdefine __src2 %7
                %elifnnum sizeof%8 ;第二源操作数为内存值,比如为一个m256值,而且是可commutative的,则交换第一第二源操作数的顺序
                    ; 3-operand AVX instructions with a memory arg can only have it in src2,
                    ; whereas SSE emulation prefers to have it in src1 (i.e. the mov).
                    ; So, if the instruction is commutative with a memory arg, swap them.
                    %xdefine __src1 %8
                    %xdefine __src2 %7
                %endif
            %endif
        %endif
        %ifnidn %6, __src1					;目的操作数和第一源操作数不同
            %if %0 >= 9						;%0>9,表明该指令至少有4个参数
                CHECK_AVX_INSTR_EMU {%1 %6, %7, %8, %9}, %6, __src2, %9
            %else
                CHECK_AVX_INSTR_EMU {%1 %6, %7, %8}, %6, __src2
            %endif
            %if __sizeofreg == 8			;当前为mmx指令
                MOVQ %6, __src1				;使用movq指令将第一源操作数移到目的寄存器
            %elif %3						;浮点数使用movaps宏对应的指令
                MOVAPS %6, __src1
            %else							;否则使用movdqa宏对应的指令
                MOVDQA %6, __src1
            %endif
        %endif
        %if %0 >= 9	 ;指令有4个参数,上面已经使用mov*指令将第一操作数移到寄存器
            %1 %6, __src2, %9	;这里只需要对剩余的参数进行操作				
        %else		;指令有3个参数,上面已经使用mov*指令将第一操作数移到%6寄存器,
            %1 %6, __src2		;然后使用指令对%6和第二源操作数进行操作
        %endif
    %elif %0 >= 9	;不使用指令模拟时,使用真正的AVX相关指令
        __instr %6, %7, %8, %9
    %elif %0 == 8
        __instr %6, %7, %8
    %elif %0 == 7
        __instr %6, %7
    %else
        __instr %6
    %endif
%endmacro

;%1 == instruction
;%2 == minimal instruction set
;%3 == 1 if float, 0 if int
;%4 == 1 if 4-operand emulation, 0 if 3-operand emulation, 255 otherwise (no emulation)
;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
%macro AVX_INSTR 1-5 fnord, 0, 255, 0
    %macro %1 1-10 fnord, fnord, fnord, fnord, %1, %2, %3, %4, %5	;将AVX指令定义为宏
        %ifidn %2, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1					;%6表示上面的%1,%1表示第一个fnord
        %elifidn %3, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2
        %elifidn %4, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3
        %elifidn %5, fnord
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4
        %else
            RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4, %5
        %endif
    %endmacro
%endmacro

; Instructions with both VEX and non-VEX encodings
; Non-destructive instructions are written without parameters
AVX_INSTR addpd, sse2, 1, 0, 1
AVX_INSTR addps, sse, 1, 0, 1
AVX_INSTR addsd, sse2, 1, 0, 0
AVX_INSTR addss, sse, 1, 0, 0
AVX_INSTR addsubpd, sse3, 1, 0, 0
AVX_INSTR addsubps, sse3, 1, 0, 0
AVX_INSTR aesdec, aesni, 0, 0, 0
AVX_INSTR aesdeclast, aesni, 0, 0, 0
AVX_INSTR aesenc, aesni, 0, 0, 0
AVX_INSTR aesenclast, aesni, 0, 0, 0
AVX_INSTR aesimc, aesni
AVX_INSTR aeskeygenassist, aesni
AVX_INSTR andnpd, sse2, 1, 0, 0
AVX_INSTR andnps, sse, 1, 0, 0
AVX_INSTR andpd, sse2, 1, 0, 1
AVX_INSTR andps, sse, 1, 0, 1
AVX_INSTR blendpd, sse4, 1, 1, 0
AVX_INSTR blendps, sse4, 1, 1, 0
AVX_INSTR blendvpd, sse4 ; can't be emulated
AVX_INSTR blendvps, sse4 ; can't be emulated
AVX_INSTR cmppd, sse2, 1, 1, 0
AVX_INSTR cmpps, sse, 1, 1, 0
AVX_INSTR cmpsd, sse2, 1, 1, 0
AVX_INSTR cmpss, sse, 1, 1, 0
AVX_INSTR comisd, sse2
AVX_INSTR comiss, sse
AVX_INSTR cvtdq2pd, sse2
AVX_INSTR cvtdq2ps, sse2
AVX_INSTR cvtpd2dq, sse2
AVX_INSTR cvtpd2ps, sse2
AVX_INSTR cvtps2dq, sse2
AVX_INSTR cvtps2pd, sse2
AVX_INSTR cvtsd2si, sse2
AVX_INSTR cvtsd2ss, sse2, 1, 0, 0
AVX_INSTR cvtsi2sd, sse2, 1, 0, 0
AVX_INSTR cvtsi2ss, sse, 1, 0, 0
AVX_INSTR cvtss2sd, sse2, 1, 0, 0
AVX_INSTR cvtss2si, sse
AVX_INSTR cvttpd2dq, sse2
AVX_INSTR cvttps2dq, sse2
AVX_INSTR cvttsd2si, sse2
AVX_INSTR cvttss2si, sse
AVX_INSTR divpd, sse2, 1, 0, 0
AVX_INSTR divps, sse, 1, 0, 0
AVX_INSTR divsd, sse2, 1, 0, 0
AVX_INSTR divss, sse, 1, 0, 0
AVX_INSTR dppd, sse4, 1, 1, 0
AVX_INSTR dpps, sse4, 1, 1, 0
AVX_INSTR extractps, sse4
AVX_INSTR haddpd, sse3, 1, 0, 0
AVX_INSTR haddps, sse3, 1, 0, 0
AVX_INSTR hsubpd, sse3, 1, 0, 0
AVX_INSTR hsubps, sse3, 1, 0, 0
AVX_INSTR insertps, sse4, 1, 1, 0
AVX_INSTR lddqu, sse3
AVX_INSTR ldmxcsr, sse
AVX_INSTR maskmovdqu, sse2
AVX_INSTR maxpd, sse2, 1, 0, 1
AVX_INSTR maxps, sse, 1, 0, 1
AVX_INSTR maxsd, sse2, 1, 0, 0
AVX_INSTR maxss, sse, 1, 0, 0
AVX_INSTR minpd, sse2, 1, 0, 1
AVX_INSTR minps, sse, 1, 0, 1
AVX_INSTR minsd, sse2, 1, 0, 0
AVX_INSTR minss, sse, 1, 0, 0
AVX_INSTR movapd, sse2
AVX_INSTR movaps, sse
AVX_INSTR movd, mmx
AVX_INSTR movddup, sse3
AVX_INSTR movdqa, sse2
AVX_INSTR movdqu, sse2
AVX_INSTR movhlps, sse, 1, 0, 0
AVX_INSTR movhpd, sse2, 1, 0, 0
AVX_INSTR movhps, sse, 1, 0, 0
AVX_INSTR movlhps, sse, 1, 0, 0
AVX_INSTR movlpd, sse2, 1, 0, 0
AVX_INSTR movlps, sse, 1, 0, 0
AVX_INSTR movmskpd, sse2
AVX_INSTR movmskps, sse
AVX_INSTR movntdq, sse2
AVX_INSTR movntdqa, sse4
AVX_INSTR movntpd, sse2
AVX_INSTR movntps, sse
AVX_INSTR movq, mmx
AVX_INSTR movsd, sse2, 1, 0, 0
AVX_INSTR movshdup, sse3
AVX_INSTR movsldup, sse3
AVX_INSTR movss, sse, 1, 0, 0
AVX_INSTR movupd, sse2
AVX_INSTR movups, sse
AVX_INSTR mpsadbw, sse4, 0, 1, 0
AVX_INSTR mulpd, sse2, 1, 0, 1
AVX_INSTR mulps, sse, 1, 0, 1
AVX_INSTR mulsd, sse2, 1, 0, 0
AVX_INSTR mulss, sse, 1, 0, 0
AVX_INSTR orpd, sse2, 1, 0, 1
AVX_INSTR orps, sse, 1, 0, 1
AVX_INSTR pabsb, ssse3
AVX_INSTR pabsd, ssse3
AVX_INSTR pabsw, ssse3
AVX_INSTR packsswb, mmx, 0, 0, 0
AVX_INSTR packssdw, mmx, 0, 0, 0
AVX_INSTR packuswb, mmx, 0, 0, 0
AVX_INSTR packusdw, sse4, 0, 0, 0
AVX_INSTR paddb, mmx, 0, 0, 1
AVX_INSTR paddw, mmx, 0, 0, 1
AVX_INSTR paddd, mmx, 0, 0, 1
AVX_INSTR paddq, sse2, 0, 0, 1
AVX_INSTR paddsb, mmx, 0, 0, 1
AVX_INSTR paddsw, mmx, 0, 0, 1
AVX_INSTR paddusb, mmx, 0, 0, 1
AVX_INSTR paddusw, mmx, 0, 0, 1
AVX_INSTR palignr, ssse3, 0, 1, 0
AVX_INSTR pand, mmx, 0, 0, 1
AVX_INSTR pandn, mmx, 0, 0, 0
AVX_INSTR pavgb, mmx2, 0, 0, 1
AVX_INSTR pavgw, mmx2, 0, 0, 1
AVX_INSTR pblendvb, sse4 ; can't be emulated
AVX_INSTR pblendw, sse4, 0, 1, 0
AVX_INSTR pclmulqdq, fnord, 0, 1, 0
AVX_INSTR pclmulhqhqdq, fnord, 0, 0, 0
AVX_INSTR pclmulhqlqdq, fnord, 0, 0, 0
AVX_INSTR pclmullqhqdq, fnord, 0, 0, 0
AVX_INSTR pclmullqlqdq, fnord, 0, 0, 0
AVX_INSTR pcmpestri, sse42
AVX_INSTR pcmpestrm, sse42
AVX_INSTR pcmpistri, sse42
AVX_INSTR pcmpistrm, sse42
AVX_INSTR pcmpeqb, mmx, 0, 0, 1
AVX_INSTR pcmpeqw, mmx, 0, 0, 1
AVX_INSTR pcmpeqd, mmx, 0, 0, 1
AVX_INSTR pcmpeqq, sse4, 0, 0, 1
AVX_INSTR pcmpgtb, mmx, 0, 0, 0
AVX_INSTR pcmpgtw, mmx, 0, 0, 0
AVX_INSTR pcmpgtd, mmx, 0, 0, 0
AVX_INSTR pcmpgtq, sse42, 0, 0, 0
AVX_INSTR pextrb, sse4
AVX_INSTR pextrd, sse4
AVX_INSTR pextrq, sse4
AVX_INSTR pextrw, mmx2
AVX_INSTR phaddw, ssse3, 0, 0, 0
AVX_INSTR phaddd, ssse3, 0, 0, 0
AVX_INSTR phaddsw, ssse3, 0, 0, 0
AVX_INSTR phminposuw, sse4
AVX_INSTR phsubw, ssse3, 0, 0, 0
AVX_INSTR phsubd, ssse3, 0, 0, 0
AVX_INSTR phsubsw, ssse3, 0, 0, 0
AVX_INSTR pinsrb, sse4, 0, 1, 0
AVX_INSTR pinsrd, sse4, 0, 1, 0
AVX_INSTR pinsrq, sse4, 0, 1, 0
AVX_INSTR pinsrw, mmx2, 0, 1, 0
AVX_INSTR pmaddwd, mmx, 0, 0, 1
AVX_INSTR pmaddubsw, ssse3, 0, 0, 0
AVX_INSTR pmaxsb, sse4, 0, 0, 1
AVX_INSTR pmaxsw, mmx2, 0, 0, 1
AVX_INSTR pmaxsd, sse4, 0, 0, 1
AVX_INSTR pmaxub, mmx2, 0, 0, 1
AVX_INSTR pmaxuw, sse4, 0, 0, 1
AVX_INSTR pmaxud, sse4, 0, 0, 1
AVX_INSTR pminsb, sse4, 0, 0, 1
AVX_INSTR pminsw, mmx2, 0, 0, 1
AVX_INSTR pminsd, sse4, 0, 0, 1
AVX_INSTR pminub, mmx2, 0, 0, 1
AVX_INSTR pminuw, sse4, 0, 0, 1
AVX_INSTR pminud, sse4, 0, 0, 1
AVX_INSTR pmovmskb, mmx2
AVX_INSTR pmovsxbw, sse4
AVX_INSTR pmovsxbd, sse4
AVX_INSTR pmovsxbq, sse4
AVX_INSTR pmovsxwd, sse4
AVX_INSTR pmovsxwq, sse4
AVX_INSTR pmovsxdq, sse4
AVX_INSTR pmovzxbw, sse4
AVX_INSTR pmovzxbd, sse4
AVX_INSTR pmovzxbq, sse4
AVX_INSTR pmovzxwd, sse4
AVX_INSTR pmovzxwq, sse4
AVX_INSTR pmovzxdq, sse4
AVX_INSTR pmuldq, sse4, 0, 0, 1
AVX_INSTR pmulhrsw, ssse3, 0, 0, 1
AVX_INSTR pmulhuw, mmx2, 0, 0, 1
AVX_INSTR pmulhw, mmx, 0, 0, 1
AVX_INSTR pmullw, mmx, 0, 0, 1
AVX_INSTR pmulld, sse4, 0, 0, 1
AVX_INSTR pmuludq, sse2, 0, 0, 1
AVX_INSTR por, mmx, 0, 0, 1
AVX_INSTR psadbw, mmx2, 0, 0, 1
AVX_INSTR pshufb, ssse3, 0, 0, 0
AVX_INSTR pshufd, sse2
AVX_INSTR pshufhw, sse2
AVX_INSTR pshuflw, sse2
AVX_INSTR psignb, ssse3, 0, 0, 0
AVX_INSTR psignw, ssse3, 0, 0, 0
AVX_INSTR psignd, ssse3, 0, 0, 0
AVX_INSTR psllw, mmx, 0, 0, 0
AVX_INSTR pslld, mmx, 0, 0, 0
AVX_INSTR psllq, mmx, 0, 0, 0
AVX_INSTR pslldq, sse2, 0, 0, 0
AVX_INSTR psraw, mmx, 0, 0, 0
AVX_INSTR psrad, mmx, 0, 0, 0
AVX_INSTR psrlw, mmx, 0, 0, 0
AVX_INSTR psrld, mmx, 0, 0, 0
AVX_INSTR psrlq, mmx, 0, 0, 0
AVX_INSTR psrldq, sse2, 0, 0, 0
AVX_INSTR psubb, mmx, 0, 0, 0
AVX_INSTR psubw, mmx, 0, 0, 0
AVX_INSTR psubd, mmx, 0, 0, 0
AVX_INSTR psubq, sse2, 0, 0, 0
AVX_INSTR psubsb, mmx, 0, 0, 0
AVX_INSTR psubsw, mmx, 0, 0, 0
AVX_INSTR psubusb, mmx, 0, 0, 0
AVX_INSTR psubusw, mmx, 0, 0, 0
AVX_INSTR ptest, sse4
AVX_INSTR punpckhbw, mmx, 0, 0, 0
AVX_INSTR punpckhwd, mmx, 0, 0, 0
AVX_INSTR punpckhdq, mmx, 0, 0, 0
AVX_INSTR punpckhqdq, sse2, 0, 0, 0
AVX_INSTR punpcklbw, mmx, 0, 0, 0
AVX_INSTR punpcklwd, mmx, 0, 0, 0
AVX_INSTR punpckldq, mmx, 0, 0, 0
AVX_INSTR punpcklqdq, sse2, 0, 0, 0
AVX_INSTR pxor, mmx, 0, 0, 1
AVX_INSTR rcpps, sse
AVX_INSTR rcpss, sse, 1, 0, 0
AVX_INSTR roundpd, sse4
AVX_INSTR roundps, sse4
AVX_INSTR roundsd, sse4, 1, 1, 0
AVX_INSTR roundss, sse4, 1, 1, 0
AVX_INSTR rsqrtps, sse
AVX_INSTR rsqrtss, sse, 1, 0, 0
AVX_INSTR shufpd, sse2, 1, 1, 0
AVX_INSTR shufps, sse, 1, 1, 0
AVX_INSTR sqrtpd, sse2
AVX_INSTR sqrtps, sse
AVX_INSTR sqrtsd, sse2, 1, 0, 0
AVX_INSTR sqrtss, sse, 1, 0, 0
AVX_INSTR stmxcsr, sse
AVX_INSTR subpd, sse2, 1, 0, 0
AVX_INSTR subps, sse, 1, 0, 0
AVX_INSTR subsd, sse2, 1, 0, 0
AVX_INSTR subss, sse, 1, 0, 0
AVX_INSTR ucomisd, sse2
AVX_INSTR ucomiss, sse
AVX_INSTR unpckhpd, sse2, 1, 0, 0
AVX_INSTR unpckhps, sse, 1, 0, 0
AVX_INSTR unpcklpd, sse2, 1, 0, 0
AVX_INSTR unpcklps, sse, 1, 0, 0
AVX_INSTR xorpd, sse2, 1, 0, 1
AVX_INSTR xorps, sse, 1, 0, 1

; 3DNow instructions, for sharing code between AVX, SSE and 3DN
AVX_INSTR pfadd, 3dnow, 1, 0, 1
AVX_INSTR pfsub, 3dnow, 1, 0, 0
AVX_INSTR pfmul, 3dnow, 1, 0, 1

; base-4 constants for shuffles
%assign i 0
%rep 256
    %assign j ((i>>6)&3)*1000 + ((i>>4)&3)*100 + ((i>>2)&3)*10 + (i&3)
    %if j < 10
        CAT_XDEFINE q000, j, i
    %elif j < 100
        CAT_XDEFINE q00, j, i
    %elif j < 1000
        CAT_XDEFINE q0, j, i
    %else
        CAT_XDEFINE q, j, i
    %endif
    %assign i i+1
%endrep
%undef i
%undef j

%macro FMA_INSTR 3
    %macro %1 4-7 %1, %2, %3
        %if cpuflag(xop)
            v%5 %1, %2, %3, %4
        %elifnidn %1, %4
            %6 %1, %2, %3
            %7 %1, %4
        %else
            %error non-xop emulation of ``%5 %1, %2, %3, %4'' is not supported
        %endif
    %endmacro
%endmacro

FMA_INSTR  pmacsww,  pmullw, paddw
FMA_INSTR  pmacsdd,  pmulld, paddd ; sse4 emulation
FMA_INSTR pmacsdql,  pmuldq, paddq ; sse4 emulation
FMA_INSTR pmadcswd, pmaddwd, paddd

; tzcnt is equivalent to "rep bsf" and is backwards-compatible with bsf.
; This lets us use tzcnt without bumping the yasm version requirement yet.
%define tzcnt rep bsf

; Macros for consolidating FMA3 and FMA4 using 4-operand (dst, src1, src2, src3) syntax.
; FMA3 is only possible if dst is the same as one of the src registers.
; Either src2 or src3 can be a memory operand.
%macro FMA4_INSTR 2-*
    %push fma4_instr
    %xdefine %$prefix %1
    %rep %0 - 1
        %macro %$prefix%2 4-6 %$prefix, %2
            %if notcpuflag(fma3) && notcpuflag(fma4)
                %error use of ``%5%6'' fma instruction in cpuname function: current_function
            %elif cpuflag(fma4)
                v%5%6 %1, %2, %3, %4
            %elifidn %1, %2
                ; If %3 or %4 is a memory operand it needs to be encoded as the last operand.
                %ifnum sizeof%3
                    v%{5}213%6 %2, %3, %4
                %else
                    v%{5}132%6 %2, %4, %3
                %endif
            %elifidn %1, %3
                v%{5}213%6 %3, %2, %4
            %elifidn %1, %4
                v%{5}231%6 %4, %2, %3
            %else
                %error fma3 emulation of ``%5%6 %1, %2, %3, %4'' is not supported
            %endif
        %endmacro
        %rotate 1
    %endrep
    %pop
%endmacro

FMA4_INSTR fmadd,    pd, ps, sd, ss
FMA4_INSTR fmaddsub, pd, ps
FMA4_INSTR fmsub,    pd, ps, sd, ss
FMA4_INSTR fmsubadd, pd, ps
FMA4_INSTR fnmadd,   pd, ps, sd, ss
FMA4_INSTR fnmsub,   pd, ps, sd, ss

; workaround: vpbroadcastq is broken in x86_32 due to a yasm bug (fixed in 1.3.0)
%ifdef __YASM_VER__
    %if __YASM_VERSION_ID__ < 0x01030000 && ARCH_X86_64 == 0
        %macro vpbroadcastq 2
            %if sizeof%1 == 16
                movddup %1, %2
            %else
                vbroadcastsd %1, %2
            %endif
        %endmacro
    %endif
%endif


;Win64
;一个函数在调用时,前四个参数是从左至右依次存放于RCX、RDX、R8、R9寄存器里面,剩下的参数从左至右顺序入栈;
;调用者负责在栈上分配32字节的“shadow space”,用于存放那四个存放调用参数的寄存器的值(亦即前四个调用参数);
;RAX,RCX,RDX,R8,R9,R10,R11是“易挥发”的,不用特别保护,其余寄存器需要保护。(x86下只有eax, ecx, edx是易挥发的)
;栈需要16字节对齐,“call”指令会入栈一个8字节的返回值
;整数前 4 个参数传入 RCX、RDX、R8 和 R9 中。其他参数传递到堆栈中。

;GCC64
;当参数少于7个时, 参数从左到右放入寄存器: rdi, rsi, rdx, rcx, r8, r9。
;常用寄存器有16个,分为x86通用寄存器以及r8-r15寄存器。
;通用寄存器中,函数执行前后必须保持原始的寄存器有3个:是rbx、rbp、rsp。rx寄存器中,最后4个必须保持原值:r12、r13、r14、r15。
;保持原值的意义是为了让当前函数有可信任的寄存器,减小在函数调用过程中的保存&恢复操作。除了rbp、rsp用于特定用途外,其余5个寄存器可随意使用。
;通用寄存器中,不必假设保存值可随意使用的寄存器有5个:是rax、rcx、rdx、rdi、rsi。其中rax用于第一个返回寄存器(当 然也可以用于其它用途),rdx用于第二个返回寄存器(在调用函数时也用于第三个参数寄存器)。rcx用于第四个参数。rdi用于第一个参数。rsi用于 第二个函数参数。
;r8、r9分配用于第5、第6个参数。


  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
ffmpeg-5.0-1.5.7-windows-x86_64.jar 是一个用于在 Windows 平台上运行的 FFmpeg 库文件。它是一个开源的音视频处理工具,可以从多种媒体文件中提取、转码和编辑音视频流。 这个库文件是基于 FFmpeg 项目的最新版本 5.0 开发的。它支持在 Windows 64 位操作系统上运行,并提供了一系列功能强大的音视频处理方法。它可以读取和写入各种常见的音视频格式,包括 MP4、AVI、FLV、MOV 等。用户可以使用该库来提取音频或视频流,转码音视频文件,剪辑视频,添加字幕等。 要使用 ffmpeg-5.0-1.5.7-windows-x86_64.jar,首先需要在您的 Java 项目中引入该库文件。您可以将其作为依赖项添加到项目的 Classpath 中。然后,您可以通过在 Java 代码中调用相应的方法来使用 FFmpeg 功能。 例如,您可以使用 FFmpeg 在音频文件中提取音频流,然后对其进行编码或解码。您可以使用 FFmpeg 在视频文件中提取视频流,并进行截图或修改分辨率。您还可以使用 FFmpeg 对多个媒体文件进行合并或拆分操作。 除了提供强大的音视频处理功能外,ffmpeg-5.0-1.5.7-windows-x86_64.jar 还提供了丰富的文档和示例代码,以帮助用户更好地了解和使用该库。您可以参考官方文档和示例代码,了解每个方法的使用方法和参数说明。 总之,ffmpeg-5.0-1.5.7-windows-x86_64.jar 是一个在 Windows 平台上运行的 FFmpeg 库文件,提供了强大的音视频处理功能。用户可以使用它来处理音视频文件,实现音视频提取、转码、编辑等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值