text stringlengths 1 1.05M |
|---|
MEM_LOC1 = 0x200 # Example of using variable
add(r0, r2, r3)
sub(r2, r4, r4)
load(r2, MEM_LOC1)
label("L1")
move(r2, r7)
jmp(L1)
|
; A164429: Number of binary strings of length n with no substrings equal to 0000, 0011, or 1011.
; 1,2,4,8,13,21,33,50,75,112,166,245,361,531,780,1145,1680,2464,3613,5297,7765,11382,16683,24452,35838,52525,76981,112823,165352,242337,355164,520520,762861,1118029,1638553,2401418,3519451,5158008,7559430,11078885,16236897,23796331,34875220,51112121,74908456,109783680,160895805,235804265,345587949,506483758,742288027,1087875980,1594359742,2336647773,3424523757,5018883503,7355531280,10780055041,15798938548,23154469832,33934524877,49733463429,72887933265,106822458146,156555921579,229443854848,336266312998,492822234581,722266089433,1058532402435,1551354637020,2273620726457,3332153128896,4883507765920,7157128492381,10489281621281,15372789387205,22529917879590,33019199500875,48391988888084,70921906767678,103941106268557,152333095156645,223255001924327,327196108192888,479529203349537,702784205273868,1029980313466760,1509509516816301,2212293722090173,3242274035556937,4751783552373242,6964077274463419
mov $3,$0
add $0,1
cal $0,69241 ; Number of Hamiltonian paths in the graph on n vertices {1,...,n}, with i adjacent to j iff |i-j|<=2.
sub $0,1
mov $2,$0
cmp $2,0
add $0,$2
mov $1,$0
add $1,$3
|
%ifdef CONFIG
{
"RegData": {
"MM6": ["0x8000000000000000", "0x3FFF"],
"MM7": ["0x8000000000000000", "0x3FFF"]
},
"Mode": "32BIT"
}
%endif
lea edx, [data]
fld tword [edx + 8 * 0]
lea edx, [data2]
fld tword [edx + 8 * 0]
fst st1
hlt
align 8
data:
dt 2.0
dq 0
data2:
dt 1.0
dq 0
|
CanLearnTMHMMove:
ld a, [wCurPartySpecies]
ld [wCurSpecies], a
call GetBaseData
ld hl, wBaseTMHM
push hl
ld a, [wPutativeTMHMMove]
ld b, a
ld c, 0
ld hl, TMHMMoves
.loop
ld a, [hli]
and a
jr z, .end
cp b
jr z, .asm_11659
inc c
jr .loop
.asm_11659
pop hl
ld b, CHECK_FLAG
push de
ld d, 0
predef SmallFarFlagAction
pop de
ret
.end
pop hl
ld c, 0
ret
GetTMHMMove:
ld a, [wTempTMHM]
dec a
ld hl, TMHMMoves
ld b, 0
ld c, a
add hl, bc
ld a, [hl]
ld [wTempTMHM], a
ret
INCLUDE "data/moves/tmhm_moves.asm"
|
; A152090: a(n) = 2^n*Product_{k=1..floor((n-1)/2)} (1 + 2*cos(k*Pi/n)^2 + 4*cos(k*Pi/n)^4).
; Submitted by Christian Krause
; 1,1,1,3,7,16,39,91,217,513,1216,2881,6825,16171,38311,90768,215047,509491,1207089,2859841,6775552,16052673,38032081,90105811,213479175,505776016,1198287271,2838988683,6726147337,15935624641,37754768064
mov $5,1
lpb $0
sub $0,1
max $0,1
sub $3,$4
add $1,$3
sub $3,$2
add $1,$3
mov $4,$2
mov $2,$3
add $4,$1
add $5,$4
mov $3,$5
lpe
mov $0,$5
|
; A074503: a(n) = 1^n + 2^n + 7^n.
; 3,10,54,352,2418,16840,117714,823672,5765058,40354120,282476274,1977328792,13841291298,96889018600,678223089234,4747561542712,33232930635138,232630514118280,1628413598172594,11398895185897432
mov $2,2
pow $2,$0
add $2,2
mov $3,7
pow $3,$0
add $2,$3
mov $4,$2
add $4,2
mul $4,2
gcd $1,$4
sub $1,12
div $1,2
add $1,3
|
#Código mínimo. Soma 2 números fixos, imprime o resultado e sai
addi $t0, $zero, 3
addi $t1, $zero, 4
add $s0, $t0, $t1 # $s0 = 3 + 4
# Imprime resultado
addi $v0, $zero, 1 # print_int syscall code = 1
add $a0, $zero, $s0
syscall
# Sai do programa
addi $v0, $zero, 10 # exit syscall code = 10
syscall
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r14
push %r8
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x4b87, %rsi
nop
nop
nop
nop
cmp %r12, %r12
mov (%rsi), %rdi
nop
and %r8, %r8
lea addresses_WT_ht+0x53a7, %rsi
lea addresses_normal_ht+0xdb87, %rdi
add $4707, %r11
mov $49, %rcx
rep movsw
nop
nop
add $34520, %rcx
lea addresses_UC_ht+0x17dcb, %r8
nop
nop
nop
nop
nop
and $43057, %rbp
mov $0x6162636465666768, %rdi
movq %rdi, %xmm4
and $0xffffffffffffffc0, %r8
vmovaps %ymm4, (%r8)
nop
nop
add %r11, %r11
lea addresses_normal_ht+0x1c987, %rsi
lea addresses_WC_ht+0x18b87, %rdi
nop
nop
nop
inc %r14
mov $67, %rcx
rep movsl
nop
nop
nop
sub $1869, %r8
lea addresses_WC_ht+0x16cb, %rsi
lea addresses_UC_ht+0x181c7, %rdi
nop
nop
inc %r12
mov $8, %rcx
rep movsw
nop
cmp $19081, %r8
lea addresses_D_ht+0x17d07, %r8
sub $32187, %rcx
vmovups (%r8), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %r14
nop
nop
nop
xor %rbp, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r8
pop %r14
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r14
push %rbp
push %rdi
push %rsi
// Load
lea addresses_PSE+0x7787, %rdi
nop
nop
xor %r12, %r12
movb (%rdi), %r13b
nop
nop
nop
nop
nop
sub %rdi, %rdi
// Load
lea addresses_normal+0x8dc7, %r13
nop
nop
nop
nop
nop
add %rbp, %rbp
mov (%r13), %r14
nop
nop
nop
nop
nop
cmp %r13, %r13
// Store
lea addresses_WC+0x1b562, %r12
xor %rsi, %rsi
movw $0x5152, (%r12)
nop
nop
nop
nop
xor $40017, %rdi
// Store
lea addresses_WT+0x18287, %r14
and $6325, %r13
movw $0x5152, (%r14)
nop
nop
nop
nop
xor %r14, %r14
// Store
lea addresses_PSE+0x1d37f, %rsi
dec %rbp
movw $0x5152, (%rsi)
nop
nop
nop
sub %rbp, %rbp
// Store
lea addresses_D+0xff87, %rsi
clflush (%rsi)
nop
nop
and $57242, %r13
mov $0x5152535455565758, %r12
movq %r12, (%rsi)
nop
nop
nop
nop
xor %rdi, %rdi
// Store
mov $0x1ab58300000006a7, %rdi
nop
nop
nop
nop
nop
xor $20183, %r11
mov $0x5152535455565758, %rsi
movq %rsi, (%rdi)
// Exception!!!
nop
nop
nop
mov (0), %r14
nop
nop
nop
xor $16734, %rsi
// Store
mov $0xf87, %r13
xor $37847, %r14
mov $0x5152535455565758, %rsi
movq %rsi, %xmm6
movups %xmm6, (%r13)
// Exception!!!
nop
mov (0), %rdi
nop
and %rdi, %rdi
// Faulty Load
lea addresses_PSE+0x16787, %r14
nop
nop
nop
add $9246, %r12
mov (%r14), %r11w
lea oracles, %r14
and $0xff, %r11
shlq $12, %r11
mov (%r14,%r11,1), %r11
pop %rsi
pop %rdi
pop %rbp
pop %r14
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_PSE', 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 1, 'type': 'addresses_PSE', 'congruent': 9}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal', 'congruent': 4}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WC', 'congruent': 0}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_PSE', 'congruent': 3}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_D', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_NC', 'congruent': 4}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_P', 'congruent': 10}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_PSE', 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_UC_ht', 'congruent': 9}}
{'dst': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_WT_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 32, 'type': 'addresses_UC_ht', 'congruent': 1}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 8, 'type': 'addresses_normal_ht'}}
{'dst': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 7}}
{'33': 12}
33 33 33 33 33 33 33 33 33 33 33 33
*/
|
.orig x3000
START
; first show initial strings before modification
; print all three strings on one line
LEA R0, LF ; print newline
PUTS
LEA R0, S1 ; print the strings
PUTS
LEA R0, S2
PUTS
LEA R0, S3
PUTS
LEA R0, LF ; print newline
PUTS
TEST1 ; first test
LEA R1, S2
LEA R2, S3
JSR STRCAT ; append S2 to S3
; after subroutine returns, S3 should be "horse+bird+"
; print all three strings on one line
LEA R0, S1 ; print the strings
PUTS
LEA R0, S2
PUTS
LEA R0, S3
PUTS
LEA R0, LF ; print newline
PUTS
TEST2 ; second test
LEA R1, S1
LEA R2, S3
JSR STRCAT ; append S1 to S3
; after subroutine returns, S3 should be "horse+bird+cat+"
; print all three strings on one line
LEA R0, S1 ; print the strings
PUTS
LEA R0, S2
PUTS
LEA R0, S3
PUTS
LEA R0, LF ; print newline
PUTS
HALT ; end program
; test data
LF .STRINGZ "\n"
S1 .STRINGZ "cat+"
S2 .STRINGZ "bird+"
S3 .STRINGZ "horse+"
.BLKW 16 ; extra space
; STRCPY
; Copy source string to destination
; Assumes: R1 - source string address
; R2 - destination address
; Returns: Nothing
; -- put your STRCPY subroutine and its data below here --
STRCPY
ST R1, STRCPY_R1 ; context save
ST R2, STRCPY_R2
ST R3, STRCPY_R3
STRCPY_LOOP
LDR R3, R1, #0 ; get current character
STR R3, R2, #0
BRz STRCPY_EXIT ; is it at null-character?
ADD R1, R1, #1 ; increment source addr
ADD R2, R2, #1 ; increment dest addr
BR STRCPY_LOOP
STRCPY_EXIT
LD R1, STRCPY_R1 ; context save
LD R2, STRCPY_R2 ; context restore
LD R3, STRCPY_R3
RET
STRCPY_R1 .BLKW 1
STRCPY_R2 .BLKW 1
STRCPY_R3 .BLKW 1
; -- put your STRCPY subroutine and its data above here --
; ONLY TURN IN YOUR STRCAT SUBROUTINE CODE AND ITS DATA.
; DO NOT TURN IN THE CALLER CODE AND DATA ABOVE
; DO NOT MODIFY ANYTHING ABOVE HERE *EXCEPT* FOR COPYING
; IN YOUR **TESTED AND WORKING** STRCPY SUBROUTINE
; STRCAT
; Append source string to destination
; Assumes: R1 - source string address
; R2 - destination address
; Returns: Nothing
STRCAT
ST R1, STRCAT_R1 ; context save
ST R2, STRCAT_R2
STRCAT_LOOP
LDR R3, R2, #0
BRz CALL_STRCPY ; is it at null character?
ADD R2, R2, #1 ; increment destination pointer
BR STRCAT_LOOP
CALL_STRCPY
BR STRCPY
STRCAT_EXIT
LD R1, STRCAT_R1 ; context restore
LD R2, STRCAT_R2
RET
STRCAT_R1 .BLKW 1
STRCAT_R2 .BLKW 1
.end
|
# =========================================================================
#
# NAME:
# DATE: June 06, 2001
# ASSIGNMENT: Example #3, CSC-201-01
# OBJECTIVE: Print "Hello World!" once then create a for loop starting
# from 0 to 99. Every 8th integer (0, 8, 16, 24, ... ) should
# be displayed on the screen.
#
# =========================================================================
.data
.align 2
# =========================================================================
prompt1: .asciiz "Hello World!\n"
prompt2: .asciiz "The current integer is: "
newline: .asciiz "\n"
# =========================================================================
.text
.align 2
main:
# =========================================================================
# $s0 - counter
# =========================================================================
# ::::: OP :::: ARGUMENTS ::::::::::::: COMMENTS ::::::::::::::::::::::::::
# =========================================================================
la $a0, prompt1
li $v0, 4
syscall # print "Hello World!"
li $s0, 0 # initialize counter
# =========================================================================
itbegins:
andi $t0, $s0, 7 # perform binary with $s0 and 7
beq $s0, 99, itends # if counter == 99, goto itends
bne $t0, 0, nomsg # if $t0 == 0, goto nomsg
la $a0, prompt2
li $v0, 4
syscall # print "The current integer is: "
move $a0, $s0
li $v0, 1
syscall # print counter
la $a0, newline
li $v0, 4
syscall # print new line
nomsg:
addi $s0, $s0, 1 # counter = counter + 1
j itbegins # jump to start of loop
itends:
# =========================================================================
li $v0, 10
syscall # exit program
# =========================================================================
# :::::::::::::::::::::::::::: END OF PROGRAM! ::::::::::::::::::::::::::::
# =========================================================================
|
// Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: Paul Koch <code@koch.ninja>
#ifndef EBM_STATS_HPP
#define EBM_STATS_HPP
#include <cmath> // log, exp, etc
#include <stddef.h> // size_t, ptrdiff_t
#include "ebm_native.h"
#include "logging.h"
#include "zones.h"
#include "ebm_internal.hpp"
#include "approximate_math.hpp"
namespace DEFINED_ZONE_NAME {
#ifndef DEFINED_ZONE_NAME
#error DEFINED_ZONE_NAME must be defined
#endif // DEFINED_ZONE_NAME
// TODO: rename FloatEbmType to DecimalDataType (or something else that doesn't imply specifically float32)
// TODO: before applying a model update for classification, check to see that the probability implied by the
// logit exceeds 1/number_of_samples in either the positive or negative direction. If it does, then modify
// the update so that the probability does not exceed a certainty of 1/number_of_samples, since we
// really can't make statements of probability beyond close to that threshold (make this a tunable option)
// TODO: In addition to limiting logits on individual feature bins, we should also limit them on individual samples
// (make this a tunable option)
// TODO: we should consider having a min_samples, which will eliminate any class with less than that number of
// samples, although we'll record the base rate in the model and then we can re-build the tensor with the
// base rate in any classes that we removed (make it an optional tunable value)
// TODO: we can also add new classes at prediction time.. they just get 1/n_samples (make it an optional tunable value)
static_assert(
std::numeric_limits<FloatEbmType>::is_iec559,
"If IEEE 754 isn't guaranteed, then we can't use or compare infinity values in any standard way. "
"We can't even guarantee that infinity exists as a concept."
);
constexpr FloatEbmType k_hessianMin = std::numeric_limits<FloatEbmType>::denorm_min();
constexpr FloatEbmType k_gainMin = FloatEbmType { 0 };
// HANDLING SPECIAL FLOATING POINT VALUES (NaN/infinities/denormals/-0):
// - it should be virtually impossible to get NaN values anywhere in this code without being given an
// adversarial dataset or adversarial input parameters [see notes below], but they are possible so we need to
// detect/handle them at some level.
// - it should be virtually impossible to get +-infinity values in classification. We could get +infinity
// values if the user gives us regression targets above sqrt(std::numeric_limits<FloatEbmType>::max())
// [see notes below], but those regression targets are huge and the caller should just avoid them.
// We can't avoid the possibility of the user passing us ridiculously huge regression targets,
// and huge inputs are something that has no perfect solution. We just need to figure out how to
// deal with these if +-infinities occur.
// - for classification, if we forcibly limit the logits to a positive and negative range defined by 1/n_samples or
// some constant min/max values, we should avoid +-infinity (this is not implemented at the time of this writing)
// - we don't crash or really cause any problems if denormals are rounded down to zero. For classification, any
// denormal value would be indistinguishable from zero in term of the differences in probabilities, so there is
// no benefit in attempting to preserve denormals. In theory, for regression a caller might care about numbers
// in the denormal range. We don't need to actively zero denormals for regression though, so we'll just ignore
// this issue and if they occur we'll just let them propagate if the hardware allows.
// - Our approximate exp/log functions zero denormals since they make things slower and aren't useful in the
// domain of classification where they are used. We also like getting consistent results between environments,
// and zeroing denormals is more standard since not all hardware supports denormals (although is it very common today)
// - negative 0 is a no-op for us. We don't care if -0 becomes +0 in our code. It matters though in our floating
// point approximate exp/log functions, so we check for it there.
// - our strategy, for reasons described below, is to allow NaN and +-infinity values to propagate through our
// computations. We will have a single check for these almost-illegal values at the end. We terminate all
// boosting if we see any NaN or +-infinity values. In the future this might change so that we limit the logit
// values to a range that makes sense, which would allow boosting to continue for classification beyond where
// +-infinities would otherwise be generated.
// - we ensure that any NaN or +-infinity values DO NOT CRASH the program, or cause an infinite loop, but
// beyond that we give no guarantees. The caller can see NaN, +-infinity, or simply wrong values if they give
// us adversarial inputs, since the cost of handling them is too high and not even guaranteed to work.
//
// - most compilers have flags that give unspecified behavior when either NaN or +-infinity are generated,
// or propagated, or in conditional statements involving them. Our code can't tolerate these switches being
// enabled since we can sometimes generate these values, and in general we need to accept NaN values from our caller.
// - g++ makes std::isnan fail to work when the compiler flags indicate no NaN values are present, so we don't use
// "-ffast-math". -fno-finite-math-only would solve this, but we still want NaN comparisons to work outside of
// just std::isnan for NaN propagation.
// - given our need to allow NaN and +-infinity values, we can then also use NaN and infinity propagation to avoid
// checking individual samples for overflows, and we propagate the overflows to the final result which we check.
// We also use some of the odd properties of NaN comparison that rely on a high degree of compliance with IEEE-754
// - most compilers have switches that allow the compiler to re-order math operations. We've found issues with
// these switches, so our code needs to be compiled with strict adherence to floating point operations. Once
// we found a bug where the compiler was optimizing "log(x) + log(y)" into "log(x * y)", which then overflowed.
// - Generally +-infinity are treated better than NaN under the compiler switches that make floating points
// less IEEE 754 compliant
// - many compilers seem to virtually require the switches enabling floating point deviations from IEEE-754 in
// order to enable SIMD, since they want to re-order things like addition instructions.
// (reordering additions is not IEEE-754 compliant). Since we can't accept IEEE-754 compiler re-orderings
// we need to do our own SIMD optimizations instead of allowing the compiler to auto-vectorize
// - given that we are very CPU bound, we would REALLY like our code to be as SIMD friendly as possible
// (possibly about 16x faster for AVX-512 using float32)
// - any branching instructions inside a loop will destroy the ability to generate SIMD instructions for the loop.
// Non-branching conditional statements in SIMD are allowed via bit masks.
// - since we want SIMD, we need to avoid branching instructions that exit the loop, so if we did want to handle
// special floating point values, we'd need to either signal an error on any of the computational values and exit
// the loop for all, or use NaN or infinity propagation to take the error to the end of the loop
// - old hardware used to have penalties of hundreds of CPU cycles for handling: NaN, +-infinity, and denomral
// values. This has generally been resolved on newer hardware.
// https://www.agner.org/optimize/nan_propagation.pdf
// - even if there are huge penalties for handling special numeric values, we can stop boosting after a single
// completed round if they occur and get propagated, and a several hundred CPU cycle penalty will generally be
// less than the total time of doing the rest of the training, which is generally at least dozens of
// features and hundreds of boosting rounds.
// - for Intel x86, we enable SSE for floating point instead of x87, since x87 has performance problems and
// rounding inconsistencies (they use 80 bit floating point values in the registers)
// - there are C/C++ ways of turning floating point exceptions on or off, but most systems don't do that. We'll
// let our caller choose if those exceptions are enabled, and if so they can at least detect the exceptions.
// If we wanted to specify that exceptions would not occur, then we could use the special comparison functions
// designed to emulate quiet NaN behavior: std::islessequal, etc..
// - even though the is_iec559 static_assert doesn't correctly indicate when IEEE 754 is broken due to compiler
// flags, we should check it anyways because if it's false then we could have even more crazy semantics regarding
// floating point numbers, such as no infinities, etc.
// - in practice, we can't rely on the compiler having IEEE-754 compatibility, even if is_iec559 is true. I've
// personally seen deviations from correct rounding in float to integer conversion. Some compilers use the
// Intel x87 registers which have non-conformant results, etc. Here are some other compiler examples of deviations:
// https://randomascii.wordpress.com/2013/07/16/floating-point-determinism/
// - If IEEE-754 was properly followed (which it isn't), floating point operations would have these properties:
// - SEE reference https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
// - these operations would have exact outcomes, guaranteed to be rounded correctly to the last bit:
// addition, subtraction, multiplication, division and square root in all versions of IEEE-754 (IEEE-754-1985)
// we don't use sqrt though as we return MSE as our metric for regression
// - exp and log would be guaranteed to be correctly rounded to the last bin in IEEE-754-2008 and later
// https://en.wikipedia.org/wiki/IEEE_754
// - background: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
// - BUT, if we use approximate exp and log functions, we could guarantee identical results, at least in
// theory in all versions of IEEE-754. This does not seem to occur in practice, and I believe the culprit is
// the rounding between floating point and integers is slightly different, at least on VS compilers.
// - floating point integers (1.0, 2.0, 3.0, etc) have exact representations up to very large numbers where
// the jumps between floating point numbers are greater than 1
// - fractions of a power of 2 (1/2.0, 1/4.0, 1/8.0, etc) have exact representations down to very small numbers
//
// IEEE 754 special value operations:
// denormal values don't get rounded to zero
// NaN values get propagated in operations
// anything compared to a NaN, is false, except for "a != a" (where a is NaN), which is true!
// Take note that "a == a" is FALSE for NaN values!!!
// log(-ANYTHING) = NaN
// +infinity + -infinity = NaN
// -infinity + +infinity = NaN
// -infinity - -infinity = NaN
// +infinity - +infinity = NaN
// +-infinity * +-0 = NaN
// +-0 * +-infinity = NaN
// +-0 / +-0 = NaN
// +-infinity / +-infinity = NaN
// +infinity + +infinity = +infinity
// +infinity - -infinity = +infinity
// -infinity + -infinity = -infinity
// -infinity - +infinity = -infinity
// +-infinity * +-infinity = +-infinity
// +-FINITE * +-infinity = +-infinity
// +-NON_ZERO / +-0 = +-infinity
// +-FINITE / +-infinity = +-0
//
// WHY NaN or infinity values can't happen in our code, except it truly exceptional, almost adversarial conditions:
// - once we get a NaN value in almost any computation, even for a single sample's score, it'll
// spread through our system like a wildfire making everything NaN
// - once we get an infinity value in almost ANY computation, even for a single sample's score,
// it'll turn into a NaN soon, and then everything will become a NaN
// - so, to evaluate the possibility of NaN or infinity values, we need to look everywhere that could generates
// such values [see table of operations above that can these values]
// - Generally, the reason why in practice we never see NaN or infinity values is that the boosting algorithm
// tends to push errors towards zero, and in the places where it's pushing towards infinity, like for exp(logits),
// it does so slowly enough that we shouldn't reach infinity in semi-reasonable numbers of boosting rounds.
// We can also further dissuade this from occurring by clipping the logits to reasonable positive or negative values
// that don't exceed the 1/n_samples ranges where we can't really make any kinds of predictions anyways.
// - looking purely at operators, NaN or infinity values in our code could be introduced in these places:
// - In regression, if the user passes us NaN or +-infinity as one of the regression targets. This is
// almost the only legitimate way to reach +-infinity or NaN. If this occurs, we'll get a mean squared
// error of +infinity on our FIRST attempt at boosting. We can detect the overflow of +infinity in our
// caller and alert the user to the overflow. This will also cover the case where mean squared error
// overflows more gradually during the training. Even though this is a legitimate overflow, the user
// really needs to do something to handle the condition since there isn't really much that we can do with
// such large numbers, so pushing the error back to them is the best solution anyways.
// If we really wanted to, we could eliminate all errors from large regression targets by limiting the
// user to a maximum regression target value (of 7.2e+134) if FloatEbmType is a float64 and much less for float32
// - In regression, if the user gives us regression targets (either positive or negative) with absolute
// values greater than sqrt(std::numeric_limits<FloatEbmType>::max()), or if several rounds of boosting
// leads to large square errors, then we'll overflow to +infinity in
// ComputeSingleSampleSquaredErrorRegressionFromGradient. This won't infect any of our existing training sample
// scores, or model graphs, but it will lead to us returning to our caller a +infinity mean squared
// error value. The normal response to any big mean squared error would be for our caller to terminate
// via early stopping, which is a fine outcome. If the caller ignores the +infinity mean squared error,
// then they can continue to boost without issues, although all the validation scores will end up as NaN.
// Our caller can detect the +infinity means squared error themselves and optionally throw a nice
// exception plus a message for the end user so that they understand what happened. The user just needs to
// not give us such high regression targets. If we really wanted to, we could eliminate this error by
// limiting the user to a maximum regression target value. The maximum value would be:
// sqrt(std::numeric_limits<FloatEbmType>::max()) / 2^64 = 7.2e+134 for float64 and much less for float32.
// Since there must be less than 2^64 samples, the square of that number occurring 2^64 times won't overflow
// a double
// - In regression, if the user gives us regression targets (either positive or negative) with values below
// but close to +-std::numeric_limits<FloatEbmType>::max(), the sumGradient can reach +-infinity
// since they are a sum. After sumGradient reaches +-infinity, we'll get a graph update with a
// +infinity, and some samples with +-infinity scores. Then, on the next feature that we boost on,
// we'll calculate a model update for some samples inside ComputeSinglePartitionUpdate
// as +-infinity/sumHessian, which will be +-infinity (of the same sign). Then, when we go to calculate
// our new sample scores, we'll subtract +infinity-(+infinity) or -infinity-(-infinity), which will
// result in NaN. After that, everything melts down to NaN. The user just needs to not give us such
// high regression targets. If we really wanted to, we could eliminate all errors from large regression
// targets by limiting the user to a maximum regression target value (of 7.2e+134)
// - In multiclass, in TransformScoreToGradientMulticlass, we could get either NaN or +infinity if sumExp was 0
// in the division "ourExp / sumExp", (NaN occurs if ourExp was also zero). This could in theory only
// occur in multiclass if all the logits were very very negative. e^(very_big_negative_logit) = 0.
// This is VERY VERY unlikely in any normal dataset because all the logits would need to be very very negative.
// Logits in multiclass move in opposite directions while training, so having all logits very negative
// shouldn't occur, except possibly in exceptionally contrived situations with extreme logits at
// initialization. Our higher level caller though should be getting the initialization logits from previous
// boosting using this code, so this shouldn't happen if this code doesn't return such values, which is true.
// - In multiclass, In TransformScoreToGradientMulticlass NaN can come from infinity/infinity, which can happen
// if any of the e^logits terms reach close to infinity. Doubles have a max value around 1.8e308,
// and ln(1.8e308) = approx +709.79, so if any logit reaches above 709 we could have a problem.
// If ANY logit in any class reaches this high, we should get such a result. We should also get this
// result if the sum of a couple very big logits overflows, but the sum would require the terms to be in
// the same neighborhood of logits with values around 709, like two with 708, etc.
// BUT, reaching logits in the range of 709 is almost impossible without adversarial inputs since boosting
// will always be working hard to push the error toward zero on the training set.
// MORE INFO on why logits of 709 are virtually impossible:
// For computing the model update, when gradient is close to zero, at the limit the sums used in the
// model update of sumGradients/sumHessians are mathematically at worst +-1 (before applying the learningRate):
// Segment_model_update = sumGradients / sumHessians =>
// gradient / [gradient * (1 - gradient)] => gradient / [gradient * (1)] => 1
// When our predictor is very certain, but wrong, we get gradients like -1, and 1. In those
// cases we have a big numerator (relatively) and a small denominator, so those cases are weighted extra heavily,
// and are weighted much higher than +-1. The overall effect is that we train more on the errors, but
// in these cases the movement is opposite to the existing value, so high positive numbers become more
// negative, and vise versa, so they act in a restorative way and don't contribute to runaway logits.
// For wrong predictions: Update = sumGradient / sumHessian => +-1 / [1 * (1 - 1)] =>
// +-1 / 0 => +-infinity but the algorithm will fight against +-infinity since it won't let the gradient
// values get too large before it aggressively corrects them back in the direction of zero. If the logits
// are traveling in the correct direction, then the logit updates will go down to +-1. Then, we apply the
// learningRate, which is by default 0.01. If those values hold, then the post-learningRate update is a
// maximum of +-0.01, and it will take around 70,900 rounds of boosting for the logit to reach the 709
// neighbourhood. Our default number of rounds is 5000, so we won't get close under normal parameters.
// - For multiclass, in theory, if we got a big number of +-infinity as a logit update, we could
// overflow a section of the graph. We'll hit overflows inside TransformScoreToGradientMulticlass though
// first when the logits get to 709-ish numbers, so it isn't really possible for the logits themselves
// to overflow first to +-infinity in the graphs for multiclass
// - For binary and multiclass classification, log loss can reach infinity if we are very certain of one or
// more predictions which are incorrectly predicted in the validation set. This is almost impossible to
// occur in real datasets, since log loss will be going up before we reach infinity, so if our caller is
// using early stopping, then they'll terminate the learning beforehand.
// It could happen though if the caller doesn't have early stopping, or specifies an exact number of
// boosting rounds. In any case, we might want to limit probabilities to within 1/number_of_samples since
// we want to avoid scenarios that completely blow up and exit early
// - For binary and multiclass classification, ComputeSinglePartitionUpdate has a
// division that can overflow to infinity or NaN values making the logits in our graph infinity or NaN.
// - for any learning, adversarial inputs like ridiculously huge learningRate parameters or NaN values
// could cause these conditions
// - In InverseLinkFunctionThenCalculateGradientBinaryClassification, the exp term could get to zero or +infinity, but division
// by infinity leads to zero, so this shouldn't propagate the infinity term, or create new NaN values.
// Even if our logits reached +-infinity InverseLinkFunctionThenCalculateGradientBinaryClassification should
// return valid numbers
// - if our boosting code gets passed NaN or +-infinity values as predictor scores
// (regression predictions or logits) Normally, our higher level library (python, R, etc..) calculates
// the predictor scores based on prior boosting rounds from within this core library. So we shouldn't
// get such extreme values unless this C++ code generates NaN, or +-infinities,
// and we've shown above that this is very unlikely for non-adversarial inputs.
// - Even before our first e^logit reaches +infinity, we might get a scenario where none of the e^logits
// are infinity yet, BUT the sum reaches infinity and in that case we'll get BIG_NUMBER/infinity,
// which will be zero, which is the opposite of the mathematical result we want of BIG_NUMBER/BIG_NUMBER,
// which should be 1, and it will therefore drive that gradient and logit update in the wrong direction,
// so if we ever see an infinity in any multiclass denominator term, we're already in a bad situation.
// There is a solution where we could subtract a constant from all the multiclass logits, or make the highest
// one equal to zero and keep the rest as negative values, which is mathematical no-op, but... why?
//
// - ComputeSinglePartitionUpdate will end with a divide by zero if the hessian is zero.
// The hessian can be zero if the gradient is +-1. For binary classification, if 1 + ? = 1, due to
// numeracy issues, then the denominator term in InverseLinkFunctionThenCalculateGradientBinaryClassification will be one,
// leading to numeracy issues later on due to the 1. Epsilon is the smallest number that you can
// add to 1 and get a non-1. For doubles epsilon is 2.2204460492503131e-016. e^-36.043 and with an
// update rate of 0.01, that means around 3604 rounds of boosting. We're still good given that our default
// is a max of 5000 boosting rounds. Multiclass has the same issues in summing the e^logit values.
// - there is an asymmetry between small logits and large ones. Only small ones lead to a problem because
// for 1 + ?, the ? needs to be small so that the result is 1. With big values we get a 1/big_value, which is
// ok since there is more resolution for floating points around zero. For binary classification we can
// flip the sign of the logits and make large ones small and small ones large somehow since they are the reciprocal,
// but we'd rather not add more computation for that.
// - after we've decided on a model update, we can check to see what the probability predicted would be with
// just this 1 feature (we'd need to know the intercept if we wanted to do this better) and if that probability
// was beyond the 1/number_of_samples or (number_of_samples-1)/number_of_samples probability range, then we can
// be pretty confident that the algorithm is being wildly optimistic, since we have insufficient data to
// determine a probability that extreme. So, we can look at the existing feature logits, and calculate if
// any individual bin logit plus the logit update exceeds that probability, and then we can trim the update
// logit such that the total never goes above that maximum value. This isn't really for avoiding +-infinity or NaN
// values completely, but it helps. This is to ensure that we don't terminate the algorithm prematurely
// for a single case that isn't being predicted well due to runaway logits in the training set where there are
// no samples of a particular class in a bin. By limiting beyond 1/number_of_samples probabilities
// we won't get completely wild in predicting samples in the validation set.
// - for binary classification, we can just check that the absolute value of the logit doesn't exceed
// either +-std::log(1/sumHessian), and if it does we can just reduce it to that value.
// - for multiclass, the correction is a bit harder. We'd prefer not needing to calculate the true probability
// of each class, but we can do an approximate job in logit space. First off, there can only be one class
// with a big probability at a time, so we first need to find out if any item exceeds (sumHessian - 1) / sumHessian
// probability. For the biggest probability, the only two values that matter are the biggest and second
// biggest logits. Reduce the biggest probability so that it doesn't exceed the second biggest probability
// by std:log(1/sumHessian). There can be unlimited items with probabilities that are too low. After fixing
// the biggest probability, we need to check to see if any of these are too low. If any are lower than
// std:log(1/sumHessian) from the max logit, the raise them to that level.
// - even though multiclass logits won't average to zero, we can be somewhat confident that none of them will
// change by more than learingRate logits per boosting round, so they can't diverge to more than 709 logits
// difference for at least 70,900/2=35,400 rounds. That's still acceptable.
// - probably the first place we'll get an issue is for multiclass, where we might get one logit that
// causes e^logit to be large enough that adding all the other e^logit values doesn't add anything to
// the higher e^logit value. Once that happens, then we'll get e^logit/e^logit = 1, then our... TODO complete
// - from conversation with Rich, we don't really know how to do Laplacian smoothing on boosted decision trees,
// and it's done post process anyways, so wouldn't help during tree building. It would apply a skew to the
// updates if used during training.
// - EVEN with all of these precautions though, a malicious user could create a training set such that
// many individual features could have high logits, and then they could create an exceptional validation
// sample that was the opposite of what's in the training data for every such feature. As we add the
// logits together we could then reach a number greater than 709, and overflow double at e^709.
// - to guard against adversarial datasets like this, we can just accept that we might get +-infinity
// and then NaN, and just report those extreme results back to the caller, or we could put in a
// per-sample logit maximum. Checking for these extreme logits per sample seems unreasonable given that
// it's hard to imagine this happening on a real dataset, so for now we'll just accept that we might
// hit +-infinity, or NaN and then report odd results. Also, getting to this point would require
// 70,900 rounds of boosting!
// - when we have a bin with zero samples of a particular class, we might get some interesting results. This needs
// more exploration (TODO, explore this)
// - In the future (TODO: this needs to be completed) we're going to only update a feature_group update when
// it improves the overall log loss, so bins with low counts of a class won't be able to hijack the algorithm
// as a whole since the algorithm will just turn off feature_groups with bad predictions for the validation set
// - useful resources:
// - comparing floats -> https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
// - details on float representations -> https://www.volkerschatz.com/science/float.html
// - things that are guaranteed and not -> https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
//
// Other issues:
// - if we have large numbers of samples, around 2^53 (lookup the exact number), then we can get to the point
// were "N + 1" results in "N", since the next expressible number above "N" is "N + 2". We can get to this
// point with sufficient numbers of samples in the histogram generator. To combat this, if we break the
// histogram generation in separate work items less than a certain size, we can then merge the resulting histograms
// which would sidestep the issue since we'd never be adding 1 to a number that was fairly small.
class EbmStats final {
public:
EbmStats() = delete; // this is a static class. Do not construct
INLINE_ALWAYS static FloatEbmType CalculateHessianFromGradientBinaryClassification(const FloatEbmType gradient) {
// this function IS performance critical as it's called on every sample * cClasses * cInnerBags
// normally you would calculate the hessian from the class probability, but for classification it's possible
// to calculate from the gradient since our gradient is (r - p) where r is either 0 or 1, and our
// hessian is p * (1 - p). By taking the absolute value of (r - p) we're at a positive distance from either
// 0 or 1, and then we flip sides on "p" and "(1 - p)". For binary classification this is useful since
// we can calcualte our gradient directly in a more exact way (especially when approximates are involved)
// and then calculate the hessian without subtracting from 1, which also introduces unbalanced floating point
// noise, unlike the more balanaced approach we're taking here
// gradient can be NaN -> We can get a NaN result inside ComputeSinglePartitionUpdate
// for sumGradient / sumHessian if both are zero. Once one segment of one graph has a NaN logit, then some sample will have a NaN
// logit, and InverseLinkFunctionThenCalculateGradientBinaryClassification will return a NaN value. Getting both sumGradient and sumHessian to zero is hard.
// sumGradient can always be zero since it's a sum of positive and negative values sumHessian is harder to get to zero,
// since it's a sum of positive numbers. The sumHessian is the sum of values returned from this function. gradient
// must be -1, 0, or +1 to make the denominator zero. -1 and +1 are hard, but not impossible to get to with really bad inputs,
// since boosting tends to push errors towards 0. An error of 0 is most likely when the hessian term in either
// InverseLinkFunctionThenCalculateGradientBinaryClassification or TransformScoreToGradientMulticlass becomes close to epsilon. Once that happens
// for InverseLinkFunctionThenCalculateGradientBinaryClassification the 1 + epsilon = 1, then we have 1/1, which is exactly 1, then we subtract 1 from 1.
// This can happen after as little as 3604 rounds of boosting, if learningRate is 0.01, and every boosting round we update by the limit of
// 0.01 [see notes at top of EbmStats.h]. It might happen for a single sample even faster if multiple variables boost the logit
// upwards. We just terminate boosting after that many rounds if this occurs.
// gradient CANNOT be +-infinity -> even with an +-infinity logit, see InverseLinkFunctionThenCalculateGradientBinaryClassification and TransformScoreToGradientMulticlass
// for binary classification, -1 <= gradient && gradient <= 1 -> see InverseLinkFunctionThenCalculateGradientBinaryClassification
// for multiclass, -1 - k_epsilonGradient <= gradient && gradient <= 1 -> see TransformScoreToGradientMulticlass
// propagate NaN or deliver weird results if NaNs aren't properly propaged. This is acceptable considering how hard you have to
// work to generate such an illegal value, and given that we won't crash
EBM_ASSERT(
std::isnan(gradient) ||
!std::isinf(gradient) && FloatEbmType { -1 } - k_epsilonGradient <= gradient && gradient <= FloatEbmType { 1 }
);
// this function pre-computes a portion of an equation that we'll use later. We're computing it now since we can share
// the work of computing it between inner bags. It's not possible to reason about this function in isolation though.
// Here are the responses for various inputs for this function (but this function in isolation isn't useful):
// -1 -> 0
// -0.999 -> 0.000999
// -0.5 -> 0.25
// -0.001 -> 0.000999
// 0 -> 0
// +0.001 -> 0.000999
// +0.5 -> 0.25
// +0.999 -> 0.000999
// +1 -> 0
// when we use this hessian term retuned inside ComputeSinglePartitionUpdate, if there was only
// a single hessian term, or multiple similar ones, at the limit we'd get the following for the following inputs:
// boosting is working propertly and we're close to zero error:
// - slice_model_update = sumGradient / sumHessian => gradient / [gradient * (1 - gradient)] =>
// gradient / [gradient * (1)] => +-1 but we multiply this by the learningRate of 0.01 (default), to get +-0.01
// when boosting is making a mistake, but is certain about it's prediction:
// - slice_model_update = sumGradient / sumHessian => gradient / [gradient * (1 - gradient)] => +-1 / [1 * (0)] =>
// +-infinity
// but this shouldn't really happen inside the training set, because as the error gets bigger our boosting algorithm will correct corse by
// updating in the opposite direction. Divergence to infinity is a possibility in the validation set, but the training set pushes it's error to
// zero. It may be possible to construct an adversarial dataset with negatively correlated features that cause a bouncing around that leads to
// divergence, but that seems unlikely in a normal dataset
// our resulting function looks like this:
//
// small_model_update
// | *
// | *
// | *
// | *
// | *
// 0.01|*
// |
// -1-------------1--- gradient
// |
// *|-0.01
// * |
// * |
// * |
// * |
// * |
//
// We have +-infinity asympotes at +-1
// We have a discontinuity at 0, where we flip from positive to negative
// the overall effect is that we train more on errors (error is +-1), and less on things with close to zero error
// !!! IMPORTANT: Newton-Raphson step, as illustrated in Friedman's original paper (https://statweb.stanford.edu/~jhf/ftp/trebst.pdf, page 9). Note that
// they are using t * (2 - t) since they have a 2 in their objective
const FloatEbmType absGradient = std::abs(gradient); // abs will return the same type that it is given, either float or double
const FloatEbmType hessian = absGradient * (FloatEbmType { 1 } - absGradient);
// - it would be somewhat bad if absGradient could get larger than 1, even if just due to floating point error reasons,
// since this would flip the sign on ret to negative. Later in ComputeSinglePartitionUpdate,
// The sign flip for ret will cause the update to be the opposite from what was desired. This should only happen
// once we've overflowed our boosting rounds though such that 1 + epsilon = 1, after about 3604 boosting rounds
// At that point, undoing one round of boosting isn't going to hurt.
// the maximum return value occurs when gradient is 0.5 (which is exactly representable in floating points), which gives 0.25
// 0.25 has an exact representations in floating point numbers, at least in IEEE 754, which we statically check for at compile time
// I don't think we need an espilon at the top figure. Given that all three numbers invovled (0.5, 1, 0.25) have exact representations,
// we should get the exact return of 0.25 for 0.5, and never larger than 0.25
// IEEE 754 guarantees that these values have exact representations AND it also guarantees that the results of addition and multiplication
// for these operations are rounded to the nearest bit exactly, so we shouldn't be able to get anything outside of this range.
// our input allows values slightly larger than 1, after subtracting 1 from 1 + some_small_value, we can get a slight negative value
// when we get to this point, we're already in a position where we'll get a NaN or infinity or something else that will stop boosting
// with our abs inputs confined to the range of -k_epsilonGradient -> 1, we can't get a new NaN value here, so only check against propaged NaN
// values from gradient
EBM_ASSERT(std::isnan(gradient) || !std::isinf(hessian) && -k_epsilonGradient <= hessian && hessian <= FloatEbmType { 0.25 });
return hessian;
}
INLINE_ALWAYS static FloatEbmType CalcPartialGain(const FloatEbmType sumGradient, const FloatEbmType sumHessian) {
// typically this is not performance critical, unless the caller has a very large number of bins
// This gain function used to determine splits is equivalent to minimizing sum of squared error SSE, which
// can be seen following the derivation of Equation #7 in Ping Li's paper -> https://arxiv.org/pdf/1203.3491.pdf
EBM_ASSERT(FloatEbmType { 0 } < k_hessianMin);
const FloatEbmType partialGain = UNLIKELY(sumHessian < k_hessianMin) ?
FloatEbmType { 0 } : sumGradient / sumHessian * sumGradient;
// This function should not create new NaN values, but if either sumGradient or sumHessian is a NaN then the
// result will be a NaN. This could happen for instance if large value samples added to +inf in one bin and -inf
// in another bin, and then the two bins are added together. That would lead to NaN even without NaN samples.
EBM_ASSERT(std::isnan(sumGradient) || std::isnan(sumHessian) || FloatEbmType { 0 } <= partialGain);
return partialGain;
}
INLINE_ALWAYS static FloatEbmType CalcPartialGainFromUpdate(const FloatEbmType update, const FloatEbmType sumHessian) {
// the update is: sumGradient / sumHessian
// For gain we want sumGradient * sumGradient / sumHessian
// we can get there by doing: update * update * sumHessian
// which can be simplified as: (sumGradient / sumHessian) * (sumGradient / sumHessian) * sumHessian
// and then: (sumGradient / sumHessian) * sumGradient
// finally: sumGradient * sumGradient / sumHessian
EBM_ASSERT(FloatEbmType { 0 } < k_hessianMin);
const FloatEbmType partialGain = UNLIKELY(sumHessian < k_hessianMin) ?
FloatEbmType { 0 } : update * update * sumHessian;
EBM_ASSERT(std::isnan(update) || std::isnan(sumHessian) || FloatEbmType { 0 } <= partialGain);
return partialGain;
}
WARNING_PUSH
WARNING_DISABLE_POTENTIAL_DIVIDE_BY_ZERO
INLINE_ALWAYS static FloatEbmType ComputeSinglePartitionUpdate(
const FloatEbmType sumGradient,
const FloatEbmType sumHessian
) {
// this is NOT a performance critical function. It only gets called AFTER we've decided where to split, so only a few times per Boosting step
// for regression, sumGradient can be NaN -> if the user gives us regression targets (either positive or negative) with values below but close to
// +-std::numeric_limits<FloatEbmType>::max(), the sumGradient can reach +-infinity since they are a sum.
// After sumGradient reaches +-infinity, we'll get a graph update with a +infinity, and some samples with +-infinity scores
// Then, on the next feature that we boost on, we'll calculate a model update for some samples
// inside ComputeSinglePartitionUpdate as +-infinity/sumHessian, which will be +-infinity (of the same sign).
// Then, when we go to calculate our new sample scores, we'll subtract +infinity-(+infinity) or -infinity-(-infinity),
// which will result in NaN. After that, everything melts down to NaN. The user just needs to not give us such high regression targets.
// If we really wanted to, we could eliminate all errors from large regression targets by limiting the user to a maximum regression target value
// (of 7.2e+134)
// for classification, sumGradient can be NaN -> We can get a NaN result inside ComputeSinglePartitionUpdate
// for sumGradient / sumHessian if both are zero. Once one segment of one graph has a NaN logit, then some sample will have a NaN
// logit, and InverseLinkFunctionThenCalculateGradientBinaryClassification will return a NaN value. Getting both sumGradient and sumHessian to zero is hard.
// sumGradient can always be zero since it's a sum of positive and negative values sumHessian is harder to get to zero,
// since it's a sum of positive numbers. The sumHessian is the sum of values returned from this function. gradient
// must be -1, 0, or +1 to make the denominator zero. -1 and +1 are hard, but not impossible to get to with really inputs,
// since boosting tends to push errors towards 0. An error of 0 is most likely when the denominator term in either
// InverseLinkFunctionThenCalculateGradientBinaryClassification or TransformScoreToGradientMulticlass becomes close to epsilon. Once that happens
// for InverseLinkFunctionThenCalculateGradientBinaryClassification the 1 + epsilon = 1, then we have 1/1, which is exactly 1, then we subtract 1 from 1.
// This can happen after as little as 3604 rounds of boosting, if learningRate is 0.01, and every boosting round we update by the limit of
// 0.01 [see notes at top of EbmStats.h]. It might happen for a single sample even faster if multiple variables boost the logit
// upwards. We just terminate boosting after that many rounds if this occurs.
// for regression, sumGradient can be any legal value, including +infinity or -infinity
//
// for classification, sumGradient CANNOT be +-infinity-> even with an +-infinity logit, see InverseLinkFunctionThenCalculateGradientBinaryClassification and TransformScoreToGradientMulticlass
// also, since -cSamples <= sumGradient && sumGradient <= cSamples, and since cSamples must be 64 bits or lower, we cann't overflow
// to infinity when taking the sum
// for regression, sumHessian can be NaN -> sumHessian is calculated from gradient. Since gradient can be NaN (as described above), then
// sumHessian can be NaN
// for classification, sumHessian cannot be infinity -> per the notes in CalculateHessianFromGradientBinaryClassification
// since this is classification, -cSamples <= sumGradient && sumGradient <= cSamples
//EBM_ASSERT(!std::isinf(sumGradient)); // a 64-bit number can't get a value larger than a double to overflow to infinity
// since this is classification, 0 <= sumHessian && sumHessian <= 0.25 * cSamples (see notes in CalculateHessianFromGradientBinaryClassification),
// so sumHessian can't be infinity
//EBM_ASSERT(!std::isinf(sumHessian)); // a 64-bit number can't get a value larger than a double to overflow to infinity
// sumHessian can be very slightly negative, for floating point numeracy reasons. On the face, this is bad because it flips the direction
// of our update. We should only hit this condition when our error gets so close to zero that we should be hitting other numeracy issues though
// and even if it does happen, it should be EXTREMELY rare, and since we're using boosting, it will recover the lost round next time.
// Also, this should only happen when we are at an extremem logit anyways, and going back one step won't hurt anything. It's not worth
// the cost of the comparison to check for the error condition
//EBM_ASSERT(std::isnan(sumHessian) || -k_epsilonGradient <= sumHessian);
// sumGradient can always be much smaller than sumHessian, since it's a sum, so it can add positive and negative numbers such that it reaches
// almost zero whlie sumHessian is always positive
// sumHessian can always be much smaller than sumGradient. Example: 0.999 -> the sumHessian will be 0.000999 (see CalculateHessianFromGradientBinaryClassification)
// since the denominator term always goes up as we add new numbers (it's always positive), we can only have a zero in that term if ALL samples have
// low denominators
// the denominator can be close to zero only when gradient is -1, 0, or 1 for all cases, although they can be mixed up between these values.
// Given that our algorithm tries to drive error to zero and it will drive it increasingly strongly the farther it gets from zero,
// it seems really unlikley that we'll get a zero numerator by having a series of
// -1 and 1 values that perfectly cancel eachother out because it means they were driven to the opposite of the correct answer
// If the denominator is zero, then it's a strong indication that all the gradients are close to zero.
// if all the gradients are close to zero, then the numerator is also going to be close to zero
// So, if the sumHessian is close to zero, we can assume the sumGradient numerator will be too. At this point with all the gradients very close to zero
// we might as well stop learning on these samples and set the update to zero for this section anyways, but we don't want branches here,
// so we'll just leave it
// for Gradient regression, 1 < cSamples && cSamples < 2^64 (since it's a 64 bit integer in 64 bit address space app
//EBM_ASSERT(!std::isnan(sumHessian)); // this starts as an integer
//EBM_ASSERT(!std::isinf(sumHessian)); // this starts as an integer
// for Gradient regression, -infinity <= sumGradient && sumGradient <= infinity (it's regression which has a larger range)
// even if we trim inputs of +-infinity from the user to std::numeric_limits<FloatEbmType>::max() or std::numeric_limits<FloatEbmType>::lowest(),
// we'll still reach +-infinity if we add a bunch of them together, so sumGradient can reach +-infinity.
// After sumGradient reaches +-infinity, we'll get an update and some samples with +-infinity scores
// Then, on the next feature we boost on, we'll calculate an model update for some samples (inside this function) as
// +-infinity/sumHessian, which will be +-infinity (of the same sign). Then, when we go to find our new sample scores, we'll
// subtract +infinity-(+infinity) or -infinity-(-infinity), which will result in NaN. After that, everything melts down to NaN.
// all the weights can be zero in which case even if we have no splits our sumHessian can be zero
EBM_ASSERT(FloatEbmType { 0 } <= sumHessian);
return (FloatEbmType { 0 } == sumHessian) ? FloatEbmType { 0 } : (-sumGradient / sumHessian);
// return can be NaN if both sumGradient and sumHessian are zero, or if we're propagating a NaN value. Neither sumGradient nor
// sumHessian can be infinity, so that's not a source of NaN
// return can be infinity if sumHessian is extremely close to zero, while sumGradient is non-zero (very hard). This could happen if
// the gradient was near +-1
// return can be any other positive or negative number
}
WARNING_POP
INLINE_ALWAYS static FloatEbmType ComputeSinglePartitionUpdateGradientSum(const FloatEbmType sumGradient) {
// this is NOT a performance critical call. It only gets called AFTER we've decided where to split, so only a few times per feature_group boost
return sumGradient;
}
INLINE_ALWAYS static FloatEbmType ComputeGradientRegressionMSEInit(const FloatEbmType predictorScore, const FloatEbmType target) {
// this function is NOT performance critical as it's called on every sample, but only during initialization.
// for MSE regression, the gradient is the residual, and we can calculate it once at init and we don't need
// to keep the original scores when computing the gradient updates.
// it's possible to reach NaN or +-infinity within this module, so predictorScore can be those values
// since we can reach such values anyways, we might as well not check for them during initialization and detect the
// NaN or +-infinity values in one of our boosting rounds and then terminate the algorithm once those special values
// have propagaged, which we need to handle anyways
const FloatEbmType gradient = predictorScore - target;
// if target and predictorScore are both +infinity or both -infinity, then we'll generate a NaN value
return gradient;
}
INLINE_ALWAYS static FloatEbmType ComputeGradientRegressionMSEFromOriginalGradient(const FloatEbmType originalGradient, const FloatEbmType modelUpdate) {
// this function IS performance critical as it's called on every sample
// for MSE regression, the gradient is the residual, and we can calculate it once at init and we don't need
// to keep the original scores when computing the gradient updates, so we only need the previous gradient
// originalGradient can be +-infinity, or NaN. See note in ComputeSinglePartitionUpdate
// this function is here to document where we're calculating regression, like InverseLinkFunctionThenCalculateGradientBinaryClassification below. It doesn't do anything,
// but it serves as an indication that the calculation would be placed here if we changed it in the future
return originalGradient + modelUpdate;
}
INLINE_ALWAYS static FloatEbmType InverseLinkFunctionThenCalculateGradientBinaryClassification(
const FloatEbmType predictorScore,
const size_t target
) {
// this IS a performance critical function. It gets called per sample!
// predictorScore can be NaN -> We can get a NaN result inside ComputeSinglePartitionUpdate
// for sumGradient / sumHessian if both are zero. Once one segment of one graph has a NaN logit, then some sample will have a NaN
// logit
// predictorScore can be +-infinity -> we can overflow to +-infinity
EBM_ASSERT(0 == target || 1 == target);
// this function outputs 0 if we perfectly predict the target with 100% certainty. To do so, predictorScore would need to be either
// infinity or -infinity
// this function outputs 1 if actual value was 1 but we incorrectly predicted with 100% certainty that it was 0 by having
// predictorScore be -infinity
// this function outputs -1 if actual value was 0 but we incorrectly predicted with 100% certainty that it was 1 by having predictorScore
// be infinity
//
// this function outputs 0.5 if actual value was 1 but we were 50%/50% by having predictorScore be 0
// this function outputs -0.5 if actual value was 0 but we were 50%/50% by having predictorScore be 0
// TODO : In the future we'll sort our data by the target value, so we'll know ahead of time if 0 == target. We expect 0 to be the
// default target, so we should flip the value of predictorScore so that we don't need to negate it for the default 0 case
// TODO: we can probably remove the negation on 1 == target via : return binned_actual_value - 1 + (1 / (np.exp(training_log_odds_prediction) + 1))
// once we've moved to sorted training data
// exp will return the same type that it is given, either float or double
// TODO: for the ApproxExp function, we can change the constant to being a negative once we change to sorting by our target value
// then we don't need to even take the negative of predictorScore below
// !!! IMPORTANT: when using an approximate exp function, the formula used to compute the gradients becomes very
// important. We want something that is balanced from positive to negative, which this version
// does IF the classes are roughly balanced since the positive or negative value is
// determined by only the target, unlike if we used a forumala that relied
// on the exp function returning a 1 at the 0 value, which our approximate exp does not give
// In time, you'd expect boosting to make targets with 0 more negative, leading to a positive
// term in the exp, and targets with 1 more positive, leading to a positive term in the exp
// So both classes get the same treatment in terms of errors in the exp function (both in the
// positive domain)
// We do still want the error of the positive cases and the error of the negative cases to
// sum to zero in the aggregate, so we want to choose our exp function to have average error
// sums of zero.
// I've made a copy of this formula as a comment to reference to what is good in-case the
// formula is changed in the code without reading this comment
// const FloatEbmType gradient = (UNPREDICTABLE(0 == target) ? FloatEbmType { -1 } : FloatEbmType { 1 }) / (FloatEbmType { 1 } + ExpForBinaryClassification(UNPREDICTABLE(0 == target) ? -predictorScore : predictorScore));
// !!! IMPORTANT: SEE ABOVE
const FloatEbmType gradient = (UNPREDICTABLE(0 == target) ? FloatEbmType { 1 } : FloatEbmType { -1 }) / (FloatEbmType { 1 } +
ExpForBinaryClassification<false>(UNPREDICTABLE(0 == target) ? -predictorScore : predictorScore));
// exp always yields a positive number or zero, and I can't imagine any reasonable implementation that would violate this by returning a negative number
// given that 1.0 is an exactly representable number in IEEE 754, I can't see 1 + exp(anything) ever being less than 1, even with floating point jitter
// again, given that the numerator 1.0 is an exactly representable number, I can't see (+-1.0 / something_1_or_greater) ever having an absolute value
// above 1.0 especially, since IEEE 754 guarnatees that addition and division yield numbers rounded correctly to the last binary decimal place
// IEEE 754, which we check for at compile time, specifies that +-1/infinity = 0
// gradient cannot be +-infinity -> even if predictorScore is +-infinity we then get +-1 division by 1, or division by +infinity, which are +-1
// or 0 respectively
// gradient can only be NaN if our inputs are NaN
// So...
EBM_ASSERT(std::isnan(predictorScore) || !std::isinf(gradient) && FloatEbmType { -1 } <= gradient && gradient <= FloatEbmType { 1 });
// gradient can't be +-infinity, since an infinity in the denominator would just lead us to zero for the gradient value!
#ifndef NDEBUG
const FloatEbmType expVal = std::exp(predictorScore);
FloatEbmType gradientDebug;
FloatEbmType hessianDebug;
InverseLinkFunctionThenCalculateGradientAndHessianMulticlass(FloatEbmType { 1 } + expVal, expVal, target, 1, gradientDebug, hessianDebug);
// the TransformScoreToGradientMulticlass can't be +-infinity per notes in TransformScoreToGradientMulticlass,
// but it can generate a new NaN value that we wouldn't get in the binary case due to numeric instability issues with having multiple logits
// if either is a NaN value, then don't compare since we aren't sure that we're exactly equal in those cases because of numeric instability reasons
EBM_ASSERT(std::isnan(predictorScore) || std::isnan(gradientDebug) || std::abs(gradientDebug - gradient) < k_epsilonGradientForBinaryToMulticlass);
#endif // NDEBUG
return gradient;
}
INLINE_ALWAYS static void InverseLinkFunctionThenCalculateGradientAndHessianMulticlass(
const FloatEbmType sumExp,
const FloatEbmType itemExp,
const size_t target,
const size_t iVector,
FloatEbmType & gradientOut,
FloatEbmType & hessianOut
) {
// this IS a performance critical function. It gets called per sample AND per-class!
// trainingLogWeight (which calculates itemExp) can be NaN -> We can get a NaN result inside ComputeSinglePartitionUpdate
// for sumGradient / sumHessian if both are zero. Once one segment of one graph has a NaN logit, then some sample will have a NaN
// logit
// trainingLogWeight (which calculates itemExp) can be any number from -infinity to +infinity -> through addition, it can overflow to +-infinity
// sumExp can be NaN -> predictorScore is used when calculating sumExp, so if predictorScore can be NaN, then sumExp can be NaN
// sumExp can be any number from 0 to +infinity -> each e^logit term can't be less than zero, and I can't imagine any implementation
// that would result in a negative exp result from adding a series of positive values.
EBM_ASSERT(std::isnan(sumExp) || FloatEbmType { 0 } <= sumExp);
// itemExp can be anything from 0 to +infinity, or NaN (through propagation)
EBM_ASSERT(std::isnan(itemExp) || FloatEbmType { 0 } <= itemExp); // no reasonable implementation should lead to a negative exp value
// mathematically sumExp must be larger than itemExp BUT in practice itemExp might be SLIGHTLY larger due to numerical issues ->
// since sumExp is a sum of positive terms that includes itemExp, it cannot be lower mathematically.
// sumExp, having been computed from non-exact floating points, could be numerically slightly outside of the range that we would otherwise
// mathematically expect. For sample, if EbmExp(trainingLogWeight) resulted in a number that rounds down, but the floating point processor
// preserves extra bits between computations AND if sumExp, which includes the term EbmExp(trainingLogWeight) was rounded down and then subsequently
// added to numbers below the threshold of epsilon at the value of EbmExp(trainingLogWeight), then by the time we get to the division of
// EbmExp(trainingLogWeight) / sumExp could see the numerator as higher, and result in a value slightly greater than 1!
EBM_ASSERT(std::isnan(sumExp) || itemExp - k_epsilonGradient <= sumExp);
const FloatEbmType probability = itemExp / sumExp;
// probability can be NaN ->
// - If itemExp AND sumExp are exactly zero or exactly infinity then itemExp / sumExp will lead to NaN
// - If sumExp is zero, then itemExp pretty much needs to be zero, since if any of the terms in the sumation are
// larger than a fraction. It is very difficult to see how sumExp could be 0 because it would require that we have 3 or more logits that have
// all either been driven very close to zero, but our algorithm drives multiclass logits appart from eachother, so some should be positive, and
// therefor the exp of those numbers non-zero
// - it is possible, but difficult to see how both itemExp AND sumExp could be infinity because all we need is for itemExp to be greater than
// about 709.79. If one itemExp is +infinity then so is sumExp. Each update is mostly limited to units of 0.01 logits
// (0.01 learningRate * 1 from InverseLinkFunctionThenCalculateGradientBinaryClassification or TransformScoreToGradientMulticlass), so if we've done more than 70,900 boosting
// rounds we can get infinities or NaN values. This isn't very likekly by itself given that our default is a max of 2000 rounds, but it is possible
// if someone is tweaking the parameters way past their natural values
// probability can be SLIGHTLY larger than 1 due to numeric issues -> this should only happen if sumExp == itemExp approximately, so there can be no
// other logit terms in sumExp, and this would only happen after many many rounds of boosting (see above about 70,900 rounds of boosting).
// - if probability was slightly larger than 1, we shouldn't expect a crash. What would happen is that in our next call to CalculateHessianFromGradientBinaryClassification, we
// would find our denomiator term as a negative number (normally it MUST be positive). If that happens, then later when we go to compute the
// small model update, we'll inadvertently flip the sign of the update, but since CalculateHessianFromGradientBinaryClassification was close to the discontinuity at 0,
// we know that the update should have a value of 1 * learningRate = 0.01 for default input parameters. This means that even in the very very
// very unlikely case that we flip our sign due to numericacy error, which only happens after an unreasonable number of boosting rounds, we'll
// flip the sign on a minor update to the logits. We can tollerate this sign flip and next round we're not likely to see the same sign flip, so
// boosting will recover the mistake with more boosting rounds
// probability must be positive -> both the numerator and denominator are positive, so no reasonable implementation should lead to a negative number
// probability can be zero -> sumExp can be infinity when itemExp is non-infinity. This occurs when only one of the terms has overflowed to +infinity
// probability can't be infinity -> even if itemExp is slightly bigger than sumExp due to numeric reasons, the division is going to be close to 1
// we can't really get an infinity in itemExp without also getting an infinity in sumExp, so probability can't be infinity without getting a NaN
EBM_ASSERT(std::isnan(probability) ||
!std::isinf(probability) && FloatEbmType { 0 } <= probability && probability <= FloatEbmType { 1 } + k_epsilonGradient);
const FloatEbmType yi = UNPREDICTABLE(iVector == target) ? FloatEbmType { 1 } : FloatEbmType { 0 };
// if probability cannot be +infinity, and needs to be between 0 and 1 + small_value, or NaN, then gradient can't be inifinity either
const FloatEbmType gradient = probability - yi;
// mathematicaly we're limited to the range of range 0 <= probability && probability <= 1, but with floating point issues
// we can get an probability value slightly larger than 1, which could lead to -1.00000000001-ish results
// just like for the division by zero conditions, we'd need many many boosting rounds for probability to get to 1, since
// the sum of e^logit must be about equal to e^logit for this class, which should require thousands of rounds (70,900 or so)
// also, the boosting algorthm tends to push results to zero, so a result more negative than -1 would be very exceptional
EBM_ASSERT(std::isnan(probability) || !std::isinf(gradient) && FloatEbmType { -1 } - k_epsilonGradient <= gradient && gradient <= FloatEbmType { 1 });
const FloatEbmType hessian = probability * (FloatEbmType { 1 } - probability);
gradientOut = gradient;
hessianOut = hessian;
}
INLINE_ALWAYS static FloatEbmType ComputeSingleSampleLogLossBinaryClassification(
const FloatEbmType predictorScore,
const size_t target
) {
// this IS a performance critical function. It gets called per validation sample!
// we are confirmed to get the same log loss value as scikit-learn for binary and multiclass classification
// trainingLogWeight can be NaN -> We can get a NaN result inside ComputeSinglePartitionUpdate
// for sumGradient / sumHessian if both are zero. Once one segment of one graph has a NaN logit, then some sample will have a NaN
// logit
// trainingLogWeight can be any number from -infinity to +infinity -> through addition, it can overflow to +-infinity
EBM_ASSERT(0 == target || 1 == target);
const FloatEbmType ourExp = ExpForLogLossBinaryClassification<false>(UNPREDICTABLE(0 == target) ? predictorScore : -predictorScore);
// no reasonable implementation of exp should lead to a negative value
EBM_ASSERT(std::isnan(predictorScore) || FloatEbmType { 0 } <= ourExp);
// exp will always be positive, and when we add 1, we'll always be guaranteed to have a positive number, so log shouldn't ever fail due to negative
// numbers the exp term could overlfow to infinity, but that should only happen in pathalogical scenarios where our train set is driving the logits
// one way to a very very certain outcome (essentially 100%) and the validation set has the opposite, but in that case our ultimate convergence is
// infinity anyways, and we'll be generaly driving up the log loss, so we legitimately want our loop to terminate training since we're getting a
// worse and worse model, so going to infinity isn't bad in that case
const FloatEbmType singleSampleLogLoss = LogForLogLoss<false>(FloatEbmType { 1 } + ourExp); // log & exp will return the same type that it is given, either float or double
// singleSampleLogLoss can be NaN, but only though propagation -> we're never taking the log of any number close to a negative,
// so we should only get propagation NaN values
// singleSampleLogLoss can be +infinity -> can happen when the logit is greater than 709, which can happen after about 70,900 boosting rounds
// singleSampleLogLoss always positive -> the 1 term inside the log has an exact floating point representation, so no reasonable floating point framework should
// make adding a positive number to 1 a number less than 1. It's hard to see how any reasonable log implementatation that would give a negative
// exp given a 1, since 1 has an exact floating point number representation, and it computes to another exact floating point number, and who
// would seriously make a log function that take 1 and returns a negative.
// So,
EBM_ASSERT(std::isnan(predictorScore) || FloatEbmType { 0 } <= singleSampleLogLoss); // log(1) == 0
// TODO : check our approxmiate log above for handling of 1 exactly. We might need to change the above assert to allow a small negative value
// if our approxmiate log doesn't guarantee non-negative results AND numbers slightly larger than 1
#ifndef NDEBUG
const FloatEbmType expVal = std::exp(predictorScore);
const FloatEbmType singleSampleLogLossDebug = EbmStats::ComputeSingleSampleLogLossMulticlass(
FloatEbmType { 1 } + expVal, 0 == target ? FloatEbmType { 1 } : expVal
);
EBM_ASSERT(std::isnan(singleSampleLogLoss) || std::isinf(singleSampleLogLoss) || std::isnan(singleSampleLogLossDebug) || std::isinf(singleSampleLogLossDebug) || std::abs(singleSampleLogLossDebug - singleSampleLogLoss) < k_epsilonGradientForBinaryToMulticlass);
#endif // NDEBUG
return singleSampleLogLoss;
}
INLINE_ALWAYS static FloatEbmType ComputeSingleSampleLogLossMulticlass(
const FloatEbmType sumExp,
const FloatEbmType itemExp
) {
// this IS a performance critical function. It gets called per validation sample!
// we are confirmed to get the same log loss value as scikit-learn for binary and multiclass classification
// aValidationLogWeight (calculates itemExp) numbers can be NaN -> We can get a NaN result inside ComputeSinglePartitionUpdate
// for sumGradient / sumHessian if both are zero. Once one segment of one graph has a NaN logit, then some sample will have a NaN
// logit
// aValidationLogWeight (calculates itemExp) numbers can be any number from -infinity to +infinity -> through addition, it can overflow to +-infinity
// sumExp can be NaN -> predictorScore is used when calculating sumExp, so if predictorScore can be NaN, then sumExp can be NaN
// sumExp can be any number from 0 to +infinity -> each e^logit term can't be less than zero, and I can't imagine any implementation
// that would result in a negative exp result from adding a series of positive values.
EBM_ASSERT(std::isnan(sumExp) || FloatEbmType { 0 } <= sumExp);
// validationLogWeight (calculates itemExp) can be any number between -infinity to +infinity, or NaN
// itemExp can be anything from 0 to +infinity, or NaN (through propagation)
EBM_ASSERT(std::isnan(itemExp) || FloatEbmType { 0 } <= itemExp); // no reasonable implementation of exp should lead to a negative value
// mathematically sumExp must be larger than itemExp BUT in practice itemExp might be SLIGHTLY larger due to numerical issues ->
// since sumExp is a sum of positive terms that includes itemExp, it cannot be lower mathematically.
// sumExp, having been computed from non-exact floating points, could be numerically slightly outside of the range that we would otherwise
// mathematically expect. For sample, if EbmExp(trainingLogWeight) resulted in a number that rounds down, but the floating point processor
// preserves extra bits between computations AND if sumExp, which includes the term EbmExp(trainingLogWeight) was rounded down and then subsequently
// added to numbers below the threshold of epsilon at the value of EbmExp(trainingLogWeight), then by the time we get to the division of
// EbmExp(trainingLogWeight) / sumExp could see the numerator as higher, and result in a value slightly greater than 1!
EBM_ASSERT(std::isnan(sumExp) || itemExp - k_epsilonGradient <= sumExp);
const FloatEbmType invertedProbability = sumExp / itemExp;
// invertedProbability can be NaN ->
// - If itemExp AND sumExp are exactly zero or exactly infinity then sumExp / itemExp will lead to NaN
// - If sumExp is zero, then itemExp pretty much needs to be zero, since if any of the terms in the sumation are
// larger than a fraction. It is very difficult to see how sumExp could be 0 because it would require that we have 3 or more logits that have
// all either been driven very close to zero, but our algorithm drives multiclass logits appart from eachother, so some should be positive, and
// therefore the exp of those numbers non-zero
// - it is possible, but difficult to see how both itemExp AND sumExp could be infinity because all we need is for itemExp to be greater than
// about 709.79. If one itemExp is +infinity then so is sumExp. Each update is mostly limited to units of 0.01 logits
// (0.01 learningRate * 1 from InverseLinkFunctionThenCalculateGradientBinaryClassification or TransformScoreToGradientMulticlass), so if we've done more than 70,900 boosting
// rounds we can get infinities or NaN values. This isn't very likekly by itself given that our default is a max of 2000 rounds, but it is possible
// if someone is tweaking the parameters way past their natural values
// invertedProbability can be SLIGHTLY smaller than 1 due to numeric issues -> this should only happen if sumExp == itemExp approximately, so there can be no
// other logit terms in sumExp, and this would only happen after many many rounds of boosting (see above about 70,900 rounds of boosting).
// - if invertedProbability was slightly smaller than 1, we shouldn't expect a crash. We'll get a slighly negative log, which would otherwise be impossible.
// We check this before returning the log loss to our caller, since they do not expect negative log losses.
// invertedProbability must be positive -> both the numerator and denominator are positive, so no reasonable implementation should lead to a negative number
// invertedProbability can be +infinity -> sumExp can be infinity when itemExp is non-infinity, or itemExp can be sufficiently small to cause a divide by zero.
// This occurs when only one of the terms has overflowed to +infinity
// we can tollerate numbers very very slightly less than 1. These make the log loss go down slightly as they lead to negative log
// values, but we can tollerate this drop and rely on other features for the log loss calculation
EBM_ASSERT(std::isnan(invertedProbability) || FloatEbmType { 1 } - k_epsilonLogLoss <= invertedProbability);
const FloatEbmType singleSampleLogLoss = LogForLogLoss<false>(invertedProbability);
// we're never taking the log of any number close to a negative, so we won't get a NaN result here UNLESS invertedProbability was already NaN and we're NaN
// propegating
// we're using two numbers that probably can't be represented by exact representations
// so, the fraction might be a tiny bit smaller than one, in which case the output would be a tiny
// bit negative. We can just let other subsequent adds cover this up
EBM_ASSERT(std::isnan(singleSampleLogLoss) || -k_epsilonLogLoss <= singleSampleLogLoss); // log(1) == 0
return singleSampleLogLoss;
}
INLINE_ALWAYS static FloatEbmType ComputeSingleSampleSquaredErrorRegressionFromGradient(const FloatEbmType gradient) {
// this IS a performance critical function. It gets called per validation sample!
// for MSE, the gradient is the error and we square it
// gradient can be +-infinity, or NaN. See note in ComputeSinglePartitionUpdate
// we are confirmed to get the same mean squared error value as scikit-learn for regression
return gradient * gradient;
// gradient can be anything from 0 to +infinity, or NaN
}
};
} // DEFINED_ZONE_NAME
#endif // EBM_STATS_HPP |
; A004517: Generalized nim sum n + n in base 7.
; Submitted by Jamie Morken(s3)
; 0,2,4,6,1,3,5,14,16,18,20,15,17,19,28,30,32,34,29,31,33,42,44,46,48,43,45,47,7,9,11,13,8,10,12,21,23,25,27,22,24,26,35,37,39,41,36,38,40,98,100,102,104,99,101,103,112
mov $3,1
lpb $0
mov $2,$0
div $0,7
mul $2,9
mod $2,7
mul $2,$3
add $1,$2
mul $3,7
lpe
mov $0,$1
|
; A316627: a(1)=2, a(2)=3; a(n) = a(n+1-a(n-1))+a(n-a(n-2)) for n > 2.
; Submitted by Jamie Morken(w4)
; 2,3,4,4,5,6,6,7,8,8,8,9,10,10,11,12,12,12,13,14,14,15,16,16,16,16,17,18,18,19,20,20,20,21,22,22,23,24,24,24,24,25,26,26,27,28,28,28,29,30,30,31,32,32,32,32,32,33,34,34,35,36,36,36,37,38,38,39,40,40,40,40,41,42,42,43,44,44,44,45,46,46,47,48,48,48,48,48,49,50,50,51,52,52,52,53,54,54,55,56
add $0,1
mov $2,$0
mov $6,4
lpb $0
lpb $0,$6
mov $6,$2
lpb $0
add $6,1
sub $6,$0
div $0,2
lpe
lpe
sub $0,1
lpe
add $0,1
|
/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2021 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/base/rendering/renderabletrailorbit.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/scene/translation.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/opengl/programobject.h>
#include <numeric>
#include <optional>
// This class is using a VBO ring buffer + a constantly updated point as follows:
// Structure of the array with a _resolution of 16. FF denotes the floating position that
// is updated every frame:
// ---------------------------------------------------------------------------------
// | FF | | | | | | | | | | | | | | | |
// ---------------------------------------------------------------------------------
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// <------ newer in time oldest
//
// In the begining the floating value starts at 0; this means that array element 0 is
// updated and uploaded to the GPU at every frame. The FF+1 element is the newest fixed
// location and FF-1 element is the oldest fixed location (including wrapping around the
// array) with the times of _lastPointTime and _firstPointTime.
//
// If the time progresses forwards and abs(time - _lastPointTime) becomes big enough, the
// oldest point is removed and a new fixed location is added. In the ring buffer this
// would be represented as:
// ---------------------------------------------------------------------------------
// | | | | | | | | | | | | | | | | FF |
// ---------------------------------------------------------------------------------
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// <------ newer in time oldest
//
// Thus making the floating point traverse backwards through the array and element 0 being
// the newest fixed point. If the time processes backwards, the floating point moves
// towards the upper areas of the array instead.
// In both cases, only the values that have been changed will be uploaded to the GPU.
//
// For the rendering, this is achieved by using an index buffer that is twice the size of
// the vertex buffer containing identical two sequences indexing the vertex array.
// In an example of size 8:
// ---------------------------------------------------------------------------------------
// |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|12|13|14|15|
// ---------------------------------------------------------------------------------------
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
//
// The rendering step needs to know only the offset into the array (denoted by FF as the
// floating position above) and use the index array from the position. Since the indices
// in this array wrap around, so will the rendering of the vertices. Example:
// FF := 10
// Rendering 16 elements will 'generate' the index buffer:
// 10 11 12 13 14 15 00 01 02 03 04 05 06 07 08 09
//
//
// NB: This method was implemented without a ring buffer before by manually shifting the
// items in memory as was shown to be much slower than the current system. ---abock
namespace {
constexpr openspace::properties::Property::PropertyInfo PeriodInfo = {
"Period",
"Period (in days)",
"The objects period, i.e. the length of its orbit around the parent object given "
"in (Earth) days. In the case of Earth, this would be a sidereal year "
"(=365.242 days). If this values is specified as multiples of the period, it is "
"possible to show the effects of precession."
};
constexpr openspace::properties::Property::PropertyInfo ResolutionInfo = {
"Resolution",
"Number of samples along the orbit",
"The number of samples along the orbit. This determines the resolution of the "
"trail; the tradeoff being that a higher resolution is able to resolve more "
"detail, but will take more resources while rendering, too. The higher, the "
"smoother the trail, but also more memory will be used."
};
constexpr openspace::properties::Property::PropertyInfo RenderableTypeInfo = {
"RenderableType",
"RenderableType",
"This value specifies if the orbit should be rendered in the Background,"
"Opaque, Transparent, or Overlay rendering step. Default is Transparent."
};
struct [[codegen::Dictionary(RenderableTrailOrbit)]] Parameters {
// [[codegen::verbatim(PeriodInfo.description)]]
double period;
// [[codegen::verbatim(ResolutionInfo.description)]]
int resolution;
enum class RenderableType {
Background,
Opaque,
PreDeferredTransparent,
PostDeferredTransparent,
Overlay
};
// [[codegen::verbatim(RenderableTypeInfo.description)]]
std::optional<RenderableType> renderableType;
};
#include "renderabletrailorbit_codegen.cpp"
} // namespace
namespace openspace {
documentation::Documentation RenderableTrailOrbit::Documentation() {
documentation::Documentation doc = codegen::doc<Parameters>(
"base_renderable_renderabletrailorbit"
);
// Insert the parents documentation entries until we have a verifier that can deal
// with class hierarchy
documentation::Documentation parentDoc = RenderableTrail::Documentation();
doc.entries.insert(
doc.entries.end(),
parentDoc.entries.begin(),
parentDoc.entries.end()
);
return doc;
}
RenderableTrailOrbit::RenderableTrailOrbit(const ghoul::Dictionary& dictionary)
: RenderableTrail(dictionary)
, _period(PeriodInfo, 0.0, 0.0, 1e9)
, _resolution(ResolutionInfo, 10000, 1, 1000000)
{
const Parameters p = codegen::bake<Parameters>(dictionary);
_translation->onParameterChange([this]() { _needsFullSweep = true; });
// Period is in days
using namespace std::chrono;
_period = p.period * duration_cast<seconds>(hours(24)).count();
_period.onChange([&] { _needsFullSweep = true; _indexBufferDirty = true; });
_period.setExponent(5.f);
addProperty(_period);
_resolution = p.resolution;
_resolution.onChange([&] { _needsFullSweep = true; _indexBufferDirty = true; });
_resolution.setExponent(3.5f);
addProperty(_resolution);
// We store the vertices with (excluding the wrapping) decending temporal order
_primaryRenderInformation.sorting = RenderInformation::VertexSorting::NewestFirst;
if (p.renderableType.has_value()) {
switch (*p.renderableType) {
case Parameters::RenderableType::Background:
setRenderBin(Renderable::RenderBin::Background);
break;
case Parameters::RenderableType::Opaque:
setRenderBin(Renderable::RenderBin::Opaque);
break;
case Parameters::RenderableType::PreDeferredTransparent:
setRenderBin(Renderable::RenderBin::PreDeferredTransparent);
break;
case Parameters::RenderableType::PostDeferredTransparent:
setRenderBin(Renderable::RenderBin::PostDeferredTransparent);
break;
case Parameters::RenderableType::Overlay:
setRenderBin(Renderable::RenderBin::Overlay);
break;
default:
throw ghoul::MissingCaseException();
}
}
else {
setRenderBin(Renderable::RenderBin::Overlay);
}
}
void RenderableTrailOrbit::initializeGL() {
RenderableTrail::initializeGL();
glGenVertexArrays(1, &_primaryRenderInformation._vaoID);
glGenBuffers(1, &_primaryRenderInformation._vBufferID);
glGenBuffers(1, &_primaryRenderInformation._iBufferID);
}
void RenderableTrailOrbit::deinitializeGL() {
glDeleteVertexArrays(1, &_primaryRenderInformation._vaoID);
glDeleteBuffers(1, &_primaryRenderInformation._vBufferID);
glDeleteBuffers(1, &_primaryRenderInformation._iBufferID);
RenderableTrail::deinitializeGL();
}
void RenderableTrailOrbit::update(const UpdateData& data) {
// Overview:
// 1. Update trails
// 2. Update floating position
// 3. Determine which parts of the array to upload and upload the data
// 1
// Update the trails; the report contains whether any of the other values has been
// touched and if so, how many
const UpdateReport report = updateTrails(data);
_previousTime = data.time.j2000Seconds();
// Do not do anything if no point needs to be updated
if (!report.permanentPointsNeedUpdate && !report.floatingPointNeedsUpdate) {
return;
}
// 2
// Write the current location into the floating position
const glm::vec3 p = _translation->position({
{},
data.time,
Time(0.0)
});
_vertexArray[_primaryRenderInformation.first] = { p.x, p.y, p.z };
glBindVertexArray(_primaryRenderInformation._vaoID);
glBindBuffer(GL_ARRAY_BUFFER, _primaryRenderInformation._vBufferID);
// 3
if (!report.permanentPointsNeedUpdate) {
if (report.floatingPointNeedsUpdate) {
// If no other values have been touched, we only need to upload the
// floating value
glBufferSubData(
GL_ARRAY_BUFFER,
_primaryRenderInformation.first * sizeof(TrailVBOLayout),
sizeof(TrailVBOLayout),
_vertexArray.data() + _primaryRenderInformation.first
);
}
}
else {
// Otherwise we need to check how many values have been changed
if (report.nUpdated == UpdateReport::All) {
// If all of the values have been invalidated, we need to upload the entire
// array
glBufferData(
GL_ARRAY_BUFFER,
_vertexArray.size() * sizeof(TrailVBOLayout),
_vertexArray.data(),
GL_STREAM_DRAW
);
if (_indexBufferDirty) {
// We only need to upload the index buffer if it has been invalidated
// by changing the number of values we want to represent
glBindBuffer(
GL_ELEMENT_ARRAY_BUFFER,
_primaryRenderInformation._iBufferID
);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
_indexArray.size() * sizeof(unsigned int),
_indexArray.data(),
GL_STATIC_DRAW
);
_indexBufferDirty = false;
}
}
else {
// The lambda expression that will upload parts of the array starting at
// begin and containing length number of elements
auto upload = [this](int begin, int length) {
glBufferSubData(
GL_ARRAY_BUFFER,
begin * sizeof(TrailVBOLayout),
sizeof(TrailVBOLayout) * length,
_vertexArray.data() + begin
);
};
// Only update the changed ones
// Since we are using a ring buffer, the number of updated needed might be
// bigger than our current points, which means we have to split the upload
// into two calls.
if (report.nUpdated > 0) {
// deltaT is positive, so the pointer is moving backwards and update has
// to happen towards the front
// Starting index
const int i = _primaryRenderInformation.first;
// Number of values
const int n = report.nUpdated + 1; // +1 for the floating position
// Total size of the array
const int s = _primaryRenderInformation.count;
if (i + n <= s) {
// The current index is small enough to just use one upload call
upload(i, n);
}
else {
// The current index is too close to the wrap around part, so we need
// to split the upload into two parts:
// 1. from the current index to the end of the array
// 2. the rest starting from the beginning of the array
const int first = s - i;
const int second = n - first;
upload(i, first); // 1
upload(0, second); // 2
}
}
else {
// deltaT is negative, so the pointer is moving forwards
// The current index
const int i = _primaryRenderInformation.first;
// Number of values
const int n = std::abs(report.nUpdated) + 1; // +1 for the floating pos
// Total size of the array
const int s = _primaryRenderInformation.count;
if (i + 1 >= n) {
// The current index is big enough to fit everything into one call
upload(i+1 - n, n);
}
else {
// The current index is too close to the beginning of the array, so we
// need to split the upload into two parts:
// 1. from the beginning of the array to the current index
// 2. filling the back of the array with the rest
const int b = n - (i + 1);
upload(0, i + 1); // 1
upload(s-b, b); // 2
}
}
}
}
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindVertexArray(0);
// Updating bounding sphere
glm::vec3 maxVertex(-std::numeric_limits<float>::max());
glm::vec3 minVertex(std::numeric_limits<float>::max());
auto setMax = [&maxVertex, &minVertex](const TrailVBOLayout& vertexData) {
maxVertex.x = std::max(maxVertex.x, vertexData.x);
maxVertex.y = std::max(maxVertex.y, vertexData.y);
maxVertex.z = std::max(maxVertex.z, vertexData.z);
minVertex.x = std::min(minVertex.x, vertexData.x);
minVertex.y = std::min(minVertex.y, vertexData.y);
minVertex.z = std::min(minVertex.z, vertexData.z);
};
std::for_each(_vertexArray.begin(), _vertexArray.end(), setMax);
setBoundingSphere(glm::distance(maxVertex, minVertex) / 2.f);
}
RenderableTrailOrbit::UpdateReport RenderableTrailOrbit::updateTrails(
const UpdateData& data)
{
if (_needsFullSweep) {
fullSweep(data.time.j2000Seconds());
return { false, true, UpdateReport::All } ;
}
constexpr const double Epsilon = 1e-7;
// When time stands still (at the iron hill), we don't need to perform any work
if (std::abs(data.time.j2000Seconds() - _previousTime) < Epsilon) {
return { false, false, 0 };
}
const double secondsPerPoint = _period / (_resolution - 1);
// How much time has passed since the last permanent point
const double delta = data.time.j2000Seconds() - _lastPointTime;
// We'd like to test for equality with 0 here, but due to rounding issues, we won't
// get there. If this check is not here, we will trigger the positive or negative
// branch below even though we don't have to
//
// This might become a bigger issue if we are starting to look at very short time
// intervals
if (std::abs(delta) < Epsilon) {
return { false, false, 0 };
}
if (delta > 0.0) {
// Check whether we need to drop a new permanent point. This is only the case if
// enough (> secondsPerPoint) time has passed since the last permanent point
if (std::abs(delta) < secondsPerPoint) {
return { true, false, 0 };
}
// See how many points we need to drop
const int nNewPoints = static_cast<int>(floor(delta / secondsPerPoint));
// If we would need to generate more new points than there are total points in the
// array, it is faster to regenerate the entire array
if (nNewPoints >= _resolution) {
fullSweep(data.time.j2000Seconds());
return { false, true, UpdateReport::All };
}
for (int i = 0; i < nNewPoints; ++i) {
_lastPointTime += secondsPerPoint;
// Get the new permanent point and write it into the (previously) floating
// location
const glm::vec3 p = _translation->position({
{},
Time(_lastPointTime),
Time(0.0)
});
_vertexArray[_primaryRenderInformation.first] = { p.x, p.y, p.z };
// Move the current pointer back one step to be used as the new floating
// location
--_primaryRenderInformation.first;
// And loop around if necessary
if (_primaryRenderInformation.first < 0) {
_primaryRenderInformation.first += _primaryRenderInformation.count;
}
}
// The previously oldest permanent point has been moved nNewPoints steps into the
// future
_firstPointTime += nNewPoints * secondsPerPoint;
return { false, true, nNewPoints };
}
else {
// See how many new points needs to be generated. Delta is negative, so we need
// to invert the ratio
const int nNewPoints = -(static_cast<int>(floor(delta / secondsPerPoint)));
// If we would need to generate more new points than there are total points in the
// array, it is faster to regenerate the entire array
if (nNewPoints >= _resolution) {
fullSweep(data.time.j2000Seconds());
return { false, true, UpdateReport::All };
}
for (int i = 0; i < nNewPoints; ++i) {
_firstPointTime -= secondsPerPoint;
// Get the new permanent point and write it into the (previously) floating
// location
const glm::vec3 p = _translation->position({
{},
Time(_firstPointTime),
Time(0.0)
});
_vertexArray[_primaryRenderInformation.first] = { p.x, p.y, p.z };
// if we are on the upper bounds of the array, we start at 0
if (_primaryRenderInformation.first == _primaryRenderInformation.count - 1) {
// If it is at the beginning, set it to the end first
_primaryRenderInformation.first = 0;
}
else {
// Move the current pointer fowards one step to be used as the new
// floating
++_primaryRenderInformation.first;
}
}
// The previously youngest point has become nNewPoints steps older
_lastPointTime -= nNewPoints * secondsPerPoint;
return { false, true, -nNewPoints };
}
}
void RenderableTrailOrbit::fullSweep(double time) {
// Reserve the space for the vertices
_vertexArray.clear();
_vertexArray.resize(_resolution);
// The index buffer stays constant until we change the size of the array
if (_indexBufferDirty) {
// Create the index buffer and fill it with two ranges for [0, _resolution)
_indexArray.clear();
_indexArray.resize(_resolution * 2);
std::iota(_indexArray.begin(), _indexArray.begin() + _resolution, 0);
std::iota(_indexArray.begin() + _resolution, _indexArray.end(), 0);
}
_lastPointTime = time;
const double secondsPerPoint = _period / (_resolution - 1);
// starting at 1 because the first position is a floating current one
for (int i = 1; i < _resolution; ++i) {
const glm::vec3 p = _translation->position({ {}, Time(time), Time(0.0) });
_vertexArray[i] = { p.x, p.y, p.z };
time -= secondsPerPoint;
}
_primaryRenderInformation.first = 0;
_primaryRenderInformation.count = _resolution;
_firstPointTime = time + secondsPerPoint;
_needsFullSweep = false;
}
} // namespace openspace
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; SMS_01_OUTPUT_TERMINAL_TTY_Z88DK
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Windowed output terminal for fixed width fonts.
; Implements tty_z88dk terminal emulation.
;
; ;;;;;;;;;;;;;;;;;;;;
; DRIVER CLASS DIAGRAM
; ;;;;;;;;;;;;;;;;;;;;
;
; CONSOLE_01_OUTPUT_TERMINAL (root, abstract)
; SMS_01_OUTPUT_TERMINAL_BASE (abstract)
; SMS_01_OUTPUT_TERMINAL (concrete)
; SMS_01_OUTPUT_TERMINAL_TTY_Z88DK (concrete)
;
; Can be instantiated to implement a CONSOLE_01_OUTPUT_TERMINAL.
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM STDIO
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * STDIO_MSG_PUTC
; Generates multiple OTERM_MSG_PUTC messages.
;
; * STDIO_MSG_WRIT
; Generates multiple OTERM_MSG_PUTC messages.
;
; * STDIO_MSG_SEEK -> no error, do nothing
; * STDIO_MSG_FLSH -> no error, do nothing
; * STDIO_MSG_ICTL
; * STDIO_MSG_CLOS -> no error, do nothing
;
; Any other messages are reported as errors via
; error_enotsup_zc
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM CONSOLE_01_OUTPUT_TERMINAL
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_PUTC
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; MESSAGES CONSUMED FROM SMS_01_OUTPUT_TERMINAL_BASE
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * OTERM_MSG_TTY
; * OTERM_MSG_PRINTC
; * OTERM_MSG_BELL
; * OTERM_MSG_SCROLL
; * OTERM_MSG_CLS
; * OTERM_MSG_PAUSE
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; IOCTLs UNDERSTOOD BY THIS DRIVER
; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; * IOCTL_OTERM_CRLF
; enable / disable crlf processing
;
; * IOCTL_OTERM_BELL
; enable / disable terminal bell
;
; * IOCTL_OTERM_SIGNAL
; enable / disable signal bell
;
; * IOCTL_OTERM_COOK
; enable / disable cook mode (tty emulation)
;
; * IOCTL_OTERM_PAUSE
; enable / disable pause when window filled
;
; * IOCTL_OTERM_PAGE
; select scroll or page mode
;
; * IOCTL_OTERM_CLEAR
; enable / disable clear window when in page mode
;
; * IOCTL_OTERM_CLS
; clear window, set (x,y) = (0,0)
;
; * IOCTL_OTERM_RESET_SCROLL
; reset scroll count
;
; * IOCTL_OTERM_GET_WINDOW_COORD
; get coord of top left corner of window
;
; * IOCTL_OTERM_SET_WINDOW_COORD
; set coord of top left corner of window
;
; * IOCTL_OTERM_GET_WINDOW_RECT
; get window size
;
; * IOCTL_OTERM_SET_WINDOW_RECT
; set window size
;
; * IOCTL_OTERM_GET_CURSOR_COORD
;
; * IOCTL_OTERM_SET_CURSOR_COORD
;
; * IOCTL_OTERM_GET_OTERM
;
; * IOCTL_OTERM_SCROLL
;
; * IOCTL_OTERM_SCROLL_LIMIT
;
; * IOCTL_OTERM_SCREEN_MAP_ADDRESS
;
; * IOCTL_OTERM_CHARACTER_PATTERN_OFFSET
;
; * IOCTL_OTERM_PRINT_FLAGS
;
; * IOCTL_OTERM_BACKGROUND_CHARACTER
;
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
; BYTES RESERVED IN FDSTRUCT
; ;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; offset (wrt FDSTRUCT.JP) description
;
; 8..13 mutex
; 14 x coordinate
; 15 y coordinate
; 16 window.x
; 17 window.width
; 18 window.y
; 19 window.height
; 20 scroll_limit
; 21/22 screen map base address
; 23/24 character pattern offset (in characters)
; 25 flags: H-FLIP (bit 1), V-FLIP (bit 2), COLORHALF (bit 3), OVERSPRITES (bit 4)
; 26/27 background character (clear screen character, absolute)
; 28 tty_z88dk.call (205)
; 29/30 tty_z88dk.state
; 31 tty_z88dk.action
; 32 tty_z88dk.param_1
; 33 tty_z88dk.param_2
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC sms_01_output_terminal_tty_z88dk
EXTERN OTERM_MSG_TTY, STDIO_MSG_FLSH, STDIO_MSG_ICTL
EXTERN sms_01_output_terminal
EXTERN sms_01_output_terminal_tty_z88dk_oterm_msg_tty
EXTERN sms_01_output_terminal_tty_z88dk_stdio_msg_flsh
EXTERN sms_01_output_terminal_tty_z88dk_stdio_msg_ictl
sms_01_output_terminal_tty_z88dk:
cp OTERM_MSG_TTY
jp z, sms_01_output_terminal_tty_z88dk_oterm_msg_tty
cp STDIO_MSG_FLSH
jp z, sms_01_output_terminal_tty_z88dk_stdio_msg_flsh
cp STDIO_MSG_ICTL
jp z, sms_01_output_terminal_tty_z88dk_stdio_msg_ictl
jp sms_01_output_terminal ; forward to library
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r15
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1005, %r11
and $4662, %r13
movw $0x6162, (%r11)
nop
nop
nop
nop
nop
sub $58321, %r15
lea addresses_D_ht+0x5925, %r10
nop
nop
nop
nop
and $54072, %r15
vmovups (%r10), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $0, %xmm1, %rbx
nop
sub %r15, %r15
lea addresses_UC_ht+0xcca5, %r10
nop
nop
nop
nop
inc %rdi
movb $0x61, (%r10)
sub $11674, %r10
lea addresses_A_ht+0x17845, %r15
nop
nop
nop
sub $56314, %rsi
and $0xffffffffffffffc0, %r15
movaps (%r15), %xmm7
vpextrq $0, %xmm7, %r10
cmp $43187, %rsi
lea addresses_UC_ht+0x9075, %rsi
lea addresses_normal_ht+0x19825, %rdi
nop
nop
nop
nop
and %r15, %r15
mov $17, %rcx
rep movsb
nop
nop
xor $16722, %r15
lea addresses_A_ht+0x9305, %rsi
lea addresses_WC_ht+0x15525, %rdi
dec %rbx
mov $73, %rcx
rep movsq
nop
cmp %rsi, %rsi
lea addresses_A_ht+0x1b025, %rbx
nop
nop
inc %r11
mov $0x6162636465666768, %r15
movq %r15, (%rbx)
nop
nop
nop
add $22574, %r10
lea addresses_normal_ht+0x1dde5, %rbx
nop
nop
nop
xor $49015, %rdi
mov $0x6162636465666768, %r13
movq %r13, (%rbx)
xor $35029, %rdi
lea addresses_WC_ht+0x8125, %rsi
lea addresses_UC_ht+0xae5, %rdi
nop
nop
nop
nop
nop
and $34194, %r13
mov $71, %rcx
rep movsq
nop
sub $35470, %rcx
lea addresses_WT_ht+0x1d85, %r10
nop
nop
nop
nop
and $4854, %r11
mov (%r10), %rsi
nop
nop
dec %r15
lea addresses_D_ht+0x1eaa5, %r15
nop
nop
nop
sub $24315, %rsi
movl $0x61626364, (%r15)
nop
nop
nop
add %r13, %r13
lea addresses_normal_ht+0x12d25, %r11
cmp $42455, %rsi
movb (%r11), %r13b
nop
nop
nop
and $31943, %rcx
lea addresses_WC_ht+0x4f66, %r11
clflush (%r11)
nop
nop
nop
nop
nop
sub $11644, %rbx
movl $0x61626364, (%r11)
nop
xor $40393, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r15
push %r9
push %rdx
push %rsi
// Store
lea addresses_WC+0x18525, %r15
nop
nop
dec %r14
mov $0x5152535455565758, %r12
movq %r12, %xmm4
movntdq %xmm4, (%r15)
nop
nop
nop
cmp %rdx, %rdx
// Faulty Load
lea addresses_WC+0x18525, %r15
sub $3864, %rdx
mov (%r15), %r9
lea oracles, %rdx
and $0xff, %r9
shlq $12, %r9
mov (%rdx,%r9,1), %r9
pop %rsi
pop %rdx
pop %r9
pop %r15
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 16}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 3, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2}}
{'src': {'NT': False, 'same': True, 'congruent': 9, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_UC_ht', 'AVXalign': True, 'size': 1}}
{'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_A_ht', 'AVXalign': True, 'size': 16}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 1, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 7, 'type': 'addresses_normal_ht'}}
{'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}}
{'src': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 1, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4}}
{'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4}}
{'58': 21776, '00': 53}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; A133878: n modulo 8 repeated 8 times.
; 1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5
add $0,8
div $0,8
mod $0,8
|
; A313116: Coordination sequence Gal.5.116.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,4,9,14,19,24,29,34,39,44,48,52,57,62,67,72,77,82,87,92,96,100,105,110,115,120,125,130,135,140,144,148,153,158,163,168,173,178,183,188,192,196,201,206,211,216,221,226,231,236
mov $2,$0
trn $0,1
add $0,4
mov $1,$0
lpb $0,1
sub $0,1
trn $1,2
trn $3,$1
sub $1,8
add $3,2
lpe
mov $1,$3
lpb $2,1
add $1,3
sub $2,1
lpe
sub $1,7
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "jitpch.h"
#include "ssaconfig.h"
#include "ssarenamestate.h"
#include "ssabuilder.h"
namespace
{
/**
* Method that finds a common IDom parent, much like least common ancestor.
*
* @param finger1 A basic block that might share IDom ancestor with finger2.
* @param finger2 A basic block that might share IDom ancestor with finger1.
*
* @see "A simple, fast dominance algorithm" by Keith D. Cooper, Timothy J. Harvey, Ken Kennedy.
*
* @return A basic block whose IDom is the dominator for finger1 and finger2,
* or else NULL. This may be called while immediate dominators are being
* computed, and if the input values are members of the same loop (each reachable from the other),
* then one may not yet have its immediate dominator computed when we are attempting
* to find the immediate dominator of the other. So a NULL return value means that the
* the two inputs are in a cycle, not that they don't have a common dominator ancestor.
*/
static inline BasicBlock* IntersectDom(BasicBlock* finger1, BasicBlock* finger2)
{
while (finger1 != finger2)
{
if (finger1 == nullptr || finger2 == nullptr)
{
return nullptr;
}
while (finger1 != nullptr && finger1->bbPostOrderNum < finger2->bbPostOrderNum)
{
finger1 = finger1->bbIDom;
}
if (finger1 == nullptr)
{
return nullptr;
}
while (finger2 != nullptr && finger2->bbPostOrderNum < finger1->bbPostOrderNum)
{
finger2 = finger2->bbIDom;
}
}
return finger1;
}
} // end of anonymous namespace.
// =================================================================================
// SSA
// =================================================================================
void Compiler::fgSsaBuild()
{
// If this is not the first invocation, reset data structures for SSA.
if (fgSsaPassesCompleted > 0)
{
fgResetForSsa();
}
SsaBuilder builder(this);
builder.Build();
fgSsaPassesCompleted++;
#ifdef DEBUG
JitTestCheckSSA();
#endif // DEBUG
#ifdef DEBUG
if (verbose)
{
JITDUMP("\nAfter fgSsaBuild:\n");
fgDispBasicBlocks(/*dumpTrees*/ true);
}
#endif // DEBUG
}
void Compiler::fgResetForSsa()
{
for (unsigned i = 0; i < lvaCount; ++i)
{
lvaTable[i].lvPerSsaData.Reset();
}
lvMemoryPerSsaData.Reset();
for (MemoryKind memoryKind : allMemoryKinds())
{
m_memorySsaMap[memoryKind] = nullptr;
}
for (BasicBlock* blk = fgFirstBB; blk != nullptr; blk = blk->bbNext)
{
// Eliminate phis.
for (MemoryKind memoryKind : allMemoryKinds())
{
blk->bbMemorySsaPhiFunc[memoryKind] = nullptr;
}
if (blk->bbStmtList != nullptr)
{
Statement* last = blk->lastStmt();
blk->bbStmtList = blk->FirstNonPhiDef();
if (blk->bbStmtList != nullptr)
{
blk->bbStmtList->SetPrevStmt(last);
}
}
// Clear post-order numbers and SSA numbers; SSA construction will overwrite these,
// but only for reachable code, so clear them to avoid analysis getting confused
// by stale annotations in unreachable code.
blk->bbPostOrderNum = 0;
for (Statement* stmt : blk->Statements())
{
for (GenTree* tree = stmt->GetTreeList(); tree != nullptr; tree = tree->gtNext)
{
if (tree->IsLocal())
{
tree->AsLclVarCommon()->SetSsaNum(SsaConfig::RESERVED_SSA_NUM);
continue;
}
}
}
}
}
/**
* Constructor for the SSA builder.
*
* @param pCompiler Current compiler instance.
*
* @remarks Initializes the class and member pointers/objects that use constructors.
*/
SsaBuilder::SsaBuilder(Compiler* pCompiler)
: m_pCompiler(pCompiler)
, m_allocator(pCompiler->getAllocator(CMK_SSA))
, m_visitedTraits(0, pCompiler) // at this point we do not know the size, SetupBBRoot can add a block
#ifdef SSA_FEATURE_DOMARR
, m_pDomPreOrder(nullptr)
, m_pDomPostOrder(nullptr)
#endif
{
}
//------------------------------------------------------------------------
// TopologicalSort: Topologically sort the graph and return the number of nodes visited.
//
// Arguments:
// postOrder - The array in which the arranged basic blocks have to be returned.
// count - The size of the postOrder array.
//
// Return Value:
// The number of nodes visited while performing DFS on the graph.
int SsaBuilder::TopologicalSort(BasicBlock** postOrder, int count)
{
Compiler* comp = m_pCompiler;
// TopologicalSort is called first so m_visited should already be empty
assert(BitVecOps::IsEmpty(&m_visitedTraits, m_visited));
// Display basic blocks.
DBEXEC(VERBOSE, comp->fgDispBasicBlocks());
DBEXEC(VERBOSE, comp->fgDispHandlerTab());
auto DumpBlockAndSuccessors = [](Compiler* comp, BasicBlock* block) {
#ifdef DEBUG
if (comp->verboseSsa)
{
printf("[SsaBuilder::TopologicalSort] Pushing " FMT_BB ": [", block->bbNum);
AllSuccessorEnumerator successors(comp, block);
unsigned index = 0;
while (true)
{
bool isEHsucc = successors.IsNextEHSuccessor();
BasicBlock* succ = successors.NextSuccessor(comp);
if (succ == nullptr)
{
break;
}
printf("%s%s" FMT_BB, (index++ ? ", " : ""), (isEHsucc ? "[EH]" : ""), succ->bbNum);
}
printf("]\n");
}
#endif
};
// Compute order.
int postIndex = 0;
BasicBlock* block = comp->fgFirstBB;
BitVecOps::AddElemD(&m_visitedTraits, m_visited, block->bbNum);
ArrayStack<AllSuccessorEnumerator> blocks(m_allocator);
blocks.Emplace(comp, block);
DumpBlockAndSuccessors(comp, block);
while (!blocks.Empty())
{
BasicBlock* block = blocks.TopRef().Block();
BasicBlock* succ = blocks.TopRef().NextSuccessor(comp);
if (succ != nullptr)
{
// if the block on TOS still has unreached successors, visit them
if (BitVecOps::TryAddElemD(&m_visitedTraits, m_visited, succ->bbNum))
{
blocks.Emplace(comp, succ);
DumpBlockAndSuccessors(comp, succ);
}
}
else
{
// all successors have been visited
blocks.Pop();
DBG_SSA_JITDUMP("[SsaBuilder::TopologicalSort] postOrder[%d] = " FMT_BB "\n", postIndex, block->bbNum);
postOrder[postIndex] = block;
block->bbPostOrderNum = postIndex;
postIndex += 1;
}
}
// In the absence of EH (because catch/finally have no preds), this should be valid.
// assert(postIndex == (count - 1));
return postIndex;
}
/**
* Computes the immediate dominator IDom for each block iteratively.
*
* @param postOrder The array of basic blocks arranged in postOrder.
* @param count The size of valid elements in the postOrder array.
*
* @see "A simple, fast dominance algorithm." paper.
*/
void SsaBuilder::ComputeImmediateDom(BasicBlock** postOrder, int count)
{
JITDUMP("[SsaBuilder::ComputeImmediateDom]\n");
// TODO-Cleanup: We currently have two dominance computations happening. We should unify them; for
// now, at least forget the results of the first.
for (BasicBlock* blk = m_pCompiler->fgFirstBB; blk != nullptr; blk = blk->bbNext)
{
blk->bbIDom = nullptr;
}
// Add entry point to visited as its IDom is NULL.
BitVecOps::ClearD(&m_visitedTraits, m_visited);
BitVecOps::AddElemD(&m_visitedTraits, m_visited, m_pCompiler->fgFirstBB->bbNum);
assert(postOrder[count - 1] == m_pCompiler->fgFirstBB);
bool changed = true;
while (changed)
{
changed = false;
// In reverse post order, except for the entry block (count - 1 is entry BB).
for (int i = count - 2; i >= 0; --i)
{
BasicBlock* block = postOrder[i];
DBG_SSA_JITDUMP("Visiting in reverse post order: " FMT_BB ".\n", block->bbNum);
// Find the first processed predecessor block.
BasicBlock* predBlock = nullptr;
for (flowList* pred = m_pCompiler->BlockPredsWithEH(block); pred; pred = pred->flNext)
{
if (BitVecOps::IsMember(&m_visitedTraits, m_visited, pred->flBlock->bbNum))
{
predBlock = pred->flBlock;
break;
}
}
// There could just be a single basic block, so just check if there were any preds.
if (predBlock != nullptr)
{
DBG_SSA_JITDUMP("Pred block is " FMT_BB ".\n", predBlock->bbNum);
}
// Intersect DOM, if computed, for all predecessors.
BasicBlock* bbIDom = predBlock;
for (flowList* pred = m_pCompiler->BlockPredsWithEH(block); pred; pred = pred->flNext)
{
if (predBlock != pred->flBlock)
{
BasicBlock* domAncestor = IntersectDom(pred->flBlock, bbIDom);
// The result may be NULL if "block" and "pred->flBlock" are part of a
// cycle -- neither is guaranteed ordered wrt the other in reverse postorder,
// so we may be computing the IDom of "block" before the IDom of "pred->flBlock" has
// been computed. But that's OK -- if they're in a cycle, they share the same immediate
// dominator, so the contribution of "pred->flBlock" is not necessary to compute
// the result.
if (domAncestor != nullptr)
{
bbIDom = domAncestor;
}
}
}
// Did we change the bbIDom value? If so, we go around the outer loop again.
if (block->bbIDom != bbIDom)
{
changed = true;
// IDom has changed, update it.
DBG_SSA_JITDUMP("bbIDom of " FMT_BB " becomes " FMT_BB ".\n", block->bbNum, bbIDom ? bbIDom->bbNum : 0);
block->bbIDom = bbIDom;
}
// Mark the current block as visited.
BitVecOps::AddElemD(&m_visitedTraits, m_visited, block->bbNum);
DBG_SSA_JITDUMP("Marking block " FMT_BB " as processed.\n", block->bbNum);
}
}
}
#ifdef SSA_FEATURE_DOMARR
/**
* Walk the DOM tree and compute pre and post-order arrangement of the tree.
*
* @param curBlock The current block being operated on at some recursive level.
* @param domTree The DOM tree as a map (block -> set of child blocks.)
* @param preIndex The initial index given to the first block visited in pre order.
* @param postIndex The initial index given to the first block visited in post order.
*
* @remarks This would help us answer queries such as "a dom b?" in constant time.
* For example, if a dominated b, then Pre[a] < Pre[b] but Post[a] > Post[b]
*/
void SsaBuilder::DomTreeWalk(BasicBlock* curBlock, BlkToBlkVectorMap* domTree, int* preIndex, int* postIndex)
{
JITDUMP("[SsaBuilder::DomTreeWalk] block %s:\n", curBlock->dspToString());
// Store the order number at the block number in the pre order list.
m_pDomPreOrder[curBlock->bbNum] = *preIndex;
++(*preIndex);
BlkVector* domChildren = domTree->LookupPointer(curBlock);
if (domChildren != nullptr)
{
for (BasicBlock* child : *domChildren)
{
if (curBlock != child)
{
DomTreeWalk(child, domTree, preIndex, postIndex);
}
}
}
// Store the order number at the block number in the post order list.
m_pDomPostOrder[curBlock->bbNum] = *postIndex;
++(*postIndex);
}
#endif
/**
* Using IDom of each basic block, add a mapping from block->IDom -> block.
* @param pCompiler Compiler instance
* @param block The basic block that will become the child node of it's iDom.
* @param domTree The output domTree which will hold the mapping "block->bbIDom" -> "block"
*
*/
/* static */
void SsaBuilder::ConstructDomTreeForBlock(Compiler* pCompiler, BasicBlock* block, BlkToBlkVectorMap* domTree)
{
BasicBlock* bbIDom = block->bbIDom;
// bbIDom for (only) fgFirstBB will be NULL.
if (bbIDom == nullptr)
{
return;
}
// If the bbIDom map key doesn't exist, create one.
BlkVector* domChildren = domTree->Emplace(bbIDom, domTree->GetAllocator());
DBG_SSA_JITDUMP("Inserting " FMT_BB " as dom child of " FMT_BB ".\n", block->bbNum, bbIDom->bbNum);
// Insert the block into the block's set.
domChildren->push_back(block);
}
/**
* Using IDom of each basic block, compute the whole tree. If a block "b" has IDom "i",
* then, block "b" is dominated by "i". The mapping then is i -> { ..., b, ... }, in
* other words, "domTree" is a tree represented by nodes mapped to their children.
*
* @param pCompiler Compiler instance
* @param domTree The output domTree which will hold the mapping "block->bbIDom" -> "block"
*
*/
/* static */
void SsaBuilder::ComputeDominators(Compiler* pCompiler, BlkToBlkVectorMap* domTree)
{
JITDUMP("*************** In SsaBuilder::ComputeDominators(Compiler*, ...)\n");
// Construct the DOM tree from bbIDom
for (BasicBlock* block = pCompiler->fgFirstBB; block != nullptr; block = block->bbNext)
{
ConstructDomTreeForBlock(pCompiler, block, domTree);
}
DBEXEC(pCompiler->verboseSsa, DisplayDominators(domTree));
}
/**
* Compute the DOM tree into a map(block -> set of blocks) adjacency representation.
*
* Using IDom of each basic block, compute the whole tree. If a block "b" has IDom "i",
* then, block "b" is dominated by "i". The mapping then is i -> { ..., b, ... }
*
* @param postOrder The array of basic blocks arranged in postOrder.
* @param count The size of valid elements in the postOrder array.
* @param domTree A map of (block -> set of blocks) tree representation that is empty.
*
*/
void SsaBuilder::ComputeDominators(BasicBlock** postOrder, int count, BlkToBlkVectorMap* domTree)
{
JITDUMP("*************** In SsaBuilder::ComputeDominators(BasicBlock** postOrder, int count, ...)\n");
// Construct the DOM tree from bbIDom
for (int i = 0; i < count; ++i)
{
ConstructDomTreeForBlock(m_pCompiler, postOrder[i], domTree);
}
DBEXEC(m_pCompiler->verboseSsa, DisplayDominators(domTree));
#ifdef SSA_FEATURE_DOMARR
// Allocate space for constant time computation of (a DOM b?) query.
unsigned bbArrSize = m_pCompiler->fgBBNumMax + 1; // We will use 1-based bbNums as indices into these arrays, so
// add 1.
m_pDomPreOrder = new (&m_allocator) int[bbArrSize];
m_pDomPostOrder = new (&m_allocator) int[bbArrSize];
// Initial counters.
int preIndex = 0;
int postIndex = 0;
// Populate the pre and post order of the tree.
DomTreeWalk(m_pCompiler->fgFirstBB, domTree, &preIndex, &postIndex);
#endif
}
#ifdef DEBUG
/**
* Display the DOM tree.
*
* @param domTree A map of (block -> set of blocks) tree representation.
*/
/* static */
void SsaBuilder::DisplayDominators(BlkToBlkVectorMap* domTree)
{
printf("After computing dominator tree: \n");
for (BlkToBlkVectorMap::KeyIterator nodes = domTree->Begin(); !nodes.Equal(domTree->End()); ++nodes)
{
printf(FMT_BB " := {", nodes.Get()->bbNum);
int index = 0;
for (BasicBlock* child : nodes.GetValue())
{
printf("%s" FMT_BB, (index++ == 0) ? "" : ",", child->bbNum);
}
printf("}\n");
}
}
#endif // DEBUG
//------------------------------------------------------------------------
// ComputeDominanceFrontiers: Compute flow graph dominance frontiers
//
// Arguments:
// postOrder - an array containing all flow graph blocks
// count - the number of blocks in the postOrder array
// mapDF - a caller provided hashtable that will be populated
// with blocks and their dominance frontiers (only those
// blocks that have non-empty frontiers will be included)
//
// Notes:
// Recall that the dominance frontier of a block B is the set of blocks
// B3 such that there exists some B2 s.t. B3 is a successor of B2, and
// B dominates B2. Note that this dominance need not be strict -- B2
// and B may be the same node.
// See "A simple, fast dominance algorithm", by Cooper, Harvey, and Kennedy.
//
void SsaBuilder::ComputeDominanceFrontiers(BasicBlock** postOrder, int count, BlkToBlkVectorMap* mapDF)
{
DBG_SSA_JITDUMP("Computing DF:\n");
for (int i = 0; i < count; ++i)
{
BasicBlock* block = postOrder[i];
DBG_SSA_JITDUMP("Considering block " FMT_BB ".\n", block->bbNum);
// Recall that B3 is in the dom frontier of B1 if there exists a B2
// such that B1 dom B2, !(B1 dom B3), and B3 is an immediate successor
// of B2. (Note that B1 might be the same block as B2.)
// In that definition, we're considering "block" to be B3, and trying
// to find B1's. To do so, first we consider the predecessors of "block",
// searching for candidate B2's -- "block" is obviously an immediate successor
// of its immediate predecessors. If there are zero or one preds, then there
// is no pred, or else the single pred dominates "block", so no B2 exists.
flowList* blockPreds = m_pCompiler->BlockPredsWithEH(block);
// If block has 0/1 predecessor, skip.
if ((blockPreds == nullptr) || (blockPreds->flNext == nullptr))
{
DBG_SSA_JITDUMP(" Has %d preds; skipping.\n", blockPreds == nullptr ? 0 : 1);
continue;
}
// Otherwise, there are > 1 preds. Each is a candidate B2 in the definition --
// *unless* it dominates "block"/B3.
for (flowList* pred = blockPreds; pred != nullptr; pred = pred->flNext)
{
DBG_SSA_JITDUMP(" Considering predecessor " FMT_BB ".\n", pred->flBlock->bbNum);
// If we've found a B2, then consider the possible B1's. We start with
// B2, since a block dominates itself, then traverse upwards in the dominator
// tree, stopping when we reach the root, or the immediate dominator of "block"/B3.
// (Note that we are guaranteed to encounter this immediate dominator of "block"/B3:
// a predecessor must be dominated by B3's immediate dominator.)
// Along this way, make "block"/B3 part of the dom frontier of the B1.
// When we reach this immediate dominator, the definition no longer applies, since this
// potential B1 *does* dominate "block"/B3, so we stop.
for (BasicBlock* b1 = pred->flBlock; (b1 != nullptr) && (b1 != block->bbIDom); // !root && !loop
b1 = b1->bbIDom)
{
DBG_SSA_JITDUMP(" Adding " FMT_BB " to dom frontier of pred dom " FMT_BB ".\n", block->bbNum,
b1->bbNum);
BlkVector& b1DF = *mapDF->Emplace(b1, m_allocator);
// It's possible to encounter the same DF multiple times, ensure that we don't add duplicates.
if (b1DF.empty() || (b1DF.back() != block))
{
b1DF.push_back(block);
}
}
}
}
#ifdef DEBUG
if (m_pCompiler->verboseSsa)
{
printf("\nComputed DF:\n");
for (int i = 0; i < count; ++i)
{
BasicBlock* b = postOrder[i];
printf("Block " FMT_BB " := {", b->bbNum);
BlkVector* bDF = mapDF->LookupPointer(b);
if (bDF != nullptr)
{
int index = 0;
for (BasicBlock* f : *bDF)
{
printf("%s" FMT_BB, (index++ == 0) ? "" : ",", f->bbNum);
}
}
printf("}\n");
}
}
#endif
}
//------------------------------------------------------------------------
// ComputeIteratedDominanceFrontier: Compute the iterated dominance frontier
// for the specified block.
//
// Arguments:
// b - the block to computed the frontier for
// mapDF - a map containing the dominance frontiers of all blocks
// bIDF - a caller provided vector where the IDF is to be stored
//
// Notes:
// The iterated dominance frontier is formed by a closure operation:
// the IDF of B is the smallest set that includes B's dominance frontier,
// and also includes the dominance frontier of all elements of the set.
//
void SsaBuilder::ComputeIteratedDominanceFrontier(BasicBlock* b, const BlkToBlkVectorMap* mapDF, BlkVector* bIDF)
{
assert(bIDF->empty());
BlkVector* bDF = mapDF->LookupPointer(b);
if (bDF != nullptr)
{
// Compute IDF(b) - start by adding DF(b) to IDF(b).
bIDF->reserve(bDF->size());
BitVecOps::ClearD(&m_visitedTraits, m_visited);
for (BasicBlock* f : *bDF)
{
BitVecOps::AddElemD(&m_visitedTraits, m_visited, f->bbNum);
bIDF->push_back(f);
}
// Now for each block f from IDF(b) add DF(f) to IDF(b). This may result in new
// blocks being added to IDF(b) and the process repeats until no more new blocks
// are added. Note that since we keep adding to bIDF we can't use iterators as
// they may get invalidated. This happens to be a convenient way to avoid having
// to track newly added blocks in a separate set.
for (size_t newIndex = 0; newIndex < bIDF->size(); newIndex++)
{
BasicBlock* f = (*bIDF)[newIndex];
BlkVector* fDF = mapDF->LookupPointer(f);
if (fDF != nullptr)
{
for (BasicBlock* ff : *fDF)
{
if (BitVecOps::TryAddElemD(&m_visitedTraits, m_visited, ff->bbNum))
{
bIDF->push_back(ff);
}
}
}
}
}
#ifdef DEBUG
if (m_pCompiler->verboseSsa)
{
printf("IDF(" FMT_BB ") := {", b->bbNum);
int index = 0;
for (BasicBlock* f : *bIDF)
{
printf("%s" FMT_BB, (index++ == 0) ? "" : ",", f->bbNum);
}
printf("}\n");
}
#endif
}
/**
* Returns the phi GT_PHI node if the variable already has a phi node.
*
* @param block The block for which the existence of a phi node needs to be checked.
* @param lclNum The lclNum for which the occurrence of a phi node needs to be checked.
*
* @return If there is a phi node for the lclNum, returns the GT_PHI tree, else NULL.
*/
static GenTree* GetPhiNode(BasicBlock* block, unsigned lclNum)
{
// Walk the statements for phi nodes.
for (Statement* stmt : block->Statements())
{
// A prefix of the statements of the block are phi definition nodes. If we complete processing
// that prefix, exit.
if (!stmt->IsPhiDefnStmt())
{
break;
}
GenTree* tree = stmt->GetRootNode();
GenTree* phiLhs = tree->AsOp()->gtOp1;
assert(phiLhs->OperGet() == GT_LCL_VAR);
if (phiLhs->AsLclVarCommon()->GetLclNum() == lclNum)
{
return tree->AsOp()->gtOp2;
}
}
return nullptr;
}
//------------------------------------------------------------------------
// InsertPhi: Insert a new GT_PHI statement.
//
// Arguments:
// block - The block where to insert the statement
// lclNum - The variable number
//
void SsaBuilder::InsertPhi(BasicBlock* block, unsigned lclNum)
{
var_types type = m_pCompiler->lvaGetDesc(lclNum)->TypeGet();
GenTree* lhs = m_pCompiler->gtNewLclvNode(lclNum, type);
// PHIs and all the associated nodes do not generate any code so the costs are always 0
lhs->SetCosts(0, 0);
GenTree* phi = new (m_pCompiler, GT_PHI) GenTreePhi(type);
phi->SetCosts(0, 0);
GenTree* asg = m_pCompiler->gtNewAssignNode(lhs, phi);
// Evaluate the assignment RHS (the PHI node) first. This way the LHS will end up right
// in front of the assignment in the linear order, that ensures that using gtGetParent
// on the LHS to find the assignment doesn't have to traverse the PHI and its args.
asg->gtFlags |= GTF_REVERSE_OPS;
asg->SetCosts(0, 0);
// Create the statement and chain everything in linear order - PHI, LCL_VAR, ASG
Statement* stmt = m_pCompiler->gtNewStmt(asg);
stmt->SetTreeList(phi);
phi->gtNext = lhs;
lhs->gtPrev = phi;
lhs->gtNext = asg;
asg->gtPrev = lhs;
#ifdef DEBUG
unsigned seqNum = 1;
for (GenTree* node = stmt->GetTreeList(); node != nullptr; node = node->gtNext)
{
node->gtSeqNum = seqNum++;
}
#endif // DEBUG
m_pCompiler->fgInsertStmtAtBeg(block, stmt);
JITDUMP("Added PHI definition for V%02u at start of " FMT_BB ".\n", lclNum, block->bbNum);
}
//------------------------------------------------------------------------
// AddPhiArg: Add a new GT_PHI_ARG node to an existing GT_PHI node.
//
// Arguments:
// block - The block that contains the statement
// stmt - The statement that contains the GT_PHI node
// lclNum - The variable number
// ssaNum - The SSA number
// pred - The predecessor block
//
void SsaBuilder::AddPhiArg(
BasicBlock* block, Statement* stmt, GenTreePhi* phi, unsigned lclNum, unsigned ssaNum, BasicBlock* pred)
{
#ifdef DEBUG
// Make sure it isn't already present: we should only add each definition once.
for (GenTreePhi::Use& use : phi->Uses())
{
assert(use.GetNode()->AsPhiArg()->GetSsaNum() != ssaNum);
}
#endif // DEBUG
var_types type = m_pCompiler->lvaGetDesc(lclNum)->TypeGet();
GenTree* phiArg = new (m_pCompiler, GT_PHI_ARG) GenTreePhiArg(type, lclNum, ssaNum, pred);
// Costs are not relevant for PHI args.
phiArg->SetCosts(0, 0);
// The argument order doesn't matter so just insert at the front of the list because
// it's easier. It's also easier to insert in linear order since the first argument
// will be first in linear order as well.
phi->gtUses = new (m_pCompiler, CMK_ASTNode) GenTreePhi::Use(phiArg, phi->gtUses);
GenTree* head = stmt->GetTreeList();
assert(head->OperIs(GT_PHI, GT_PHI_ARG));
stmt->SetTreeList(phiArg);
phiArg->gtNext = head;
head->gtPrev = phiArg;
#ifdef DEBUG
unsigned seqNum = 1;
for (GenTree* node = stmt->GetTreeList(); node != nullptr; node = node->gtNext)
{
node->gtSeqNum = seqNum++;
}
#endif // DEBUG
DBG_SSA_JITDUMP("Added PHI arg u:%d for V%02u from " FMT_BB " in " FMT_BB ".\n", ssaNum, lclNum, pred->bbNum,
block->bbNum);
}
/**
* Inserts phi functions at DF(b) for variables v that are live after the phi
* insertion point i.e., v in live-in(b).
*
* To do so, the function computes liveness, dominance frontier and inserts a phi node,
* if we have var v in def(b) and live-in(l) and l is in DF(b).
*
* @param postOrder The array of basic blocks arranged in postOrder.
* @param count The size of valid elements in the postOrder array.
*/
void SsaBuilder::InsertPhiFunctions(BasicBlock** postOrder, int count)
{
JITDUMP("*************** In SsaBuilder::InsertPhiFunctions()\n");
// Compute dominance frontier.
BlkToBlkVectorMap mapDF(m_allocator);
ComputeDominanceFrontiers(postOrder, count, &mapDF);
EndPhase(PHASE_BUILD_SSA_DF);
// Use the same IDF vector for all blocks to avoid unnecessary memory allocations
BlkVector blockIDF(m_allocator);
JITDUMP("Inserting phi functions:\n");
for (int i = 0; i < count; ++i)
{
BasicBlock* block = postOrder[i];
DBG_SSA_JITDUMP("Considering dominance frontier of block " FMT_BB ":\n", block->bbNum);
blockIDF.clear();
ComputeIteratedDominanceFrontier(block, &mapDF, &blockIDF);
if (blockIDF.empty())
{
continue;
}
// For each local var number "lclNum" that "block" assigns to...
VarSetOps::Iter defVars(m_pCompiler, block->bbVarDef);
unsigned varIndex = 0;
while (defVars.NextElem(&varIndex))
{
unsigned lclNum = m_pCompiler->lvaTrackedIndexToLclNum(varIndex);
DBG_SSA_JITDUMP(" Considering local var V%02u:\n", lclNum);
if (!m_pCompiler->lvaInSsa(lclNum))
{
DBG_SSA_JITDUMP(" Skipping because it is excluded.\n");
continue;
}
// For each block "bbInDomFront" that is in the dominance frontier of "block"...
for (BasicBlock* bbInDomFront : blockIDF)
{
DBG_SSA_JITDUMP(" Considering " FMT_BB " in dom frontier of " FMT_BB ":\n", bbInDomFront->bbNum,
block->bbNum);
// Check if variable "lclNum" is live in block "*iterBlk".
if (!VarSetOps::IsMember(m_pCompiler, bbInDomFront->bbLiveIn, varIndex))
{
continue;
}
// Check if we've already inserted a phi node.
if (GetPhiNode(bbInDomFront, lclNum) == nullptr)
{
// We have a variable i that is defined in block j and live at l, and l belongs to dom frontier of
// j. So insert a phi node at l.
InsertPhi(bbInDomFront, lclNum);
}
}
}
// Now make a similar phi definition if the block defines memory.
if (block->bbMemoryDef != 0)
{
// For each block "bbInDomFront" that is in the dominance frontier of "block".
for (BasicBlock* bbInDomFront : blockIDF)
{
DBG_SSA_JITDUMP(" Considering " FMT_BB " in dom frontier of " FMT_BB " for Memory phis:\n",
bbInDomFront->bbNum, block->bbNum);
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// Share the PhiFunc with ByrefExposed.
assert(memoryKind > ByrefExposed);
bbInDomFront->bbMemorySsaPhiFunc[memoryKind] = bbInDomFront->bbMemorySsaPhiFunc[ByrefExposed];
continue;
}
// Check if this memoryKind is defined in this block.
if ((block->bbMemoryDef & memoryKindSet(memoryKind)) == 0)
{
continue;
}
// Check if memoryKind is live into block "*iterBlk".
if ((bbInDomFront->bbMemoryLiveIn & memoryKindSet(memoryKind)) == 0)
{
continue;
}
// Check if we've already inserted a phi node.
if (bbInDomFront->bbMemorySsaPhiFunc[memoryKind] == nullptr)
{
// We have a variable i that is defined in block j and live at l, and l belongs to dom frontier
// of
// j. So insert a phi node at l.
JITDUMP("Inserting phi definition for %s at start of " FMT_BB ".\n",
memoryKindNames[memoryKind], bbInDomFront->bbNum);
bbInDomFront->bbMemorySsaPhiFunc[memoryKind] = BasicBlock::EmptyMemoryPhiDef;
}
}
}
}
}
EndPhase(PHASE_BUILD_SSA_INSERT_PHIS);
}
/**
* Rename the local variable tree node.
*
* If the given tree node is a local variable, then for a def give a new count, if use,
* then give the count in the top of stack, i.e., current count (used for last def.)
*
* @param tree Tree node where an SSA variable is used or def'ed.
* @param pRenameState The incremental rename information stored during renaming process.
*
* @remarks This method has to maintain parity with TreePopStacks corresponding to pushes
* it makes for defs.
*/
void SsaBuilder::TreeRenameVariables(GenTree* tree, BasicBlock* block, SsaRenameState* pRenameState, bool isPhiDefn)
{
// This is perhaps temporary -- maybe should be done elsewhere. Label GT_INDs on LHS of assignments, so we
// can skip these during (at least) value numbering.
if (tree->OperIs(GT_ASG))
{
GenTree* lhs = tree->AsOp()->gtOp1->gtEffectiveVal(/*commaOnly*/ true);
GenTree* trueLhs = lhs->gtEffectiveVal(/*commaOnly*/ true);
if (trueLhs->OperIsIndir())
{
trueLhs->gtFlags |= GTF_IND_ASG_LHS;
}
else if (trueLhs->OperGet() == GT_CLS_VAR)
{
trueLhs->gtFlags |= GTF_CLS_VAR_ASG_LHS;
}
}
// Figure out if "tree" may make a new GC heap state (if we care for this block).
if ((block->bbMemoryHavoc & memoryKindSet(GcHeap)) == 0)
{
if (tree->OperIs(GT_ASG) || tree->OperIsBlkOp())
{
if (m_pCompiler->ehBlockHasExnFlowDsc(block))
{
GenTreeLclVarCommon* lclVarNode;
bool isLocal = tree->DefinesLocal(m_pCompiler, &lclVarNode);
bool isAddrExposedLocal = isLocal && m_pCompiler->lvaVarAddrExposed(lclVarNode->GetLclNum());
bool hasByrefHavoc = ((block->bbMemoryHavoc & memoryKindSet(ByrefExposed)) != 0);
if (!isLocal || (isAddrExposedLocal && !hasByrefHavoc))
{
// It *may* define byref memory in a non-havoc way. Make a new SSA # -- associate with this node.
unsigned ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
if (!hasByrefHavoc)
{
pRenameState->PushMemory(ByrefExposed, block, ssaNum);
m_pCompiler->GetMemorySsaMap(ByrefExposed)->Set(tree, ssaNum);
#ifdef DEBUG
if (JitTls::GetCompiler()->verboseSsa)
{
printf("Node ");
Compiler::printTreeID(tree);
printf(" (in try block) may define memory; ssa # = %d.\n", ssaNum);
}
#endif // DEBUG
// Now add this SSA # to all phis of the reachable catch blocks.
AddMemoryDefToHandlerPhis(ByrefExposed, block, ssaNum);
}
if (!isLocal)
{
// Add a new def for GcHeap as well
if (m_pCompiler->byrefStatesMatchGcHeapStates)
{
// GcHeap and ByrefExposed share the same stacks, SsaMap, and phis
assert(!hasByrefHavoc);
assert(*m_pCompiler->GetMemorySsaMap(GcHeap)->LookupPointer(tree) == ssaNum);
assert(block->bbMemorySsaPhiFunc[GcHeap] == block->bbMemorySsaPhiFunc[ByrefExposed]);
}
else
{
if (!hasByrefHavoc)
{
// Allocate a distinct defnum for the GC Heap
ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
}
pRenameState->PushMemory(GcHeap, block, ssaNum);
m_pCompiler->GetMemorySsaMap(GcHeap)->Set(tree, ssaNum);
AddMemoryDefToHandlerPhis(GcHeap, block, ssaNum);
}
}
}
}
}
}
if (!tree->IsLocal())
{
return;
}
unsigned lclNum = tree->AsLclVarCommon()->GetLclNum();
// Is this a variable we exclude from SSA?
if (!m_pCompiler->lvaInSsa(lclNum))
{
tree->AsLclVarCommon()->SetSsaNum(SsaConfig::RESERVED_SSA_NUM);
return;
}
if ((tree->gtFlags & GTF_VAR_DEF) != 0)
{
// Allocate a new SSA number for this definition tree.
unsigned ssaNum = m_pCompiler->lvaTable[lclNum].lvPerSsaData.AllocSsaNum(m_allocator, block, tree);
if ((tree->gtFlags & GTF_VAR_USEASG) != 0)
{
// This is a partial definition of a variable. The node records only the SSA number
// of the use that is implied by this partial definition. The SSA number of the new
// definition will be recorded in the m_opAsgnVarDefSsaNums map.
tree->AsLclVarCommon()->SetSsaNum(pRenameState->Top(lclNum));
m_pCompiler->GetOpAsgnVarDefSsaNums()->Set(tree, ssaNum);
}
else
{
tree->AsLclVarCommon()->SetSsaNum(ssaNum);
}
pRenameState->Push(block, lclNum, ssaNum);
// If necessary, add "lclNum/ssaNum" to the arg list of a phi def in any
// handlers for try blocks that "block" is within. (But only do this for "real" definitions,
// not phi definitions.)
if (!isPhiDefn)
{
AddDefToHandlerPhis(block, lclNum, ssaNum);
}
}
else if (!isPhiDefn) // Phi args already have ssa numbers.
{
// This case is obviated by the short-term "early-out" above...but it's in the right direction.
// Is it a promoted struct local?
if (m_pCompiler->lvaTable[lclNum].lvPromoted)
{
assert(tree->TypeGet() == TYP_STRUCT);
LclVarDsc* varDsc = &m_pCompiler->lvaTable[lclNum];
// If has only a single field var, treat this as a use of that field var.
// Otherwise, we don't give SSA names to uses of promoted struct vars.
if (varDsc->lvFieldCnt == 1)
{
lclNum = varDsc->lvFieldLclStart;
}
else
{
tree->AsLclVarCommon()->SetSsaNum(SsaConfig::RESERVED_SSA_NUM);
return;
}
}
tree->AsLclVarCommon()->SetSsaNum(pRenameState->Top(lclNum));
}
}
void SsaBuilder::AddDefToHandlerPhis(BasicBlock* block, unsigned lclNum, unsigned ssaNum)
{
assert(m_pCompiler->lvaTable[lclNum].lvTracked); // Precondition.
unsigned lclIndex = m_pCompiler->lvaTable[lclNum].lvVarIndex;
EHblkDsc* tryBlk = m_pCompiler->ehGetBlockExnFlowDsc(block);
if (tryBlk != nullptr)
{
DBG_SSA_JITDUMP("Definition of local V%02u/d:%d in block " FMT_BB
" has exn handler; adding as phi arg to handlers.\n",
lclNum, ssaNum, block->bbNum);
while (true)
{
BasicBlock* handler = tryBlk->ExFlowBlock();
// Is "lclNum" live on entry to the handler?
if (VarSetOps::IsMember(m_pCompiler, handler->bbLiveIn, lclIndex))
{
#ifdef DEBUG
bool phiFound = false;
#endif
// A prefix of blocks statements will be SSA definitions. Search those for "lclNum".
for (Statement* stmt : handler->Statements())
{
// If the tree is not an SSA def, break out of the loop: we're done.
if (!stmt->IsPhiDefnStmt())
{
break;
}
GenTree* tree = stmt->GetRootNode();
assert(tree->IsPhiDefn());
if (tree->AsOp()->gtOp1->AsLclVar()->GetLclNum() == lclNum)
{
// It's the definition for the right local. Add "ssaNum" to the RHS.
AddPhiArg(handler, stmt, tree->gtGetOp2()->AsPhi(), lclNum, ssaNum, block);
#ifdef DEBUG
phiFound = true;
#endif
break;
}
}
assert(phiFound);
}
unsigned nextTryIndex = tryBlk->ebdEnclosingTryIndex;
if (nextTryIndex == EHblkDsc::NO_ENCLOSING_INDEX)
{
break;
}
tryBlk = m_pCompiler->ehGetDsc(nextTryIndex);
}
}
}
void SsaBuilder::AddMemoryDefToHandlerPhis(MemoryKind memoryKind, BasicBlock* block, unsigned ssaNum)
{
if (m_pCompiler->ehBlockHasExnFlowDsc(block))
{
// Don't do anything for a compiler-inserted BBJ_ALWAYS that is a "leave helper".
if (block->bbJumpKind == BBJ_ALWAYS && (block->bbFlags & BBF_INTERNAL) && (block->bbPrev->isBBCallAlwaysPair()))
{
return;
}
// Otherwise...
DBG_SSA_JITDUMP("Definition of %s/d:%d in block " FMT_BB " has exn handler; adding as phi arg to handlers.\n",
memoryKindNames[memoryKind], ssaNum, block->bbNum);
EHblkDsc* tryBlk = m_pCompiler->ehGetBlockExnFlowDsc(block);
while (true)
{
BasicBlock* handler = tryBlk->ExFlowBlock();
// Is memoryKind live on entry to the handler?
if ((handler->bbMemoryLiveIn & memoryKindSet(memoryKind)) != 0)
{
// Add "ssaNum" to the phi args of memoryKind.
BasicBlock::MemoryPhiArg*& handlerMemoryPhi = handler->bbMemorySsaPhiFunc[memoryKind];
#if DEBUG
if (m_pCompiler->byrefStatesMatchGcHeapStates)
{
// When sharing phis for GcHeap and ByrefExposed, callers should ask to add phis
// for ByrefExposed only.
assert(memoryKind != GcHeap);
if (memoryKind == ByrefExposed)
{
// The GcHeap and ByrefExposed phi funcs should always be in sync.
assert(handlerMemoryPhi == handler->bbMemorySsaPhiFunc[GcHeap]);
}
}
#endif
if (handlerMemoryPhi == BasicBlock::EmptyMemoryPhiDef)
{
handlerMemoryPhi = new (m_pCompiler) BasicBlock::MemoryPhiArg(ssaNum);
}
else
{
#ifdef DEBUG
BasicBlock::MemoryPhiArg* curArg = handler->bbMemorySsaPhiFunc[memoryKind];
while (curArg != nullptr)
{
assert(curArg->GetSsaNum() != ssaNum);
curArg = curArg->m_nextArg;
}
#endif // DEBUG
handlerMemoryPhi = new (m_pCompiler) BasicBlock::MemoryPhiArg(ssaNum, handlerMemoryPhi);
}
DBG_SSA_JITDUMP(" Added phi arg u:%d for %s to phi defn in handler block " FMT_BB ".\n", ssaNum,
memoryKindNames[memoryKind], memoryKind, handler->bbNum);
if ((memoryKind == ByrefExposed) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// Share the phi between GcHeap and ByrefExposed.
handler->bbMemorySsaPhiFunc[GcHeap] = handlerMemoryPhi;
}
}
unsigned tryInd = tryBlk->ebdEnclosingTryIndex;
if (tryInd == EHblkDsc::NO_ENCLOSING_INDEX)
{
break;
}
tryBlk = m_pCompiler->ehGetDsc(tryInd);
}
}
}
/**
* Walk the block's tree in the evaluation order and give var definitions and uses their
* SSA names.
*
* @param block Block for which SSA variables have to be renamed.
* @param pRenameState The incremental rename information stored during renaming process.
*
*/
void SsaBuilder::BlockRenameVariables(BasicBlock* block, SsaRenameState* pRenameState)
{
// Walk the statements of the block and rename the tree variables.
// First handle the incoming memory states.
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// ByrefExposed and GcHeap share any phi this block may have,
assert(block->bbMemorySsaPhiFunc[memoryKind] == block->bbMemorySsaPhiFunc[ByrefExposed]);
// so we will have already allocated a defnum for it if needed.
assert(memoryKind > ByrefExposed);
block->bbMemorySsaNumIn[memoryKind] = pRenameState->TopMemory(ByrefExposed);
}
else
{
// Is there an Phi definition for memoryKind at the start of this block?
if (block->bbMemorySsaPhiFunc[memoryKind] != nullptr)
{
unsigned ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
pRenameState->PushMemory(memoryKind, block, ssaNum);
DBG_SSA_JITDUMP("Ssa # for %s phi on entry to " FMT_BB " is %d.\n", memoryKindNames[memoryKind],
block->bbNum, ssaNum);
block->bbMemorySsaNumIn[memoryKind] = ssaNum;
}
else
{
block->bbMemorySsaNumIn[memoryKind] = pRenameState->TopMemory(memoryKind);
}
}
}
// We need to iterate over phi definitions, to give them SSA names, but we need
// to know which are which, so we don't add phi definitions to handler phi arg lists.
// Statements are phi defns until they aren't.
bool isPhiDefn = true;
Statement* firstNonPhi = block->FirstNonPhiDef();
for (Statement* stmt : block->Statements())
{
if (stmt == firstNonPhi)
{
isPhiDefn = false;
}
for (GenTree* tree = stmt->GetTreeList(); tree; tree = tree->gtNext)
{
TreeRenameVariables(tree, block, pRenameState, isPhiDefn);
}
}
// Now handle the final memory states.
for (MemoryKind memoryKind : allMemoryKinds())
{
MemoryKindSet memorySet = memoryKindSet(memoryKind);
// If the block defines memory, allocate an SSA variable for the final memory state in the block.
// (This may be redundant with the last SSA var explicitly created, but there's no harm in that.)
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// We've already allocated the SSA num and propagated it to shared phis, if needed,
// when processing ByrefExposed.
assert(memoryKind > ByrefExposed);
assert(((block->bbMemoryDef & memorySet) != 0) ==
((block->bbMemoryDef & memoryKindSet(ByrefExposed)) != 0));
block->bbMemorySsaNumOut[memoryKind] = pRenameState->TopMemory(ByrefExposed);
}
else
{
if ((block->bbMemoryDef & memorySet) != 0)
{
unsigned ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
pRenameState->PushMemory(memoryKind, block, ssaNum);
AddMemoryDefToHandlerPhis(memoryKind, block, ssaNum);
block->bbMemorySsaNumOut[memoryKind] = ssaNum;
}
else
{
block->bbMemorySsaNumOut[memoryKind] = pRenameState->TopMemory(memoryKind);
}
}
DBG_SSA_JITDUMP("Ssa # for %s on entry to " FMT_BB " is %d; on exit is %d.\n", memoryKindNames[memoryKind],
block->bbNum, block->bbMemorySsaNumIn[memoryKind], block->bbMemorySsaNumOut[memoryKind]);
}
}
/**
* Walk through the phi nodes of a given block and assign rhs variables to them.
*
* Also renumber the rhs variables from top of the stack.
*
* @param block Block for which phi nodes have to be assigned their rhs arguments.
* @param pRenameState The incremental rename information stored during renaming process.
*
*/
void SsaBuilder::AssignPhiNodeRhsVariables(BasicBlock* block, SsaRenameState* pRenameState)
{
for (BasicBlock* succ : block->GetAllSuccs(m_pCompiler))
{
// Walk the statements for phi nodes.
for (Statement* stmt : succ->Statements())
{
// A prefix of the statements of the block are phi definition nodes. If we complete processing
// that prefix, exit.
if (!stmt->IsPhiDefnStmt())
{
break;
}
GenTree* tree = stmt->GetRootNode();
GenTreePhi* phi = tree->gtGetOp2()->AsPhi();
unsigned lclNum = tree->AsOp()->gtOp1->AsLclVar()->GetLclNum();
unsigned ssaNum = pRenameState->Top(lclNum);
// Search the arglist for an existing definition for ssaNum.
// (Can we assert that its the head of the list? This should only happen when we add
// during renaming for a definition that occurs within a try, and then that's the last
// value of the var within that basic block.)
bool found = false;
for (GenTreePhi::Use& use : phi->Uses())
{
if (use.GetNode()->AsPhiArg()->GetSsaNum() == ssaNum)
{
found = true;
break;
}
}
if (!found)
{
AddPhiArg(succ, stmt, phi, lclNum, ssaNum, block);
}
}
// Now handle memory.
for (MemoryKind memoryKind : allMemoryKinds())
{
BasicBlock::MemoryPhiArg*& succMemoryPhi = succ->bbMemorySsaPhiFunc[memoryKind];
if (succMemoryPhi != nullptr)
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// We've already propagated the "out" number to the phi shared with ByrefExposed,
// but still need to update bbMemorySsaPhiFunc to be in sync between GcHeap and ByrefExposed.
assert(memoryKind > ByrefExposed);
assert(block->bbMemorySsaNumOut[memoryKind] == block->bbMemorySsaNumOut[ByrefExposed]);
assert((succ->bbMemorySsaPhiFunc[ByrefExposed] == succMemoryPhi) ||
(succ->bbMemorySsaPhiFunc[ByrefExposed]->m_nextArg ==
(succMemoryPhi == BasicBlock::EmptyMemoryPhiDef ? nullptr : succMemoryPhi)));
succMemoryPhi = succ->bbMemorySsaPhiFunc[ByrefExposed];
continue;
}
if (succMemoryPhi == BasicBlock::EmptyMemoryPhiDef)
{
succMemoryPhi = new (m_pCompiler) BasicBlock::MemoryPhiArg(block->bbMemorySsaNumOut[memoryKind]);
}
else
{
BasicBlock::MemoryPhiArg* curArg = succMemoryPhi;
unsigned ssaNum = block->bbMemorySsaNumOut[memoryKind];
bool found = false;
// This is a quadratic algorithm. We might need to consider some switch over to a hash table
// representation for the arguments of a phi node, to make this linear.
while (curArg != nullptr)
{
if (curArg->m_ssaNum == ssaNum)
{
found = true;
break;
}
curArg = curArg->m_nextArg;
}
if (!found)
{
succMemoryPhi = new (m_pCompiler) BasicBlock::MemoryPhiArg(ssaNum, succMemoryPhi);
}
}
DBG_SSA_JITDUMP(" Added phi arg for %s u:%d from " FMT_BB " in " FMT_BB ".\n",
memoryKindNames[memoryKind], block->bbMemorySsaNumOut[memoryKind], block->bbNum,
succ->bbNum);
}
}
// If "succ" is the first block of a try block (and "block" is not also in that try block)
// then we must look at the vars that have phi defs in the corresponding handler;
// the current SSA name for such vars must be included as an argument to that phi.
if (m_pCompiler->bbIsTryBeg(succ))
{
assert(succ->hasTryIndex());
unsigned tryInd = succ->getTryIndex();
while (tryInd != EHblkDsc::NO_ENCLOSING_INDEX)
{
// Check if the predecessor "block" is within the same try block.
if (block->hasTryIndex())
{
for (unsigned blockTryInd = block->getTryIndex(); blockTryInd != EHblkDsc::NO_ENCLOSING_INDEX;
blockTryInd = m_pCompiler->ehGetEnclosingTryIndex(blockTryInd))
{
if (blockTryInd == tryInd)
{
// It is; don't execute the loop below.
tryInd = EHblkDsc::NO_ENCLOSING_INDEX;
break;
}
}
// The loop just above found that the predecessor "block" is within the same
// try block as "succ." So we don't need to process this try, or any
// further outer try blocks here, since they would also contain both "succ"
// and "block".
if (tryInd == EHblkDsc::NO_ENCLOSING_INDEX)
{
break;
}
}
EHblkDsc* succTry = m_pCompiler->ehGetDsc(tryInd);
// This is necessarily true on the first iteration, but not
// necessarily on the second and subsequent.
if (succTry->ebdTryBeg != succ)
{
break;
}
// succ is the first block of this try. Look at phi defs in the handler.
// For a filter, we consider the filter to be the "real" handler.
BasicBlock* handlerStart = succTry->ExFlowBlock();
for (Statement* stmt : handlerStart->Statements())
{
GenTree* tree = stmt->GetRootNode();
// Check if the first n of the statements are phi nodes. If not, exit.
if (tree->OperGet() != GT_ASG || tree->AsOp()->gtOp2 == nullptr ||
tree->AsOp()->gtOp2->OperGet() != GT_PHI)
{
break;
}
// Get the phi node from GT_ASG.
GenTree* lclVar = tree->AsOp()->gtOp1;
unsigned lclNum = lclVar->AsLclVar()->GetLclNum();
// If the variable is live-out of "blk", and is therefore live on entry to the try-block-start
// "succ", then we make sure the current SSA name for the
// var is one of the args of the phi node. If not, go on.
LclVarDsc* lclVarDsc = &m_pCompiler->lvaTable[lclNum];
if (!lclVarDsc->lvTracked ||
!VarSetOps::IsMember(m_pCompiler, block->bbLiveOut, lclVarDsc->lvVarIndex))
{
continue;
}
GenTreePhi* phi = tree->gtGetOp2()->AsPhi();
unsigned ssaNum = pRenameState->Top(lclNum);
// See if this ssaNum is already an arg to the phi.
bool alreadyArg = false;
for (GenTreePhi::Use& use : phi->Uses())
{
if (use.GetNode()->AsPhiArg()->GetSsaNum() == ssaNum)
{
alreadyArg = true;
break;
}
}
if (!alreadyArg)
{
AddPhiArg(handlerStart, stmt, phi, lclNum, ssaNum, block);
}
}
// Now handle memory.
for (MemoryKind memoryKind : allMemoryKinds())
{
BasicBlock::MemoryPhiArg*& handlerMemoryPhi = handlerStart->bbMemorySsaPhiFunc[memoryKind];
if (handlerMemoryPhi != nullptr)
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// We've already added the arg to the phi shared with ByrefExposed if needed,
// but still need to update bbMemorySsaPhiFunc to stay in sync.
assert(memoryKind > ByrefExposed);
assert(block->bbMemorySsaNumOut[memoryKind] == block->bbMemorySsaNumOut[ByrefExposed]);
assert(handlerStart->bbMemorySsaPhiFunc[ByrefExposed]->m_ssaNum ==
block->bbMemorySsaNumOut[memoryKind]);
handlerMemoryPhi = handlerStart->bbMemorySsaPhiFunc[ByrefExposed];
continue;
}
if (handlerMemoryPhi == BasicBlock::EmptyMemoryPhiDef)
{
handlerMemoryPhi =
new (m_pCompiler) BasicBlock::MemoryPhiArg(block->bbMemorySsaNumOut[memoryKind]);
}
else
{
// This path has a potential to introduce redundant phi args, due to multiple
// preds of the same try-begin block having the same live-out memory def, and/or
// due to nested try-begins each having preds with the same live-out memory def.
// Avoid doing quadratic processing on handler phis, and instead live with the
// occasional redundancy.
handlerMemoryPhi = new (m_pCompiler)
BasicBlock::MemoryPhiArg(block->bbMemorySsaNumOut[memoryKind], handlerMemoryPhi);
}
DBG_SSA_JITDUMP(" Added phi arg for %s u:%d from " FMT_BB " in " FMT_BB ".\n",
memoryKindNames[memoryKind], block->bbMemorySsaNumOut[memoryKind], block->bbNum,
handlerStart->bbNum);
}
}
tryInd = succTry->ebdEnclosingTryIndex;
}
}
}
}
/**
* Perform variable renaming.
*
* Walks the blocks and renames all var defs with ssa numbers and all uses with the
* SSA number that is in the top of the stack. Assigns phi node rhs variables
* (i.e., the arguments to the phi.) Then, calls the function recursively on child
* nodes in the DOM tree to continue the renaming process.
*
* @param block Block for which SSA variables have to be renamed.
* @param pRenameState The incremental rename information stored during renaming process.
*
* @remarks At the end of the method, m_uses and m_defs should be populated linking the
* uses and defs.
*
* @see Briggs, Cooper, Harvey and Simpson "Practical Improvements to the Construction
* and Destruction of Static Single Assignment Form."
*/
void SsaBuilder::RenameVariables(BlkToBlkVectorMap* domTree, SsaRenameState* pRenameState)
{
JITDUMP("*************** In SsaBuilder::RenameVariables()\n");
// The first thing we do is treat parameters and must-init variables as if they have a
// virtual definition before entry -- they start out at SSA name 1.
for (unsigned lclNum = 0; lclNum < m_pCompiler->lvaCount; lclNum++)
{
if (!m_pCompiler->lvaInSsa(lclNum))
{
continue;
}
LclVarDsc* varDsc = &m_pCompiler->lvaTable[lclNum];
assert(varDsc->lvTracked);
if (varDsc->lvIsParam || m_pCompiler->info.compInitMem || varDsc->lvMustInit ||
VarSetOps::IsMember(m_pCompiler, m_pCompiler->fgFirstBB->bbLiveIn, varDsc->lvVarIndex))
{
unsigned ssaNum = varDsc->lvPerSsaData.AllocSsaNum(m_allocator);
// In ValueNum we'd assume un-inited variables get FIRST_SSA_NUM.
assert(ssaNum == SsaConfig::FIRST_SSA_NUM);
pRenameState->Push(m_pCompiler->fgFirstBB, lclNum, ssaNum);
}
}
// In ValueNum we'd assume un-inited memory gets FIRST_SSA_NUM.
// The memory is a parameter. Use FIRST_SSA_NUM as first SSA name.
unsigned initMemorySsaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
assert(initMemorySsaNum == SsaConfig::FIRST_SSA_NUM);
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// GcHeap shares its stack with ByrefExposed; don't re-push.
continue;
}
pRenameState->PushMemory(memoryKind, m_pCompiler->fgFirstBB, initMemorySsaNum);
}
// Initialize the memory ssa numbers for unreachable blocks. ValueNum expects
// memory ssa numbers to have some intitial value.
for (BasicBlock* block = m_pCompiler->fgFirstBB; block; block = block->bbNext)
{
if (block->bbIDom == nullptr)
{
for (MemoryKind memoryKind : allMemoryKinds())
{
block->bbMemorySsaNumIn[memoryKind] = initMemorySsaNum;
block->bbMemorySsaNumOut[memoryKind] = initMemorySsaNum;
}
}
}
struct BlockWork
{
BasicBlock* m_blk;
bool m_processed; // Whether the this block have already been processed: its var renamed, and children
// processed.
// If so, awaiting only BlockPopStacks.
BlockWork(BasicBlock* blk, bool processed = false) : m_blk(blk), m_processed(processed)
{
}
};
typedef jitstd::vector<BlockWork> BlockWorkStack;
BlockWorkStack* blocksToDo = new (m_allocator) BlockWorkStack(m_allocator);
blocksToDo->push_back(BlockWork(m_pCompiler->fgFirstBB)); // Probably have to include other roots of dom tree.
while (blocksToDo->size() != 0)
{
BlockWork blockWrk = blocksToDo->back();
blocksToDo->pop_back();
BasicBlock* block = blockWrk.m_blk;
DBG_SSA_JITDUMP("[SsaBuilder::RenameVariables](" FMT_BB ", processed = %d)\n", block->bbNum,
blockWrk.m_processed);
if (!blockWrk.m_processed)
{
// Push the block back on the stack with "m_processed" true, to record the fact that when its children have
// been (recursively) processed, we still need to call BlockPopStacks on it.
blocksToDo->push_back(BlockWork(block, true));
BlockRenameVariables(block, pRenameState);
// Assign arguments to the phi node of successors, corresponding to the block's index.
AssignPhiNodeRhsVariables(block, pRenameState);
// Recurse with the block's DOM children.
BlkVector* domChildren = domTree->LookupPointer(block);
if (domChildren != nullptr)
{
for (BasicBlock* child : *domChildren)
{
DBG_SSA_JITDUMP("[SsaBuilder::RenameVariables](pushing dom child " FMT_BB ")\n", child->bbNum);
blocksToDo->push_back(BlockWork(child));
}
}
}
else
{
// Done, pop all SSA numbers pushed in this block.
pRenameState->PopBlockStacks(block);
DBG_SSA_JITDUMP("[SsaBuilder::RenameVariables] done with " FMT_BB "\n", block->bbNum);
}
}
}
#ifdef DEBUG
/**
* Print the blocks, the phi nodes get printed as well.
* @example:
* After SSA BB02:
* [0027CC0C] ----------- stmtExpr void (IL 0x019...0x01B)
* N001 ( 1, 1) [0027CB70] ----------- const int 23
* N003 ( 3, 3) [0027CBD8] -A------R-- = int
* N002 ( 1, 1) [0027CBA4] D------N--- lclVar int V01 arg1 d:5
*
* After SSA BB04:
* [0027D530] ----------- stmtExpr void (IL ???... ???)
* N002 ( 0, 0) [0027D4C8] ----------- phi int
* [0027D8CC] ----------- lclVar int V01 arg1 u:5
* [0027D844] ----------- lclVar int V01 arg1 u:4
* N004 ( 2, 2) [0027D4FC] -A------R-- = int
* N003 ( 1, 1) [0027D460] D------N--- lclVar int V01 arg1 d:3
*/
void SsaBuilder::Print(BasicBlock** postOrder, int count)
{
for (int i = count - 1; i >= 0; --i)
{
printf("After SSA " FMT_BB ":\n", postOrder[i]->bbNum);
m_pCompiler->gtDispBlockStmts(postOrder[i]);
}
}
#endif // DEBUG
/**
* Build SSA form.
*
* Sorts the graph topologically.
* - Collects them in postOrder array.
*
* Identifies each block's immediate dominator.
* - Computes this in bbIDom of each BasicBlock.
*
* Computes DOM tree relation.
* - Computes domTree as block -> set of blocks.
* - Computes pre/post order traversal of the DOM tree.
*
* Inserts phi nodes.
* - Computes dominance frontier as block -> set of blocks.
* - Allocates block use/def/livein/liveout and computes it.
* - Inserts phi nodes with only rhs at the beginning of the blocks.
*
* Renames variables.
* - Walks blocks in evaluation order and gives uses and defs names.
* - Gives empty phi nodes their rhs arguments as they become known while renaming.
*
* @return true if successful, for now, this must always be true.
*
* @see "A simple, fast dominance algorithm" by Keith D. Cooper, Timothy J. Harvey, Ken Kennedy.
* @see Briggs, Cooper, Harvey and Simpson "Practical Improvements to the Construction
* and Destruction of Static Single Assignment Form."
*/
void SsaBuilder::Build()
{
#ifdef DEBUG
if (m_pCompiler->verbose)
{
printf("*************** In SsaBuilder::Build()\n");
}
#endif
// Ensure that there's a first block outside a try, so that the dominator tree has a unique root.
SetupBBRoot();
// Just to keep block no. & index same add 1.
int blockCount = m_pCompiler->fgBBNumMax + 1;
JITDUMP("[SsaBuilder] Max block count is %d.\n", blockCount);
// Allocate the postOrder array for the graph.
BasicBlock** postOrder;
if (blockCount > DEFAULT_MIN_OPTS_BB_COUNT)
{
postOrder = new (m_allocator) BasicBlock*[blockCount];
}
else
{
postOrder = (BasicBlock**)alloca(blockCount * sizeof(BasicBlock*));
}
m_visitedTraits = BitVecTraits(blockCount, m_pCompiler);
m_visited = BitVecOps::MakeEmpty(&m_visitedTraits);
// Topologically sort the graph.
int count = TopologicalSort(postOrder, blockCount);
JITDUMP("[SsaBuilder] Topologically sorted the graph.\n");
EndPhase(PHASE_BUILD_SSA_TOPOSORT);
// Compute IDom(b).
ComputeImmediateDom(postOrder, count);
// Compute the dominator tree.
BlkToBlkVectorMap* domTree = new (m_allocator) BlkToBlkVectorMap(m_allocator);
ComputeDominators(postOrder, count, domTree);
EndPhase(PHASE_BUILD_SSA_DOMS);
// Compute liveness on the graph.
m_pCompiler->fgLocalVarLiveness();
EndPhase(PHASE_BUILD_SSA_LIVENESS);
// Mark all variables that will be tracked by SSA
for (unsigned lclNum = 0; lclNum < m_pCompiler->lvaCount; lclNum++)
{
m_pCompiler->lvaTable[lclNum].lvInSsa = IncludeInSsa(lclNum);
}
// Insert phi functions.
InsertPhiFunctions(postOrder, count);
// Rename local variables and collect UD information for each ssa var.
SsaRenameState renameState(m_allocator, m_pCompiler->lvaCount);
RenameVariables(domTree, &renameState);
EndPhase(PHASE_BUILD_SSA_RENAME);
#ifdef DEBUG
// At this point we are in SSA form. Print the SSA form.
if (m_pCompiler->verboseSsa)
{
Print(postOrder, count);
}
#endif
}
void SsaBuilder::SetupBBRoot()
{
// Allocate a bbroot, if necessary.
// We need a unique block to be the root of the dominator tree.
// This can be violated if the first block is in a try, or if it is the first block of
// a loop (which would necessarily be an infinite loop) -- i.e., it has a predecessor.
// If neither condition holds, no reason to make a new block.
if (!m_pCompiler->fgFirstBB->hasTryIndex() && m_pCompiler->fgFirstBB->bbPreds == nullptr)
{
return;
}
BasicBlock* bbRoot = m_pCompiler->bbNewBasicBlock(BBJ_NONE);
bbRoot->bbFlags |= BBF_INTERNAL;
// May need to fix up preds list, so remember the old first block.
BasicBlock* oldFirst = m_pCompiler->fgFirstBB;
// Copy the liveness information from the first basic block.
if (m_pCompiler->fgLocalVarLivenessDone)
{
VarSetOps::Assign(m_pCompiler, bbRoot->bbLiveIn, oldFirst->bbLiveIn);
VarSetOps::Assign(m_pCompiler, bbRoot->bbLiveOut, oldFirst->bbLiveIn);
}
// Copy the bbWeight. (This is technically wrong, if the first block is a loop head, but
// it shouldn't matter...)
bbRoot->inheritWeight(oldFirst);
// There's an artifical incoming reference count for the first BB. We're about to make it no longer
// the first BB, so decrement that.
assert(oldFirst->bbRefs > 0);
oldFirst->bbRefs--;
m_pCompiler->fgInsertBBbefore(m_pCompiler->fgFirstBB, bbRoot);
assert(m_pCompiler->fgFirstBB == bbRoot);
if (m_pCompiler->fgComputePredsDone)
{
m_pCompiler->fgAddRefPred(oldFirst, bbRoot);
}
}
//------------------------------------------------------------------------
// IncludeInSsa: Check if the specified variable can be included in SSA.
//
// Arguments:
// lclNum - the variable number
//
// Return Value:
// true if the variable is included in SSA
//
bool SsaBuilder::IncludeInSsa(unsigned lclNum)
{
LclVarDsc* varDsc = &m_pCompiler->lvaTable[lclNum];
if (varDsc->lvAddrExposed)
{
return false; // We exclude address-exposed variables.
}
if (!varDsc->lvTracked)
{
return false; // SSA is only done for tracked variables
}
// lvPromoted structs are never tracked...
assert(!varDsc->lvPromoted);
if (varDsc->lvOverlappingFields)
{
return false; // Don't use SSA on structs that have overlapping fields
}
if (varDsc->lvIsStructField &&
(m_pCompiler->lvaGetParentPromotionType(lclNum) != Compiler::PROMOTION_TYPE_INDEPENDENT))
{
// SSA must exclude struct fields that are not independent
// - because we don't model the struct assignment properly when multiple fields can be assigned by one struct
// assignment.
// - SSA doesn't allow a single node to contain multiple SSA definitions.
// - and PROMOTION_TYPE_DEPENDEDNT fields are never candidates for a register.
//
// Example mscorlib method: CompatibilitySwitches:IsCompatibilitySwitchSet
//
return false;
}
// otherwise this variable is included in SSA
return true;
}
#ifdef DEBUG
// This method asserts that SSA name constraints specified are satisfied.
void Compiler::JitTestCheckSSA()
{
struct SSAName
{
unsigned m_lvNum;
unsigned m_ssaNum;
static unsigned GetHashCode(SSAName ssaNm)
{
return ssaNm.m_lvNum << 16 | ssaNm.m_ssaNum;
}
static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
{
return ssaNm1.m_lvNum == ssaNm2.m_lvNum && ssaNm1.m_ssaNum == ssaNm2.m_ssaNum;
}
};
typedef JitHashTable<ssize_t, JitSmallPrimitiveKeyFuncs<ssize_t>, SSAName> LabelToSSANameMap;
typedef JitHashTable<SSAName, SSAName, ssize_t> SSANameToLabelMap;
// If we have no test data, early out.
if (m_nodeTestData == nullptr)
{
return;
}
NodeToTestDataMap* testData = GetNodeTestData();
// First we have to know which nodes in the tree are reachable.
NodeToIntMap* reachable = FindReachableNodesInNodeTestData();
LabelToSSANameMap* labelToSSA = new (getAllocatorDebugOnly()) LabelToSSANameMap(getAllocatorDebugOnly());
SSANameToLabelMap* ssaToLabel = new (getAllocatorDebugOnly()) SSANameToLabelMap(getAllocatorDebugOnly());
if (verbose)
{
printf("\nJit Testing: SSA names.\n");
}
for (NodeToTestDataMap::KeyIterator ki = testData->Begin(); !ki.Equal(testData->End()); ++ki)
{
TestLabelAndNum tlAndN;
GenTree* node = ki.Get();
bool nodeExists = testData->Lookup(node, &tlAndN);
assert(nodeExists);
if (tlAndN.m_tl == TL_SsaName)
{
if (node->OperGet() != GT_LCL_VAR)
{
printf("SSAName constraint put on non-lcl-var expression ");
printTreeID(node);
printf(" (of type %s).\n", varTypeName(node->TypeGet()));
unreached();
}
GenTreeLclVarCommon* lcl = node->AsLclVarCommon();
int dummy;
if (!reachable->Lookup(lcl, &dummy))
{
printf("Node ");
printTreeID(lcl);
printf(" had a test constraint declared, but has become unreachable at the time the constraint is "
"tested.\n"
"(This is probably as a result of some optimization -- \n"
"you may need to modify the test case to defeat this opt.)\n");
unreached();
}
if (verbose)
{
printf(" Node: ");
printTreeID(lcl);
printf(", SSA name = <%d, %d> -- SSA name class %d.\n", lcl->GetLclNum(), lcl->GetSsaNum(),
tlAndN.m_num);
}
SSAName ssaNm;
if (labelToSSA->Lookup(tlAndN.m_num, &ssaNm))
{
if (verbose)
{
printf(" Already in hash tables.\n");
}
// The mapping(s) must be one-to-one: if the label has a mapping, then the ssaNm must, as well.
ssize_t num2;
bool ssaExists = ssaToLabel->Lookup(ssaNm, &num2);
assert(ssaExists);
// And the mappings must be the same.
if (tlAndN.m_num != num2)
{
printf("Node: ");
printTreeID(lcl);
printf(", SSA name = <%d, %d> was declared in SSA name class %d,\n", lcl->GetLclNum(),
lcl->GetSsaNum(), tlAndN.m_num);
printf(
"but this SSA name <%d,%d> has already been associated with a different SSA name class: %d.\n",
ssaNm.m_lvNum, ssaNm.m_ssaNum, num2);
unreached();
}
// And the current node must be of the specified SSA family.
if (!(lcl->GetLclNum() == ssaNm.m_lvNum && lcl->GetSsaNum() == ssaNm.m_ssaNum))
{
printf("Node: ");
printTreeID(lcl);
printf(", SSA name = <%d, %d> was declared in SSA name class %d,\n", lcl->GetLclNum(),
lcl->GetSsaNum(), tlAndN.m_num);
printf("but that name class was previously bound to a different SSA name: <%d,%d>.\n",
ssaNm.m_lvNum, ssaNm.m_ssaNum);
unreached();
}
}
else
{
ssaNm.m_lvNum = lcl->GetLclNum();
ssaNm.m_ssaNum = lcl->GetSsaNum();
ssize_t num;
// The mapping(s) must be one-to-one: if the label has no mapping, then the ssaNm may not, either.
if (ssaToLabel->Lookup(ssaNm, &num))
{
printf("Node: ");
printTreeID(lcl);
printf(", SSA name = <%d, %d> was declared in SSA name class %d,\n", lcl->GetLclNum(),
lcl->GetSsaNum(), tlAndN.m_num);
printf("but this SSA name has already been associated with a different name class: %d.\n", num);
unreached();
}
// Add to both mappings.
labelToSSA->Set(tlAndN.m_num, ssaNm);
ssaToLabel->Set(ssaNm, tlAndN.m_num);
if (verbose)
{
printf(" added to hash tables.\n");
}
}
}
}
}
#endif // DEBUG
|
SECTION code_fp_math48
PUBLIC _islessgreater_callee
EXTERN cm48_sdcciy_islessgreater_callee
defc _islessgreater_callee = cm48_sdcciy_islessgreater_callee
|
/*
* Copyright 2018-2021 Mahdi Khanalizadeh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
.intel_syntax noprefix
.global linux_syscall3
linux_syscall3:
push ebx
mov eax, [esp+20] # arg4 -> #
mov edx, [esp+16] # arg3 -> arg3
mov ecx, [esp+12] # arg2 -> arg2
mov ebx, [esp+ 8] # arg1 -> arg1
int 0x80
pop ebx
ret
|
BITS 32
extern main
global start
start:
call main
jmp 0
|
; A096023: Numbers congruent to {63, 123, 183, 243, 303, 363} mod 420.
; 63,123,183,243,303,363,483,543,603,663,723,783,903,963,1023,1083,1143,1203,1323,1383,1443,1503,1563,1623,1743,1803,1863,1923,1983,2043,2163,2223,2283,2343,2403,2463,2583,2643,2703,2763,2823,2883,3003,3063,3123
mul $0,7
div $0,6
mov $1,$0
mul $1,60
add $1,63
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r8
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xbfae, %rbx
nop
nop
nop
nop
nop
xor $38182, %r8
mov (%rbx), %r11d
nop
nop
cmp %r13, %r13
lea addresses_WC_ht+0xd5f4, %r9
nop
nop
nop
add %rdi, %rdi
mov (%r9), %esi
nop
nop
nop
nop
nop
add $28004, %r8
lea addresses_WC_ht+0x4ae2, %rsi
lea addresses_UC_ht+0x73d0, %rdi
clflush (%rdi)
add %r13, %r13
mov $17, %rcx
rep movsq
nop
nop
nop
sub $3880, %rcx
lea addresses_WC_ht+0x121f4, %rbx
nop
nop
sub $4207, %r11
movl $0x61626364, (%rbx)
nop
nop
add %rcx, %rcx
lea addresses_D_ht+0x136f4, %r13
nop
nop
nop
nop
xor %r9, %r9
mov (%r13), %rdi
nop
nop
nop
nop
nop
cmp $43168, %rcx
lea addresses_D_ht+0x5d5c, %rsi
lea addresses_UC_ht+0x79f4, %rdi
nop
nop
nop
dec %rbx
mov $15, %rcx
rep movsq
nop
xor %r13, %r13
lea addresses_D_ht+0x1cd64, %rbx
nop
nop
nop
nop
xor $41559, %rdi
vmovups (%rbx), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $1, %xmm4, %r9
nop
nop
and %rbx, %rbx
lea addresses_D_ht+0x2284, %rsi
lea addresses_normal_ht+0xe1f4, %rdi
nop
nop
nop
sub %r11, %r11
mov $63, %rcx
rep movsq
nop
nop
xor %r11, %r11
lea addresses_A_ht+0x82c6, %r11
cmp $45842, %rcx
and $0xffffffffffffffc0, %r11
movaps (%r11), %xmm6
vpextrq $0, %xmm6, %rdi
nop
nop
dec %rdi
lea addresses_normal_ht+0x1b9f4, %rcx
nop
nop
nop
nop
add $29129, %r13
mov $0x6162636465666768, %rsi
movq %rsi, (%rcx)
nop
xor %r8, %r8
lea addresses_WT_ht+0x154f4, %rsi
lea addresses_D_ht+0x125f4, %rdi
add $50870, %rbx
mov $116, %rcx
rep movsq
nop
add $17887, %r9
lea addresses_WT_ht+0x7bf4, %r8
nop
nop
nop
nop
nop
and %r9, %r9
mov $0x6162636465666768, %rsi
movq %rsi, (%r8)
nop
nop
nop
nop
sub %rsi, %rsi
lea addresses_WT_ht+0x163da, %r13
nop
xor %r9, %r9
mov $0x6162636465666768, %r8
movq %r8, %xmm6
movups %xmm6, (%r13)
nop
cmp %r11, %r11
lea addresses_A_ht+0x1aef4, %r13
clflush (%r13)
nop
nop
nop
dec %rbx
mov (%r13), %edi
nop
nop
nop
nop
dec %rdi
lea addresses_WC_ht+0x1b534, %rdi
nop
nop
nop
nop
dec %r13
mov $0x6162636465666768, %r9
movq %r9, %xmm3
vmovups %ymm3, (%rdi)
nop
lfence
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %rbx
push %rcx
push %rdx
push %rsi
// Store
mov $0x1f4, %rdx
nop
nop
nop
nop
nop
dec %rcx
mov $0x5152535455565758, %r11
movq %r11, %xmm3
vmovups %ymm3, (%rdx)
nop
nop
nop
and %rdx, %rdx
// Faulty Load
mov $0x2d64c00000001f4, %rcx
nop
and $53140, %r11
vmovups (%rcx), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $0, %xmm0, %rdx
lea oracles, %rsi
and $0xff, %rdx
shlq $12, %rdx
mov (%rsi,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rcx
pop %rbx
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'same': False, 'size': 1, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_P', 'same': False, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 8, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 32, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': True}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 16, 'congruent': 1, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_normal_ht', 'same': True, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 16, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 32, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'e6': 51, '1a': 55, 'b0': 40, '54': 57, '1e': 65, 'f8': 64, '1c': 63, 'd4': 70, '80': 58, '2a': 58, '46': 48, '8a': 78, 'c4': 59, '0e': 65, 'de': 53, '32': 54, 'dc': 55, '76': 52, '5a': 47, '04': 61, '68': 56, 'e2': 60, 'd6': 65, '9c': 56, 'bc': 57, '34': 54, 'fe': 61, 'ee': 60, '5e': 53, '28': 68, 'f2': 61, '22': 46, '14': 61, '98': 65, 'a6': 43, '18': 77, '6c': 78, '62': 60, '6e': 57, 'ea': 66, '60': 59, 'a2': 53, 'f0': 53, '0c': 51, '12': 44, 'ac': 68, '2e': 57, '9a': 59, '38': 63, 'ae': 56, 'd2': 58, 'c6': 53, '4e': 50, '5c': 54, 'b4': 69, 'ca': 60, 'ba': 62, 'a8': 67, 'b8': 58, '48': 61, 'fa': 57, 'da': 60, '2c': 66, 'ec': 65, 'd8': 63, 'e4': 76, '9e': 53, 'c8': 72, '44': 63, 'cc': 66, '66': 64, '82': 67, '08': 69, '3c': 60, '24': 66, '36': 72, '56': 48, '4a': 54, 'ce': 63, '42': 46, '58': 13620, '3e': 44, '20': 46, 'c2': 54, 'b2': 52, '26': 48, '74': 66, '50': 45, '5f': 1, '0a': 51, '30': 48, '3a': 64, 'be': 65, '90': 52, '88': 59, '8e': 68, '7e': 63, '94': 61, '40': 52, '7a': 69, 'f4': 69, '52': 53, '6a': 51, 'fc': 52, 'd0': 55, '16': 58, 'f6': 63, '02': 59, 'e0': 48, '92': 67, 'e8': 55, '10': 44, 'c0': 57, '7c': 55, '96': 44, 'aa': 62, '4c': 63, '72': 60, '84': 61, '06': 59, '78': 55, '8c': 60, 'b6': 65, 'a4': 66, '86': 48, '70': 35, '00': 862, 'a0': 58, '64': 55}
9c 58 00 1e 58 58 58 58 00 58 36 58 34 58 58 58 00 44 58 58 58 82 58 58 58 a0 58 58 ac 58 58 58 58 72 38 58 a2 58 58 58 e2 7e b8 4a be 58 58 00 00 58 66 00 30 58 58 58 58 58 58 58 58 2c 58 58 00 c4 58 58 82 92 7c 00 b2 58 58 58 58 a2 80 00 58 58 58 00 4a d2 00 58 14 04 58 58 58 58 b4 58 58 58 58 1e 58 c0 58 58 7e 36 32 ac 58 58 58 58 4a 58 d6 58 58 58 58 58 58 58 58 ee 58 58 c4 d8 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 96 58 58 6a 58 58 58 58 dc 58 58 3c 58 cc 58 58 dc f2 dc 58 b2 f2 a6 6a 58 58 58 06 58 58 82 58 58 ec 58 58 50 58 58 64 00 58 58 20 70 58 58 58 58 e2 58 a2 58 58 58 58 c4 58 58 52 58 ba 58 58 ae 58 58 2a 58 58 58 58 52 26 58 58 58 58 58 ca 1c 58 e4 1c 58 58 58 58 58 ae 9e 58 58 74 58 58 ac f2 58 58 66 54 58 58 58 48 b2 58 58 58 06 0c 58 2c 58 58 58 60 58 d8 06 58 58 58 58 a0 58 58 5c 58 58 58 66 58 58 58 58 58 4c ce 58 58 d8 58 58 50 58 58 16 5a 58 ca b6 00 fc 86 00 d0 58 58 b6 58 58 58 58 58 58 b8 58 b4 58 58 58 58 22 58 58 58 58 58 02 ee 58 58 d4 58 58 58 c0 58 58 b6 00 58 d8 fe 58 00 58 58 58 ee 58 58 58 00 fa 00 82 58 78 58 58 58 98 58 9a a0 58 58 7a 58 58 58 00 8c 00 58 58 58 08 58 58 5c b2 08 58 38 58 58 54 58 f4 58 58 58 58 58 58 58 58 60 58 58 1e e2 0c f0 58 fa 58 58 58 cc 58 58 58 58 58 58 80 58 58 58 58 96 9c 58 3a 58 f2 00 66 58 58 92 58 58 58 58 40 58 58 58 58 58 b6 58 58 58 58 58 58 58 58 1a 58 58 7e 58 58 50 9a 58 0a 54 92 58 f6 58 36 1e 58 58 c8 58 46 58 58 58 24 58 58 be f2 9c 58 6c 58 58 58 58 a6 28 76 58 58 58 14 00 be 6a 58 58 ae 78 00 58 00 58 9a 58 58 58 58 58 58 58 ba 58 80 58 58 58 58 58 48 8e 26 58 58 58 58 58 58 58 96 58 58 58 e4 58 58 58 2c 58 58 82 58 58 58 fa 48 58 58 58 58 58 7a 58 58 58 58 58 58 00 58 58 52 58 58 58 58 58 14 00 aa a4 b4 58 58 da 58 58 58 1a 58 ac 58 58 58 58 58 58 36 56 58 58 58 58 58 24 58 58 58 aa 58 58 5e 58 2e 18 58 2c 58 58 38 58 42 ca 58 58 58 58 58 58 38 58 58 36 00 58 58 58 84 da 58 58 78 58 68 58 58 58 58 58 4c 58 58 7a 58 58 58 c2 58 58 58 58 b6 58 4a ac 58 d6 58 66 00 1e 58 c2 58 58 16 ea 58 58 58 58 58 58 58 58 58 b6 1a d0 58 58 58 58 00 00 58 18 ec 58 d2 58 60 58 58 58 64 58 72 58 e0 58 58 14 58 58 58 58 e2 58 58 58 b2 58 58 58 58 58 e4 58 76 00 ca f4 58 58 aa 58 58 48 58 58 58 5c 4c 58 44 58 c8 5e 58 58 58 58 58 8e 58 de 58 58 58 5e 58 02 58 58 58 58 0a 58 58 76 9c 00 aa 58 58 58 90 00 00 10 5c 58 14 58 24 00 e2 fe 58 58 04 58 58 58 58 58 c2 58 58 58 58 6a 58 58 58 58 58 58 58 f8 58 58 e2 58 58 c0 58 58 40 58 58 58 58 26 58 58 58 58 7e 58 a8 58 58 58 86 58 fa 58 58 e4 58 58 58 58 f6 52 58 58 58 58 58 58 28 58 58 00 58 00 fa 20 58 58 58 58 34 58 58 f0 58 fa 58 58 58 58 58 58 f2 58 58 58 26 00 be 58 26 58 dc cc e0 58 58 58 c0 58 4a 00 5a 58 00 2a 58 58 58 46 26 58 58 1e 58 62 58 ca 84 58 58 58 58 b4 58 98 fa b6 58 c8 58 58 24 58 58 58 58 58 58 58 9c 58 58 58 2e 58 00 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 f4 58 58 58 f2 58 58 58 b2 84 96 58 26 58 ba 58 ce 58 58 58 4e 58 0a 58 da 00 58 58 a6 58 20 e8 36 58 58 58 58 d0 58 e6 2a 3e ec 58 58 06 58 c8 58 00
*/
|
; A143580: Duplicate of A010059.
; 1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0,0
lpb $0,1
add $1,$0
div $0,2
lpe
gcd $1,2
sub $1,1
|
; A022100: Fibonacci sequence beginning 1, 10.
; 1,10,11,21,32,53,85,138,223,361,584,945,1529,2474,4003,6477,10480,16957,27437,44394,71831,116225,188056,304281,492337,796618,1288955,2085573,3374528,5460101,8834629,14294730,23129359,37424089,60553448,97977537,158530985
mov $1,1
mov $2,9
lpb $0
sub $0,1
mov $3,$2
mov $2,$1
add $1,$3
lpe
mov $0,$1
|
//****************************************************************************
// (c) 2008, 2009 by the openOR Team
//****************************************************************************
// The contents of this file are available under the GPL v2.0 license
// or under the openOR comercial license. see
// /Doc/openOR_free_license.txt or
// /Doc/openOR_comercial_license.txt
// for Details.
//****************************************************************************
/**
* @file
* @author Christian Winne
* @ingroup openOR_core_math
*/
#ifndef openOR_core_Math_detail_determinant_impl_hpp
#define openOR_core_Math_detail_determinant_impl_hpp
#include <boost/mpl/assert.hpp>
#include <boost/mpl/void.hpp>
#include <boost/type_traits/is_same.hpp>
#include <openOR/Math/matrix.hpp>
namespace openOR {
namespace Math {
namespace Impl {
template<class Type, int Dim>
struct Determinant {
typename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {
// function has to be implemented
BOOST_MPL_ASSERT((boost::is_same<Type, boost::mpl::void_>));
}
};
//determinant of 2x2 matrix
template<class Type>
struct Determinant<Type, 2> {
typename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {
return Math::get<0, 0>(mat) * Math::get<1, 1>(mat) - Math::get<0, 1>(mat) * Math::get<1, 0>(mat);
}
};
//determinant of 3x3 matrix
template<class Type>
struct Determinant<Type, 3> {
typename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {
return Math::get<0, 0>(mat) * Math::get<1, 1>(mat) * Math::get<2, 2>(mat) +
Math::get<0, 1>(mat) * Math::get<1, 2>(mat) * Math::get<2, 0>(mat) +
Math::get<0, 2>(mat) * Math::get<1, 0>(mat) * Math::get<2, 1>(mat) -
Math::get<2, 0>(mat) * Math::get<1, 1>(mat) * Math::get<0, 2>(mat) -
Math::get<2, 1>(mat) * Math::get<1, 2>(mat) * Math::get<0, 0>(mat) -
Math::get<2, 2>(mat) * Math::get<1, 0>(mat) * Math::get<0, 1>(mat);
}
};
//determinant of 4x4 matrix
template<class Type>
struct Determinant<Type, 4> {
typename MatrixTraits<Type>::ValueType operator()(const Type& mat) const {
return Math::get<0, 0>(mat) * Math::get<1, 1>(mat) * Math::get<2, 2>(mat) * Math::get<3, 3>(mat) +
Math::get<0, 0>(mat) * Math::get<1, 2>(mat) * Math::get<2, 3>(mat) * Math::get<3, 1>(mat) +
Math::get<0, 0>(mat) * Math::get<1, 3>(mat) * Math::get<2, 1>(mat) * Math::get<3, 2>(mat) +
Math::get<0, 1>(mat) * Math::get<1, 0>(mat) * Math::get<2, 3>(mat) * Math::get<3, 2>(mat) +
Math::get<0, 1>(mat) * Math::get<1, 2>(mat) * Math::get<2, 0>(mat) * Math::get<3, 3>(mat) +
Math::get<0, 1>(mat) * Math::get<1, 3>(mat) * Math::get<2, 2>(mat) * Math::get<3, 0>(mat) +
Math::get<0, 2>(mat) * Math::get<1, 0>(mat) * Math::get<2, 1>(mat) * Math::get<3, 3>(mat) +
Math::get<0, 2>(mat) * Math::get<1, 1>(mat) * Math::get<2, 3>(mat) * Math::get<3, 0>(mat) +
Math::get<0, 2>(mat) * Math::get<1, 3>(mat) * Math::get<2, 0>(mat) * Math::get<3, 1>(mat) +
Math::get<0, 3>(mat) * Math::get<1, 0>(mat) * Math::get<2, 2>(mat) * Math::get<3, 1>(mat) +
Math::get<0, 3>(mat) * Math::get<1, 1>(mat) * Math::get<2, 0>(mat) * Math::get<3, 2>(mat) +
Math::get<0, 3>(mat) * Math::get<1, 2>(mat) * Math::get<2, 1>(mat) * Math::get<3, 0>(mat) -
Math::get<0, 0>(mat) * Math::get<1, 1>(mat) * Math::get<2, 3>(mat) * Math::get<3, 2>(mat) -
Math::get<0, 0>(mat) * Math::get<1, 2>(mat) * Math::get<2, 1>(mat) * Math::get<3, 3>(mat) -
Math::get<0, 0>(mat) * Math::get<1, 3>(mat) * Math::get<2, 2>(mat) * Math::get<3, 1>(mat) -
Math::get<0, 1>(mat) * Math::get<1, 0>(mat) * Math::get<2, 2>(mat) * Math::get<3, 3>(mat) -
Math::get<0, 1>(mat) * Math::get<1, 2>(mat) * Math::get<2, 3>(mat) * Math::get<3, 0>(mat) -
Math::get<0, 1>(mat) * Math::get<1, 3>(mat) * Math::get<2, 0>(mat) * Math::get<3, 2>(mat) -
Math::get<0, 2>(mat) * Math::get<1, 0>(mat) * Math::get<2, 3>(mat) * Math::get<3, 1>(mat) -
Math::get<0, 2>(mat) * Math::get<1, 1>(mat) * Math::get<2, 0>(mat) * Math::get<3, 3>(mat) -
Math::get<0, 2>(mat) * Math::get<1, 3>(mat) * Math::get<2, 1>(mat) * Math::get<3, 0>(mat) -
Math::get<0, 3>(mat) * Math::get<1, 0>(mat) * Math::get<2, 1>(mat) * Math::get<3, 2>(mat) -
Math::get<0, 3>(mat) * Math::get<1, 1>(mat) * Math::get<2, 2>(mat) * Math::get<3, 0>(mat) -
Math::get<0, 3>(mat) * Math::get<1, 2>(mat) * Math::get<2, 0>(mat) * Math::get<3, 1>(mat);
}
};
}
}
}
#endif
|
*=$0801 ; basic start
!WORD +
!WORD 10
!BYTE $9E
!TEXT "2061"
!BYTE 0
+ !WORD 0
jmp main
waitborder
; lda $d011
; bmi ok
;wait
; lda $d012
; cmp #30
; bcs wait
;ok
wait
lda $d011
bpl wait
rts
cnt !byte 0
ieindex !byte 0
beindex !byte 0
betab !byte $00,$01,$08,$09 ; before dc0e (wraps into ietab, len=8!)
!byte $10,$11,$18,$19
ietab !byte $10,$11,$18,$19 ; init dc0e
!byte 0
i4 !byte 0 ; init dc04
ie !byte 0 ; init dc0e
b4 !byte 0 ; before dc04
be !byte 0 ; before dc0e
a4 !byte 0 ; after dc04
ad !byte 0 ; after dc0d
ae !byte 0 ; after dc0e
main
ldx #0
-
lda #1
sta $d800,x
sta $d900,x
sta $da00,x
sta $db00,x
lda #$20
sta $0400,x
sta $0500,x
sta $0600,x
sta $0700,x
inx
bne -
lda #0
sta i4
lda #4
sta b4
lda #0
sta ieindex
sta beindex
loop
sei
lda #$7f
sta $dc0d
lda #$81
sta $dc0d
jsr waitborder
lda #0
sta $dc0e
sta $dc05
ldx ieindex
lda ietab,x
sta ie
ldx beindex
ldy betab,x
sty be
; write values "init"
ldx i4
stx $dc04 ; i4
ldx #$10 ; force load, but do not start
stx $dc0e
bit $dc0d ; ack
sta $dc0e ; ie
; write values "before"
lda b4
sta $dc04 ; b4
sty $dc0e ; be
; get values "after"
lda $dc04 ; a4
ldx $dc0d ; ad
ldy $dc0e ; ae
sta a4
stx ad
sty ae
jsr $fda3 ; initialize I/O
cli
; ------------------------------------------------------------------------------
compare
ldx cnt
lda a4
sta $0400,x
lda ad
sta $0400+(7*40),x
lda ae
sta $0400+(14*40),x
inx
stx cnt
inc beindex
lda beindex
cmp #8
bcc jmploop
lda #0
sta beindex
inc ieindex
lda ieindex
cmp #5
bcc jmploop
lda #0
sta ieindex
; jmp *
dec b4
lda b4
cmp #$fe
bne jmploop
; lda #20
; sta b4
jmp finish
; dec i4
; bpl jmploop
; jmp finish
jmploop
jmp loop
finish
ldy #5
sty $d020
ldx #0
lp1:
ldy #5
lda $0400,x
cmp reference,x
beq sk1
ldy #10
sty $d020
sk1:
tya
sta $d800,x
inx
cpx #40*6
bne lp1
ldx #0
lp2:
ldy #5
lda $0400+(7*40),x
cmp reference+(7*40),x
beq sk2
ldy #10
sty $d020
sk2:
tya
sta $d800+(7*40),x
inx
cpx #40*6
bne lp2
ldx #0
lp3:
ldy #5
lda $0400+(14*40),x
cmp reference+(14*40),x
beq sk3
ldy #10
sty $d020
sk3:
tya
sta $d800+(14*40),x
inx
cpx #40*6
bne lp3
lda $d020
and #$0f
ldx #0 ; success
cmp #10
bne nofail
ldx #$ff ; failure
nofail:
stx $d7ff
jmp *
reference:
!binary "reload0a.ref",,2
|
; Pisq (c)2000 Stepan Roh
IDEAL
P386
MODEL small, C
STACK 200h
DATASEG
; informacni text
info db 'Pisq (c)2000 SR',13,10
db '(_|brain1.exe) (_|brain2.exe)',13,10
db '$'
; vypisy do stavove (prvni) radky
; format: cislo_tahu body_pro_O O kdo_je_na_tahu_-_sipka X body_pro_X text
str_human db '000 00 O X 00 Hit "S" for surrender', 0
str_brain db '000 00 O X 00 ', 0
str_again_q db '000 00 O X 00 Again (y/n)? ', 0
str_brain_err db '000 00 O X 00 Error loading brain! ', 0
str_file_err db '000 00 O X 00 File I/O error! ', 0
; nastaveni textoveho rezimu
TEXT_SEG equ 0b800h ; segment pameti vram v textu
TEXT_MODE equ 3 ; textovy mod
old_mode db ? ; stary textovy mod
text_width dw ? ; sirka obrazovky
text_width_df dw ? ; sirka obrazovky nasobena DESK_FSIZE
; veci tykajici se hry
NAME_LEN equ 13 ; max. delka jmena
brain1 db NAME_LEN dup(?), 0 ; jmeno prvniho hrace (max. 13 znaku)
brain2 db NAME_LEN dup(?), 0 ; jmeno druheho hrace (max. 13 znaku)
lbrain1 db 0 ; delka jmena prvniho hrace
; - 0 znaci cloveka (i u lbrain2)
lbrain2 db 0 ; delka jmena druheho hrace
; - musi byt ihned za lbrain1
score1 db 0 ; skore prvniho hrace
score2 db 0 ; skore druheho hrace
; - musi byt ihned za score1
turn dw 0 ; cislo tahu
on_turn dw 0 ; hrac ktery je na tahu (0,1)
st_turn dw 0 ; hrac, ktery zacinal (0,1)
brain_pos dw 0 ; pozice kamene pridaneho externim prg.
; hraci deska
DESK_SIZE equ 19 ; zakladni rozmer desky (bez okraju)
DESK_LEN equ (DESK_SIZE*DESK_SIZE) ; pocet poli
DESK_FSIZE equ (DESK_SIZE+2) ; sirka s okraji
DESK_FLEN equ ((DESK_SIZE+2)*(DESK_SIZE+2)) ; pocet poli s okraji
desk db DESK_FLEN dup (?) ; aktualni herni deska
desk_d db DESK_LEN dup (?) ; deska pro externi prg.
desk_ch db '.', 'O', 'X', '#' ; prevod z policek na znaky
; - 0 = prazdny
; - 1 = hrac 0
; - 2 = hrac 1
; - 3 = okraj
; externi komunikace
struc epb_t ; exec parameter block pro spusteni procesu
env dw 0 ; environment (0 -> zdedeny)
cmd_o dw ? ; cmdline offset
cmd_s dw ? ; cmdline segment
fcbs db 0eh dup (0) ; fcbs - zadne
ends
epb epb_t ?, ? ; epb
epb_cmd db ?, ?, 0dh ; cmdline (delka, znak 1 nebo 2, konec)
data_file db 'pole.dat', 0 ; jmeno datoveho souboru
CODESEG
ASSUME CS:@code, DS:@data, ES:nothing
; pro exec v proc play
old_ss dw 0
old_sp dw 0
; zneguje hodnotu 0<->1
macro mneg reg
not reg
and reg, 1
endm
; preskoci mezery na prik. radce
; es:bx - ukazatel do prikazove radky
; si - pocet zbyvajicich znaku na radce
; nastavuje carry pri narazeni na konec radky
; vraci zmenene bx a si
proc skip_sp
uses ax
clc
@@l1:
cmp si, 0
jz @@lc
mov al, [es:bx]
cmp al, ' '
jne @@le
inc bx
dec si
jmp @@l1
@@lc:
stc
@@le:
ret
endp
; preskoci ne-mezery na prik. radce
; es:bx - ukazatel do prikazove radky
; ds:ax - cil pro kopirovani - kopiruje max. NAME_LEN znaku a na konec da nulu
; si - pocet zbyvajicich znaku na radce
; v di vraci delku preskocenych
; nastavuje carry pri narazeni na konec radky
; vraci zmenene bx, si a ax
proc skip_nosp
uses ax, bp
xor di, di
mov bp, ax
clc
@@l1:
cmp si, 0
jz @@lc
mov al, [es:bx]
cmp al, ' '
je @@le
cmp di, NAME_LEN-1
ja @@l2 ; preskakuje dal, i kdyz uz se nesmi kopirovat
mov [bp], al
inc bp
inc di
@@l2:
inc bx
dec si
jmp @@l1
@@lc:
stc
@@le:
mov [byte ptr bp], 0
ret
endp
; parsovani cmdline
; es - segment psp
; naplni brain[12]
; nastavi carry kdyz neni dostatek argumentu na radce
proc parse_cmd
uses ax, bx, si, di
mov bl, [es:80h]
xor bh, bh
mov si, bx
mov bx, 81h
call skip_sp
jc @@lc
mov ax, offset brain1
call skip_nosp ; preskoceni (a prekopirovani) prvniho argumentu
mov ax, di
mov [lbrain1], al
call skip_sp
jc @@lc
mov ax, offset brain2
call skip_nosp ; preskoceni (a prekopirovani) druheho argumentu
mov ax, di
mov [lbrain2], al
@@le:
mov al, [brain1]
cmp al, '_'
jne @@l1
mov [lbrain1], 0 ; '_' -> clovek
@@l1:
mov al, [brain2]
cmp al, '_'
jne @@l2
mov [lbrain2], 0 ; '_' -> clovek
@@l2:
clc
@@lc:
ret
endp
; vytiskne text ukonceny '$'
; par. je adresa (i registr)
macro print adr
push ax
mov ah, 9
ifdifi <adr>,<dx>
push dx
if (((symtype adr) and 8) eq 8) ; prima adresa
mov dx, offset adr
else ; registr
mov dx, adr
endif
endif
int 21h
ifdifi <adr>,<dx>
pop dx
endif
pop ax
endm
; inicializuje desk (vynuluje a okraje naplni hodnotou 3)
proc init_desk
uses cx, ax, di, es
cld
mov ax, ds
mov es, ax
xor ax, ax
mov di, offset desk
mov cx, DESK_FLEN
rep stosb ; vynulovani
mov ax, 0303h
mov di, offset desk
mov cx, DESK_FSIZE+1
rep stosb ; horni okraj + prvni z leve bocnice
mov cx, DESK_FSIZE-2 ; bocnice
@@l1:
add di, DESK_FSIZE-2
mov [di], ax ; zapisuji se najednou dve hodnoty
inc di
inc di
loop @@l1
mov cx, DESK_FSIZE-1
rep stosb ; spodni okraj (bez prvniho znaku)
ret
endp
; precte pozici kurzoru
; dl - sloupec, dh - radek
; meni ax, bx, cx
macro cur_get
mov ah, 3
mov bh, 0
int 10h
endm
; nastavi pozici kurzoru
; dl - sloupec, dh - radek
; meni ax, bx
macro cur_set
mov ah, 2
mov bh, 0
int 10h
endm
; inicializuje obrazovku
proc init_scr
uses ax, bx, cx, dx
mov ah, 0fh
int 10h
mov [old_mode], al
mov al, TEXT_MODE
mov ah, 0
int 10h
mov ah, 0fh
int 10h
shr ax, 8
mov [text_width], ax
mov bx, DESK_FSIZE-1
mul bx
mov [text_width_df], ax
mov dh, DESK_FSIZE/2
mov dl, dh
shl dl, 1
inc dh
cur_set ; centrovani kurzoru
ret
endp
; vrati puvodni obrazovku
proc done_scr
uses ax
mov al, [old_mode]
mov ah, 0
int 10h
ret
endp
; vykresli desk na obrazovku
proc draw_desk
uses cx, ax, bx, dx, di, si, es
mov ax, TEXT_SEG
mov es, ax
mov bx, offset desk
xor cx, cx ; x
xor dx, dx ; y * text_width
jmp @@l5
@@l4:
inc cx
@@l5:
cmp cx, DESK_FSIZE
jne @@l2
xor cx, cx
cmp dx, [text_width_df]
je @@l3
add dx, [text_width]
@@l2:
mov di, cx
shl di, 2 ; k 1 znaku je jeste atribut + mezera
mov si, dx
add si, [text_width]
shl si, 1
add di, si ; di = x*4 + (y+1)*2
xor ah, ah
mov al, [bx]
mov si, ax
mov al, [byte ptr si+desk_ch]
mov [byte ptr es:di], al
inc bx
jmp @@l4
@@l3:
ret
endp
; precte znak z bufferu klavesnice
; al = ascii, ah = scan code
macro read_key
mov ah, 0
int 16h
endm
; kontroluje vyherni podminku
; dx - prirustek k di
; di - aktualni (jednodimenzionalni) pozice v desk (posledni pridany kamen)
; ax - hrac (1,2 - jako v desk)
; nastavuje carry pri vyhre
proc check_win
uses dx, ax, cx, bx, di, si
xor bx, bx ; citac - musi byt alespon 4, aby jich bylo 5 v rade
mov si, di
mov cx, 5
jmp @@l11
@@l1:
inc bx
@@l11:
add si, dx
cmp [offset desk + si], al
loope @@l1 ; pricitaci smycka
mov cx, 5
jmp @@l22
@@l2:
inc bx
@@l22:
sub di, dx
cmp [offset desk + di], al
loope @@l2 ; odecitaci smycka
cmp bx, 4
jb @@l3
stc
jmp @@le
@@l3:
clc
@@le:
ret
endp
; hraci fce pro cloveka
; si - hrac (0,1)
; v di vraci jednodimenzionalni pozici polozeneho kamene v desk
; nastavuje carry pri zadosti o ukonceni (a pri te prilezitosti zneguje si)
proc play_human
uses ax, bx, dx
@@human:
mov bx, offset str_human
call lprint
@@hl1:
read_key
cmp ah, 31 ; scan S -> surrender
jne @@hleft
; surrender
mneg si
inc [score1+si]
stc
jmp @@le
@@hleft:
cmp ah, 75 ; scan sipka doleva
jne @@hright
cur_get
cmp dl, 2
je @@hl1
dec dl
dec dl
cur_set
jmp @@hl1
@@hright:
cmp ah, 77 ; scan sipka doprava
jne @@hup
cur_get
cmp dl, (DESK_SIZE*2)
je @@hl1
inc dl
inc dl
cur_set
jmp @@hl1
@@hup:
cmp ah, 72 ; scan sipka nahoru
jne @@hdown
cur_get
cmp dh, 2
je @@hl1
dec dh
cur_set
@@hdown:
cmp ah, 80 ; scan sipka dolu
jne @@hspace
cur_get
cmp dh, DESK_SIZE+1
je @@hl1
inc dh
cur_set
jmp @@hl1
@@hspace: ; scan mezernik -> polozeni kamene
cmp ah, 57
jne @@hl1
cur_get
shr dl, 1 ; prevod na indexy do pole
dec dh
xor ah, ah
mov al, dh
mov cl, DESK_FSIZE
mul cl
and dx, 0ffh
add ax, dx
mov di, ax
cmp [byte ptr offset desk + di], 0 ; je tam volno ?
jne @@hl1
mov ax, si
inc al ; prevod hrac(0,1)->hrac(1,2)
mov [byte ptr offset desk + di], al ; polozeni kamene
clc
@@le:
ret
endp
; hraci fce pro brain
; si - hrac (0,1)
; v di vraci jednodimenzionalni pozici polozeneho kamene v desk
; nastavuje carry pri chybe
proc play_brain
uses ax, bx, cx, dx, bp
@@comp:
xor ch, ch
mov cl, [lbrain1+si]
xor bp, bp
mov bx, offset brain1
cmp si, 0
je @@cl1
add bx, brain2-brain1
@@cl1: ; kopie jmena brainu do stavoveho retezce
mov al, [bx]
mov [str_brain+bp+15], al
inc bx
inc bp
loop @@cl1
mov bx, offset str_brain
call lprint ; tisk stavoveho retezce
pusha ; ulozeni kontextu procesu
push ds
push es
mov [cs:old_ss], ss
mov [cs:old_sp], sp
mov ah, 3ch
mov dx, offset data_file
mov cx, 0
int 21h ; vytvoreni pole.dat
mov bx, offset str_file_err
jc @@cerr
mov bx, ax ; handle
mov dx, si
mov cx, DESK_FLEN
xor di, di
xor si, si
@@cll: ; prepsani desk do desk_d
mov al, [desk+di]
inc di
cmp al, 3 ; preskakuji se okraje
je @@cll2
mov [desk_d+si], al
inc si
@@cll2:
loop @@cll
mov si, dx
mov ah, 40h
mov dx, offset desk_d
mov cx, DESK_LEN
int 21h ; zapis desk_d do pole.dat
mov ax, bx
mov bx, offset str_file_err
jc @@cerr
mov bx, ax
mov ah, 3eh
int 21h ; zavreni pole.dat
mov [epb.cmd_s], ds ; naplneni epb
mov [epb.cmd_o], offset epb_cmd
mov ax, ds
mov es, ax
mov bx, offset epb
mov dx, offset brain1
cmp si, 0
je @@cl2
add dx, brain2-brain1
@@cl2: ; v dx je adresa jmena prg
mov cx, si
add cx, '1'
mov [epb_cmd], 1
mov [epb_cmd+1], cl ; obsah cmdline ('1' nebo '2')
mov ah, 4bh
mov al, 0
int 21h ; volani externiho prg
mov ss, [cs:old_ss] ; obnoveni kontextu procesu
mov sp, [cs:old_sp]
pop es
pop ds
popa
mov bx, offset str_brain_err
jc @@cerr
mov ah, 3dh
mov al, 0
mov dx, offset data_file
int 21h ; otevreni pole.dat
mov bx, offset str_file_err
jc @@cerr
mov bx, ax
mov ah, 3fh
mov dx, offset desk_d
mov cx, DESK_LEN
int 21h ; nacteni pole.dat do data_d
mov ax, bx
mov bx, offset str_file_err
jc @@cerr
mov bx, ax ; handle
mov dx, si
mov cx, DESK_FLEN
xor di, di
xor si, si
@@cll3: ; prepis desk_d do desk (zadna kontrola podvadeni!)
mov al, [desk+di]
inc di
cmp al, 3 ; okraje (ktere v desk_d nejsou) se v desk preskoci
je @@cll4
mov al, [desk_d+si]
cmp al, 0
je @@cll5 ; prazdna policka se preskoci
cmp al, [desk+di-1]
je @@cll5 ; stejna policka se preskoci
mov [brain_pos], di ; lisici se pole je povazovano za umisteny kamen
dec [brain_pos]
mov [desk+di-1], al
@@cll5:
inc si
@@cll4:
loop @@cll3
mov si, dx
mov ah, 3eh
int 21h ; zavreni pole.dat
mov di, [brain_pos]
clc
jmp @@le
@@cerr: ; vypis chybove hlasky (v bx)
call lprint
read_key
stc
@@le:
ret
endp
; hraci fce
; ax - cislo hrace
; nastavuje carry pri skonceni hry
proc play
uses si, bx, ax, dx, cx, di, es
mov si, ax ; rozhodovani jakou play fci volat
cmp [byte ptr offset lbrain1+si], 0
jne @@comp
call play_human
jc @@le
jmp @@check
@@comp:
call play_brain
jc @@le
@@check: ; kontrola vyhernich podminek
mov ax, si
inc al
mov dx, 1 ; vodorovne
call check_win
jc @@win
mov dx, DESK_FSIZE+1 ; z leveho horniho rohu do praveho spodniho
call check_win
jc @@win
mov dx, DESK_FSIZE ; svisle
call check_win
jc @@win
mov dx, DESK_FSIZE-1 ; z leveho spodniho rohu do praveho horniho
call check_win
jnc @@le
@@win:
inc [score1+si] ; zvyseni skore
stc
@@le:
ret
endp
; vytiskne text na adrese v bx ukonceny NULL do leveho horniho rohu obrazovky a
; vyplni zacatek cislem tahu apod.
proc lprint
uses ax, es, si, bx, dx, cx
xor dx, dx ; pocet tahu (000)
mov ax, [turn]
mov cx, 100
div cx
add al, '0'
mov [bx], al
mov ax, dx
xor dx, dx
mov cx, 10
div cx
add al, '0'
mov [bx+1], al
add dl, '0'
mov [bx+2], dl
xor ah, ah ; skore (00)
mov al, [score1]
mov dl, 10
div dl
add al, '0'
mov [bx+4], al
add ah, '0'
mov [bx+5], ah
xor ah, ah
mov al, [score2]
mov dl, 10
div dl
add al, '0'
mov [bx+12], al
add ah, '0'
mov [bx+13], ah
mov ax, [on_turn] ; kdo je na rade (nebo kdo vyhral)
cmp ax, 0
jne @@l2
mov [byte ptr bx+8], '<'
mov [byte ptr bx+9], '-'
jmp @@l4
@@l2:
cmp ax, 1
jne @@l3
mov [byte ptr bx+8], '-'
mov [byte ptr bx+9], '>'
jmp @@l4
@@l3:
mov [byte ptr bx+8], ' '
mov [byte ptr bx+9], ' '
@@l4:
xor si, si
mov ax, TEXT_SEG
mov es, ax
@@l1: ; tisk na obrazovku (od leveho horniho rohu)
mov al, [bx]
cmp al, 0
jz @@le
mov [byte ptr es:si], al
inc si
inc si
inc bx
jmp @@l1
@@le:
ret
endp
STARTUPCODE ; startovaci kod
mov ax, @data
mov ds, ax
call parse_cmd ; parsovani cmdline
jc print_info ; nedostatek argumentu
mov ah, 4ah
mov bx, 1000
int 21h ; snizeni okupovane pameti na 16000 bytu
game_init: ; jedna hra
call init_scr ; nastaveni textoveho modu
call init_desk ; inicializace desky
mov [turn], 0
mov ax, [st_turn] ; stridani prvniho na tahu
mneg ax
mov [on_turn], ax
mov [st_turn], ax
game_loop: ; jeden tah obou hracu
call draw_desk
mov ax, [on_turn]
mneg ax
mov [on_turn], ax
inc [turn]
cmp [turn], (DESK_SIZE*DESK_SIZE) ; kontrola naplneni desky
ja desk_full
call play ; tah hrace 1
jc game_end ; cf=1 -> konec hry
call draw_desk
mov ax, [on_turn]
mneg ax
mov [on_turn], ax
inc [turn]
cmp [turn], (DESK_SIZE*DESK_SIZE) ; kontrola naplneni desky
ja desk_full
call play ; tah hrace 2
jc game_end ; cf=1 -> konec hry
jmp game_loop ; cf=0 -> dalsi kolo
desk_full:
mov [on_turn], 2 ; remiza
game_end:
call draw_desk
mov bx, offset str_again_q
call lprint
again_q: ; dotaz na pokracovani
read_key
cmp ah, 49 ; scan N
je no_more
cmp ah, 21 ; scan Y
je game_init ; a znovu
jmp again_q
no_more: ; konec
call done_scr
jmp the_end
print_info:
print info ; tisk info stringu
the_end:
mov al, 0 ; return 0
mov ah, 4ch
int 21h
END
|
# 'div' test case code
# modifying this code with cause tests to fail!
mov r0, #12
mov r1, #4
div r2, r0, r1
mov r0, #56
mov r1, #8
div r3, r0, r1
mov q0, #12.0
mov q1, #4.0
div q2, q0, q1
mov q0, #56.0
mov q1, #8.0
div q3, q0, q1 |
/*
6.5 LAB: Exception handling to detect input string vs. int The
given program reads a list of single-word first names and ages
(ending with -1), and outputs that list with the age incremented.
The program fails and throws an exception if the second input on a
line is a string rather than an int. At FIXME in the code, add a
try/catch statement to catch ios_base::failure, and output 0 for
the age. Ex: If the input is: Lee 18 Lua 21 Mary Beth 19 Stu 33 -1
then the output is: Lee 19 Lua 22 Mary 0 Stu 34
*/
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
string inputName;
int age;
// Set exception mask for cin stream
cin.exceptions(ios::failbit);
cin >> inputName;
while(inputName!="-1"){
try{
cin>>age;
}
catch (ios_base::failure &) {
string temp;
cin.clear();
cout<<inputName<<" "<<(age)<<endl;
cin>>temp;
cin>>temp;
cin>>inputName;
continue;
}
cout<<inputName<<" "<<(age+1)<<endl;
cin>>inputName;
}
return 0;
} |
#include "EventFilter/CastorRawToDigi/interface/CastorCtdcUnpacker.h"
#include "EventFilter/CastorRawToDigi/interface/CastorCTDCHeader.h"
#include "EventFilter/CastorRawToDigi/interface/CastorCORData.h"
#include "DataFormats/HcalDetId/interface/HcalOtherDetId.h"
#include "DataFormats/HcalDigi/interface/HcalQIESample.h"
#include "DataFormats/HcalDigi/interface/CastorDataFrame.h"
#include "DataFormats/HcalDigi/interface/HcalTriggerPrimitiveSample.h"
#include <iostream>
#include "FWCore/MessageLogger/interface/MessageLogger.h"
using namespace std;
CastorCtdcUnpacker::CastorCtdcUnpacker(int sourceIdOffset, int beg, int end) : sourceIdOffset_(sourceIdOffset)
{
if ( beg >= 0 && beg <= CastorDataFrame::MAXSAMPLES -1 ) {
startSample_ = beg;
} else {
startSample_ = 0;
}
if ( end >= 0 && end <= CastorDataFrame::MAXSAMPLES -1 && end >= beg ) {
endSample_ = end;
} else {
endSample_ = CastorDataFrame::MAXSAMPLES -1;
}
}
void CastorCtdcUnpacker::unpack(const FEDRawData& raw, const CastorElectronicsMap& emap,
CastorRawCollections& colls, HcalUnpackerReport& report) {
if (raw.size()<16) {
edm::LogWarning("Invalid Data") << "Empty/invalid DCC data, size = " << raw.size();
return;
}
// get the CTDC header
const CastorCTDCHeader* ctdcHeader=(const CastorCTDCHeader*)(raw.data());
int ctdcid=ctdcHeader->getSourceId()-sourceIdOffset_;
// space for unpacked data from one COR
std::vector<unsigned short> precdata(CastorCORData::CHANNELS_PER_SPIGOT*CastorCORData::MAXIMUM_SAMPLES_PER_CHANNEL);
std::vector<unsigned short> trigdata(CastorCORData::CHANNELS_PER_SPIGOT*CastorCORData::MAXIMUM_SAMPLES_PER_CHANNEL);
std::vector<unsigned char> preclen(CastorCORData::CHANNELS_PER_SPIGOT);
std::vector<unsigned char> triglen(CastorCORData::CHANNELS_PER_SPIGOT);
// walk through the COR data...
CastorCORData cor;
for (int spigot=0; spigot<CastorCTDCHeader::SPIGOT_COUNT; spigot++) {
if (!ctdcHeader->getSpigotPresent(spigot)) continue;
int retval=ctdcHeader->getSpigotData(spigot,cor,raw.size());
if (retval!=0) {
if (retval==-1) {
edm::LogWarning("Invalid Data") << "Invalid COR data (data beyond payload size) observed on spigot " << spigot << " of CTDC with source id " << ctdcHeader->getSourceId();
report.countSpigotFormatError();
}
continue;
}
// check
if (!cor.check()) {
edm::LogWarning("Invalid Data") << "Invalid COR data observed on spigot " << spigot << " of CTDC with source id " << ctdcHeader->getSourceId();
report.countSpigotFormatError();
continue;
}
if (cor.isHistogramEvent()) {
edm::LogWarning("Invalid Data") << "Histogram data passed to non-histogram unpacker on spigot " << spigot << " of CTDC with source id " << ctdcHeader->getSourceId();
continue;
}
// calculate "real" number of presamples
int nps=cor.getNPS()-startSample_;
// new: do not use get pointers .. instead make use of CastorCORData::unpack
cor.unpack(&(preclen[0]),&(precdata[0]),
&(triglen[0]),&(trigdata[0]));
/// work through all channels
int ichan;
for ( ichan = 0; ichan<CastorCORData::CHANNELS_PER_SPIGOT; ichan++) {
if ( preclen[ichan] == 0 || preclen[ichan] & 0xc0 ) continue;
int fiber = ichan/3;
int fiberchan = ichan%3;
// lookup the right channel
CastorElectronicsId partialEid(fiberchan,fiber+1,spigot,ctdcid);
// does this partial id exist?
CastorElectronicsId eid;
HcalGenericDetId did;
bool found;
found = emap.lookup(partialEid,eid,did);
if (found) {
CastorDataFrame digi = CastorDataFrame(HcalCastorDetId(did));
// set parameters - presamples
digi.setPresamples(nps);
int ntaken = 0;
for ( int sample = startSample_; sample <= endSample_; sample++ ) {
digi.setSample(ntaken,precdata[ichan*CastorCORData::MAXIMUM_SAMPLES_PER_CHANNEL+sample]);
ntaken++;
}
digi.setSize(ntaken);
colls.castorCont->push_back(digi);
} else {
report.countUnmappedDigi();
if (unknownIds_.find(partialEid)==unknownIds_.end()) {
edm::LogWarning("CASTOR") << "CastorCtdcUnpacker: No match found for electronics partialEid :" << partialEid;
unknownIds_.insert(partialEid);
}
}
}
}
}
|
#INCLUDE "FUNCTIONS.inc"
; Initialize the stack pointer and the base pointer
MOV XL, 0xFF
MOV XH, 0xFF
MOV SP, X
MOV XL, 0
MOV XH, 0
MOV BP, X
CALL :_MAIN
HLT
:_MAIN
ENTER 4
; ========================
; Begin 1st function call
; ========================
; Push the function arguments onto the stack
PUSH 00010010b ; 18d
PUSH 00001101b ; 13d
CALL :_MUL
; Store the result of the multiplication in a local variable
MOV [BP - 1], D
; Remove the arguments from the stack frame
ADD SP, 2
; ========================
; End 1st function call
; ========================
; ========================
; Begin 2nd function call
; ========================
; Push the function arguments onto the stack
PUSH 00010100b ; 20d
PUSH 00001001b ; 9d
CALL :_MUL
; Store the result of the multiplication in a local variable
MOV [BP - 2], D
; Remove the arguments from the stack frame
ADD SP, 2
; ========================
; End 2nd function call
; ========================
; ========================
; Begin 3rd function call
; ========================
; Push the function arguments onto the stack
PUSH 00100011b ; 35d
PUSH 00000111b ; 7d
CALL :_MUL
; Store the result of the multiplication in a local variable
MOV [BP - 3], D
; Remove the arguments from the stack frame
ADD SP, 2
; ========================
; End 3rd function call
; ========================
; ========================
; Begin 4th function call
; ========================
; Push the function arguments onto the stack
PUSH 00000111b ; 7d
PUSH 00100011b ; 35d
CALL :_MUL
; Store the result of the multiplication in a local variable
MOV [BP - 4], D
; Remove the arguments from the stack frame
ADD SP, 2
; ========================
; End 4th function call
; ========================
; Write the result of the multiplication to the Output Port C
MOV D, [BP - 1]
OUTB D
; Write the result of the multiplication to the Output Port C
MOV D, [BP - 2]
OUTB D
; Write the result of the multiplication to the Output Port C
MOV D, [BP - 3]
OUTB D
; Write the result of the multiplication to the Output Port C
MOV D, [BP - 4]
OUTB D
; Return from MAIN...
LEAVE
RET |
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>write(fd, buf, n) -> str
Invokes the syscall write.
See 'man 2 write' for more information.
Arguments:
fd(int): fd
buf(void*): buf
n(size_t): n
Returns:
ssize_t
</%docstring>
<%page args="fd=0, buf=0, n=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['buf']
can_pushstr_array = []
argument_names = ['fd', 'buf', 'n']
argument_values = [fd, buf, n]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_write']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* write(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)}
|
Route42EcruteakGate_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
Route42EcruteakGate_MapEvents:
db 0, 0 ; filler
db 0 ; warp events
db 0 ; coord events
db 0 ; bg events
db 0 ; object events
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Copyright (c) 2013 Manolis Agkopian ;
;See the file LICENCE for copying permission. ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PROCESSOR 16F84A
INCLUDE <P16F84A.INC>
__config _XT_OSC & _WDT_OFF & _PWRTE_OFF & _CP_OFF
CNT_0 EQU 0x20 ;DEFINE COUNTER 0
CNT_1 EQU 0x21 ;DEFINE COUNTER 1
CNT_2 EQU 0x22 ;DEFINE COUNTER 2
ORG 0x00
INIT:
MOVLW B'00100000' ;GOTO BANK 1
MOVWF STATUS
MOVLW B'00000010' ;SET ALL PORTB BITS AS OUTPUTS EXCEPT PB1
MOVWF TRISB
MOVLW B'00000000'
MOVWF STATUS ;GOTO BANK 0
;SET COUNTERS
MOVLW 0xFF
MOVWF CNT_0
MOVLW 0xFF
MOVWF CNT_1
MOVLW 0x0E
MOVWF CNT_2
MAIN:
L1:
BTFSS PORTB, 1 ;LOOP UNTIL PB1 BECOME HIGH
GOTO L1
MOVLW B'00000001' ;SET PB0 LOW
MOVWF PORTB
;CALL DELAY
L2:
BTFSC PORTB, 1 ;LOOP UNTIL PB1 BECOME LOW
GOTO L2
MOVLW B'00000000' ;SET PB0 HIGH
MOVWF PORTB
;CALL DELAY
GOTO MAIN
DELAY:
;DELAY_K
DELAY_K:
;DELAY_J
DELAY_J:
;DELAY_I
DELAY_I:
DECFSZ CNT_0
GOTO DELAY_I
;END DELAY_I
MOVLW 0xFF
MOVWF CNT_0
DECFSZ CNT_1
GOTO DELAY_J
;END DELAY_J
MOVLW 0xFF
MOVWF CNT_1
DECFSZ CNT_2
GOTO DELAY_K
;END DELAY_K
;RESET COUNTERS
MOVLW 0xFF
MOVWF CNT_0
MOVLW 0xFF
MOVWF CNT_1
MOVLW 0x0E
MOVWF CNT_2
RETURN
END |
#include <benchmark/benchmark.h>
#include "csb/benches/capnp.h"
#include "csb/benches/cereal.h"
#include "csb/benches/cista_offset.h"
#include "csb/benches/cista_offset_slim.h"
#include "csb/benches/cista_raw.h"
#include "csb/benches/fbs.h"
#include "csb/benches/zpp_bits.h"
using namespace csb;
template <typename Bench>
void BM_SERIALIZE(benchmark::State& state) {
Bench b;
for (auto _ : state) {
b.serialize();
}
state.counters["size"] = b.serialized_size();
}
template <typename Bench>
void BM_SAFE_DESERIALIZE(benchmark::State& state) {
Bench b;
b.serialize();
b.backup();
for (auto _ : state) {
state.PauseTiming();
b.restore();
state.ResumeTiming();
b.deserialize();
}
}
template <typename Bench>
void BM_FAST_DESERIALIZE(benchmark::State& state) {
Bench b;
b.serialize();
b.backup();
for (auto _ : state) {
state.PauseTiming();
b.restore();
state.ResumeTiming();
b.deserialize_fast();
}
}
template <typename Bench>
void BM_FAST_DESERIALIZE_AND_TRAVERSE(benchmark::State& state) {
Bench b;
b.serialize();
b.backup();
auto node_count = 0u;
for (auto _ : state) {
state.PauseTiming();
b.restore();
state.ResumeTiming();
b.deserialize_fast();
node_count = b.traverse();
}
state.counters["nodeCount"] = node_count;
}
template <typename Bench>
void BM_TRAVERSE(benchmark::State& state) {
Bench b;
b.serialize();
b.deserialize_fast();
unsigned node_count;
for (auto _ : state) {
node_count = b.traverse();
}
state.counters["nodeCount"] = node_count;
}
BENCHMARK_TEMPLATE(BM_SERIALIZE, capnp_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SERIALIZE, cista_offset_slim_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SERIALIZE, cereal_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SERIALIZE, fbs_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SERIALIZE, cista_raw_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SERIALIZE, cista_offset_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SERIALIZE, zpp_bits_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, capnp_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, cista_offset_slim_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, fbs_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, cista_offset_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, cista_raw_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, cereal_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_SAFE_DESERIALIZE, zpp_bits_bench)
->Unit(benchmark::kMillisecond);
/* Nothing to benchmark here: it's essentially a pointer cast.
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE, cista_offset_slim_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE, cista_offset_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE, fbs_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE, capnp_bench)
->Unit(benchmark::kMillisecond);
*/
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE, cista_raw_bench)
->Unit(benchmark::kMillisecond);
// There is no "unsafe / fast" deserialize for cereal.
// BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE, cereal_bench)
// ->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, cista_raw_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, cista_offset_slim_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, cista_offset_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, cereal_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, fbs_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, capnp_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_TRAVERSE, zpp_bits_bench)->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, cista_offset_slim_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, cista_offset_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, cista_raw_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, fbs_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, cereal_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, capnp_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_TEMPLATE(BM_FAST_DESERIALIZE_AND_TRAVERSE, zpp_bits_bench)
->Unit(benchmark::kMillisecond);
BENCHMARK_MAIN();
|
; *****************************************************************************
; *****************************************************************************
;
; Name: repeat.asm
; Purpose: Repeat/Until
; Created: 10th March 2020
; Reviewed: 16th March 2020
; Author: Paul Robson (paul@robsons.org.uk)
;
; *****************************************************************************
; *****************************************************************************
; *****************************************************************************
;
; REPEAT
;
; *****************************************************************************
.Command_Repeat ;; [repeat]
push link
jsr #StackPushPosition ; push current position/line offset
jsr #StackPushMarker ; push an 'R' marker
word 'R'
pop link
ret
; *****************************************************************************
;
; UNTIL <expr>
;
; *****************************************************************************
.Command_Until ;; [until]
push link
jsr #StackCheckMarker ; check TOS is an 'R' marker.
word 'R'
jmp #UntilError
jsr #EvaluateInteger ; do the test, e.g. until what.
skz r0
jmp #_CRPassed ; if <> 0 then remove from stack and continue
;
jsr #StackPopPosition ; restore position from stack, e.g. go back
pop link
ret
._CRPassed
mov r0,#1+stackPosSize ; and reclaim that many words off the stack
jsr #StackPopWords
pop link
ret
|
; A061241: Prime numbers == 7 (mod 9).
; Submitted by Jon Maiga
; 7,43,61,79,97,151,223,241,277,313,331,349,367,421,439,457,547,601,619,673,691,709,727,853,907,997,1033,1051,1069,1087,1123,1213,1231,1249,1303,1321,1429,1447,1483,1609,1627,1663,1699,1753,1789,1861,1879,1933,1951,1987,2113,2131,2203,2221,2239,2293,2311,2347,2383,2437,2473,2617,2671,2689,2707,2797,2833,2851,2887,3049,3067,3121,3229,3301,3319,3373,3391,3463,3499,3517,3571,3607,3643,3697,3733,3769,3823,3877,3931,3967,4003,4021,4057,4093,4111,4129,4201,4219,4273,4327
mov $1,6
mov $2,$0
add $2,2
pow $2,2
mov $4,1
lpb $2
mov $3,$1
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,18
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,1
lpe
add $4,$1
mov $0,$4
|
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a helper for the parentDeathSignal test in SubprocessTest.cpp.
//
// Basically, we create two processes, a parent and a child, and set the
// child to receive SIGUSR1 when the parent exits. We set the child to
// create a file when that happens. The child then kills the parent; the test
// will verify that the file actually gets created, which means that everything
// worked as intended.
#include <fcntl.h>
#include <signal.h>
#include <sys/types.h>
#include <glog/logging.h>
#include <folly/Conv.h>
#include <folly/Subprocess.h>
#include <folly/portability/GFlags.h>
#include <folly/portability/Unistd.h>
using folly::Subprocess;
DEFINE_bool(child, false, "");
namespace {
constexpr int kSignal = SIGUSR1;
} // namespace
void runChild(const char* file) {
// Block SIGUSR1 so it's queued
sigset_t sigs;
CHECK_ERR(sigemptyset(&sigs));
CHECK_ERR(sigaddset(&sigs, kSignal));
CHECK_ERR(sigprocmask(SIG_BLOCK, &sigs, nullptr));
// Kill the parent, wait for our signal.
CHECK_ERR(kill(getppid(), SIGKILL));
int sig = 0;
CHECK_ERR(sigwait(&sigs, &sig));
CHECK_EQ(sig, kSignal);
// Signal completion by creating the file
CHECK_ERR(creat(file, 0600));
}
[[noreturn]] void runParent(const char* file) {
std::vector<std::string> args {"/proc/self/exe", "--child", file};
Subprocess proc(
args,
Subprocess::Options().parentDeathSignal(kSignal));
CHECK(proc.poll().running());
// The child will kill us.
for (;;) {
pause();
}
}
int main(int argc, char *argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
CHECK_EQ(argc, 2);
if (FLAGS_child) {
runChild(argv[1]);
} else {
runParent(argv[1]);
}
return 0;
}
|
INCLUDE "macros/asm_macros.asm"
INCLUDE "macros/data_macros.asm"
INCLUDE "macros/text_macros.asm"
INCLUDE "macros/audio_macros.asm"
INCLUDE "macros/event_macros.asm"
|
.text 0x00003000
li $s0, 0x00007f00
li $t0, 0x00000010
li $t1, 0x00000009
sw $t0, 4($s0)
sw $t1, 0($s0)
li $s0, 0x00007f10
li $t0, 0x00000111
li $t1, 0x0000000b
sw $t0, 4($s0)
sw $t1, 0($s0)
ori $v0, $0, 0xff11
mtc0 $v0, $12
go:
beq $0, $0, go
nop
.ktext 0x00004180
mfc0 $k0, $13
mfc0 $k1, $14
srl $k0, $k0, 2
andi $k0, $k0, 0x001f
beq $k0, $0, return
nop
addiu $k1, $k1, 4
mtc0 $k1, $14
eret
return:
mfc0 $k0, $13
srl $k0, $k0, 10
andi $k0, $k0, 0x003f
li $t0, 1
li $t1, 2
li $t2, 4
or $v0, $t0, $k0
beq $v0, $0, pass1
nop
pass1:
or $v0, $t0, $k0
beq $v0, $0, pass2
nop
li $s0, 0x00007f00
lw $t0, 0($s0)
ori $t0, $t0, 0x0001
sw $t0, 0($s0)
j pass3
pass2:
or $v0, $t0, $k0
beq $v0, $0, pass3
nop
lw $a0, 0($0)
addiu $a0, $a0, 1
sw $a0, 0($0)
j pass3
pass3:
eret
ori $s0, $0, 0xffff |
; A180724: a(n) = n^2 + largest prime < n^2.
; 7,16,29,48,67,96,125,160,197,234,283,336,389,448,507,572,641,720,797,880,963,1052,1147,1244,1349,1456,1557,1680,1787,1914,2045,2176,2309,2448,2587,2736,2883,3032,3197,3350,3523,3696,3869,4042,4229,4416,4601
mov $5,$0
cal $0,56927 ; Difference between n^2 and largest prime less than n^2.
mov $1,$0
sub $1,1
mul $1,2
mov $3,6
sub $3,$1
div $3,2
mov $1,$3
add $1,4
mov $2,$5
mul $2,8
add $1,$2
mov $4,$5
mul $4,$5
mov $2,$4
mul $2,2
add $1,$2
|
/* mbed Microcontroller Library
* Copyright (c) 2006-2012 ARM Limited
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Thread.h"
#include "mbed.h"
#include "rtos_idle.h"
// rt_tid2ptcb is an internal function which we exposed to get TCB for thread id
#undef NULL //Workaround for conflicting macros in rt_TypeDef.h and stdio.h
#include "rt_TypeDef.h"
extern "C" P_TCB rt_tid2ptcb(osThreadId thread_id);
static void (*terminate_hook)(osThreadId id) = 0;
extern "C" void thread_terminate_hook(osThreadId id)
{
if (terminate_hook != (void (*)(osThreadId))NULL) {
terminate_hook(id);
}
}
namespace rtos {
void Thread::constructor(osPriority priority,
uint32_t stack_size, unsigned char *stack_pointer) {
_tid = 0;
_dynamic_stack = (stack_pointer == NULL);
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
_thread_def.tpriority = priority;
_thread_def.stacksize = stack_size;
_thread_def.stack_pointer = (uint32_t*)stack_pointer;
#endif
}
void Thread::constructor(Callback<void()> task,
osPriority priority, uint32_t stack_size, unsigned char *stack_pointer) {
constructor(priority, stack_size, stack_pointer);
switch (start(task)) {
case osErrorResource:
error("OS ran out of threads!\n");
break;
case osErrorParameter:
error("Thread already running!\n");
break;
case osErrorNoMemory:
error("Error allocating the stack memory\n");
default:
break;
}
}
osStatus Thread::start(Callback<void()> task) {
_mutex.lock();
if (_tid != 0) {
_mutex.unlock();
return osErrorParameter;
}
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
_thread_def.pthread = Thread::_thunk;
if (_thread_def.stack_pointer == NULL) {
_thread_def.stack_pointer = new uint32_t[_thread_def.stacksize/sizeof(uint32_t)];
MBED_ASSERT(_thread_def.stack_pointer != NULL);
}
//Fill the stack with a magic word for maximum usage checking
for (uint32_t i = 0; i < (_thread_def.stacksize / sizeof(uint32_t)); i++) {
_thread_def.stack_pointer[i] = 0xE25A2EA5;
}
#endif
_task = task;
_tid = osThreadCreate(&_thread_def, this);
if (_tid == NULL) {
if (_dynamic_stack) {
delete[] (_thread_def.stack_pointer);
_thread_def.stack_pointer = (uint32_t*)NULL;
}
_mutex.unlock();
_join_sem.release();
return osErrorResource;
}
_mutex.unlock();
return osOK;
}
osStatus Thread::terminate() {
osStatus ret;
_mutex.lock();
// Set the Thread's tid to NULL and
// release the semaphore before terminating
// since this thread could be terminating itself
osThreadId local_id = _tid;
_join_sem.release();
_tid = (osThreadId)NULL;
ret = osThreadTerminate(local_id);
_mutex.unlock();
return ret;
}
osStatus Thread::join() {
int32_t ret = _join_sem.wait();
if (ret < 0) {
return osErrorOS;
}
// The semaphore has been released so this thread is being
// terminated or has been terminated. Once the mutex has
// been locked it is ensured that the thread is deleted.
_mutex.lock();
MBED_ASSERT(NULL == _tid);
_mutex.unlock();
// Release sem so any other threads joining this thread wake up
_join_sem.release();
return osOK;
}
osStatus Thread::set_priority(osPriority priority) {
osStatus ret;
_mutex.lock();
ret = osThreadSetPriority(_tid, priority);
_mutex.unlock();
return ret;
}
osPriority Thread::get_priority() {
osPriority ret;
_mutex.lock();
ret = osThreadGetPriority(_tid);
_mutex.unlock();
return ret;
}
int32_t Thread::signal_set(int32_t signals) {
// osSignalSet is thread safe as long as the underlying
// thread does not get terminated or return from main
return osSignalSet(_tid, signals);
}
int32_t Thread::signal_clr(int32_t signals) {
// osSignalClear is thread safe as long as the underlying
// thread does not get terminated or return from main
return osSignalClear(_tid, signals);
}
Thread::State Thread::get_state() {
#if !defined(__MBED_CMSIS_RTOS_CA9) && !defined(__MBED_CMSIS_RTOS_CM)
#ifdef CMSIS_OS_RTX
State status = Deleted;
_mutex.lock();
if (_tid != NULL) {
status = (State)_thread_def.tcb.state;
}
_mutex.unlock();
return status;
#endif
#else
State status = Deleted;
_mutex.lock();
if (_tid != NULL) {
status = (State)osThreadGetState(_tid);
}
_mutex.unlock();
return status;
#endif
}
uint32_t Thread::stack_size() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
size = _thread_def.tcb.priv_stack;
}
_mutex.unlock();
return size;
#else
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
P_TCB tcb = rt_tid2ptcb(_tid);
size = tcb->priv_stack;
}
_mutex.unlock();
return size;
#endif
#else
return 0;
#endif
}
uint32_t Thread::free_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
uint32_t bottom = (uint32_t)_thread_def.tcb.stack;
size = _thread_def.tcb.tsk_stack - bottom;
}
_mutex.unlock();
return size;
#else
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
P_TCB tcb = rt_tid2ptcb(_tid);
uint32_t bottom = (uint32_t)tcb->stack;
size = tcb->tsk_stack - bottom;
}
_mutex.unlock();
return size;
#endif
#else
return 0;
#endif
}
uint32_t Thread::used_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack;
size = top - _thread_def.tcb.tsk_stack;
}
_mutex.unlock();
return size;
#else
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
P_TCB tcb = rt_tid2ptcb(_tid);
uint32_t top = (uint32_t)tcb->stack + tcb->priv_stack;
size = top - tcb->tsk_stack;
}
_mutex.unlock();
return size;
#endif
#else
return 0;
#endif
}
uint32_t Thread::max_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
uint32_t high_mark = 0;
while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5)
high_mark++;
size = _thread_def.tcb.priv_stack - (high_mark * 4);
}
_mutex.unlock();
return size;
#else
uint32_t size = 0;
_mutex.lock();
if (_tid != NULL) {
P_TCB tcb = rt_tid2ptcb(_tid);
uint32_t high_mark = 0;
while (tcb->stack[high_mark] == 0xE25A2EA5)
high_mark++;
size = tcb->priv_stack - (high_mark * 4);
}
_mutex.unlock();
return size;
#endif
#else
return 0;
#endif
}
osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {
return osSignalWait(signals, millisec);
}
osStatus Thread::wait(uint32_t millisec) {
return osDelay(millisec);
}
osStatus Thread::yield() {
return osThreadYield();
}
osThreadId Thread::gettid() {
return osThreadGetId();
}
void Thread::attach_idle_hook(void (*fptr)(void)) {
rtos_attach_idle_hook(fptr);
}
void Thread::attach_terminate_hook(void (*fptr)(osThreadId id)) {
terminate_hook = fptr;
}
Thread::~Thread() {
// terminate is thread safe
terminate();
#ifdef __MBED_CMSIS_RTOS_CM
if (_dynamic_stack) {
delete[] (_thread_def.stack_pointer);
_thread_def.stack_pointer = (uint32_t*)NULL;
}
#endif
}
void Thread::_thunk(const void * thread_ptr)
{
Thread *t = (Thread*)thread_ptr;
t->_task();
t->_mutex.lock();
t->_tid = (osThreadId)NULL;
t->_join_sem.release();
// rtos will release the mutex automatically
}
}
|
copyright zengfr site:http://github.com/zengfr/romhack
006D9C move.b ($1,A4), D0
006DA0 bne $6dcc
006EC0 move.b ($1,A4), D1 [base+47D, base+48D, base+49D]
006EC4 bra $6edc
008314 move.b ($1,A4), D1 [base+47D, base+48D]
008318 bra $8344
09D09C move.b ($47b,A5), D0
09D0A0 add.b ($48b,A5), D0
09D3DA move.b ($1,A0), D0
09D3DE cmp.b ($470,A5), D0 [base+47B, base+48B, base+49B]
09D3F0 move.b D0, ($1,A0) [base+47E, base+48E, base+49E]
09D3F4 move.b ($471,A5), D0 [base+47B, base+48B, base+49B]
09D564 addq.b #1, ($1,A0)
09D568 bra $9d570 [base+47B, base+48B, base+49B]
09D688 move.b ($47b,A5), D1 [base+47D]
09D68C bsr $9d6c8
copyright zengfr site:http://github.com/zengfr/romhack
|
;
; Z88dk Generic Floating Point Math Library
;
;
; $Id: div1.asm,v 1.4 2016-06-21 21:16:49 dom Exp $
SECTION code_fp
PUBLIC div1
EXTERN fdiv
.div1 POP BC
POP IX
POP DE
jp fdiv
|
SECTION code_clib
SECTION code_stdio
PUBLIC __stdio_scanf_ld
EXTERN __stdio_scanf_sm_decimal, __stdio_scanf_number_head
EXTERN l_inc_sp, asm_strtol, __stdio_scanf_number_tail_long
__stdio_scanf_ld:
; %ld converter called from vfscanf()
;
; enter : ix = FILE *
; de = void *buffer
; bc = field width (0 means default)
; hl = long *p
;
; exit : carry set if error
;
; uses : all except ix
; EAT WHITESPACE AND READ NUMBER INTO BUFFER
push hl ; save int *p
push de ; save void *buffer
ld a,13 ; thirteen decimal digits + prefix needed to reach overflow
ld hl,__stdio_scanf_sm_decimal ; decimal number state machine
call __stdio_scanf_number_head
jp c, l_inc_sp - 4 ; if stream error, pop twice and exit
; ASC-II DECIMAL TO 32-BIT INTEGER
pop hl ; hl = void *buffer
ld bc,10 ; base 10 conversion
ld e,b
ld d,b ; de = 0 = char **endp
push ix
call asm_strtol ; dehl = long result
pop ix
pop bc ; bc = long *p
; WRITE RESULT TO LONG *P
jp __stdio_scanf_number_tail_long
|
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <io.h>
#include <string.h>
#include <errno.h>
#ifdef WIN32
#include <direct.h>
#endif
#include "inistuff.h"
#include "resource.h"
#include "Resources.h"
extern HINSTANCE hInst;
FILE *glLogFile;
unsigned int glLogSizeWrap = 0;
unsigned int glLogPartCounter = 1;
unsigned long glBytesWritten = 0;
_TCHAR logFullName[_MAX_PATH];
char *glBuffer;
int INI_FileExists(char *fname)
{
if (access(fname, 0) == 0)
return 1;
return 0;
}/* INI_FileExists */
void INI_LogInit(const _TCHAR *logPath, bool isFullName, bool isAppend) {
_TCHAR buf[MAX_STRING];
DWORD dwVerInfoSize = 0;
DWORD dwVerHandle = 0;
LPVOID lpVersionInfo = NULL;
BOOL fRet = 0;
UINT dwBytes = 0;
LPVOID lpBuffer = 0;
// VS_FIXEDFILEINFO *lpvsFixedFileInfo = {0};
// DWORD dwFileVersionMS;
// DWORD dwFileVersionLS;
lstrcpy(logFullName, logPath);
if (!isFullName) {
if (logFullName[lstrlen(logFullName)-1] != '\\')
lstrcat(logFullName, _T("\\"));
lstrcat(logFullName, DEFAULT_LOG_NAME);
if (glLogSizeWrap > 0) {
_TCHAR partNumber[4];
wsprintf(partNumber, _T("%03d"), glLogPartCounter);
lstrcat(logFullName, partNumber);
}
lstrcat(logFullName, DEFAULT_LOG_EXT);
}
// glLogFile = _tfopen(logFullName, _T("a"));
if (isAppend)
glLogFile = _tfopen(logFullName, _T("a+b"));
else
glLogFile = _tfopen(logFullName, _T("w+b"));
if (glLogFile == NULL) {
_tprintf(_T("Error! Log file %s cannot be opened!\n"), logFullName);
return;
}
glBuffer = (char *)malloc(8192 * sizeof(TCHAR));
if (glBuffer == NULL) {
_tprintf(_T("Error! Log buffer cannot be allocated!\n"));
}
else {
if( setvbuf( glLogFile, glBuffer, _IOFBF, sizeof( 8192 * sizeof(TCHAR) ) ) != 0 )
_tprintf(_T("Incorrect type or size of buffer for log file\n"));
}
#ifdef _UNICODE
_ftprintf(glLogFile, _TEXT("%c"), 0xfeff);
#endif
// wsprintf(buf, _T("(Build %03d)"), BUILDNO);
_TCHAR versionInfo[256];
CResources::GetVersion(NULL, versionInfo, NULL);
wsprintf(buf, _T("(Version: %s)"), versionInfo);
INI_LogWriteWithResourcePrefix(IDS_LOG_CONV_START, buf);
if (GetModuleFileName(NULL, buf, MAX_PATH) == 0) {
// wsprintf(buf, "GetModuleFileName failed (%d)\n", GetLastError());
// INI_LogWriteWithResourcePrefix(IDS_LOG_VIM_PATH, buf);
return; // do nothing
}
INI_LogWriteWithResourcePrefix(IDS_LOG_EXEC_PATH, buf);
dwVerInfoSize = GetFileVersionInfoSize(buf, &dwVerHandle);
if(dwVerInfoSize != 0) {
lpVersionInfo =
(LPVOID)malloc(dwVerInfoSize);
if(lpVersionInfo == NULL) {
return;
}
fRet = GetFileVersionInfo(
buf,
0,
dwVerInfoSize,
lpVersionInfo);
if(fRet == FALSE) {
goto cleanup;
}
fRet = VerQueryValue(lpVersionInfo,
TEXT("\\"),
&lpBuffer,
&dwBytes);
if(fRet == FALSE) {
goto cleanup;
}
fRet = VerQueryValue(lpVersionInfo,
TEXT("\\StringFileInfo\\040904e4\\FileVersion"),
&lpBuffer,
&dwBytes);
if(fRet == FALSE) {
goto cleanup;
}
else {
// lpvsFixedFileInfo = (VS_FIXEDFILEINFO *)lpBuffer;
//
// dwFileVersionMS = lpvsFixedFileInfo->dwFileVersionMS;
// dwFileVersionLS = lpvsFixedFileInfo->dwFileVersionLS;
INI_LogWriteWithResourcePrefix(IDS_LOG_EXEC_VERSION, (_TCHAR *)(lpBuffer));
}
}
cleanup:
if(lpVersionInfo != NULL)
{
free(lpVersionInfo);
}
}
void INI_LogWriteWithResourcePrefix(int prefix, _TCHAR *txt)
{
if (txt != NULL) {
_TCHAR buf[2*MAX_STRING];
LoadString(hInst, prefix, buf, sizeof(buf));
lstrcat(buf, _T(" "));
lstrcat(buf, txt);
INI_LogWrite(buf);
}
}
void INI_LogWriteWithResourcePrefixP(int prefix, _TCHAR *txt, _TCHAR *param)
{
if (txt != NULL) {
_TCHAR mask[2*MAX_STRING];
_TCHAR buf[2*MAX_STRING];
LoadString(hInst, prefix, mask, sizeof(mask));
wsprintf(buf, mask, param);
lstrcat(buf, _T(" "));
lstrcat(buf, txt);
INI_LogWrite(buf);
}
}
void INI_LogWriteWithResourcePrefixA(int prefix, char *txt)
{
if (txt != NULL) {
_TCHAR buf[2*MAX_STRING];
_TCHAR txtW[2*MAX_STRING];
LoadString(hInst, prefix, buf, sizeof(buf));
lstrcat(buf, _T(" "));
mbstowcs(txtW, txt, strlen(txt));
txtW[strlen(txt)] = '\0';
lstrcat(buf, txtW);
INI_LogWrite(buf);
}
}
void INI_LogWriteWithResourcePrefixNum(int prefix, long number, bool isUnsigned)
{
_TCHAR buf[MAX_STRING];
_TCHAR buf_number[MAX_STRING];
LoadString(hInst, prefix, buf, sizeof(buf));
if (!isUnsigned)
wsprintf(buf_number, _T(" %ld"), number);
else
wsprintf(buf_number, _T(" %lx"), number);
lstrcat(buf, buf_number);
INI_LogWrite(buf);
}
void INI_LogWriteWithResourcePrefixNumP(int prefix, long number, _TCHAR *param, bool console)
{
_TCHAR mask[MAX_STRING];
_TCHAR buf[MAX_STRING];
_TCHAR buf_number[MAX_STRING];
LoadString(hInst, prefix, mask, sizeof(mask));
wsprintf(buf, mask, param);
wsprintf(buf_number, _T(" %ld"), number);
lstrcat(buf, buf_number);
INI_LogWrite(buf);
if (console)
_tprintf(_T("%s\n"), buf);
}
void INI_LogWriteWithPrefixNum(_TCHAR * prefix, long number, bool console)
{
_TCHAR buf[MAX_STRING];
_TCHAR buf_number[MAX_STRING];
wsprintf(buf_number, _T(" %ld"), number);
lstrcpy(buf, prefix);
lstrcat(buf, buf_number);
INI_LogWrite(buf);
if (console)
_tprintf(_T("%s\n"), buf);
}
void INI_LogWriteWithResourcePrefixNumAP(int prefix, long number, char *param, bool console)
{
_TCHAR mask[MAX_STRING];
_TCHAR buf[MAX_STRING];
_TCHAR buf_number[MAX_STRING];
_TCHAR txtW[2*MAX_STRING];
LoadString(hInst, prefix, mask, sizeof(mask));
mbstowcs(txtW, param, strlen(param));
txtW[strlen(param)] = '\0';
wsprintf(buf, mask, txtW);
wsprintf(buf_number, _T(" %ld"), number);
lstrcat(buf, buf_number);
INI_LogWrite(buf);
if (console)
_tprintf(_T("%s\n"), buf);
}
void INI_LogWrite(_TCHAR *txt)
{
// char crlf[] = "\r\n";
if (glLogFile != NULL && txt != NULL) {
_TCHAR lpszOut[1024];
SYSTEMTIME st;
_TCHAR mask[] = _T("%d.%02d.%02d %02d:%02d:%02d:%03d %s");
// GetSystemTime(&st);
GetLocalTime(&st);
wsprintf(lpszOut, mask, st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, txt);
int charsWritten = _ftprintf(glLogFile, _T("%s\r\n"), lpszOut);
if (glLogSizeWrap > 0) {
glBytesWritten += (charsWritten * sizeof(TCHAR));
if (glBytesWritten > glLogSizeWrap * 0x100000) {
glLogPartCounter++;
if (glLogFile != NULL) {
_TCHAR buf[MAX_STRING];
_TCHAR buf_number[MAX_STRING];
LoadString(hInst, IDS_LOG_CONT_PART, buf, sizeof(buf));
wsprintf(buf_number, _T(" %ld"), glLogPartCounter);
lstrcat(buf, buf_number);
GetLocalTime(&st);
wsprintf(lpszOut, mask, st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, buf);
_ftprintf(glLogFile, _T("%s\r\n"), lpszOut);
fclose(glLogFile);
glLogFile = NULL;
}
glBytesWritten = 0;
_TCHAR *partPtr = logFullName + _tcslen(logFullName) - _tcslen(DEFAULT_LOG_EXT) - 3;
_TCHAR newPart[4];
wsprintf(newPart, _T("%03d"), glLogPartCounter);
_tcsncpy(partPtr, newPart, _tcslen(newPart));
_tprintf(_T("Log's new part name: %s\n"), logFullName);
glLogFile = _tfopen(logFullName, _T("w+b"));
if (glLogFile == NULL) {
_tprintf(_T("Error! Log file %s cannot be opened!\n"), logFullName);
return;
}
}
}
// fwrite(txt, strlen(txt), 1, glLogFile);
// fwrite(crlf, strlen(crlf), 1, glLogFile);
fflush(glLogFile);
}
}
void INI_LogClose() {
if (glLogFile != NULL) {
INI_LogWriteWithResourcePrefix(IDS_LOG_CONV_END, _T(""));
fclose(glLogFile);
glLogFile = NULL;
if(glBuffer != NULL)
{
free(glBuffer);
}
}
}
void INI_SetLogSizeWrap(unsigned int logSizeWrap)
{
glLogSizeWrap = logSizeWrap;
} |
#include<iostream>
using namespace std;
void bonapetite(int *arr, int n,int k,int cost)
{
int sum=0;
for (int i = 0; i < n; i++)
{
if (i == k)
{
continue;
}
else
{
sum+=arr[i];
}
}
int z=sum/2;
if (z == cost)
{
cout<<"Bon Appetit";
}
else
{
int y = abs(cost-z);
cout<<y;
}
}
int main()
{
int n,k,arr[100001];
cin>>n>>k;
for (int i = 0; i < n; i++)
{
cin>>arr[i];
}
int cost;
cin>>cost;
bonapetite(arr,n,k,cost);
return 0;
} |
.target "appleii"
printc = $FDF0
.org $801
; Prints all characters
LDA #0
main_loop:
; X = A; X++; A = X
TAX
INX
TXA
; Wait for a lil bit
LDY #0
inner_loop:
INY
BNE inner_loop
JSR printc
JMP main_loop
|
MODULE set_tiles
PUBLIC set_tiles
PUBLIC _set_tiles
GLOBAL set_xy_tt
SECTION code_driver
INCLUDE "target/gb/def/gb_globals.def"
; void __LIB__ set_tiles(uint8_t x, uint8_t y, uint8_t w, uint8_t h, unsigned char *vram_addr, unsigned char *tiles) __smallc NONBANKED;
set_tiles:
_set_tiles:
PUSH BC
ld hl,sp+4
LD C,(HL) ; BC = src
INC HL
LD B,(HL)
INC HL
LD E,(HL) ; DE = dst
DEC HL
LD D,(HL)
ld hl,sp + 14
PUSH DE ; Store address on stack for set_xy_tt
LD D,(HL) ; D = x
DEC HL
DEC HL
LD E,(HL) ; E = y
DEC HL
DEC HL
LD A,(HL-) ; A = w
DEC HL
LD L,(HL) ; L = h
LD H,A ; H = w
CALL set_xy_tt
POP BC
RET
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2019-2019 The Ctdcoin developers
//
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
////
#include "wallet.h"
#include "base58.h"
#include "checkpoints.h"
#include "coincontrol.h"
#include "kernel.h"
#include "masternode-budget.h"
#include "masternode-payments.h"
#include "net.h"
#include "script/script.h"
#include "script/sign.h"
#include "spork.h"
#include "Instantx.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
using namespace std;
/**
* Settings
*/
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
unsigned int nTxConfirmTarget = 1;
bool bSpendZeroConfChange = true;
bool fSendFreeTransactions = false;
bool fPayAtLeastCustomFee = true;
/**
* Fees smaller than this (in duffs) are considered zero fee (for transaction creation)
* We are ~100 times smaller then bitcoin now (2015-06-23), set minTxFee 10 times higher
* so it's still 10 times lower comparing to bitcoin.
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(10000);
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly {
bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
}
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return NULL;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey()
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSuctdcoinrtFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
RandAddSeedPerfmon();
CKey secret;
secret.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
// Create new metadata
int64_t nCreationTime = GetTime();
mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
nTimeFirstKey = nCreationTime;
if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
return pubkey;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
return false;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddCryptedKey(const CPubKey& vchPubKey,
const vector<unsigned char>& vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
}
return false;
}
bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
nTimeFirstKey = meta.nCreateTime;
mapKeyMetadata[pubkey.GetID()] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript& dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
nTimeFirstKey = 1; // No birthday information for watch-only keys.
NotifyWatchonlyChanged(true);
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript& dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
if (fFileBacked)
if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript& dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly)
{
SecureString strWalletPassphraseFinal;
if (!IsLocked()) {
fWalletUnlockAnonymizeOnly = anonymizeOnly;
return true;
}
strWalletPassphraseFinal = strWalletPassphrase;
CCrypter crypter;
CKeyingMaterial vMasterKey;
{
LOCK(cs_wallet);
BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) {
if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(vMasterKey)) {
fWalletUnlockAnonymizeOnly = anonymizeOnly;
return true;
}
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase;
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) {
if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey)) {
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked) {
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
BOOST_FOREACH (const CTxIn& txin, wtx.vin) {
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
result.insert(it->second);
}
return result;
}
void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = NULL;
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
const uint256& hash = it->second;
int n = mapWallet[hash].nOrderPos;
if (n < nMinOrderPos) {
nMinOrderPos = n;
copyFrom = &mapWallet[hash];
}
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
return true; // Spent
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(make_pair(outpoint, wtxid));
pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
assert(mapWallet.count(wtxid));
CWalletTx& thisTx = mapWallet[wtxid];
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
BOOST_FOREACH (const CTxIn& txin, thisTx.vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
// Find possible candidates
std::vector<COutput> vPossibleCoins;
AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_10000);
if (vPossibleCoins.empty()) {
LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n");
return false;
}
if (strTxHash.empty()) // No output specified, select the first one
return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet);
// Find specific vin
uint256 txHash = uint256S(strTxHash);
int nOutputIndex;
try {
nOutputIndex = std::stoi(strOutputIndex.c_str());
} catch (const std::exception& e) {
LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what());
return false;
}
BOOST_FOREACH (COutput& out, vPossibleCoins)
if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it!
return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet);
LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n");
return false;
}
bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
CScript pubScript;
txinRet = CTxIn(out.tx->GetHash(), out.i);
pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
CTxDestination address1;
ExtractDestination(pubScript, address1);
CBitcoinAddress address2(address1);
CKeyID keyID;
if (!address2.GetKeyID(keyID)) {
LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n");
return false;
}
if (!GetKey(keyID, keyRet)) {
LogPrintf("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n");
return false;
}
pubKeyRet = keyRet.GetPubKey();
return true;
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked) {
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
}
if (!EncryptKeys(vMasterKey)) {
if (fFileBacked) {
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
}
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload their unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked) {
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload their unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
}
NotifyStatusChanged(this);
return true;
}
int64_t CWallet::IncOrderPosNext(CWalletDB* pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
{
uint256 hash = wtxIn.GetHash();
if (fFromLoadWallet) {
mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
AddToSpends(hash);
} else {
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew) {
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext();
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew) {
// Merge
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) {
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) {
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) {
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
}
//// debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk())
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = GetArg("-walletnotify", "");
if (!strCmd.empty()) {
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
}
return true;
}
/**
* Add a transaction to the wallet, or update it.
* pblock is optional, but should be provided if the transaction is known to be in a block.
* If fUpdate is true, existing transactions will be updated.
*/
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
{
AssertLockHeld(cs_wallet);
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx)) {
CWalletTx wtx(this, tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(*pblock);
return AddToWallet(wtx);
}
}
return false;
}
void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
{
LOCK2(cs_main, cs_wallet);
if (!AddToWalletIfInvolvingMe(tx, pblock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
void CWallet::EraseFromWallet(const uint256& hash)
{
if (!fFileBacked)
return;
{
LOCK(cs_wallet);
if (mapWallet.erase(hash))
CWalletDB(strWalletFile).EraseTx(hash);
}
return;
}
isminetype CWallet::IsMine(const CTxIn& txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end()) {
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
return IsMine(prev.vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end()) {
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]) & filter)
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey)) {
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase()) {
// Generated block
if (hashBlock != 0) {
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
} else {
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end()) {
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0) {
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
list<COutputEntry>& listSent,
CAmount& nFee,
string& strSentAccount,
const isminefilter& filter) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < vout.size(); ++i) {
const CTxOut& txout = vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0) {
// Don't report 'change' txouts
if (pwallet->IsChange(txout)) {
continue;
}
} else if (!(fIsMine & filter)) {
continue;
}
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address)) {
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
COutputEntry output = {address, txout.nValue, (int)i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0) {
listSent.push_back(output);
}
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter) {
listReceived.push_back(output);
}
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
{
nReceived = nSent = nFee = 0;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (strAccount == strSentAccount) {
BOOST_FOREACH (const COutputEntry& s, listSent)
nSent += s.amount;
nFee = allFee;
}
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH (const COutputEntry& r, listReceived) {
if (pwallet->mapAddressBook.count(r.destination)) {
map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
nReceived += r.amount;
} else if (strAccount.empty()) {
nReceived += r.amount;
}
}
}
}
bool CWalletTx::WriteToDisk()
{
return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*/
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
int64_t nNow = GetTime();
CBlockIndex* pindex = pindexStart;
{
LOCK2(cs_main, cs_wallet);
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
pindex = chainActive.Next(pindex);
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
while (pindex) {
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
CBlock block;
ReadBlockFromDisk(block, pindex);
BOOST_FOREACH (CTransaction& tx, block.vtx) {
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
ret++;
}
pindex = chainActive.Next(pindex);
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
}
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) {
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && nDepth < 0) {
// Try to add to memory pool
LOCK(mempool.cs);
wtx.AcceptToMemoryPool(false);
}
}
}
bool CWalletTx::InMempool() const
{
LOCK(mempool.cs);
if (mempool.exists(GetHash())) {
return true;
}
return false;
}
void CWalletTx::RelayWalletTransaction(std::string strCommand)
{
if (!IsCoinBase()) {
if (GetDepthInMainChain() == 0) {
uint256 hash = GetHash();
LogPrintf("Relaying wtx %s\n", hash.ToString());
if (strCommand == "ix") {
mapTxLockReq.insert(make_pair(hash, (CTransaction) * this));
CreateNewLock(((CTransaction) * this));
RelayTransactionLockReq((CTransaction) * this, true);
} else {
RelayTransaction((CTransaction) * this);
}
}
}
}
set<uint256> CWalletTx::GetConflicts() const
{
set<uint256> result;
if (pwallet != NULL) {
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
void CWallet::ResendWalletTransactions()
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nTimeBestReceived < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast any of our txes that aren't in a block yet
LogPrintf("ResendWalletTransactions()\n");
{
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) {
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) {
CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction();
}
}
}
/** @} */ // end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureWatchOnlyCredit();
}
}
return nTotal;
}
/**
* populate vCoins with vector of available COutputs.
*/
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseIX) const
{
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
if (!CheckFinalTx(*pcoin))
continue;
if (fOnlyConfirmed && !pcoin->IsTrusted())
continue;
if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain(false);
// do not use IX for inputs that have less then 6 blockchain confirmations
if (fUseIX && nDepth < 6)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
bool found = false;
if (nCoinType == ONLY_NOT10000IFMN) {
found = !(fMasterNode && pcoin->vout[i].nValue == Params().MasternodeColleteralLimxDev() * COIN);
} else if (nCoinType == ONLY_10000) {
found = pcoin->vout[i].nValue == Params().MasternodeColleteralLimxDev() * COIN;
} else {
found = true;
}
if (!found) continue;
isminetype mine = IsMine(pcoin->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
(!IsLockedCoin((*it).first, i) || nCoinType == ONLY_10000) &&
(pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
(!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
vCoins.push_back(COutput(pcoin, i, nDepth,
((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
(coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO)));
}
}
}
}
map<CBitcoinAddress, vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue)
{
vector<COutput> vCoins;
AvailableCoins(vCoins, fConfirmed);
map<CBitcoinAddress, vector<COutput> > mapCoins;
BOOST_FOREACH (COutput out, vCoins) {
if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue)
continue;
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
mapCoins[CBitcoinAddress(address)].push_back(out);
}
return mapCoins;
}
static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
seed_insecure_rand();
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) {
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) {
for (unsigned int i = 0; i < vValue.size(); i++) {
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand() & 1 : !vfIncluded[i]) {
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue) {
fReachedTarget = true;
if (nTotal < nBest) {
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
}
bool CWallet::SelectStakeCoins(std::set<std::pair<const CWalletTx*, unsigned int> >& setCoins, int64_t nTargetAmount) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins, true);
int64_t nAmountSelected = 0;
BOOST_FOREACH (const COutput& out, vCoins) {
//make sure not to outrun target amount
if (nAmountSelected + out.tx->vout[out.i].nValue > nTargetAmount)
continue;
//check for min age
if (GetTime() - out.tx->GetTxTime() < nStakeMinAge)
continue;
//check that it is matured
if (out.nDepth < (out.tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10))
continue;
//add to our stake set
setCoins.insert(make_pair(out.tx, out.i));
nAmountSelected += out.tx->vout[out.i].nValue;
}
return true;
}
bool CWallet::MintableCoins()
{
int64_t nBalance = GetBalance();
if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
return error("MintableCoins() : invalid reserve balance amount");
if (nBalance <= nReserveBalance)
return false;
vector<COutput> vCoins;
AvailableCoins(vCoins, true);
BOOST_FOREACH (const COutput& out, vCoins) {
if (GetTime() - out.tx->GetTxTime() > nStakeMinAge)
return true;
}
return false;
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<CAmount, pair<const CWalletTx*, unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<CAmount>::max();
coinLowestLarger.second.first = NULL;
vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
vValue.clear();
nTotalLower = 0;
BOOST_FOREACH (const COutput& output, vCoins) {
if (!output.fSpendable)
continue;
const CWalletTx* pcoin = output.tx;
// if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth);
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
int i = output.i;
CAmount n = pcoin->vout[i].nValue;
pair<CAmount, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i));
if (n == nTargetValue) {
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
} else if (n < nTargetValue + CENT) {
vValue.push_back(coin);
nTotalLower += n;
} else if (n < coinLowestLarger.first) {
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue) {
for (unsigned int i = 0; i < vValue.size(); ++i) {
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue) {
if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue
{
// we looked at everything possible and didn't find anything, no luck
return false;
}
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) {
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
} else {
string s = "CWallet::SelectCoinsMinConf best subset: ";
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
s += FormatMoney(vValue[i].first) + " ";
}
}
LogPrintf("%s - total %s\n", s, FormatMoney(nBest));
}
return true;
}
bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const
{
// Note: this function should never be used for "always free" tx types
vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected()) {
BOOST_FOREACH (const COutput& out, vCoins) {
if (!out.fSpendable)
continue;
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
}
struct CompareByPriority {
bool operator()(const COutput& t1,
const COutput& t2) const
{
return t1.Priority() > t2.Priority();
}
};
int CWallet::CountInputsWithAmount(int64_t nInputAmount)
{
int64_t nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted()) {
int nDepth = pcoin->GetDepthInMainChain(false);
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
COutput out = COutput(pcoin, i, nDepth, true);
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
if (out.tx->vout[out.i].nValue != nInputAmount) continue;
if (IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE) continue;
nTotal++;
}
}
}
}
return nTotal;
}
bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, bool useIX)
{
CWalletTx wtx;
if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) {
tx = (CTransaction)wtx;
return true;
}
return false;
}
bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX)
{
// make our change address
CReserveKey reservekey(pwalletMain);
CScript scriptChange;
scriptChange << OP_RETURN << ToByteVector(hash);
int64_t nFeeRet = 0;
std::string strFail = "";
vector<pair<CScript, int64_t> > vecSend;
vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX));
CCoinControl* coinControl = NULL;
bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0);
if (!success) {
LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail);
return false;
}
return true;
}
bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<int64_t>& vecAmounts)
{
BOOST_FOREACH (CTxIn i, vCoins) {
if (mapWallet.count(i.prevout.hash)) {
CWalletTx& wtx = mapWallet[i.prevout.hash];
if (i.prevout.n < wtx.vout.size()) {
vecAmounts.push_back(wtx.vout[i.prevout.n].nValue);
}
} else {
LogPrintf("ConvertList -- Couldn't find transaction\n");
}
}
return true;
}
bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend,
CWalletTx& wtxNew,
CReserveKey& reservekey,
CAmount& nFeeRet,
std::string& strFailReason,
const CCoinControl* coinControl,
AvailableCoinsType coin_type,
bool useIX,
CAmount nFeePay)
{
if (useIX && nFeePay < CENT) nFeePay = CENT;
CAmount nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
if (nValue < 0) {
strFailReason = _("Transaction amounts must be positive");
return false;
}
nValue += s.second;
}
if (vecSend.empty() || nValue < 0) {
strFailReason = _("Transaction amounts must be positive");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
{
LOCK2(cs_main, cs_wallet);
{
nFeeRet = 0;
if (nFeePay > 0) nFeeRet = nFeePay;
while (true) {
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
CAmount nTotalValue = nValue + nFeeRet;
double dPriority = 0;
// vouts to the payees
if (coinControl && !coinControl->fSplitBlock) {
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
CTxOut txout(s.second, s.first);
if (txout.IsDust(::minRelayTxFee)) {
strFailReason = _("Transaction amount too small");
return false;
}
txNew.vout.push_back(txout);
}
} else //UTXO Splitter Transaction
{
int nSplitBlock;
if (coinControl)
nSplitBlock = coinControl->nSplitBlock;
else
nSplitBlock = 1;
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
for (int i = 0; i < nSplitBlock; i++) {
if (i == nSplitBlock - 1) {
uint64_t nRemainder = s.second % nSplitBlock;
txNew.vout.push_back(CTxOut((s.second / nSplitBlock) + nRemainder, s.first));
} else
txNew.vout.push_back(CTxOut(s.second / nSplitBlock, s.first));
}
}
}
// Choose coins to use
set<pair<const CWalletTx*, unsigned int> > setCoins;
CAmount nValueIn = 0;
if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) {
if (coin_type == ALL_COINS) {
strFailReason = _("Insufficient funds.");
}
if (useIX) {
strFailReason += " " + _("InstantX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again.");
}
return false;
}
BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) {
CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
//The coin age after the next block (depth+1) is used instead of the current,
//reflecting an assumption the user would accept a bit more delay for
//a chance at a free transaction.
//But mempool inputs might still be in the mempool, so their age stays 0
int age = pcoin.first->GetDepthInMainChain();
if (age != 0)
age += 1;
dPriority += (double)nCredit * age;
}
CAmount nChange = nValueIn - nValue - nFeeRet;
if (nChange > 0) {
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-ctdcoin-address
CScript scriptChange;
// coin control: send change to custom address
if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
scriptChange = GetScriptForDestination(coinControl->destChange);
// no coin control: send change to newly generated address
else {
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey);
assert(ret); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
}
CTxOut newTxOut(nChange, scriptChange);
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (newTxOut.IsDust(::minRelayTxFee)) {
nFeeRet += nChange;
nChange = 0;
reservekey.ReturnKey();
} else {
// Insert change txn at random position:
vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1);
txNew.vout.insert(position, newTxOut);
}
} else
reservekey.ReturnKey();
// Fill vin
BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins)
txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins)
if (!SignSignature(*this, *coin.first, txNew, nIn++)) {
strFailReason = _("Signing transaction failed");
return false;
}
// Embed the constructed transaction data in wtxNew.
*static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_STANDARD_TX_SIZE) {
strFailReason = _("Transaction too large");
return false;
}
dPriority = wtxNew.ComputePriority(dPriority, nBytes);
// Can we complete this as a free transaction?
if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) {
// Not enough fee: enough priority?
double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
// Not enough mempool history to estimate: use hard-coded AllowFree.
if (dPriorityNeeded <= 0 && AllowFree(dPriority))
break;
// Small enough, and priority high enough, to send for free
if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
break;
}
CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) {
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded) // Done, enough fee included
break;
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
}
return true;
}
bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay)
{
vector<pair<CScript, CAmount> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay);
}
// ppcoin: create coin stake transaction
bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CMutableTransaction& txNew, unsigned int& nTxNewTime)
{
txNew.vin.clear();
txNew.vout.clear();
// Mark coin stake transaction
CScript scriptEmpty;
scriptEmpty.clear();
txNew.vout.push_back(CTxOut(0, scriptEmpty));
// Choose coins to use
int64_t nBalance = GetBalance();
if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
return error("CreateCoinStake : invalid reserve balance amount");
if (nBalance <= nReserveBalance)
return false;
// presstab HyperStake - Initialize as static and don't update the set on every run of CreateCoinStake() in order to lighten resource use
static std::set<pair<const CWalletTx*, unsigned int> > setStakeCoins;
static int nLastStakeSetUpdate = 0;
if (GetTime() - nLastStakeSetUpdate > nStakeSetUpdateTime) {
setStakeCoins.clear();
if (!SelectStakeCoins(setStakeCoins, nBalance - nReserveBalance))
return false;
nLastStakeSetUpdate = GetTime();
}
if (setStakeCoins.empty())
return false;
vector<const CWalletTx*> vwtxPrev;
int64_t nCredit = 0;
CScript scriptPubKeyKernel;
//prevent staking a time that won't be accepted
if (GetAdjustedTime() <= chainActive.Tip()->nTime)
MilliSleep(10000);
BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) {
//make sure that enough time has elapsed between
CBlockIndex* pindex = NULL;
BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock);
if (it != mapBlockIndex.end())
pindex = it->second;
else {
if (fDebug)
LogPrintf("CreateCoinStake() failed to find block index \n");
continue;
}
// Read block header
CBlockHeader block = pindex->GetBlockHeader();
bool fKernelFound = false;
uint256 hashProofOfStake = 0;
COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
nTxNewTime = GetAdjustedTime();
//iterates each utxo inside of CheckStakeKernelHash()
if (CheckStakeKernelHash(nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true)) {
//Double check that this will pass time requirements
if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast()) {
LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n");
continue;
}
// Found a kernel
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : kernel found\n");
vector<valtype> vSolutions;
txnouttype whichType;
CScript scriptPubKeyOut;
scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) {
LogPrintf("CreateCoinStake : failed to parse kernel\n");
break;
}
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType);
if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) {
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : no suctdcoinrt for kernel type=%d\n", whichType);
break; // only suctdcoinrt pay to public key and pay to address
}
if (whichType == TX_PUBKEYHASH) // pay to address type
{
//convert to pay to public key type
CKey key;
if (!keystore.GetKey(uint160(vSolutions[0]), key)) {
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
}
scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
} else
scriptPubKeyOut = scriptPubKeyKernel;
txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
nCredit += pcoin.first->vout[pcoin.second].nValue;
vwtxPrev.push_back(pcoin.first);
txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
//presstab HyperStake - calculate the total size of our new output including the stake reward so that we can use it to decide whether to split the stake outputs
const CBlockIndex* pIndex0 = chainActive.Tip();
uint64_t nTotalSize = pcoin.first->vout[pcoin.second].nValue + GetBlockValue(pIndex0->nHeight);
//presstab HyperStake - if MultiSend is set to send in coinstake we will add our outputs here (values asigned further down)
if (nTotalSize / 2 > nStakeSplitThreshold * COIN)
txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType);
fKernelFound = true;
break;
}
if (fKernelFound)
break; // if kernel is found stop searching
}
if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
return false;
// Calculate reward
uint64_t nReward;
const CBlockIndex* pIndex0 = chainActive.Tip();
nReward = GetBlockValue(pIndex0->nHeight+1);
nCredit += nReward;
int64_t nMinFee = 0;
while (true) {
// Set output amount
if (txNew.vout.size() == 3) {
txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
} else
txNew.vout[1].nValue = nCredit - nMinFee;
// Limit size
unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5)
return error("CreateCoinStake : exceeded coinstake size limit");
CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
// Check enough fee is paid
if (nMinFee < nFeeNeeded) {
nMinFee = nFeeNeeded;
continue; // try signing again
} else {
if (fDebug)
LogPrintf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
break;
}
}
//Masternode payment
FillBlockPayee(txNew, nMinFee, true);
// Sign
int nIn = 0;
BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) {
if (!SignSignature(*this, *pcoin, txNew, nIn++))
return error("CreateCoinStake : failed to sign coinstake");
}
// Successfully generated coinstake
nLastStakeSetUpdate = 0; //this will trigger stake set to repopulate next round
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Notify that old coins are spent
set<uint256> updated_hahes;
BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) {
// notify only once
if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue;
CWalletTx& coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
updated_hahes.insert(txin.prevout.hash);
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
// Broadcast
if (!wtxNew.AcceptToMemoryPool(false)) {
// This must not fail. The transaction has already been signed and recorded.
LogPrintf("CommitTransaction() : Error: Transaction not valid\n");
return false;
}
wtxNew.RelayWalletTransaction(strCommand);
}
return true;
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
{
if (!pwalletdb.WriteAccountingEntry_Backend(acentry))
return false;
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
return true;
}
CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
{
// payTxFee is user-set "I want to pay this much"
CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
// user selected total at least (default=true)
if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
nFeeNeeded = payTxFee.GetFeePerK();
// User didn't set: use -txconfirmtarget to estimate...
if (nFeeNeeded == 0)
nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
// ... unless we don't have enough mempool data, in which case fall
// back to a hard-coded fee
if (nFeeNeeded == 0)
nFeeNeeded = minTxFee.GetFee(nTxBytes);
// prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
// But always obey the maximum
if (nFeeNeeded > maxTxFee)
nFeeNeeded = maxTxFee;
return nFeeNeeded;
}
int64_t CWallet::GetTotalValue(std::vector<CTxIn> vCoins)
{
int64_t nTotalValue = 0;
CWalletTx wtx;
BOOST_FOREACH (CTxIn i, vCoins) {
if (mapWallet.count(i.prevout.hash)) {
CWalletTx& wtx = mapWallet[i.prevout.hash];
if (i.prevout.n < wtx.vout.size()) {
nTotalValue += wtx.vout[i.prevout.n].nValue;
}
} else {
LogPrintf("GetTotalValue -- Couldn't find transaction\n");
}
}
return nTotalValue;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return DB_LOAD_OK;
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE) {
if (CDB::Rewrite(strWalletFile, "\x04pool")) {
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// the requires a new key.
}
}
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
fFirstRunRet = !vchDefaultKey.IsValid();
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
if (!fFileBacked)
return DB_LOAD_OK;
DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE) {
if (CDB::Rewrite(strWalletFile, "\x04pool")) {
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW));
if (!fFileBacked)
return false;
if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
return false;
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
if (fFileBacked) {
// Delete destdata tuples associated with address
std::string strAddress = CBitcoinAddress(address).ToString();
BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) {
CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
}
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
if (!fFileBacked)
return false;
CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
bool CWallet::SetDefaultKey(const CPubKey& vchPubKey)
{
if (fFileBacked) {
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
}
vchDefaultKey = vchPubKey;
return true;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH (int64_t nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
if (IsLocked())
return false;
int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0);
for (int i = 0; i < nKeys; i++) {
int64_t nIndex = i + 1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0);
while (setKeyPool.size() < (nTargetSize + 1)) {
int64_t nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
double dProgress = 100.f * nEnd / (nTargetSize + 1);
std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress);
uiInterface.InitMessage(strMsg);
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
// Get the oldest key
if (setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
if (fFileBacked) {
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
}
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex)
{
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result)
{
int64_t nIndex = 0;
CKeyPool keypool;
{
LOCK(cs_wallet);
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1) {
if (IsLocked()) return false;
result = GenerateNewKey();
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
int64_t nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) {
CWalletTx* pcoin = &walletEntry.second;
if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
CTxDestination addr;
if (!IsMine(pcoin->vout[i]))
continue;
if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
set<set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
set<set<CTxDestination> > groupings;
set<CTxDestination> grouping;
BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) {
CWalletTx* pcoin = &walletEntry.second;
if (pcoin->vin.size() > 0) {
bool any_mine = false;
// group all input addresses with each other
BOOST_FOREACH (CTxIn txin, pcoin->vin) {
CTxDestination address;
if (!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine) {
BOOST_FOREACH (CTxOut txout, pcoin->vout)
if (IsChange(txout)) {
CTxDestination txoutAddr;
if (!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0) {
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (IsMine(pcoin->vout[i])) {
CTxDestination address;
if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
set<set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses
map<CTxDestination, set<CTxDestination>*> setmap; // map addresses to the unique group containing it
BOOST_FOREACH (set<CTxDestination> grouping, groupings) {
// make a set of all the groups hit by this new group
set<set<CTxDestination>*> hits;
map<CTxDestination, set<CTxDestination>*>::iterator it;
BOOST_FOREACH (CTxDestination address, grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
set<CTxDestination>* merged = new set<CTxDestination>(grouping);
BOOST_FOREACH (set<CTxDestination>* hit, hits) {
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
BOOST_FOREACH (CTxDestination element, *merged)
setmap[element] = merged;
}
set<set<CTxDestination> > ret;
BOOST_FOREACH (set<CTxDestination>* uniqueGrouping, uniqueGroupings) {
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
{
LOCK(cs_wallet);
set<CTxDestination> result;
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) {
const CTxDestination& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey)
{
if (nIndex == -1) {
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH (const int64_t& id, setKeyPool) {
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes() : read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
setAddress.insert(keyID);
}
}
bool CWallet::UpdatedTransaction(const uint256& hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end()) {
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
return true;
}
}
return false;
}
void CWallet::LockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
class CAffectedKeysVisitor : public boost::static_visitor<void>
{
private:
const CKeyStore& keystore;
std::vector<CKeyID>& vKeys;
public:
CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript& script)
{
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
BOOST_FOREACH (const CTxDestination& dest, vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID& keyId)
{
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID& scriptId)
{
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const CNoDestination& none) {}
};
void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
if (it->second.nCreateTime)
mapKeyBirth[it->first] = it->second.nCreateTime;
// map in which we'll infer heights of other keys
CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys;
GetKeys(setKeys);
BOOST_FOREACH (const CKeyID& keyid, setKeys) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
setKeys.clear();
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
// iterate over all wallet transactions...
const CWalletTx& wtx = (*it).second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
BOOST_FOREACH (const CKeyID& keyid, vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
}
unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (wtx.hashBlock != 0) {
if (mapBlockIndex.count(wtx.hashBlock)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
{
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
TxItems txOrdered = wtxOrdered;
for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = (*it).second.first;
if (pwtx == &wtx)
continue;
CAccountingEntry* const pacentry = (*it).second.second;
int64_t nSmartTime;
if (pwtx) {
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime)
nSmartTime = pwtx->nTimeReceived;
} else
nSmartTime = pacentry->nTime;
if (nSmartTime <= latestTolerated) {
latestEntry = nSmartTime;
if (nSmartTime > latestNow)
latestNow = nSmartTime;
break;
}
}
}
int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else
LogPrintf("AddToWallet() : found %s in block %s not in index\n",
wtx.GetHash().ToString(),
wtx.hashBlock.ToString());
}
return nTimeSmart;
}
bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
}
bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
}
bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if (i != mapAddressBook.end()) {
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if (j != i->second.destdata.end()) {
if (value)
*value = j->second;
return true;
}
}
return false;
}
void CWallet::AutoCombineDust()
{
if (IsInitialBlockDownload() || IsLocked()) {
return;
}
map<CBitcoinAddress, vector<COutput> > mapCoinsByAddress = AvailableCoinsByAddress(true, 0);
//coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address
for (map<CBitcoinAddress, vector<COutput> >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) {
vector<COutput> vCoins, vRewardCoins;
vCoins = it->second;
//MilliSleep(nAutoCombineThresholdTime*60000);
MilliSleep(5000);
//find masternode rewards that need to be combined
CCoinControl* coinControl = new CCoinControl();
CAmount nTotalRewardsValue = 0;
BOOST_FOREACH (const COutput& out, vCoins) {
//no coins should get this far if they dont have proper maturity, this is double checking
if (out.tx->IsCoinStake() && out.tx->GetDepthInMainChain() < Params().COINBASE_MATURITY() + 1 )
continue;
if (out.Value() > nAutoCombineThreshold * COIN)
continue;
COutPoint outpt(out.tx->GetHash(), out.i);
coinControl->Select(outpt);
vRewardCoins.push_back(out);
nTotalRewardsValue += out.Value();
}
//if no inputs found then return
if (!coinControl->HasSelected())
continue;
//we cannot combine one coin with itself
if (vRewardCoins.size() <= 1)
continue;
vector<pair<CScript, int64_t> > vecSend;
CScript scriptPubKey = GetScriptForDestination(it->first.Get());
vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue));
// Create the transaction and commit it to the network
CWalletTx wtx;
CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch
string strErr;
int64_t nFeeRet = 0;
//get the fee amount
CWalletTx wtxdummy;
CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0));
vecSend[0].second = nTotalRewardsValue - nFeeRet - 500;
if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0))) {
LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr);
continue;
}
if (!CommitTransaction(wtx, keyChange)) {
LogPrintf("AutoCombineDust transaction commit failed\n");
continue;
}
LogPrintf("AutoCombineDust sent transaction\n");
delete coinControl;
}
}
bool CWallet::MultiSend()
{
if (IsInitialBlockDownload() || IsLocked()) {
LogPrintf("Multisend Locked or Sync not complete - Limx Dev wallet.cpp L3394\n");
return false;
}
if (chainActive.Tip()->nHeight <= nLastMultiSendHeight) {
LogPrintf("Multisend: lastmultisendheight is higher than current best height\n");
return false;
}
std::vector<COutput> vCoins;
AvailableCoins(vCoins);
int stakeSent = 0;
int mnSent = 0;
BOOST_FOREACH (const COutput& out, vCoins) {
//need output with precise confirm count - this is how we identify which is the output to send
if (out.tx->GetDepthInMainChain() != Params().COINBASE_MATURITY() + 1)
continue;
COutPoint outpoint(out.tx->GetHash(), out.i);
bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx);
bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both
if (!(sendMSOnStake || sendMSonMNReward))
continue;
CTxDestination destMyAddress;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) {
LogPrintf("Multisend: failed to extract destination\n");
continue;
}
//Disabled Addresses won't send MultiSend transactions
if (vDisabledAddresses.size() > 0) {
for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) {
if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) {
LogPrintf("Multisend: disabled address preventing multisend\n");
return false;
}
}
}
// create new coin control, populate it with the selected utxo, create sending vector
CCoinControl* cControl = new CCoinControl();
COutPoint outpt(out.tx->GetHash(), out.i);
cControl->Select(outpt);
cControl->destChange = destMyAddress;
CWalletTx wtx;
CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch
int64_t nFeeRet = 0;
vector<pair<CScript, int64_t> > vecSend;
// loop through multisend vector and add amounts and addresses to the sending vector
const isminefilter filter = ISMINE_SPENDABLE;
int64_t nAmount = 0;
for (unsigned int i = 0; i < vMultiSend.size(); i++) {
// MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int
nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100;
CBitcoinAddress strAddSend(vMultiSend[i].first);
CScript scriptPubKey;
scriptPubKey = GetScriptForDestination(strAddSend.Get());
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
//get the fee amount
CWalletTx wtxdummy;
string strErr;
CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0));
CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second;
if (nLastSendAmount < nFeeRet + 500) {
LogPrintf("%s: fee of %s is too large to insert into last output\n");
return false;
}
vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500;
// Create the transaction and commit it to the network
if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0))) {
LogPrintf("MultiSend createtransaction failed\n");
return false;
}
if (!CommitTransaction(wtx, keyChange)) {
LogPrintf("MultiSend transaction commit failed\n");
return false;
} else
fMultiSendNotify = true;
delete cControl;
//write nLastMultiSendHeight to DB
CWalletDB walletdb(strWalletFile);
nLastMultiSendHeight = chainActive.Tip()->nHeight;
if (!walletdb.WriteMSettings(fMultiSendStake, fMultiSendMasternodeReward, nLastMultiSendHeight))
LogPrintf("Failed to write MultiSend setting to DB\n");
LogPrintf("MultiSend successfully sent\n");
if (sendMSOnStake)
stakeSent++;
else
mnSent++;
//stop iterating if we are done
if (mnSent > 0 && stakeSent > 0)
return true;
if (stakeSent > 0 && !fMultiSendMasternodeReward)
return true;
if (mnSent > 0 && !fMultiSendStake)
return true;
}
return true;
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
int CMerkleTx::SetMerkleBranch(const CBlock& block)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
// Update the tx's hashBlock
hashBlock = block.GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
if (block.vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)block.vtx.size()) {
vMerkleBranch.clear();
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = block.GetMerkleBranch(nIndex);
// Is the tx in a block that's in the main chain
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
const CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified) {
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const
{
AssertLockHeld(cs_main);
int nResult = GetDepthInMainChainINTERNAL(pindexRet);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
if (enableIX) {
if (nResult < 6) {
int signatures = GetTransactionLockSignatures();
if (signatures >= INSTANTX_SIGNATURES_REQUIRED) {
return nInstantXDepth + nResult;
}
}
}
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees)
{
CValidationState state;
return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees);
}
int CMerkleTx::GetTransactionLockSignatures() const
{
if (fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2;
if (!IsSporkActive(SPORK_2_INSTANTX)) return -3;
if (!fEnableInstantX) return -1;
//compile consessus vote
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
if (i != mapTxLocks.end()) {
return (*i).second.CountSignatures();
}
return -1;
}
bool CMerkleTx::IsTransactionLockTimedOut() const
{
if (!fEnableInstantX) return 0;
//compile consessus vote
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
if (i != mapTxLocks.end()) {
return GetTime() > (*i).second.nTimeout;
}
return false;
}
bool CWallet::CreateMessageTransaction(CWalletTx& wtxFrom,
const CAmount& nMessageFee,
const vector<pair<CScript, CAmount> >& vecSend,
CWalletTx& wtxNew,
CReserveKey& reservekey,
CAmount& nFeeRet,
std::string& strFailReason,
CAmount nFeePay)
{
CAmount nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
if (nValue < 0) {
strFailReason = _("Transaction amounts must be positive");
return false;
}
nValue += s.second;
}
if (vecSend.empty() || nValue < 0) {
strFailReason = _("Transaction amounts must be positive");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
{
LOCK2(cs_main, cs_wallet);
{
nFeeRet = 0;
if (nFeePay > 0) nFeeRet = nFeePay;
while (true) {
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
double dPriority = 0;
// vouts to the payees
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
CTxOut txout(s.second, s.first);
txNew.vout.push_back(txout);
}
reservekey.ReturnKey();
// Fill vin
for(unsigned int i=0; i<wtxFrom.vout.size(); i++) {
if(wtxFrom.vout[i].nValue == nMessageFee) {
CTxIn vin(wtxFrom.GetHash(), i);
txNew.vin.push_back(vin);
}
}
if(txNew.vin.size() == 0) {
strFailReason = _("Invalid message vin");
return false;
}
// Sign
int nIn = 0;
if (!SignSignature(*this, wtxFrom, txNew, nIn++)) {
strFailReason = _("Signing transaction failed");
return false;
}
// Embed the constructed transaction data in wtxNew.
*static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_STANDARD_TX_SIZE) {
strFailReason = _("Transaction too large");
return false;
}
dPriority = wtxNew.ComputePriority(dPriority, nBytes);
// Can we complete this as a free transaction?
if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) {
// Not enough fee: enough priority?
double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
// Not enough mempool history to estimate: use hard-coded AllowFree.
if (dPriorityNeeded <= 0 && AllowFree(dPriority))
break;
// Small enough, and priority high enough, to send for free
if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
break;
}
CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) {
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded) // Done, enough fee included
break;
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
}
return true;
}
|
.686
.model flat,stdcall
option casemap:none
include .\bnlib.inc
include .\bignum.inc
.code
bnToHex proc uses edi esi ebx bn:DWORD,ptrStr:DWORD
mov esi,bn
mov edi,ptrStr
.if BN_IS_ZERO(esi)
mov dword ptr [edi],'00'
mov eax,2
ret
.endif
.if [esi].BN.bSigned
mov byte ptr [edi],'-'
inc edi
.endif
mov eax,[esi].BN.dwSize
lea esi,[esi].BN.dwArray[eax*4-4]
mov ecx,[esi]
mov edx,ecx
bswap ecx
mov ebx,3
dec cl
sbb ebx,0
dec ch
sbb ebx,0
dec dh
sbb ebx,0
.repeat
movzx eax,byte ptr [esi+ebx]
mov ecx,eax
shr ecx,4
and eax,1111b
and ecx,1111b
cmp eax,10
sbb edx,edx
adc eax,0
lea eax,[eax+edx*8+('0'+7)]
cmp ecx,10
sbb edx,edx
adc ecx,0
shl eax,8
lea ecx,[ecx+edx*8+('0'+7)]
or eax,ecx
mov [edi],ax
add edi,2
dec ebx
.until sign?
mov esi,bn
mov ebx,[esi].BN.dwSize
jmp @F
.repeat
mov ecx,[esi].BN.dwArray[ebx*4-4]
mov edx,ecx
shr edx,4
push ebx
and ecx,0F0F0F0Fh
and edx,0F0F0F0Fh
lea ebx,[ecx+06060606h]
lea eax,[edx+06060606h]
and ebx,10101010h
and eax,10101010h
shr ebx,4
shr eax,4
lea ecx,[ecx+ebx*8+30303030h]
lea edx,[edx+eax*8+30303030h]
sub ecx,ebx
sub edx,eax
pop ebx
mov [edi+7],cl
mov [edi+6],dl
mov [edi+5],ch
mov [edi+4],dh
shr ecx,16
mov byte ptr [edi+8],0
shr edx,16
mov [edi+3],cl
mov [edi+2],dl
mov [edi+1],ch
mov [edi+0],dh
add edi,8
@@: dec ebx
.until zero?
mov eax,edi
sub eax,ptrStr
mov [edi],bl
ret
bnToHex endp
end
|
; this file is part of Release, written by Malban in 2017
;
HIGH_SCORE_ZERO_POS = $7090
X_STEP_LETTERS = 20
;
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
display_highscore
clr demo_mode
jsr init_objects
jsr spawnStarfield
ldd #PC_SCORE
std NEXT_OBJECT,u
jsr spawnStarfield
ldd #PC_SCORE
std NEXT_OBJECT,u
jsr spawnStarfield
ldd #PC_SCORE
std NEXT_OBJECT,u
jsr spawnStarfield
ldd #PC_SCORE
std NEXT_OBJECT,u
jsr spawnStarfield
ldd #PC_SCORE
std NEXT_OBJECT,u
INIT_MUSIC highscoreMusic
display_highscore_intern
jsr PLY_PLAY
jsr Wait_Recal
ldx RecalCounter ; recal counter, about 21 Minutes befor roll over
leax 1,x
stx RecalCounter
_DP_TO_D0 ; round_startup_main expects dp set to d0
JSR do_ym_sound2_no_sfx
jsr Intensity_5F
ldd #HIGH_SCORE_ZERO_POS
std tmp1
lda #5
sta tmp_count
ldy #highScoreBlock
next_score_entry
lda #3
sta tmp_count2
next_name_letter
_SCALE (SCALE_FACTOR_GAME) ; everything we do with "positioning" is scale SCALE_FACTOR_GAME
ldd tmp1 ; the current move vector
MY_MOVE_TO_D_START_NT
LDB ,y+ ; first char of three letter name
; lets calculate the abc-table offset...
SUBB # 'A' ; subtract smallest letter, so A has 0 offset
LSLB ; multiply by two, since addresses are 16 bit
ldx #_abc ; and add the abc (table of vector list address of the alphabet's letters)
LDX b,X ; in x now address of first letter vectorlist
_SCALE 24 ; (SCROLL_SCALE_FACTOR) ; drawing of letters is done in SCROLL_SCALE_FACTOR
lda mov_x
adda #X_STEP_LETTERS
sta mov_x
MY_MOVE_TO_B_END
jsr myDraw_VL_mode3
_ZERO_VECTOR_BEAM ; draw each letter with a move from zero, more stable
dec tmp_count2
bne next_name_letter
lda mov_x
adda #2*X_STEP_LETTERS
sta mov_x
_SCALE (SCALE_FACTOR_GAME) ; everything we do with "positioning" is scale SCALE_FACTOR_GAME
; put to be displayed bcd score as csa score into player score
; player_score
ldd tmp1 ; the current move vector
MY_MOVE_TO_D_START
leau ,y
leay 3,y
ldx #player_score
jsr bcd_to_csa
pshs y
lda mov_y
suba #50
sta mov_y
lda #$90
sta mov_x
jsr in_game_score ;#isfunction
puls y
dec tmp_count
lbne next_score_entry
jsr getButtonState ; is a button pressed?
beq display_highscore_intern2
cmpb #3 ; same aslast state
beq display_highscore_intern2
cmpb #2 ; as released - possibly from highscore return
beq display_highscore_intern2
lda #15
jsr init_objects
ldb #3
stb last_button_state
stb current_button_state
INIT_MUSIC titleMusic
jmp title_main1_hs_ret
display_highscore_intern2
ldd #emptyStreamInMove
std inMovePointer
ldu list_objects_head
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in reg a place to be edited
BLINK_LENGTH = 50/3 ; 1/3 second
edit_highscore
nega
adda #5
; in a now the compare value to ourcounter
sta hs_place_got
lda #3
sta hs_place_edit
lda #BLINK_LENGTH
sta hs_blink_count
clr hs_blink_state
; save player hs
ldx #player_score
ldu #star_0_score
ldd ,x++
std ,u++
ldd ,x++
std ,u++
ldd ,x++
std ,u++
edit_highscore_inner
jsr PLY_PLAY
jsr Wait_Recal
ldx RecalCounter ; recal counter, about 21 Minutes befor roll over
leax 1,x
stx RecalCounter
_DP_TO_D0 ; round_startup_main expects dp set to d0
JSR do_ym_sound2
jsr Intensity_5F
ldd #HIGH_SCORE_ZERO_POS
std tmp1
lda #5
sta tmp_count
ldy #highScoreBlock
next_score_entry_edit
lda #3
sta tmp_count2
next_name_letter_edit
_SCALE (SCALE_FACTOR_GAME) ; everything we do with "positioning" is scale SCALE_FACTOR_GAME
ldd tmp1 ; the current move vector
MY_MOVE_TO_D_START_NT
LDB ,y+ ; first char of three letter name
; lets calculate the abc-table offset...
SUBB # 'A' ; subtract smallest letter, so A has 0 offset
LSLB ; multiply by two, since addresses are 16 bit
ldx #_abc ; and add the abc (table of vector list address of the alphabet's letters)
LDX b,X ; in x now address of first letter vectorlist
; check if current place is the "blinker"
lda tmp_count
cmpa hs_place_got
bne no_blinker
lda tmp_count2
cmpa hs_place_edit
bne no_blinker
; here we have our blinking position
dec hs_blink_count
bne no_blink_state_change
lda #BLINK_LENGTH
sta hs_blink_count
lda hs_blink_state
bne clear_blink_state
inc hs_blink_state
bra no_blink_state_change
clear_blink_state
clr hs_blink_state
no_blink_state_change
tst hs_blink_state
bne no_blinker ;if blink state != than display normal character
; load SPACE
ldx #ABC_28
no_blinker:
_SCALE 24 ; (SCROLL_SCALE_FACTOR) ; drawing of letters is done in SCROLL_SCALE_FACTOR
lda mov_x
adda #X_STEP_LETTERS
sta mov_x
MY_MOVE_TO_B_END
jsr myDraw_VL_mode3
_ZERO_VECTOR_BEAM ; draw each letter with a move from zero, more stable
dec tmp_count2
bne next_name_letter_edit
lda mov_x
adda #2*X_STEP_LETTERS
sta mov_x
_SCALE (SCALE_FACTOR_GAME) ; everything we do with "positioning" is scale SCALE_FACTOR_GAME
; put to be displayed bcd score as csa score into player score
; player_score
ldd tmp1 ; the current move vector
MY_MOVE_TO_D_START
leau ,y
leay 3,y
ldx #player_score
jsr bcd_to_csa
lda mov_y
suba #50
sta mov_y
lda #$90
sta mov_x
pshs y
jsr in_game_score ;#isfunction
puls y
dec tmp_count
lbne next_score_entry_edit
jsr query_joystick
ldy #highScoreBlock
LDB last_joy_x ; only jump if last joy pos was zero (needed for testing later)
LDA Vec_Joy_1_X ; load joystick 1 position X to A
STA last_joy_x ; store this joystick position
BEQ hs_no_new_xpos
BMI pos_left_hse ; joystick moved to left
pos_right_hse:
TSTB ; test the old joystick position
BNE positioning_done_hse ; was center
; pos dec 1
dec hs_place_edit
bne hs_no_new_xpos
inc hs_place_edit
bra hs_no_new_xpos
pos_left_hse:
TSTB ; test the old joystick position
BNE positioning_done_hse ; was center
; pos inc 1
inc hs_place_edit
lda #4
cmpa hs_place_edit
bne hs_no_new_xpos
lda #3
sta hs_place_edit
bra hs_no_new_xpos
hs_no_new_xpos:
; todo check y
LDB last_joy_y ; only jump if last joy pos was zero (needed for testing later)
LDA Vec_Joy_1_Y ; load joystick 1 position X to A
STA last_joy_y ; store this joystick position
BEQ hs_no_new_ypos
BMI pos_down_hse ; joystick moved to left
pos_up_hse:
TSTB ; test the old joystick position
BNE positioning_done_hse ; was center
lda hs_place_got
nega
adda #5
ldb #6
mul
leay d,y
lda hs_place_edit
nega
adda #3
leay a,y
; in y now the to be changed letter
lda ,y
inca
cmpa # 'Z'
bls no_overflow_plus_hs
lda # 'A'
no_overflow_plus_hs
sta ,y
bra hs_no_new_ypos
pos_down_hse:
TSTB ; test the old joystick position
BNE positioning_done_hse ; was center
lda hs_place_got
nega
adda #5
ldb #6
mul
leay d,y
lda hs_place_edit
nega
adda #3
leay a,y
; in y now the to be changed letter
lda ,y
deca
cmpa # 'A'
bhs no_overflow_minus_hs
lda # 'Z'
no_overflow_minus_hs
sta ,y
bra hs_no_new_ypos
; letter inc 1
positioning_done_hse
hs_no_new_ypos
jsr getButtonState ; is a button pressed?
lbeq edit_highscore_inner
check_buttons_edit
cmpb #3 ; same aslast state
lbeq edit_highscore_inner
cmpb #2 ; as released - possibly from highscore return
lbeq edit_highscore_inner
ldb #3
stb last_button_state
stb current_button_state
; restore player hs
ldu #player_score
ldx #star_0_score
ldd ,x++
std ,u++
ldd ,x++
std ,u++
ldd ,x++
std ,u++
rts
; bra title_main1
|
//--------------------------------------------------------------------
// Copyright 2020. Bioinformatic and Genomics Lab.
// Hanyang University, Seoul, Korea
// Coded by Jang-il Sohn (sohnjangil@gmail.com)
//--------------------------------------------------------------------
#ifndef ETCHING_CALLER_HPP
#define ETCHING_CALLER_HPP
#include <set>
#include <map>
#include <unordered_set>
#include <iostream>
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <limits>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <api/BamAlignment.h>
#include <api/BamReader.h>
#include <api/BamWriter.h>
#include "my_vcf.hpp"
#include "Peak_memory_measure.hpp"
#include "CPU_TIME_measure.hpp"
const std::string version = "ETCHING_v1.3.7 (2021.10.26.)";
const std::string PROGRAM = "Program: etching_caller";
const std::string VERSION = "Version: " + version;
const std::string CONTACT = "Contact:\n\tJang-il Sohn (sohnjangil@gmail.com)\n\tJin-Wu Nam (jwnam@hanyang.ac.kr)";
using Position = std::pair < int , int > ;
void print_version();
void caller_usage();
template < class T >
class Format{
private:
std::map < std::string , T > key;
public:
Format(){
}
~Format(){};
T & operator [](std::string cutoff){
return key[cutoff];
}
};
void find_path ( const std::string input_bam,
const std::string prefix,
const int insert_size,
const bool scanall,
const bool rescue );
void bp_to_vcf ( const std::string genome,
const std::string input_bam,
const std::string bp_file,
const std::string prefix,
const int insert_size,
const bool typing,
const std::string read_orientation,
const double tumor_purity,
const double sequencing_coverage);
int return_discordant_pair_number ( BamTools::BamReader & reader1,
const Position Pos1,
const Position Pos2,
const int insert_size,
BamTools::RefVector & references);
int return_discordant_pair_number ( BamTools::BamReader & reader1,
const Position Pos1,
const int insert_size,
BamTools::RefVector & references);
double get_wall_time();
double get_cpu_time();
std::size_t get_peak_memory();
#endif
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r15
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0xafc9, %rsi
lea addresses_normal_ht+0x1984d, %rdi
nop
nop
and $55937, %r15
mov $30, %rcx
rep movsq
nop
nop
nop
nop
nop
cmp %rsi, %rsi
lea addresses_normal_ht+0x14989, %r14
nop
nop
nop
nop
and %r8, %r8
mov (%r14), %r9
nop
xor %r9, %r9
lea addresses_normal_ht+0x13be9, %rsi
clflush (%rsi)
nop
add $14049, %rcx
mov $0x6162636465666768, %r15
movq %r15, (%rsi)
nop
nop
nop
nop
nop
cmp %r8, %r8
lea addresses_WC_ht+0x75b3, %rsi
clflush (%rsi)
nop
nop
nop
cmp $11673, %r9
movb $0x61, (%rsi)
nop
nop
nop
nop
cmp %rcx, %rcx
lea addresses_WC_ht+0xf9d9, %rdi
nop
cmp $27755, %rsi
mov $0x6162636465666768, %r14
movq %r14, %xmm4
movups %xmm4, (%rdi)
nop
cmp $46785, %rcx
lea addresses_WC_ht+0x15b89, %rsi
nop
nop
and %r9, %r9
movw $0x6162, (%rsi)
nop
and $29359, %rcx
lea addresses_WC_ht+0xad89, %r8
cmp %rcx, %rcx
movups (%r8), %xmm4
vpextrq $0, %xmm4, %r14
nop
nop
nop
add %rsi, %rsi
lea addresses_UC_ht+0xa13a, %r15
inc %rdi
mov (%r15), %r14
nop
nop
nop
cmp $298, %rsi
lea addresses_WC_ht+0x12b89, %rsi
lea addresses_D_ht+0x12b09, %rdi
and $10568, %r15
mov $44, %rcx
rep movsw
cmp %r14, %r14
lea addresses_WC_ht+0x14489, %rcx
nop
xor $45424, %r15
mov (%rcx), %r8
inc %r8
lea addresses_D_ht+0x16959, %rsi
lea addresses_normal_ht+0x18c31, %rdi
nop
nop
nop
nop
nop
and $28484, %r15
mov $99, %rcx
rep movsb
nop
nop
and $5756, %r15
lea addresses_WT_ht+0x15337, %rcx
nop
nop
add $42374, %rdi
mov (%rcx), %r14d
nop
nop
sub $28160, %r15
lea addresses_WT_ht+0x16407, %rdi
nop
nop
nop
nop
nop
add $14683, %r8
mov (%rdi), %r14d
nop
nop
nop
nop
xor %r8, %r8
lea addresses_normal_ht+0x15719, %rsi
nop
nop
nop
nop
cmp %rcx, %rcx
movl $0x61626364, (%rsi)
nop
nop
nop
nop
nop
inc %rdi
lea addresses_WT_ht+0xb5d9, %rsi
lea addresses_normal_ht+0x64fd, %rdi
nop
nop
nop
nop
nop
cmp %r12, %r12
mov $54, %rcx
rep movsl
nop
inc %rcx
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r15
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r8
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_UC+0x5977, %r12
nop
dec %r8
movl $0x51525354, (%r12)
xor $20652, %r12
// Load
lea addresses_D+0x1e189, %rcx
nop
nop
nop
xor $45512, %rdi
mov (%rcx), %r10d
nop
nop
nop
add %r8, %r8
// Store
lea addresses_PSE+0xc989, %rbx
nop
nop
nop
nop
add $42214, %r11
movb $0x51, (%rbx)
nop
nop
inc %rcx
// Store
lea addresses_WT+0x5889, %r8
nop
nop
xor $13682, %rbx
movw $0x5152, (%r8)
nop
sub %rdi, %rdi
// Load
lea addresses_WC+0x1d189, %rcx
nop
nop
add %rbx, %rbx
movups (%rcx), %xmm1
vpextrq $0, %xmm1, %r12
inc %rbx
// Load
lea addresses_D+0x1a089, %r11
add $5060, %r10
movups (%r11), %xmm6
vpextrq $1, %xmm6, %rbx
nop
nop
nop
add $27575, %rdi
// REPMOV
lea addresses_A+0x1a409, %rsi
lea addresses_D+0x2589, %rdi
inc %r12
mov $100, %rcx
rep movsw
nop
nop
add %r8, %r8
// Store
lea addresses_A+0xce29, %rbx
clflush (%rbx)
nop
nop
nop
dec %r11
mov $0x5152535455565758, %rdi
movq %rdi, (%rbx)
add %rdi, %rdi
// Store
lea addresses_WC+0x11f89, %rcx
nop
nop
nop
nop
inc %r12
mov $0x5152535455565758, %rsi
movq %rsi, (%rcx)
nop
nop
nop
nop
cmp %rsi, %rsi
// Faulty Load
lea addresses_WC+0x1d189, %rdi
nop
add $9802, %r8
movaps (%rdi), %xmm1
vpextrq $0, %xmm1, %rcx
lea oracles, %rbx
and $0xff, %rcx
shlq $12, %rcx
mov (%rbx,%rcx,1), %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r8
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WC', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 4, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_D', 'same': False, 'size': 4, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 1, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WT', 'same': False, 'size': 2, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D', 'same': False, 'size': 16, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_A', 'same': False, 'size': 8, 'congruent': 5, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 8, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_WC', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': True, 'size': 8, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 8, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 16, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 2, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 16, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 8, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 4, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A156087: One ninth of the sum of the squares of the first n Fibonacci numbers with index divisible by 4.
; 0,1,50,2354,110595,5195620,244083556,11466731525,538692298134,25307071280790,1188893657899015,55852694849972936,2623887764290829000,123266872226818990089,5790919106896201705210,272049931151894661154810
lpb $0
mov $2,$0
sub $0,1
seq $2,49682 ; a(n) = (Lucas(8*n) - 2)/45.
add $3,$2
lpe
mov $0,$3
|
// Copyright (c) 2012-2013 The Crowncoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "leveldbwrapper.h"
#include "util.h"
#include <leveldb/env.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
#include <memenv.h>
#include <boost/filesystem.hpp>
void HandleError(const leveldb::Status &status) throw(leveldb_error) {
if (status.ok())
return;
if (status.IsCorruption())
throw leveldb_error("Database corrupted");
if (status.IsIOError())
throw leveldb_error("Database I/O error");
if (status.IsNotFound())
throw leveldb_error("Database entry missing");
throw leveldb_error("Unknown database error");
}
static leveldb::Options GetOptions(size_t nCacheSize) {
leveldb::Options options;
options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
options.compression = leveldb::kNoCompression;
options.max_open_files = 64;
return options;
}
CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {
penv = NULL;
readoptions.verify_checksums = true;
iteroptions.verify_checksums = true;
iteroptions.fill_cache = false;
syncoptions.sync = true;
options = GetOptions(nCacheSize);
options.create_if_missing = true;
if (fMemory) {
penv = leveldb::NewMemEnv(leveldb::Env::Default());
options.env = penv;
} else {
if (fWipe) {
printf("Wiping LevelDB in %s\n", path.string().c_str());
leveldb::DestroyDB(path.string(), options);
}
boost::filesystem::create_directory(path);
printf("Opening LevelDB in %s\n", path.string().c_str());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
if (!status.ok())
throw std::runtime_error(strprintf("CLevelDB(): error opening database environment %s", status.ToString().c_str()));
printf("Opened LevelDB successfully\n");
}
CLevelDBWrapper::~CLevelDBWrapper() {
delete pdb;
pdb = NULL;
delete options.filter_policy;
options.filter_policy = NULL;
delete options.block_cache;
options.block_cache = NULL;
delete penv;
options.env = NULL;
}
bool CLevelDBWrapper::WriteBatch(CLevelDBBatch &batch, bool fSync) throw(leveldb_error) {
leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
if (!status.ok()) {
printf("LevelDB write failure: %s\n", status.ToString().c_str());
HandleError(status);
return false;
}
return true;
}
|
;
; jcclrmmx.asm - colorspace conversion (MMX)
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
;
; Based on
; x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; This file should be assembled with NASM (Netwide Assembler),
; can *not* be assembled with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler).
; NASM is available from http://nasm.sourceforge.net/ or
; http://sourceforge.net/project/showfiles.php?group_id=6208
;
; [TAB8]
%include "jcolsamp.inc"
; --------------------------------------------------------------------------
SECTION SEG_TEXT
BITS 32
;
; Convert some rows of samples to the output colorspace.
;
; GLOBAL(void)
; jsimd_rgb_ycc_convert_mmx (JDIMENSION img_width,
; JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
; JDIMENSION output_row, int num_rows);
;
%define img_width(b) (b)+8 ; JDIMENSION img_width
%define input_buf(b) (b)+12 ; JSAMPARRAY input_buf
%define output_buf(b) (b)+16 ; JSAMPIMAGE output_buf
%define output_row(b) (b)+20 ; JDIMENSION output_row
%define num_rows(b) (b)+24 ; int num_rows
%define original_ebp ebp+0
%define wk(i) ebp-(WK_NUM-(i))*SIZEOF_MMWORD ; mmword wk[WK_NUM]
%define WK_NUM 8
%define gotptr wk(0)-SIZEOF_POINTER ; void * gotptr
align 16
global EXTN(jsimd_rgb_ycc_convert_mmx)
EXTN(jsimd_rgb_ycc_convert_mmx):
push ebp
mov eax,esp ; eax = original ebp
sub esp, byte 4
and esp, byte (-SIZEOF_MMWORD) ; align to 64 bits
mov [esp],eax
mov ebp,esp ; ebp = aligned ebp
lea esp, [wk(0)]
pushpic eax ; make a room for GOT address
push ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
get_GOT ebx ; get GOT address
movpic POINTER [gotptr], ebx ; save GOT address
mov ecx, JDIMENSION [img_width(eax)] ; num_cols
test ecx,ecx
jz near .return
push ecx
mov esi, JSAMPIMAGE [output_buf(eax)]
mov ecx, JDIMENSION [output_row(eax)]
mov edi, JSAMPARRAY [esi+0*SIZEOF_JSAMPARRAY]
mov ebx, JSAMPARRAY [esi+1*SIZEOF_JSAMPARRAY]
mov edx, JSAMPARRAY [esi+2*SIZEOF_JSAMPARRAY]
lea edi, [edi+ecx*SIZEOF_JSAMPROW]
lea ebx, [ebx+ecx*SIZEOF_JSAMPROW]
lea edx, [edx+ecx*SIZEOF_JSAMPROW]
pop ecx
mov esi, JSAMPARRAY [input_buf(eax)]
mov eax, INT [num_rows(eax)]
test eax,eax
jle near .return
alignx 16,7
.rowloop:
pushpic eax
push edx
push ebx
push edi
push esi
push ecx ; col
mov esi, JSAMPROW [esi] ; inptr
mov edi, JSAMPROW [edi] ; outptr0
mov ebx, JSAMPROW [ebx] ; outptr1
mov edx, JSAMPROW [edx] ; outptr2
movpic eax, POINTER [gotptr] ; load GOT address (eax)
cmp ecx, byte SIZEOF_MMWORD
jae short .columnloop
alignx 16,7
%if RGB_PIXELSIZE == 3 ; ---------------
.column_ld1:
push eax
push edx
lea ecx,[ecx+ecx*2] ; imul ecx,RGB_PIXELSIZE
test cl, SIZEOF_BYTE
jz short .column_ld2
sub ecx, byte SIZEOF_BYTE
xor eax,eax
mov al, BYTE [esi+ecx]
.column_ld2:
test cl, SIZEOF_WORD
jz short .column_ld4
sub ecx, byte SIZEOF_WORD
xor edx,edx
mov dx, WORD [esi+ecx]
shl eax, WORD_BIT
or eax,edx
.column_ld4:
movd mmA,eax
pop edx
pop eax
test cl, SIZEOF_DWORD
jz short .column_ld8
sub ecx, byte SIZEOF_DWORD
movd mmG, DWORD [esi+ecx]
psllq mmA, DWORD_BIT
por mmA,mmG
.column_ld8:
test cl, SIZEOF_MMWORD
jz short .column_ld16
movq mmG,mmA
movq mmA, MMWORD [esi+0*SIZEOF_MMWORD]
mov ecx, SIZEOF_MMWORD
jmp short .rgb_ycc_cnv
.column_ld16:
test cl, 2*SIZEOF_MMWORD
mov ecx, SIZEOF_MMWORD
jz short .rgb_ycc_cnv
movq mmF,mmA
movq mmA, MMWORD [esi+0*SIZEOF_MMWORD]
movq mmG, MMWORD [esi+1*SIZEOF_MMWORD]
jmp short .rgb_ycc_cnv
alignx 16,7
.columnloop:
movq mmA, MMWORD [esi+0*SIZEOF_MMWORD]
movq mmG, MMWORD [esi+1*SIZEOF_MMWORD]
movq mmF, MMWORD [esi+2*SIZEOF_MMWORD]
.rgb_ycc_cnv:
; mmA=(00 10 20 01 11 21 02 12)
; mmG=(22 03 13 23 04 14 24 05)
; mmF=(15 25 06 16 26 07 17 27)
movq mmD,mmA
psllq mmA,4*BYTE_BIT ; mmA=(-- -- -- -- 00 10 20 01)
psrlq mmD,4*BYTE_BIT ; mmD=(11 21 02 12 -- -- -- --)
punpckhbw mmA,mmG ; mmA=(00 04 10 14 20 24 01 05)
psllq mmG,4*BYTE_BIT ; mmG=(-- -- -- -- 22 03 13 23)
punpcklbw mmD,mmF ; mmD=(11 15 21 25 02 06 12 16)
punpckhbw mmG,mmF ; mmG=(22 26 03 07 13 17 23 27)
movq mmE,mmA
psllq mmA,4*BYTE_BIT ; mmA=(-- -- -- -- 00 04 10 14)
psrlq mmE,4*BYTE_BIT ; mmE=(20 24 01 05 -- -- -- --)
punpckhbw mmA,mmD ; mmA=(00 02 04 06 10 12 14 16)
psllq mmD,4*BYTE_BIT ; mmD=(-- -- -- -- 11 15 21 25)
punpcklbw mmE,mmG ; mmE=(20 22 24 26 01 03 05 07)
punpckhbw mmD,mmG ; mmD=(11 13 15 17 21 23 25 27)
pxor mmH,mmH
movq mmC,mmA
punpcklbw mmA,mmH ; mmA=(00 02 04 06)
punpckhbw mmC,mmH ; mmC=(10 12 14 16)
movq mmB,mmE
punpcklbw mmE,mmH ; mmE=(20 22 24 26)
punpckhbw mmB,mmH ; mmB=(01 03 05 07)
movq mmF,mmD
punpcklbw mmD,mmH ; mmD=(11 13 15 17)
punpckhbw mmF,mmH ; mmF=(21 23 25 27)
%else ; RGB_PIXELSIZE == 4 ; -----------
.column_ld1:
test cl, SIZEOF_MMWORD/8
jz short .column_ld2
sub ecx, byte SIZEOF_MMWORD/8
movd mmA, DWORD [esi+ecx*RGB_PIXELSIZE]
.column_ld2:
test cl, SIZEOF_MMWORD/4
jz short .column_ld4
sub ecx, byte SIZEOF_MMWORD/4
movq mmF,mmA
movq mmA, MMWORD [esi+ecx*RGB_PIXELSIZE]
.column_ld4:
test cl, SIZEOF_MMWORD/2
mov ecx, SIZEOF_MMWORD
jz short .rgb_ycc_cnv
movq mmD,mmA
movq mmC,mmF
movq mmA, MMWORD [esi+0*SIZEOF_MMWORD]
movq mmF, MMWORD [esi+1*SIZEOF_MMWORD]
jmp short .rgb_ycc_cnv
alignx 16,7
.columnloop:
movq mmA, MMWORD [esi+0*SIZEOF_MMWORD]
movq mmF, MMWORD [esi+1*SIZEOF_MMWORD]
movq mmD, MMWORD [esi+2*SIZEOF_MMWORD]
movq mmC, MMWORD [esi+3*SIZEOF_MMWORD]
.rgb_ycc_cnv:
; mmA=(00 10 20 30 01 11 21 31)
; mmF=(02 12 22 32 03 13 23 33)
; mmD=(04 14 24 34 05 15 25 35)
; mmC=(06 16 26 36 07 17 27 37)
movq mmB,mmA
punpcklbw mmA,mmF ; mmA=(00 02 10 12 20 22 30 32)
punpckhbw mmB,mmF ; mmB=(01 03 11 13 21 23 31 33)
movq mmG,mmD
punpcklbw mmD,mmC ; mmD=(04 06 14 16 24 26 34 36)
punpckhbw mmG,mmC ; mmG=(05 07 15 17 25 27 35 37)
movq mmE,mmA
punpcklwd mmA,mmD ; mmA=(00 02 04 06 10 12 14 16)
punpckhwd mmE,mmD ; mmE=(20 22 24 26 30 32 34 36)
movq mmH,mmB
punpcklwd mmB,mmG ; mmB=(01 03 05 07 11 13 15 17)
punpckhwd mmH,mmG ; mmH=(21 23 25 27 31 33 35 37)
pxor mmF,mmF
movq mmC,mmA
punpcklbw mmA,mmF ; mmA=(00 02 04 06)
punpckhbw mmC,mmF ; mmC=(10 12 14 16)
movq mmD,mmB
punpcklbw mmB,mmF ; mmB=(01 03 05 07)
punpckhbw mmD,mmF ; mmD=(11 13 15 17)
movq mmG,mmE
punpcklbw mmE,mmF ; mmE=(20 22 24 26)
punpckhbw mmG,mmF ; mmG=(30 32 34 36)
punpcklbw mmF,mmH
punpckhbw mmH,mmH
psrlw mmF,BYTE_BIT ; mmF=(21 23 25 27)
psrlw mmH,BYTE_BIT ; mmH=(31 33 35 37)
%endif ; RGB_PIXELSIZE ; ---------------
; mm0=(R0 R2 R4 R6)=RE, mm2=(G0 G2 G4 G6)=GE, mm4=(B0 B2 B4 B6)=BE
; mm1=(R1 R3 R5 R7)=RO, mm3=(G1 G3 G5 G7)=GO, mm5=(B1 B3 B5 B7)=BO
; (Original)
; Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
; Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
; Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
;
; (This implementation)
; Y = 0.29900 * R + 0.33700 * G + 0.11400 * B + 0.25000 * G
; Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
; Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
movq MMWORD [wk(0)], mm0 ; wk(0)=RE
movq MMWORD [wk(1)], mm1 ; wk(1)=RO
movq MMWORD [wk(2)], mm4 ; wk(2)=BE
movq MMWORD [wk(3)], mm5 ; wk(3)=BO
movq mm6,mm1
punpcklwd mm1,mm3
punpckhwd mm6,mm3
movq mm7,mm1
movq mm4,mm6
pmaddwd mm1,[GOTOFF(eax,PW_F0299_F0337)] ; mm1=ROL*FIX(0.299)+GOL*FIX(0.337)
pmaddwd mm6,[GOTOFF(eax,PW_F0299_F0337)] ; mm6=ROH*FIX(0.299)+GOH*FIX(0.337)
pmaddwd mm7,[GOTOFF(eax,PW_MF016_MF033)] ; mm7=ROL*-FIX(0.168)+GOL*-FIX(0.331)
pmaddwd mm4,[GOTOFF(eax,PW_MF016_MF033)] ; mm4=ROH*-FIX(0.168)+GOH*-FIX(0.331)
movq MMWORD [wk(4)], mm1 ; wk(4)=ROL*FIX(0.299)+GOL*FIX(0.337)
movq MMWORD [wk(5)], mm6 ; wk(5)=ROH*FIX(0.299)+GOH*FIX(0.337)
pxor mm1,mm1
pxor mm6,mm6
punpcklwd mm1,mm5 ; mm1=BOL
punpckhwd mm6,mm5 ; mm6=BOH
psrld mm1,1 ; mm1=BOL*FIX(0.500)
psrld mm6,1 ; mm6=BOH*FIX(0.500)
movq mm5,[GOTOFF(eax,PD_ONEHALFM1_CJ)] ; mm5=[PD_ONEHALFM1_CJ]
paddd mm7,mm1
paddd mm4,mm6
paddd mm7,mm5
paddd mm4,mm5
psrld mm7,SCALEBITS ; mm7=CbOL
psrld mm4,SCALEBITS ; mm4=CbOH
packssdw mm7,mm4 ; mm7=CbO
movq mm1, MMWORD [wk(2)] ; mm1=BE
movq mm6,mm0
punpcklwd mm0,mm2
punpckhwd mm6,mm2
movq mm5,mm0
movq mm4,mm6
pmaddwd mm0,[GOTOFF(eax,PW_F0299_F0337)] ; mm0=REL*FIX(0.299)+GEL*FIX(0.337)
pmaddwd mm6,[GOTOFF(eax,PW_F0299_F0337)] ; mm6=REH*FIX(0.299)+GEH*FIX(0.337)
pmaddwd mm5,[GOTOFF(eax,PW_MF016_MF033)] ; mm5=REL*-FIX(0.168)+GEL*-FIX(0.331)
pmaddwd mm4,[GOTOFF(eax,PW_MF016_MF033)] ; mm4=REH*-FIX(0.168)+GEH*-FIX(0.331)
movq MMWORD [wk(6)], mm0 ; wk(6)=REL*FIX(0.299)+GEL*FIX(0.337)
movq MMWORD [wk(7)], mm6 ; wk(7)=REH*FIX(0.299)+GEH*FIX(0.337)
pxor mm0,mm0
pxor mm6,mm6
punpcklwd mm0,mm1 ; mm0=BEL
punpckhwd mm6,mm1 ; mm6=BEH
psrld mm0,1 ; mm0=BEL*FIX(0.500)
psrld mm6,1 ; mm6=BEH*FIX(0.500)
movq mm1,[GOTOFF(eax,PD_ONEHALFM1_CJ)] ; mm1=[PD_ONEHALFM1_CJ]
paddd mm5,mm0
paddd mm4,mm6
paddd mm5,mm1
paddd mm4,mm1
psrld mm5,SCALEBITS ; mm5=CbEL
psrld mm4,SCALEBITS ; mm4=CbEH
packssdw mm5,mm4 ; mm5=CbE
psllw mm7,BYTE_BIT
por mm5,mm7 ; mm5=Cb
movq MMWORD [ebx], mm5 ; Save Cb
movq mm0, MMWORD [wk(3)] ; mm0=BO
movq mm6, MMWORD [wk(2)] ; mm6=BE
movq mm1, MMWORD [wk(1)] ; mm1=RO
movq mm4,mm0
punpcklwd mm0,mm3
punpckhwd mm4,mm3
movq mm7,mm0
movq mm5,mm4
pmaddwd mm0,[GOTOFF(eax,PW_F0114_F0250)] ; mm0=BOL*FIX(0.114)+GOL*FIX(0.250)
pmaddwd mm4,[GOTOFF(eax,PW_F0114_F0250)] ; mm4=BOH*FIX(0.114)+GOH*FIX(0.250)
pmaddwd mm7,[GOTOFF(eax,PW_MF008_MF041)] ; mm7=BOL*-FIX(0.081)+GOL*-FIX(0.418)
pmaddwd mm5,[GOTOFF(eax,PW_MF008_MF041)] ; mm5=BOH*-FIX(0.081)+GOH*-FIX(0.418)
movq mm3,[GOTOFF(eax,PD_ONEHALF)] ; mm3=[PD_ONEHALF]
paddd mm0, MMWORD [wk(4)]
paddd mm4, MMWORD [wk(5)]
paddd mm0,mm3
paddd mm4,mm3
psrld mm0,SCALEBITS ; mm0=YOL
psrld mm4,SCALEBITS ; mm4=YOH
packssdw mm0,mm4 ; mm0=YO
pxor mm3,mm3
pxor mm4,mm4
punpcklwd mm3,mm1 ; mm3=ROL
punpckhwd mm4,mm1 ; mm4=ROH
psrld mm3,1 ; mm3=ROL*FIX(0.500)
psrld mm4,1 ; mm4=ROH*FIX(0.500)
movq mm1,[GOTOFF(eax,PD_ONEHALFM1_CJ)] ; mm1=[PD_ONEHALFM1_CJ]
paddd mm7,mm3
paddd mm5,mm4
paddd mm7,mm1
paddd mm5,mm1
psrld mm7,SCALEBITS ; mm7=CrOL
psrld mm5,SCALEBITS ; mm5=CrOH
packssdw mm7,mm5 ; mm7=CrO
movq mm3, MMWORD [wk(0)] ; mm3=RE
movq mm4,mm6
punpcklwd mm6,mm2
punpckhwd mm4,mm2
movq mm1,mm6
movq mm5,mm4
pmaddwd mm6,[GOTOFF(eax,PW_F0114_F0250)] ; mm6=BEL*FIX(0.114)+GEL*FIX(0.250)
pmaddwd mm4,[GOTOFF(eax,PW_F0114_F0250)] ; mm4=BEH*FIX(0.114)+GEH*FIX(0.250)
pmaddwd mm1,[GOTOFF(eax,PW_MF008_MF041)] ; mm1=BEL*-FIX(0.081)+GEL*-FIX(0.418)
pmaddwd mm5,[GOTOFF(eax,PW_MF008_MF041)] ; mm5=BEH*-FIX(0.081)+GEH*-FIX(0.418)
movq mm2,[GOTOFF(eax,PD_ONEHALF)] ; mm2=[PD_ONEHALF]
paddd mm6, MMWORD [wk(6)]
paddd mm4, MMWORD [wk(7)]
paddd mm6,mm2
paddd mm4,mm2
psrld mm6,SCALEBITS ; mm6=YEL
psrld mm4,SCALEBITS ; mm4=YEH
packssdw mm6,mm4 ; mm6=YE
psllw mm0,BYTE_BIT
por mm6,mm0 ; mm6=Y
movq MMWORD [edi], mm6 ; Save Y
pxor mm2,mm2
pxor mm4,mm4
punpcklwd mm2,mm3 ; mm2=REL
punpckhwd mm4,mm3 ; mm4=REH
psrld mm2,1 ; mm2=REL*FIX(0.500)
psrld mm4,1 ; mm4=REH*FIX(0.500)
movq mm0,[GOTOFF(eax,PD_ONEHALFM1_CJ)] ; mm0=[PD_ONEHALFM1_CJ]
paddd mm1,mm2
paddd mm5,mm4
paddd mm1,mm0
paddd mm5,mm0
psrld mm1,SCALEBITS ; mm1=CrEL
psrld mm5,SCALEBITS ; mm5=CrEH
packssdw mm1,mm5 ; mm1=CrE
psllw mm7,BYTE_BIT
por mm1,mm7 ; mm1=Cr
movq MMWORD [edx], mm1 ; Save Cr
sub ecx, byte SIZEOF_MMWORD
add esi, byte RGB_PIXELSIZE*SIZEOF_MMWORD ; inptr
add edi, byte SIZEOF_MMWORD ; outptr0
add ebx, byte SIZEOF_MMWORD ; outptr1
add edx, byte SIZEOF_MMWORD ; outptr2
cmp ecx, byte SIZEOF_MMWORD
jae near .columnloop
test ecx,ecx
jnz near .column_ld1
pop ecx ; col
pop esi
pop edi
pop ebx
pop edx
poppic eax
add esi, byte SIZEOF_JSAMPROW ; input_buf
add edi, byte SIZEOF_JSAMPROW
add ebx, byte SIZEOF_JSAMPROW
add edx, byte SIZEOF_JSAMPROW
dec eax ; num_rows
jg near .rowloop
emms ; empty MMX state
.return:
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
pop ebx
mov esp,ebp ; esp <- aligned ebp
pop esp ; esp <- original ebp
pop ebp
ret
; For some reason, the OS X linker does not honor the request to align the
; segment unless we do this.
align 16
|
#include "kun.h"
#include "engine.h"
#include <chrono>
int main ()
{
Engine* const engine = new Engine ();
std::chrono::steady_clock::time_point time_begin = std::chrono::steady_clock::now ();
double current_time = 0.0f;
double accumulator = 0.0f;
bool want_exit = false;
while (!want_exit)
{
std::chrono::steady_clock::time_point time_end = std::chrono::steady_clock::now ();
std::chrono::duration<double> time_diff = time_end - time_begin;
const double new_time = time_diff.count ();
double delta_time = new_time - current_time;
current_time = new_time;
if (delta_time > 0.25f)
delta_time = 0.25f;
accumulator += delta_time;
const double time = 1.0 / 60.0;
while (accumulator >= time)
{
engine->Update (time);
accumulator -= time;
}
engine->Render ();
}
delete engine;
return 0;
}
|
; A023969: a(n) = round(sqrt(n)) - floor(sqrt(n)).
; 0,0,0,1,0,0,0,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1
lpb $0,1
trn $0,$2
mov $1,4
sub $1,$0
sub $0,1
add $2,1
trn $0,$2
lpe
trn $1,3
|
bits 64 ; set architecture
global strpbrk:function ; export strpbrk / RDI RSI parameters
strpbrk:
xor RAX, RAX ; set result to 0 in case of non-match
cmp RDI, 0 ; check if pointer null
je .end
.loop: ; loop label
xor RAX, RAX ; set result to 0 in case of non-match
cmp byte [RDI], 0 ; check if end of string
je .end
xor RCX, RCX ; set counter to 0
mov RAX, RDI ; set result to current s pointer
mov R8B, byte [RDI] ; get current char to test
.loopaccepte:
cmp byte [RSI + RCX], R8B ; check if current char is matching
je .end
cmp byte [RSI + RCX], 0 ; check if all chars not matching
je .continue
inc RCX ; inc counter to move on next byte
jmp .loopaccepte
.continue:
inc RDI ; main string pointer incrementation
jmp .loop ; continue to iterate
.end:
ret
|
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing authors:
James Fischer, High Performance Technologies, Inc.
David Richie, Stone Ridge Technology
Vincent Natoli, Stone Ridge Technology
------------------------------------------------------------------------- */
#include <stdlib.h>
#include "pair_lj_cut_opt.h"
#include "atom.h"
#include "force.h"
#include "neigh_list.h"
using namespace LAMMPS_NS;
/* ---------------------------------------------------------------------- */
PairLJCutOpt::PairLJCutOpt(LAMMPS *lmp) : PairLJCut(lmp) {}
/* ---------------------------------------------------------------------- */
void PairLJCutOpt::compute(int eflag, int vflag)
{
if (eflag || vflag) ev_setup(eflag,vflag);
else evflag = vflag_fdotr = 0;
if (evflag) {
if (eflag) {
if (force->newton_pair) return eval<1,1,1>();
else return eval<1,1,0>();
} else {
if (force->newton_pair) return eval<1,0,1>();
else return eval<1,0,0>();
}
} else {
if (force->newton_pair) return eval<0,0,1>();
else return eval<0,0,0>();
}
}
/* ---------------------------------------------------------------------- */
template < int EVFLAG, int EFLAG, int NEWTON_PAIR >
void PairLJCutOpt::eval()
{
typedef struct { double x,y,z; } vec3_t;
typedef struct {
double cutsq,lj1,lj2,lj3,lj4,offset;
double _pad[2];
} fast_alpha_t;
int i,j,ii,jj,inum,jnum,itype,jtype,sbindex;
double factor_lj;
double evdwl = 0.0;
double** _noalias x = atom->x;
double** _noalias f = atom->f;
int* _noalias type = atom->type;
int nlocal = atom->nlocal;
double* _noalias special_lj = force->special_lj;
inum = list->inum;
int* _noalias ilist = list->ilist;
int** _noalias firstneigh = list->firstneigh;
int* _noalias numneigh = list->numneigh;
vec3_t* _noalias xx = (vec3_t*)x[0];
vec3_t* _noalias ff = (vec3_t*)f[0];
int ntypes = atom->ntypes;
int ntypes2 = ntypes*ntypes;
fast_alpha_t* _noalias fast_alpha =
(fast_alpha_t*) malloc(ntypes2*sizeof(fast_alpha_t));
for (i = 0; i < ntypes; i++) for (j = 0; j < ntypes; j++) {
fast_alpha_t& a = fast_alpha[i*ntypes+j];
a.cutsq = cutsq[i+1][j+1];
a.lj1 = lj1[i+1][j+1];
a.lj2 = lj2[i+1][j+1];
a.lj3 = lj3[i+1][j+1];
a.lj4 = lj4[i+1][j+1];
a.offset = offset[i+1][j+1];
}
fast_alpha_t* _noalias tabsix = fast_alpha;
// loop over neighbors of my atoms
for (ii = 0; ii < inum; ii++) {
i = ilist[ii];
double xtmp = xx[i].x;
double ytmp = xx[i].y;
double ztmp = xx[i].z;
itype = type[i] - 1;
int* _noalias jlist = firstneigh[i];
jnum = numneigh[i];
double tmpfx = 0.0;
double tmpfy = 0.0;
double tmpfz = 0.0;
fast_alpha_t* _noalias tabsixi = (fast_alpha_t*)&tabsix[itype*ntypes];
for (jj = 0; jj < jnum; jj++) {
j = jlist[jj];
sbindex = sbmask(j);
if (sbindex == 0) {
double delx = xtmp - xx[j].x;
double dely = ytmp - xx[j].y;
double delz = ztmp - xx[j].z;
double rsq = delx*delx + dely*dely + delz*delz;
jtype = type[j] - 1;
fast_alpha_t& a = tabsixi[jtype];
if (rsq < a.cutsq) {
double r2inv = 1.0/rsq;
double r6inv = r2inv*r2inv*r2inv;
double forcelj = r6inv * (a.lj1*r6inv - a.lj2);
double fpair = forcelj*r2inv;
tmpfx += delx*fpair;
tmpfy += dely*fpair;
tmpfz += delz*fpair;
if (NEWTON_PAIR || j < nlocal) {
ff[j].x -= delx*fpair;
ff[j].y -= dely*fpair;
ff[j].z -= delz*fpair;
}
if (EFLAG) evdwl = r6inv*(a.lj3*r6inv-a.lj4) - a.offset;
if (EVFLAG)
ev_tally(i,j,nlocal,NEWTON_PAIR,
evdwl,0.0,fpair,delx,dely,delz);
}
} else {
factor_lj = special_lj[sbindex];
j &= NEIGHMASK;
double delx = xtmp - xx[j].x;
double dely = ytmp - xx[j].y;
double delz = ztmp - xx[j].z;
double rsq = delx*delx + dely*dely + delz*delz;
int jtype1 = type[j];
jtype = jtype1 - 1;
fast_alpha_t& a = tabsixi[jtype];
if (rsq < a.cutsq) {
double r2inv = 1.0/rsq;
double r6inv = r2inv*r2inv*r2inv;
fast_alpha_t& a = tabsixi[jtype];
double forcelj = r6inv * (a.lj1*r6inv - a.lj2);
double fpair = factor_lj*forcelj*r2inv;
tmpfx += delx*fpair;
tmpfy += dely*fpair;
tmpfz += delz*fpair;
if (NEWTON_PAIR || j < nlocal) {
ff[j].x -= delx*fpair;
ff[j].y -= dely*fpair;
ff[j].z -= delz*fpair;
}
if (EFLAG) {
evdwl = r6inv*(a.lj3*r6inv-a.lj4) - a.offset;
evdwl *= factor_lj;
}
if (EVFLAG) ev_tally(i,j,nlocal,NEWTON_PAIR,
evdwl,0.0,fpair,delx,dely,delz);
}
}
}
ff[i].x += tmpfx;
ff[i].y += tmpfy;
ff[i].z += tmpfz;
}
free(fast_alpha); fast_alpha = 0;
if (vflag_fdotr) virial_fdotr_compute();
}
|
TITLE("Array processing functions")
REF("Calc$CaddAA")
REF("Calc$CarrayIndex")
REF("Calc$CcountA")
REF("Calc$CleftAN")
REF("Calc$CmidAN")
REF("Calc$CmidANN")
REF("Calc$CrightAN")
REF("Calc$CsumA")
REF("Calc$CsumASC")
TOPIC_TEXT(
"[2 $$0,0#00000000000000000000000000000000:Default][b100;a50;K* $$1,0#23046025415494101427921008701515:Paragraph][i167;b50;a25;kKN1;~~~>.3917;* "
"$$2,0#52185223490867151055420261384346:Toc1`.Heading1][i333;kN11;~~~>.3917;* $$3,0#36545033421193513457240054113541:Toc2`.Heading2][i500;kN111;~~~>.3917; "
"$$4,0#65092512416424580164828413186219:Toc3`.Heading3][i167;b50;a25;kKNA;~~~>.3917;* "
"$$5,5#92291332474308709450111162202673:AppToc1`.AppHeading1][i333;kNA1;~~~>.3917;* "
"$$6,15#61887903412252554674480251236992:AppToc2`.AppHeading2][i500;kNA11;~~~>.3917; "
"$$7,7#03533551421653050355120437860335:AppToc3`.AppHeading3][i500;b100;a100;KN1;*4 "
"$$8,0#94145093439740438411010082165944:Heading1][i500;b100;a50;kKN11;*+117 $$9,0#10901425421210535753260366156531:Heading2][i500;b100;a25;kKN111;* "
"$$10,0#53209141402041366431858192225431:Heading3][i500;b100;a100;KNA;*4 $$11,8#32912651424211307887950041245434:AppHeading1][i500;b100;a50;kKNA1;*+117 "
"$$12,8#51232055453458524230328032001901:AppHeading2][i500;b100;a25;kKNA11;* $$13,8#34108020439428305453439845463579:AppHeading3][b100;a50;k*4 "
"$$14,0#49239115434362547028389207250014:Heading][b50;a25;k~~~>.3917;* $$15,15#40743698422276745552070108434023:Toc`.Heading][b100;a50;K~~~>.3917;*+117 "
"$$16,16#15422850471211852294098111138263:Topics1][l167;b50;a50;K~~~>.3917;* $$17,17#35241722455500657380289596243808:Topics2][l333;~~~>.3917; "
"$$18,18#31041344429742018840308064013200:Topics3][b83;a42;K* $$19,0#46440151113795363000000595230845:Paragraph][{_}%EN-US "
"[s14;:Calc`$CaddAA: operator `+ (pole hodnot, pole hodnot) [S ®] pole hodnot&][s0; "
"&][s14;:Calc`$CarrayIndex: operator `[`] (pole hodnot, integer) [S ®] any data "
"type&][s0; &][s0; [* Example]: mesic(27.5.1984) `= 5&][s0; The binary operator [* "
"`*] evaluates the [/ lambda`-expression] for each element of the original array and "
"returns an array composed of the results. The output array has always the same number "
"of elements as the input array. During evaluation of the lambda`-expression for each "
"input arra")
TOPIC_TEXT(
"y element the calculator variable [* I] is set to the index of the current array "
"element (first array element has index 0) and the variable [* A] contains the value "
"of the array element being processed.&][s14;:Calc`$CcountA: count (pole hodnot) [S "
"®] integer&][s14;:Calc`$CleftAN: [%00-00 left (pole hodnot, integer) ][%00-00S ®][%00-00 "
" pole hodnot]&][s0; &][s14;:Calc`$CmidAN: [%00-00 mid (pole hodnot, integer) ][%00-00S "
"®][%00-00 pole hodnot]&][s0; &][s14;:Calc`$CmidANN: [%00-00 mid (pole hodnot, integer, "
"integer) ][%00-00S ®][%00-00 pole hodnot]&][s0; &][s14;:Calc`$CrightAN: [%00-00 "
"right (pole hodnot, integer) ][%00-00S ®][%00-00 pole hodnot]&][s0; &][s14;:Calc`$CsumA: "
"sum (pole hodnot) [S ®] any data type&][s0; &][s14;:Calc`$CsumASC: [%00-00 sum(pole "
"hodnot, string ][%00-00/ identifier][%00-00 , lambda`-výraz) ][%00-00S ®][%00-00 "
" any data type]&][s0; Function adds / concatenates values calculated from the members "
"of its input array using a given [/ lambda`-expression]. [/ Lambda`-expressions] "
"may use the given [/ identifier] to access the current array element. The calculated "
"values must be of one of the supported types:&][s0; &][s0;i150;O0;+-83 [* numbers] "
"`- function returns the arithmetic sum of all such numbers; elements containing the "
"[* null] value are ignored&][s0;i150;O0;+-83 [* strings] `- function returns the "
"string concatenation of all string values&][s0;i150;O0;+-83 [* arrays] `- function "
"returns the array concatenation of all arrays&][s0;*+-83 &][s0;+-83 [*2 Example:][2 "
" ]`[1, 4, 7`].sum(`\"X`\", #(X`*X)) `= 66, `[1, 4, 7`].sum(`\"T`\", #(T.text)) `= "
"`\"147`\"&][s0; Function converts an array to its standard textual representation "
"in the format&][s0; &][s0; `[[/ first element, second element, third element...]`]&][s0; "
"&][s0; [* Example:] `[0.0, 1.0, 2.5`].text `= `\"`[0, 1, 2.5`]`\"&][s0; &][s0; ]")
|
#include <node.h>
#include <nan.h>
namespace function_arg
{
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Context;
using v8::Number;
void Add(const FunctionCallbackInfo<Value> &args)
{
Isolate *isolate = args.GetIsolate();
Local<Context> context = args.GetIsolate()->GetCurrentContext();
if (args.Length() < 2) {
Nan::ThrowTypeError("Wrong number of arguments");
return;
}
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
Nan::ThrowTypeError("Wrong arguments");
return;
}
double a = args[0]->NumberValue(context).FromJust();
double b = args[1]->NumberValue(context).FromJust();
Local<Number> num = Nan::New(a + b);
args.GetReturnValue().Set(num);
}
void init(Local<Object> exports)
{
NODE_SET_METHOD(exports, "add", Add);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, init)
} // namespace demo |
bits 16
org 0x7c00
boot:
mov ax, 0x2401
int 0x15
mov ax, 0x3
int 0x10
cli
lgdt [gdt_pointer]
mov eax, cr0
or eax,0x1
mov cr0, eax
jmp CODE_SEG:boot2
gdt_start:
dq 0x0
gdt_code:
dw 0xFFFF
dw 0x0
db 0x0
db 10011010b
db 11001111b
db 0x0
gdt_data:
dw 0xFFFF
dw 0x0
db 0x0
db 10010010b
db 11001111b
db 0x0
gdt_end:
gdt_pointer:
dw gdt_end - gdt_start
dd gdt_start
CODE_SEG equ gdt_code - gdt_start
DATA_SEG equ gdt_data - gdt_start
bits 32
boot2:
mov ax, DATA_SEG
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
mov esi,hello
mov ebx,0xb8000
.loop:
lodsb
or al,al
jz halt
or eax,0x0100
mov word [ebx], ax
add ebx,2
jmp .loop
halt:
cli
hlt
hello: db "Hello world!",0
times 510 - ($-$$) db 0
dw 0xaa55
|
; void *z80_indr(void *dst, uint16_t port)
SECTION code_z80
PUBLIC z80_indr
EXTERN asm_z80_indr
z80_indr:
pop af
pop bc
pop hl
push hl
push bc
push af
jp asm_z80_indr
|
INCLUDE "clib_cfg.asm"
SECTION code_stdio
PUBLIC __stdio_verify_valid
EXTERN __p_forward_list_locate_item, error_ebadf_mc
EXTERN __stdio_open_file_list
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $04
EXTERN __stdio_lock_file_list, __stdio_unlock_file_list
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
__stdio_verify_valid:
; Verify that FILE is on the open list
;
; enter : ix = FILE *
;
; exit : ix = FILE *
; carry set, errno = ebadf if invalid FILE
;
; uses : none, except hl=-1 on error
push hl
push af
push bc
push de
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $04
call __stdio_lock_file_list
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
push ix
pop bc
ld a,b
or c
scf
jr z, invalid_file_0
dec bc
dec bc ; bc = & FILE.link
ld hl,__stdio_open_file_list
call __p_forward_list_locate_item
invalid_file_0:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $04
push af
call __stdio_unlock_file_list
pop af
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
pop de
pop bc
jr c, invalid_file_1
valid_file:
pop af
pop hl
or a
ret
invalid_file_1:
pop af
jp error_ebadf_mc - 1
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Microsoft Research Singularity
;;;
;;; Copyright (c) Microsoft Corporation. All rights reserved.
;;;
;;; This file contains ARM-specific assembly code.
;;;
;**********************************************************************
; void *
; memmove( void *dest, const void *src, size_t count );
;
; memmove() copies 'count' bytes from the source buffer to the
; destination buffer and returns a pointer to the destination
; buffer. memmove() guarantees the overlaping buffers will
; be copied successfully.
;
;**********************************************************************
;
; $$$ NOTE $$$: These routines use the LDRH opcode which is not
; supported on ARM 3 or 3T architectures. Hence, these routines
; assume ARM 4 or later architectures.
;
;**********************************************************************
OPT 2 ; disable listing
INCLUDE kxarm.inc
OPT 1 ; reenable listing
dest RN R0
source RN R1
count RN R2
temp1 RN R3
temp2 RN R4
temp3 RN R5
temp4 RN R12
IF Thumbing
THUMBAREA
ENDIF
NESTED_ENTRY memmove
ROUT
IF Thumbing
; Switch from Thumb mode to ARM mode
DCW 0x4778 ; bx pc
DCW 0x46C0 ; nop
ENDIF
STMDB sp!, {dest,temp2,temp3,lr} ; save registers
PROLOG_END
;if source comes before destination copy from tail to head
CMP source, dest
BGE HEAD_TO_TAIL ; if source < dest
;**********************************************************************
; Copy from tail to head to avoid source overwrite because the source
; precedes the destination
;**********************************************************************
TAILTOHEAD
;Move pointers to the tails
ADD source, source, count
ADD dest, dest, count
CMP count, #8 ;if < 8 bytes, byte moves
BLT TTH_BYTEMOVE4
;check if destination is word aligned, if not then align it
ANDS temp1, dest, #3 ; 2-3 cycles
BEQ TTH_CHKSRC_ALIGN
;
;read 1 to 3 bytes until the destination is word aligned, then
;see if the source is word aligned, if it is then go back to
;word length moves, else continue on with single byte moves
;
TTH_ATTEMPTALIGN
LDRB temp2, [source, #-1]! ; 8 cycles/1-3 bytes
CMP temp1, #2
STRB temp2, [dest, #-1]!
LDRGEB temp3, [source, #-1]!
SUB count, count, temp1
LDRGTB temp2, [source, #-1]!
STRGEB temp3, [dest, #-1]!
STRGTB temp2, [dest, #-1]!
; Check if source is word aligned, if not check for word
; alignment.
TTH_CHKSRC_ALIGN
TST source, #1 ; 3-7 cycles
BNE TTH_UNALIGNED ; Unaligned moves
TST source, #2
BNE TTH_HWORD_ALIGNED ; Half Word aligned
;
; Word aligned source and destination.
; Move blocks of 32 bytes until we have less than 32 bytes left,
; then divide moves in half down to less than 4 then jump to byte
; moves.
; NOTE: Because of the overhead of pushing registers for 32 byte
; moves it is actually more efficient to use 16 byte moves for
; blocks of less than 128 bytes.
;
TTH_REALIGNED
SUBS count, count, #32 ; 2-3 cycles
BLT TTH_BLK16
TTH_BLK32 ; 20 cycles/32 bytes
LDMDB source!, {temp1,temp2,temp3,lr}
STMDB dest!, {temp1,temp2,temp3,lr}
LDMDB source!, {temp1,temp2,temp3,lr}
SUBS count, count, #32
STMDB dest!, {temp1,temp2,temp3,lr}
BGE TTH_BLK32
TTH_BLK16 ; 10 cycles/16 bytes
ADDS count, count, #16
LDMGEDB source!, {temp1, temp2, temp3, lr}
SUBGE count, count, #16
STMGEDB dest!, {temp1, temp2, temp3, lr}
TTH_BLK8 ; 6 cycles / 8 bytes
ADDS count, count, #8
LDMGEDB source!, {temp1, temp2}
SUBGE count, count, #8
STMGEDB dest!, {temp1, temp2}
TTH_BLK4 ; 6-9 cycles/4 bytes
ADDS count, count, #4
LDRGE temp1, [source, #-4]!
STRGE temp1, [dest, #-4]!
TTH_WORD_BYTES
ADDLTS count, count, #4
BEQ TTH_WORD_EXIT
LDRB temp1, [source, #-1]! ; 4-7 cycles/1 byte
CMP count, #2
STRB temp1, [dest, #-1]!
LDRGEB temp2, [source, #-1]!
LDRGTB temp3, [source, #-1]! ; 8 cycles/1-2 bytes
STRGEB temp2, [dest, #-1]!
STRGTB temp3, [dest, #-1]!
TTH_WORD_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
;
; Source and Destination are half word aligned.
; For blocks < 96 bytes it's actually more efficient to jump to
; the 8 byte copy than take the hit for setup time on 32 byte copy.
;
TTH_HWORD_ALIGNED
LDRH lr, [source, #-2]! ; 4-5 cycles
SUBS count, count, #32
MOV lr, lr, LSL #16
BLT TTH_HWORD8_TST
TTH_HWORD32 ; 35 cycles/32 bytes
LDMDB source!, {temp1,temp2,temp3,temp4}
SUBS count, count, #32
ORR lr, lr, temp4, LSR #16
MOV temp4, temp4, LSL #16
ORR temp4, temp4, temp3, LSR #16
MOV temp3, temp3, LSL #16
ORR temp3, temp3, temp2, LSR #16
MOV temp2, temp2, LSL #16
ORR temp2, temp2, temp1, LSR #16
STMDB dest!, {temp3,temp4,lr} ; Store bytes 21-32
STR temp2, [dest, #-4]! ; Store bytes 17-20
MOV lr, temp1, LSL #16
LDR temp4, [source, #-4]!
LDMDB source!, {temp1,temp2,temp3}
ORR lr, lr, temp4, LSR #16
MOV temp4, temp4, LSL #16
ORR temp4, temp4, temp3, LSR #16
MOV temp3, temp3, LSL #16
ORR temp3, temp3, temp2, LSR #16
MOV temp2, temp2, LSL #16
ORR temp2, temp2, temp1, LSR #16
STMDB dest!, {temp3,temp4,lr} ; Store bytes 5-16
STR temp2, [dest, #-4]! ; Store bytes 1-4
MOV lr, temp1, LSL #16
BGE TTH_HWORD32
TTH_HWORD8_TST
ADDS count, count, #24
BLT TTH_HWORD4
TTH_HWORD8 ; 11 cycles/8 bytes
LDMDB source!, {temp2, temp3}
SUBS count, count, #8
ORR lr, lr, temp3, LSR #16
MOV temp3, temp3, LSL #16
ORR temp3, temp3, temp2, LSR #16
STR lr, [dest, #-4]!
STR temp3, [dest, #-4]!
MOV lr, temp2, LSL #16
BGE TTH_HWORD8
TTH_HWORD4 ; 3-12 cycles/4 bytes
ADDS count, count, #4
BLT TTH_HWORD_BYTES
LDR temp1, [source, #-4]!
ORR lr, lr, temp1, LSR #16
STR lr, [dest, #-4]!
MOV lr, temp1, LSL #16
TTH_HWORD_BYTES
ADDLTS count, count, #4
BEQ TTH_HWORD_EXIT
MOV lr, lr, LSR #16 ; 11 cycles/1-3 bytes
CMP count, #2
MOVLT lr, lr, LSR #8
STRLTB lr, [dest, #-1]!
LDRGTB temp1, [source, #-1]!
STRGEH lr, [dest, #-2]!
STRGTB temp1, [dest, #-1]!
TTH_HWORD_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
TTH_UNALIGNED
TST source, #2
BEQ TTH_OFFONE
;
; 3 Byte difference between word and source.
;
TTH_OFFTHREE
LDRB temp3, [source, #-1]! ; 5-6 cycles
LDRH lr, [source, #-2]!
SUBS count, count, #32
ORR lr, lr, temp3, LSL #16
MOV lr, lr, LSL #8
BLT TTH_OFFTHREE8_TST
TTH_OFFTHREE32 ; 35 cycles/32 bytes
LDMDB source!, {temp1,temp2,temp3,temp4}
SUBS count, count, #32
ORR lr, lr, temp4, LSR #24
MOV temp4, temp4, LSL #8
ORR temp4, temp4, temp3, LSR #24
MOV temp3, temp3, LSL #8
ORR temp3, temp3, temp2, LSR #24
MOV temp2, temp2, LSL #8
ORR temp2, temp2, temp1, LSR #24
STMDB dest!, {temp3,temp4,lr} ; Store bytes 21-32
STR temp2, [dest, #-4]! ; Store bytes 17-20
MOV lr, temp1, LSL #8
LDR temp4, [source, #-4]!
LDMDB source!, {temp1,temp2,temp3}
ORR lr, lr, temp4, LSR #24
MOV temp4, temp4, LSL #8
ORR temp4, temp4, temp3, LSR #24
MOV temp3, temp3, LSL #8
ORR temp3, temp3, temp2, LSR #24
MOV temp2, temp2, LSL #8
ORR temp2, temp2, temp1, LSR #24
STMDB dest!, {temp3,temp4,lr} ; Store bytes 5-16
STR temp2, [dest, #-4]! ; Store bytes 1-4
MOV lr, temp1, LSL #8
BGE TTH_OFFTHREE32
TTH_OFFTHREE8_TST
ADDS count, count, #24
BLT TTH_OFFTHREE4
TTH_OFFTHREE8 ; 11 cycles/8 bytes
LDMDB source!, {temp1, temp2}
SUBS count, count, #8
ORR lr, lr, temp2, LSR #24
MOV temp2, temp2, LSL #8
ORR temp2, temp2, temp1, LSR #24
STR lr, [dest, #-4]! ; Store bytes 5-8
STR temp2, [dest, #-4]! ; Store bytes 1-4
MOV lr, temp1, LSL #8
BGE TTH_OFFTHREE8
TTH_OFFTHREE4 ; 3-11 cycles/4 bytes
ADDS count, count, #4
BLT TTH_OFFTHREE_BYTES
LDR temp3, [source, #-4]!
ORR lr, lr, temp3, LSR #24
STR lr, [dest, #-4]!
MOV lr, temp3, LSL #8
TTH_OFFTHREE_BYTES
ADDLTS count, count, #4
BEQ TTH_OFFTHREE_EXIT
MOV lr, lr, LSR #8 ; 11 cycles/1-3 bytes
CMP count, #2
MOVLT temp1, lr, LSR #16
STRLTB temp1, [dest, #-1]!
MOVGE temp1, lr, LSR #8
STRGEH temp1, [dest, #-2]!
STRGTB lr, [dest, #-1]!
TTH_OFFTHREE_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
;
; One Byte difference between word and source.
;
TTH_OFFONE
LDRB lr, [source, #-1]!
SUBS count, count, #32 ; 2-3 cycles
MOV lr, lr, LSL #24
BLT TTH_OFFONE8_TST
TTH_OFFONE32 ; 35 cycles/32 bytes
LDMDB source!, {temp1,temp2,temp3,temp4}
SUBS count, count, #32 ; avoid result delay
ORR lr, lr, temp4, LSR #8
MOV temp4, temp4, LSL #24
ORR temp4, temp4, temp3, LSR #8
MOV temp3, temp3, LSL #24
ORR temp3, temp3, temp2, LSR #8
MOV temp2, temp2, LSL #24
ORR temp2, temp2, temp1, LSR #8
STMDB dest!, {temp3,temp4,lr} ; Store bytes 21-32
STR temp2, [dest, #-4]! ; STore bytes 17-20
MOV lr, temp1, LSL #24
LDR temp4, [source, #-4]!
LDMDB source!, {temp1,temp2,temp3}
ORR lr, lr, temp4, LSR #8
MOV temp4, temp4, LSL #24
ORR temp4, temp4, temp3, LSR #8
MOV temp3, temp3, LSL #24
ORR temp3, temp3, temp2, LSR #8
MOV temp2, temp2, LSL #24
ORR temp2, temp2, temp1, LSR #8
STMDB dest!, {temp3,temp4,lr} ; Store bytes 5-16
STR temp2, [dest, #-4]! ; STore bytes 1-4
MOV lr, temp1, LSL #24
BGE TTH_OFFONE32
TTH_OFFONE8_TST
ADDS count, count, #24
BLT TTH_OFFONE4
TTH_OFFONE8 ; 11 cycles/8 bytes
LDMDB source!, {temp2, temp3}
SUBS count, count, #8
ORR lr, lr, temp3, LSR #8
MOV temp3, temp3, LSL #24
STR lr, [dest, #-4]!
ORR temp3, temp3, temp2, LSR #8
STR temp3, [dest, #-4]!
MOV lr, temp2, LSL #24
BGE TTH_OFFONE8
TTH_OFFONE4 ; 8-10 cycles/4 bytes
ADDS count, count, #4
BLT TTH_OFFONE_BYTES
LDR temp3, [source, #-4]!
ORR lr, lr, temp3, LSR #8
STR lr, [dest, #-4]!
MOV lr, temp3, LSL #24
TTH_OFFONE_BYTES ; 13 cycles/1-3 bytes
ADDLTS count, count, #4
BEQ TTH_OFFONE_EXIT
MOV lr, lr, LSR #24
CMP count, #2
STRB lr, [dest, #-1]!
BLT TTH_OFFONE_EXIT
LDRGEB temp1, [source, #-1]!
LDRGTB temp2, [source, #-1]!
STRGEB temp1, [dest, #-1]!
STRGTB temp2, [dest, #-1]!
TTH_OFFONE_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
TTH_BYTEMOVE4 ; 12 cycles/4 bytes
CMP count, #4
BLT TTH_LAST3
LDRB temp1, [source, #-1]!
LDRB temp2, [source, #-1]!
LDRB temp3, [source, #-1]!
LDRB lr, [source, #-1]!
SUB count, count, #4
STRB temp1, [dest, #-1]!
STRB temp2, [dest, #-1]!
STRB temp3, [dest, #-1]!
STRB lr, [dest, #-1]!
; Move the last 0-3 bytes
TTH_LAST3
CMP count, #0 ; 2 or 5 cycles
BEQ TTH_BYTEMOVE_EXIT
;
;single byte moves
;
TTH_BYTEMOVE ; 11 cycles/1-3 bytes
LDRB temp1, [source, #-1]!
CMP count, #2
STRB temp1, [dest, #-1]!
BLT TTH_BYTEMOVE_EXIT
LDRGEB temp2, [source, #-1]!
LDRGTB temp3, [source, #-1]!
STRGEB temp2, [dest, #-1]!
STRGTB temp3, [dest, #-1]!
TTH_BYTEMOVE_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
;**********************************************************************
; Copy from head to tail to avoid source overwrite because the source
; destination the source
;**********************************************************************
HEAD_TO_TAIL
;if LT 8 bytes store them and exit
CMP count, #8 ; 2-3 cycles
BLT BYTEMOVE4
;Check alignment of parameters
ANDS temp1, dest, #3 ; 2-3 cycles
BEQ SRCALIGN
; destination is at least 1 byte misaligned
; Read and write (4 - alignment) bytes to align destination.
RSB temp1, temp1, #4 ; 9 cycles
LDRB temp2, [source], #1
CMP temp1, #2
STRB temp2, [dest], #1
LDRGEB temp3, [source], #1 ; >= 2 == at least 2 bytes
LDRGTB temp2, [source], #1 ; > 2 == 3 bytes unaligned
SUB count, count, temp1
STRGEB temp3, [dest], #1
STRGTB temp2, [dest], #1
SRCALIGN ; 3 - 7 cycles
TST source, #1 ; save alignment of src
BNE UNALIGNED ; src 3 byte unaligned.
TST source, #2
BNE HWORDMOVE ; src and dst are hword aligned
;
;word aligned source and destination, move blocks of 32 bytes
;until we have less than 32 bytes left, then divide moves in
;half down to less than 4, where we will move the last 3 or less
;bytes
;
WORDMOVE
SUBS count, count, #32 ; 2-3 cycles
BLT BLK16
BLK32 ; 20 cycles/32 bytes
LDMIA source!, {temp1,temp2,temp3,lr}
STMIA dest!, {temp1,temp2,temp3,lr}
LDMIA source!, {temp1,temp2,temp3,lr}
SUBS count, count, #32
STMIA dest!, {temp1,temp2,temp3,lr}
BGE BLK32
BLK16 ; 11-4 cycles/16 bytes
ADDS count, count, #16
LDMGEIA source!, {temp1, temp2, temp3, lr}
STMGEIA dest!, {temp1, temp2, temp3, lr}
BEQ WORD_BYTES_EXIT
SUBGTS count, count, #16
BLK8 ; 6 cycles/8 bytes
ADDS count, count, #8
LDMGEIA source!, {temp1, temp2}
SUBGE count, count, #8
STMGEIA dest!, {temp1, temp2}
BLK4
ADDS count, count, #4 ; 6-9 cycles/4 bytes
LDRGE temp1, [source], #4
STRGE temp1, [dest], #4
WORD_BYTES
ADDLTS count, count, #4
BEQ WORD_BYTES_EXIT ; On zero, Return to caller
LDR temp1, [source], #4 ; 10 cycles/1-3 bytes
CMP count, #2
STRGEH temp1, [dest], #2
STRLTB temp1, [dest], #1
MOVGT temp1, temp1, LSR #16
STRGTB temp1, [dest], #1
WORD_BYTES_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
;
; half word align source and destination
;
HWORDMOVE ; 2-3 cycles
LDRH temp1, [source], #2
SUBS count, count, #32
BLT HWORD8_TST
HWORD32 ; 35 cycles/32 bytes
LDMIA source!, {temp2,temp3,temp4,lr}
ORR temp1, temp1, temp2, LSL #16
MOV temp2, temp2, LSR #16
ORR temp2, temp2, temp3, LSL #16
MOV temp3, temp3, LSR #16
ORR temp3, temp3, temp4, LSL #16
MOV temp4, temp4, LSR #16
ORR temp4, temp4, lr, LSL #16
STMIA dest!, {temp1,temp2,temp3,temp4} ; Store bytes 1-16
MOV temp1, lr, LSR #16
LDMIA source!, {temp2,temp3,temp4,lr}
ORR temp1, temp1, temp2, LSL #16
MOV temp2, temp2, LSR #16
ORR temp2, temp2, temp3, LSL #16
MOV temp3, temp3, LSR #16
ORR temp3, temp3, temp4, LSL #16
MOV temp4, temp4, LSR #16
ORR temp4, temp4, lr, LSL #16
STMIA dest!, {temp1,temp2,temp3,temp4} ; Store bytes 17-32
SUBS count, count, #32
MOV temp1, lr, LSR #16
BGE HWORD32
HWORD8_TST
ADDS count, count, #24
BLT HWORD4
HWORD8 ; 11 cycles/8 bytes
LDMIA source!, {temp2,temp3}
ORR temp1, temp1, temp2, LSL #16
MOV temp2, temp2, LSR #16
ORR temp2, temp2, temp3, LSL #16
STMIA dest!, {temp1, temp2}
SUBS count, count, #8
MOV temp1, temp3, LSR #16
BGE HWORD8
HWORD4 ; 3-7 cycles/4 bytes
ADDS count, count, #4
BLT HWORD_BYTES
LDR temp2, [source], #4
ORR temp1, temp1, temp2, LSL #16
STR temp1, [dest], #4
MOV temp1, temp2, LSR #16
HWORD_BYTES ; 5-11 cycles/1-3 bytes
ADDLTS count, count, #4
BEQ HWORD_BYTES_EXIT ; On zero, Return to caller
CMP count, #2
STRLTB temp1, [dest], #1
LDRGTB temp2, [source], #1
STRGEH temp1, [dest], #2
STRGTB temp2, [dest], #1
HWORD_BYTES_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc}
ENDIF
;
; Unaligned Moves
;
UNALIGNED
TST source, #2
BEQ UNALIGNED1
UNALIGNED3 ; 3-4 cycles
LDRB temp1, [source], #1
SUBS count, count, #32
BLT OFFTHREE8_TST
OFFTHREE32 ; 35 cycles/32 bytes
LDMIA source!, {temp2,temp3,temp4,lr}
ORR temp1, temp1, temp2, LSL #8
MOV temp2, temp2, LSR #24
ORR temp2, temp2, temp3, LSL #8
MOV temp3, temp3, LSR #24
ORR temp3, temp3, temp4, LSL #8
MOV temp4, temp4, LSR #24
ORR temp4, temp4, lr, LSL #8
STMIA dest!, {temp1,temp2,temp3,temp4} ; Store bytes 1-16
MOV temp1, lr, LSR #24
LDMIA source!, {temp2,temp3,temp4,lr}
ORR temp1, temp1, temp2, LSL #8
MOV temp2, temp2, LSR #24
ORR temp2, temp2, temp3, LSL #8
MOV temp3, temp3, LSR #24
ORR temp3, temp3, temp4, LSL #8
MOV temp4, temp4, LSR #24
ORR temp4, temp4, lr, LSL #8
STMIA dest!, {temp1,temp2,temp3,temp4} ; Store bytes 17-32
SUBS count, count, #32
MOV temp1, lr, LSR #24
BGE OFFTHREE32
OFFTHREE8_TST
ADDS count, count, #24
BLT OFFTHREE4
OFFTHREE8 ; 11 cycles/8 bytes
LDMIA source!, {temp2,temp3}
ORR temp1, temp1, temp2, LSL #8
MOV temp2, temp2, LSR #24
ORR temp2, temp2, temp3, LSL #8
STMIA dest!, {temp1, temp2}
SUBS count, count, #8
MOV temp1, temp3, LSR #24
BGE OFFTHREE8
OFFTHREE4 ; 3-7 cycles/4 bytes
ADDS count, count, #4
BLT OFFTHREE_BYTES
LDR temp2, [source], #4
ORR temp1, temp1, temp2, LSL #8
STR temp1, [dest], #4
MOV temp1, temp2, LSR #24
OFFTHREE_BYTES ; 5-12 cycles/ 1-3 bytes
ADDLTS count, count, #4
BEQ OFFTHREE_EXIT ; On zero, Return to caller
CMP count, #2
LDRGEH temp2, [source], #2
STRB temp1, [dest], #1
STRGEB temp2, [dest], #1
MOVGT temp2, temp2, LSR #8
STRGTB temp2, [dest], #1
OFFTHREE_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc} ; On zero, Return to caller
ENDIF
;
; Source is one byte from word alignment.
; Read a byte & half word then multiple words and a byte. Then
; shift and ORR them into consecutive words for STM writes
UNALIGNED1 ; 5-6 cycles
LDRB temp1, [source], #1
LDRH temp2, [source], #2
SUBS count, count, #32
ORR temp1, temp1, temp2, LSL #8
BLT OFFONE8_TST
OFFONE32 ; 35 cycles/32 bytes
LDMIA source!, {temp2, temp3, temp4, lr}
ORR temp1, temp1, temp2, LSL #24
MOV temp2, temp2, LSR #8
ORR temp2, temp2, temp3, LSL #24
MOV temp3, temp3, LSR #8
ORR temp3, temp3, temp4, LSL #24
MOV temp4, temp4, LSR #8
ORR temp4, temp4, lr, LSL #24
STMIA dest!, {temp1,temp2,temp3,temp4} ; Store bytes 1-16
MOV temp1, lr, LSR #8
LDMIA source!, {temp2,temp3,temp4,lr}
ORR temp1, temp1, temp2, LSL #24
MOV temp2, temp2, LSR #8
ORR temp2, temp2, temp3, LSL #24
MOV temp3, temp3, LSR #8
ORR temp3, temp3, temp4, LSL #24
MOV temp4, temp4, LSR #8
ORR temp4, temp4, lr, LSL #24
STMIA dest!, {temp1,temp2,temp3,temp4} ; Store bytes 17-32
SUBS count, count, #32
MOV temp1, lr, LSR #8
BGE OFFONE32
OFFONE8_TST
ADDS count, count, #24
BLT OFFONE4
OFFONE8 ; 11 cycles/8 bytes
LDMIA source!, {temp2,temp3}
ORR temp1, temp1, temp2, LSL #24
MOV temp2, temp2, LSR #8
ORR temp2, temp2, temp3, LSL #24
STMIA dest!, {temp1,temp2}
SUBS count, count, #8
MOV temp1, temp3, LSR #8
BGE OFFONE8
OFFONE4 ; 3-9 cycles/4 bytes
ADDS count, count, #4
BLT OFFONE_BYTES
LDR temp2, [source], #4
ORR temp1, temp1, temp2, LSL #24
STR temp1, [dest], #4
BEQ OFFONE_EXIT
MOV temp1, temp2, LSR #8
OFFONE_BYTES ; 11 cycles/1-3 bytes
ADDLTS count, count, #4
BEQ OFFONE_EXIT
CMP count, #2
STRLTB temp1, [dest], #1
STRGEH temp1, [dest], #2
MOVGT temp1, temp1, LSR #16
STRGTB temp1, [dest], #1
OFFONE_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc} ; Return to caller
ENDIF
BYTEMOVE4 ; 12 cycles/4 bytes
CMP count, #4
BLT MMOVEXIT
LDRB temp1, [source], #1
SUB count, count, #4
LDRB temp2, [source], #1
LDRB temp3, [source], #1
LDRB lr, [source], #1
STRB temp1, [dest], #1
STRB temp2, [dest], #1
STRB temp3, [dest], #1
STRB lr, [dest], #1
MMOVEXIT ; 2-5 cycles
CMP count, #0
IF Interworking :LOR: Thumbing
LDMEQIA sp!, {dest, temp2, temp3, lr}
BXEQ lr
ELSE
LDMEQIA sp!, {dest, temp2, temp3, pc} ; On zero, Return to caller
ENDIF
;
; Store last 3 or so bytes and exit
;
BYTEMOVE ; 4-7 cycles/1 byte
LDRB temp1, [source], #1
CMP count, #2
STRB temp1, [dest], #1
BLT BYTEMOVE_EXIT
LDRGEB temp2, [source], #1 ; 8 cycles/1-2 bytes
LDRGTB temp3, [source], #1
STRGEB temp2, [dest], #1
STRGTB temp3, [dest], #1
BYTEMOVE_EXIT
IF Interworking :LOR: Thumbing
LDMIA sp!, {dest, temp2, temp3, lr}
BX lr
ELSE
LDMIA sp!, {dest, temp2, temp3, pc} ; Return to caller
ENDIF
ENTRY_END memmove
END
|
; A158961: Numerator of Hermite(n, 2/5).
; Submitted by Jamie Morken(s4)
; 1,4,-34,-536,2956,119024,-262904,-36758816,-55018864,14483450944,82692292576,-6910956301696,-73124586123584,3854075436523264,62947282726422656,-2446063674660594176,-56994716743459368704,1728872072754637865984,55360997522959014862336,-1334540875387338019936256,-57931111148360416198964224,1102816430793896355140399104,65238932428954022429474031616,-952142344157469900936542887936,-78833341669927005397641307910144,827237446309255859533286233882624,101850626872645780185184779823210496
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
mul $2,4
mul $3,-25
mul $3,$0
mul $3,2
lpe
mov $0,$1
|
Music_BattleTowerTheme:
musicheader 4, 1, Music_BattleTowerTheme_Ch1
musicheader 1, 2, Music_BattleTowerTheme_Ch2
musicheader 1, 3, Music_BattleTowerTheme_Ch3
musicheader 1, 4, Music_BattleTowerTheme_Ch4
Music_BattleTowerTheme_Ch1:
tempo 141
volume $77
tone $0001
vibrato $12, $34
stereopanning $f
notetype $6, $94
Music_BattleTowerTheme_branch_1788a5:
note __, 16
note __, 16
note __, 12
note __, 12
dutycycle $2
octave 3
note C_, 2
note E_, 2
note G_, 4
callchannel Music_BattleTowerTheme_branch_17895e
note G_, 2
note __, 2
note C_, 4
note __, 4
intensity $92
note G_, 2
note F_, 2
note C_, 2
note E_, 2
note G_, 2
octave 4
note E_, 2
note G_, 2
note E_, 2
octave 3
note G_, 2
note E_, 2
callchannel Music_BattleTowerTheme_branch_17895e
note G_, 2
note __, 2
octave 2
note A#, 4
note __, 4
intensity $92
octave 3
note G_, 2
note D#, 2
note C_, 2
note F_, 2
note A_, 2
octave 4
note C_, 2
note F_, 2
note C_, 2
octave 3
note A_, 2
note F_, 2
intensity $93
note D_, 2
note __, 2
note E_, 4
note F_, 4
note G_, 2
note A_, 2
note A#, 8
octave 2
note A#, 8
octave 3
note C_, 2
note __, 2
note D_, 4
note E_, 4
note F_, 2
note G_, 2
note A_, 8
octave 2
note A_, 8
note A#, 2
note __, 2
octave 3
note C_, 4
note D_, 4
note D#, 2
note F_, 2
note D#, 4
note F_, 4
note G_, 4
note A#, 4
octave 4
note C_, 2
note __, 2
octave 3
note F_, 4
note __, 4
octave 2
note A_, 2
octave 3
note C_, 2
note E_, 4
note __, 4
dutycycle $3
note C_, 2
note E_, 2
note G_, 4
note A_, 4
note F_, 8
note F_, 2
note G_, 2
note A_, 8
note G_, 4
note F_, 4
note D_, 8
note A#, 2
note D_, 2
note E_, 2
note F_, 2
note G_, 2
note A_, 2
note A#, 2
octave 4
note C_, 2
note D_, 2
note C_, 2
note D_, 2
note D#, 2
note F_, 4
octave 3
note F_, 8
note C#, 2
note D#, 2
note F_, 8
note G_, 4
note F_, 4
note F_, 4
note C_, 8
note G_, 2
note F_, 2
note E_, 8
octave 4
note C_, 2
octave 3
note A#, 2
note G_, 2
note E_, 2
note C_, 4
note F_, 8
note C_, 2
note F_, 2
note A_, 8
note A#, 4
octave 4
note C_, 4
octave 3
note A#, 4
note F_, 8
note A#, 4
octave 4
note D_, 8
octave 3
note A#, 2
note A_, 2
note F_, 4
note G#, 4
note F_, 8
note G#, 4
note F_, 4
note D#, 4
note C#, 4
note F_, 4
intensity $94
octave 4
note C_, 4
octave 3
note E_, 6
note __, 2
note E_, 1
note __, 1
note E_, 1
note __, 1
note E_, 4
note __, 12
loopchannel 0, Music_BattleTowerTheme_branch_1788a5
Music_BattleTowerTheme_branch_17895e:
intensity $94
note A_, 2
note __, 2
note C_, 4
note __, 4
note A_, 1
note __, 1
note A_, 1
note __, 1
note C_, 4
note F_, 4
note __, 4
note A_, 4
endchannel
Music_BattleTowerTheme_Ch2:
vibrato $12, $34
Music_BattleTowerTheme_branch_178970:
dutycycle $3
notetype $6, $b8
octave 3
note F_, 2
note __, 2
octave 2
note A_, 4
note __, 4
octave 3
note F_, 1
note __, 1
note F_, 1
note __, 1
octave 2
note A_, 4
octave 3
note F_, 4
note __, 4
octave 2
note A_, 2
note __, 2
octave 3
note F_, 2
note __, 2
octave 2
note A_, 4
note __, 4
tone $0001
note A_, 1
note __, 1
octave 3
note C_, 1
note __, 1
note F_, 4
note __, 4
tone 0
intensity $b7
note G_, 2
octave 4
note C_, 2
note E_, 4
callchannel Music_BattleTowerTheme_branch_178a15
note A#, 4
note __, 2
note F_, 2
notetype $c, $b7
note C_, 12
notetype $6, $b7
callchannel Music_BattleTowerTheme_branch_178a15
notetype $c, $b7
note A#, 2
note __, 1
note G_, 1
note A_, 12
note A#, 1
note __, 1
note A#, 4
note G_, 1
note A_, 1
note A#, 4
note D_, 4
note A_, 1
note __, 1
note A_, 4
note G_, 1
note A_, 1
note F_, 8
note G_, 1
note __, 1
note G_, 4
note A#, 1
note A_, 1
note A#, 4
note D#, 4
note F_, 1
note __, 1
note F_, 4
note G_, 1
note F_, 1
note E_, 8
stereopanning $f0
dutycycle $2
note F_, 6
note A_, 1
note A#, 1
octave 5
note C_, 4
octave 4
note A#, 2
note A_, 2
note A#, 16
note A#, 6
note G_, 1
note A_, 1
note A#, 4
octave 5
note C_, 2
octave 4
note A#, 2
note A_, 6
note A#, 1
note A_, 1
note G_, 8
note A_, 6
note F_, 1
note A_, 1
octave 5
note C_, 4
note D_, 2
note D#, 2
note D_, 6
note C_, 2
octave 4
note A#, 8
octave 5
note C#, 6
note C_, 2
octave 4
note A#, 2
note G#, 2
note F_, 2
note G#, 2
note G_, 5
note __, 1
notetype $6, $b7
note G_, 1
note __, 1
note G_, 1
note __, 1
note G_, 4
note __, 4
stereopanning $ff
dutycycle $3
octave 3
note C_, 2
note D_, 2
note E_, 4
loopchannel 0, Music_BattleTowerTheme_branch_178970
Music_BattleTowerTheme_branch_178a15:
note F_, 2
note __, 2
note F_, 8
note C_, 2
note F_, 2
octave 5
note C_, 8
octave 4
note A#, 4
note A_, 4
endchannel
Music_BattleTowerTheme_Ch3:
vibrato $12, $34
notetype $6, $16
Music_BattleTowerTheme_branch_178a26:
stereopanning $ff
callchannel Music_BattleTowerTheme_branch_178afe
note C_, 2
note __, 2
note F_, 4
note __, 4
octave 2
note A_, 1
note __, 1
octave 3
note C_, 1
note __, 1
note F_, 4
note __, 4
stereopanning $f0
note C_, 8
callchannel Music_BattleTowerTheme_branch_178afe
note C_, 2
note __, 2
note F_, 4
note __, 4
note C_, 1
note __, 1
note C_, 1
note __, 1
note E_, 4
note C_, 4
note __, 4
note C_, 2
note __, 2
callchannel Music_BattleTowerTheme_branch_178afe
octave 2
note A#, 2
note __, 2
octave 3
note D#, 4
note __, 4
octave 2
note A#, 1
note __, 1
note A#, 1
note __, 1
octave 3
note C_, 4
note F_, 4
note __, 4
note C_, 1
note __, 1
note C_, 2
octave 2
note A#, 2
note __, 2
note A#, 4
note F_, 4
octave 3
note F_, 1
note __, 1
note F_, 2
octave 2
note A#, 2
note __, 2
octave 3
note D_, 2
note __, 2
note F_, 8
note C_, 2
note __, 2
note C_, 4
octave 2
note F_, 4
octave 3
note F_, 1
note __, 1
note F_, 1
note __, 1
octave 2
note A_, 2
note __, 2
octave 3
note C_, 2
note __, 2
note F_, 8
note D#, 2
note __, 2
note D#, 4
octave 2
note G_, 4
octave 3
note G_, 1
note __, 1
note G_, 1
note __, 1
octave 2
note G_, 2
note __, 2
note A#, 2
note __, 2
octave 3
note D#, 8
note F_, 2
note __, 2
note C_, 4
note __, 4
note C_, 2
octave 2
note F_, 2
note G_, 4
note __, 4
stereopanning $ff
note G_, 2
octave 3
note C_, 2
note E_, 4
note F_, 4
note C_, 8
note F_, 1
note __, 1
note F_, 1
note __, 1
note A_, 4
note C_, 6
note __, 2
note C_, 1
note __, 1
note C_, 1
note __, 1
note F_, 4
note D_, 8
note F_, 1
note __, 1
note F_, 1
note __, 1
note A#, 4
note A_, 4
note F_, 4
note D_, 4
note F_, 4
note C#, 8
note F_, 1
note __, 1
note F_, 1
note __, 1
note A#, 4
note F_, 8
note C#, 1
note __, 1
note C#, 1
note __, 1
note C_, 4
note F_, 8
note C_, 1
note __, 1
note C_, 1
note __, 1
note G_, 4
note C_, 4
note D_, 4
note E_, 4
note F_, 4
note C_, 8
note F_, 1
note __, 1
note F_, 1
note __, 1
note A_, 4
note C_, 8
note F_, 2
note __, 2
note F_, 4
octave 2
note A#, 8
octave 3
note F_, 1
note __, 1
note F_, 1
note __, 1
note A#, 4
octave 2
note A#, 4
octave 3
note D_, 4
note E_, 4
note F_, 4
octave 2
note G#, 8
octave 3
note C#, 1
note __, 1
note C#, 1
note __, 1
note G#, 4
octave 2
note G#, 8
octave 3
note C#, 4
note C_, 4
note G_, 8
note C_, 1
note __, 1
note C_, 1
note __, 1
note G_, 4
note __, 12
loopchannel 0, Music_BattleTowerTheme_branch_178a26
Music_BattleTowerTheme_branch_178afe:
octave 3
note C_, 2
note __, 2
note F_, 4
note __, 4
note C_, 1
note __, 1
note C_, 1
note __, 1
note F_, 4
note C_, 4
note __, 4
note C_, 2
note __, 2
endchannel
Music_BattleTowerTheme_Ch4:
togglenoise $3
notetype $c
Music_BattleTowerTheme_branch_178b11:
callchannel Music_BattleTowerTheme_branch_178b58
note D_, 2
note D_, 4
note D_, 1
note D_, 1
note D_, 4
note D_, 1
note C#, 1
note D_, 1
note C#, 1
Music_BattleTowerTheme_branch_178b1d:
callchannel Music_BattleTowerTheme_branch_178b58
callchannel Music_BattleTowerTheme_branch_178b61
loopchannel 2, Music_BattleTowerTheme_branch_178b1d
callchannel Music_BattleTowerTheme_branch_178b6c
callchannel Music_BattleTowerTheme_branch_178b61
callchannel Music_BattleTowerTheme_branch_178b6c
note D_, 2
note D_, 4
note D_, 1
note D_, 1
note D_, 8
Music_BattleTowerTheme_branch_178b35:
callchannel Music_BattleTowerTheme_branch_178b76
note D_, 2
note D_, 2
note D_, 2
note D_, 1
note D_, 1
note D_, 2
note D_, 2
note D_, 1
note C#, 1
note D_, 1
note C#, 1
loopchannel 3, Music_BattleTowerTheme_branch_178b35
callchannel Music_BattleTowerTheme_branch_178b76
note D_, 2
note D_, 2
note D_, 2
note D_, 1
note D_, 1
note D_, 4
note D_, 1
note C#, 1
note D_, 1
note C#, 1
loopchannel 0, Music_BattleTowerTheme_branch_178b11
Music_BattleTowerTheme_branch_178b58:
note D_, 2
note D_, 4
note D_, 1
note D_, 1
note D_, 2
note D_, 4
note D_, 1
note D_, 1
endchannel
Music_BattleTowerTheme_branch_178b61:
note D_, 2
note D_, 4
note D_, 1
note D_, 1
note D_, 2
note D_, 2
note D_, 1
note C#, 1
note D_, 1
note C#, 1
endchannel
Music_BattleTowerTheme_branch_178b6c:
note D_, 2
note D_, 4
note D_, 1
note D_, 1
note D_, 2
note D_, 2
note D_, 2
note D_, 1
note D_, 1
endchannel
Music_BattleTowerTheme_branch_178b76:
note D_, 2
note C#, 2
note D_, 2
note D_, 1
note C#, 1
note D_, 2
note C#, 2
note D_, 2
note D_, 1
note C#, 1
endchannel
|
// anyop.cpp,v 1.6 2001/05/19 22:26:32 schmidt Exp
// ============================================================================
//
// = LIBRARY
// TAO/tests/Param_Test
//
// = FILENAME
// anyop.cpp
//
// = DESCRIPTION
//
// = AUTHORS
// Carlos O'Ryan
//
// ============================================================================
#include "param_testCli.h"
#include "tao/corba.h"
#include "tao/debug.h"
#include "tao/Stub.h"
#include "ace/Get_Opt.h"
ACE_RCSID(Param_Test, anyop, "anyop.cpp,v 1.6 2001/05/19 22:26:32 schmidt Exp")
int
main (int argc, char *argv[])
{
int n = 1024;
ACE_TRY_NEW_ENV
{
CORBA::ORB_var orb = CORBA::ORB_init (argc,
argv,
0,
ACE_TRY_ENV);
ACE_TRY_CHECK;
ACE_Get_Opt get_opt (argc, argv, "dn:l:");
int opt;
while ((opt = get_opt ()) != EOF)
{
switch (opt)
{
case 'd':
TAO_debug_level++;
break;
case 'n':
n = ACE_OS::atoi (get_opt.optarg);
break;
case '?':
default:
ACE_DEBUG ((LM_DEBUG,
"Usage: %s "
"-d debug"
"-n <num> "
"\n",
argv[0]));
return -1;
}
}
for (int i = 0; i != n; ++i)
{
CORBA::Any any;
#if 0
// @@ TODO @@ This one crashes in deep_free!!!
{
Param_Test::Var_Array var_array;
any <<= Param_Test::Var_Array_forany (var_array);
Param_Test::Var_Array_forany forany;
if (!(any >>= forany))
{
ACE_DEBUG ((LM_DEBUG,
"Failure for Param_Test::Var_Array\n"));
}
Param_Test::Var_Array_var var =
Param_Test::Var_Array_dup (forany.in ());
any <<= Param_Test::Var_Array_forany (var.inout ());
if (!(any >>= forany))
{
ACE_DEBUG ((LM_DEBUG,
"Failure for Param_Test::Var_Array[2]\n"));
}
}
#endif /* 0 */
{
CORBA::Object_var obj =
orb->string_to_object ("corbaloc:iiop:localhost:1234/Foo/Bar",
ACE_TRY_ENV);
ACE_TRY_CHECK;
Param_Test_var param_test =
Param_Test::_unchecked_narrow (obj.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
TAO_Stub *stub = param_test->_stubobj ();
stub->type_id = CORBA::string_dup ("IDL:Param_Test:1.0");
any <<= param_test.in ();
Param_Test_ptr o;
if (!(any >>= o))
{
ACE_DEBUG ((LM_DEBUG,
"Cannot extract Param_Test (oh the horror)\n"));
}
CORBA::Boolean equiv =
param_test->_is_equivalent (o, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (!equiv)
{
ACE_DEBUG ((LM_DEBUG,
"Mismatched Param_Test extraction\n"));
}
CORBA::Object_var other;
if (!(any >>= CORBA::Any::to_object (other.inout ())))
{
ACE_DEBUG ((LM_DEBUG,
"Cannot extract Param_Test as Object\n"));
}
}
{
CORBA::Short i = 123;
any <<= i;
CORBA::Short o;
if (!(any >>= o)
|| i != o)
{
ACE_DEBUG ((LM_DEBUG,
"Failure for CORBA::Short (%d,%d)\n",
i, o));
}
}
{
CORBA::Long i = 123;
any <<= i;
CORBA::Long o;
if (!(any >>= o)
|| i != o)
{
ACE_DEBUG ((LM_DEBUG,
"Failure for CORBA::Long (%d,%d)\n",
i, o));
}
}
{
CORBA::ULongLong i = 123;
any <<= i;
CORBA::ULongLong o;
if (!(any >>= o)
|| i != o)
{
#if defined (ACE_LACKS_LONGLONG_T)
char bufferi[32];
char buffero[32];
ACE_DEBUG ((LM_DEBUG,
"Failure for CORBA::ULongLong (%s,%s)\n",
i.as_string (bufferi),
o.as_string (buffero)));
#else
ACE_DEBUG ((LM_DEBUG,
"Failure for CORBA::ULongLong (%Q,%Q)\n",
i, o));
#endif
}
}
{
CORBA::Double i = 123;
any <<= i;
CORBA::Double o;
if (!(any >>= o)
|| i != o)
{
ACE_DEBUG ((LM_DEBUG,
"Failure for CORBA::Double (%f,%f)\n",
i, o));
}
}
{
CORBA::Any i;
i <<= CORBA::Short (123);
any <<= i;
const CORBA::Any *o;
CORBA::Short oo;
if (!(any >>= o)
|| !(*o >>= oo)
|| 123 != oo)
{
ACE_DEBUG ((LM_DEBUG,
"Failure for CORBA::Any (%d)\n",
oo));
}
}
{
const char i[] = "123";
any <<= i;
const char *o;
if (!(any >>= o)
|| ACE_OS::strcmp (i, o) != 0)
{
ACE_DEBUG ((LM_DEBUG,
"Failure for char* (%s,%s)\n",
i, o));
}
}
}
}
ACE_CATCHANY
{
ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Basic_Types");
return 1;
}
ACE_ENDTRY;
return 0;
}
|
//===----------------------- algorithm.cpp --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "algorithm"
#ifdef NO_AINGLE_WASM
#include "random"
#include "mutex"
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
template void __sort<__less<char>&, char*>(char*, char*, __less<char>&);
template void __sort<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&);
template void __sort<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&);
template void __sort<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&);
template void __sort<__less<short>&, short*>(short*, short*, __less<short>&);
template void __sort<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&);
template void __sort<__less<int>&, int*>(int*, int*, __less<int>&);
template void __sort<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&);
template void __sort<__less<long>&, long*>(long*, long*, __less<long>&);
template void __sort<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&);
template void __sort<__less<long long>&, long long*>(long long*, long long*, __less<long long>&);
template void __sort<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&);
template void __sort<__less<float>&, float*>(float*, float*, __less<float>&);
template void __sort<__less<double>&, double*>(double*, double*, __less<double>&);
template void __sort<__less<long double>&, long double*>(long double*, long double*, __less<long double>&);
template bool __insertion_sort_incomplete<__less<char>&, char*>(char*, char*, __less<char>&);
template bool __insertion_sort_incomplete<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&);
template bool __insertion_sort_incomplete<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&);
template bool __insertion_sort_incomplete<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&);
template bool __insertion_sort_incomplete<__less<short>&, short*>(short*, short*, __less<short>&);
template bool __insertion_sort_incomplete<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&);
template bool __insertion_sort_incomplete<__less<int>&, int*>(int*, int*, __less<int>&);
template bool __insertion_sort_incomplete<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&);
template bool __insertion_sort_incomplete<__less<long>&, long*>(long*, long*, __less<long>&);
template bool __insertion_sort_incomplete<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&);
template bool __insertion_sort_incomplete<__less<long long>&, long long*>(long long*, long long*, __less<long long>&);
template bool __insertion_sort_incomplete<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&);
template bool __insertion_sort_incomplete<__less<float>&, float*>(float*, float*, __less<float>&);
template bool __insertion_sort_incomplete<__less<double>&, double*>(double*, double*, __less<double>&);
template bool __insertion_sort_incomplete<__less<long double>&, long double*>(long double*, long double*, __less<long double>&);
template unsigned __sort5<__less<long double>&, long double*>(long double*, long double*, long double*, long double*, long double*, __less<long double>&);
#ifdef NO_AINGLE_WASM
#ifndef _LIBCPP_HAS_NO_THREADS
_LIBCPP_SAFE_STATIC static __libcpp_mutex_t __rs_mut = _LIBCPP_MUTEX_INITIALIZER;
#endif
unsigned __rs_default::__c_ = 0;
__rs_default::__rs_default()
{
#ifndef _LIBCPP_HAS_NO_THREADS
__libcpp_mutex_lock(&__rs_mut);
#endif
__c_ = 1;
}
__rs_default::__rs_default(const __rs_default&)
{
++__c_;
}
__rs_default::~__rs_default()
{
#ifndef _LIBCPP_HAS_NO_THREADS
if (--__c_ == 0)
__libcpp_mutex_unlock(&__rs_mut);
#else
--__c_;
#endif
}
__rs_default::result_type
__rs_default::operator()()
{
static mt19937 __rs_g;
return __rs_g();
}
__rs_default
__rs_get()
{
return __rs_default();
}
#endif
_LIBCPP_END_NAMESPACE_STD
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; ScanMem16.Asm
;
; Abstract:
;
; ScanMem16 function
;
; Notes:
;
; The following BaseMemoryLib instances share the same version of this file:
;
; BaseMemoryLibRepStr
; BaseMemoryLibMmx
; BaseMemoryLibSse2
;
;------------------------------------------------------------------------------
.686
.model flat,C
.code
;------------------------------------------------------------------------------
; CONST VOID *
; EFIAPI
; InternalMemScanMem16 (
; IN CONST VOID *Buffer,
; IN UINTN Length,
; IN UINT16 Value
; );
;------------------------------------------------------------------------------
InternalMemScanMem16 PROC USES edi
mov ecx, [esp + 12]
mov edi, [esp + 8]
mov eax, [esp + 16]
repne scasw
lea eax, [edi - 2]
cmovnz eax, ecx
ret
InternalMemScanMem16 ENDP
END
|
; A190995: Fibonacci sequence beginning 9, 7.
; 9,7,16,23,39,62,101,163,264,427,691,1118,1809,2927,4736,7663,12399,20062,32461,52523,84984,137507,222491,359998,582489,942487,1524976,2467463,3992439,6459902,10452341,16912243,27364584,44276827,71641411,115918238,187559649,303477887,491037536,794515423,1285552959,2080068382,3365621341,5445689723,8811311064,14257000787,23068311851,37325312638,60393624489,97718937127,158112561616,255831498743,413944060359,669775559102,1083719619461,1753495178563,2837214798024,4590709976587,7427924774611,12018634751198,19446559525809,31465194277007,50911753802816,82376948079823,133288701882639,215665649962462,348954351845101,564620001807563,913574353652664,1478194355460227,2391768709112891,3869963064573118,6261731773686009,10131694838259127,16393426611945136,26525121450204263,42918548062149399,69443669512353662,112362217574503061,181805887086856723,294168104661359784,475973991748216507,770142096409576291,1246116088157792798,2016258184567369089,3262374272725161887,5278632457292530976,8541006730017692863,13819639187310223839,22360645917327916702,36180285104638140541,58540931021966057243,94721216126604197784,153262147148570255027,247983363275174452811,401245510423744707838,649228873698919160649,1050474384122663868487,1699703257821583029136,2750177641944246897623
mov $1,9
mov $3,7
lpb $0
sub $0,1
mov $2,$1
mov $1,$3
add $3,$2
lpe
mov $0,$1
|
<%
from pwnlib.shellcraft.mips.linux import syscall
%>
<%page args="algorithm"/>
<%docstring>
Invokes the syscall sched_get_priority_max. See 'man 2 sched_get_priority_max' for more information.
Arguments:
algorithm(int): algorithm
</%docstring>
${syscall('SYS_sched_get_priority_max', algorithm)}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1771a, %rsi
lea addresses_normal_ht+0x1d85a, %rdi
nop
nop
nop
nop
dec %r12
mov $14, %rcx
rep movsw
nop
nop
nop
nop
nop
xor $14703, %r14
pop %rsi
pop %rdi
pop %rcx
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r8
push %rax
push %rbx
push %rcx
push %rsi
// Faulty Load
lea addresses_normal+0xa85a, %rcx
nop
nop
nop
cmp $49165, %r8
movups (%rcx), %xmm0
vpextrq $0, %xmm0, %r12
lea oracles, %rax
and $0xff, %r12
shlq $12, %r12
mov (%rax,%r12,1), %r12
pop %rsi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}}
{'34': 18760}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
[ORG 0x100]
[BITS 16]
start: xor ebx,ebx
mov bx,ds ; BX=segment
shl ebx,4 ; BX="linear" address of segment base
mov eax,ebx
mov [gdt2 + 2],ax ; set base address of 32-bit segments
mov [gdt3 + 2],ax
mov [gdt4 + 2],ax ; set base address of 16-bit segments
mov [gdt5 + 2],ax
shr eax,16
mov [gdt2 + 4],al
mov [gdt3 + 4],al
mov [gdt4 + 4],al
mov [gdt5 + 4],al
mov [gdt2 + 7],ah
mov [gdt3 + 7],ah
mov [gdt4 + 7],ah
mov [gdt5 + 7],ah
lea eax,[gdt + ebx] ; EAX=PHYSICAL address of gdt
mov [gdtr + 2],eax
cli
xor ax,ax
mov es,ax
mov edx,[es:0x0D * 4] ; INT 0Dh vector -> EDX
mov [es:0x0D * 4 + 2],cs
lea ax,[trap]
mov [es:0x0D * 4],ax
mov ebx,0xB809A ; ES still 0
mov byte [es:ebx],'R' ; 'R' in upper right corner of screen
mov ax,cs
mov [RealModeCS],ax
lea ax,[do_rm]
mov [RealModeIP],ax
mov ax,0xB800
mov es,ax
lgdt [gdtr]
mov eax,cr0
or al,1
mov cr0,eax
lea si,[msg0] ; -> "still in real mode!"
mov di,(80 * 1 + 2) * 2 ; row 1, column 2
mov cx,38
cld
rep movsb
jmp SYS_CODE_SEL:do_pm ; jumps to do_pm
trap: mov ax,0xB800
mov fs,ax
mov byte [fs:0x9C],'!'
pop ax ; point stacked IP beyond...
add ax,5 ; ...the offending instruction
push ax
iret
[BITS 32]
do_pm:
xor edi,edi
xor esi,esi
lea si,[msg1] ; -> "ES, DS still real mode!"
mov di,(80 * 2 + 3) * 2 ; row 2, column 3
mov ecx,46
cld
rep movsb
mov ax,SYS_DATA_SEL
mov ds,ax
mov ss,ax
mov ax,LINEAR_SEL
mov es,ax
mov byte [es:dword 0xB8000],'0'
mov byte [es:dword 0xB8002],'1'
mov byte [es:dword 0xB8004],'2'
mov byte [es:dword 0xB8006],'3'
lea esi,[msg2] ; -> "Finally in protected mode!"
mov edi,0xB8000 + (80 * 3 + 4) * 2 ; row 3, column 4
mov ecx,52
cld
rep movsb
jmp REAL_CODE_SEL:do_16
[BITS 16]
do_16:
mov ax,REAL_DATA_SEL
mov ss,ax
mov ds,ax ; leave ES alone
mov eax,cr0
and al,0xFE
mov cr0,eax
jmp far [RealModeIP]
[BITS 16]
do_rm: mov byte [es:dword 0xB8008],'4'
xor ax,ax
mov es,ax
mov byte [es:dword 0xB800A],'5'
lea esi,[msg3] ; -> "ES, DS still protected mode!"
mov edi,0xB8000 + (80 * 4 + 5) * 2 ; row 4, column 5
mov ecx,56
cld
a32 ; same as 'db 0x67'
rep movsb
mov ax,cs
mov ds,ax
mov ss,ax
mov ax,0xB800
mov es,ax
lea si,[msg4] ; -> "back to BORING old real mode"
mov di,(80 * 5 + 6) * 2 ; row 5, column 6
mov cx,56
cld
rep movsb
xor ax,ax
mov es,ax
mov [es:0x0D * 4],edx ; EDX -> INT 0x0D vector
sti
mov ax,0x4C00
int 0x21
RealModeIP:
dw 0
RealModeCS:
dw 0
msg0: db "s t i l l i n r e a l m o d e ! "
msg1: db "E S , D S s t i l l r e a l m o d e ! "
msg2: db "F i n a l l y i n p r o t e c t e d m o d e ! "
msg3: db "E S , D S s t i l l p r o t e c t e d m o d e ! "
msg4: db "b a c k t o B O R I N G o l d r e a l m o d e "
gdtr: dw gdt_end - gdt - 1 ; GDT limit
dd gdt ; (GDT base gets set above)
gdt: dw 0 ; limit 15:0
dw 0 ; base 15:0
db 0 ; base 23:16
db 0 ; type
db 0 ; limit 19:16, flags
db 0 ; base 31:24
LINEAR_SEL equ $-gdt
dw 0xFFFF ; limit 0xFFFFF
dw 0 ; base 0
db 0
db 0x92 ; present, ring 0, data, expand-up, writable
db 0xCF ; page-granular, 32-bit
db 0
SYS_CODE_SEL equ $-gdt
gdt2: dw 0xFFFF ; limit 0xFFFFF
dw 0 ; (base gets set above)
db 0
db 0x9A ; present, ring 0, code, non-conforming, readable
db 0xCF ; page-granular, 32-bit
db 0
SYS_DATA_SEL equ $-gdt
gdt3: dw 0xFFFF ; limit 0xFFFFF
dw 0 ; (base gets set above)
db 0
db 0x92 ; present, ring 0, data, expand-up, writable
db 0xCF ; page-granular, 32-bit
db 0
REAL_CODE_SEL equ $-gdt
gdt4: dw 0xFFFF
dw 0 ; (base gets set above)
db 0
db 0x9A ; present, ring 0, code, non-conforming, readable
db 0 ; byte-granular, 16-bit
db 0
REAL_DATA_SEL equ $-gdt
gdt5: dw 0xFFFF
dw 0 ; (base gets set above)
db 0
db 0x92 ; present, ring 0, data, expand-up, writable
db 0 ; byte-granular, 16-bit
db 0
gdt_end:
|
.global s_prepare_buffers
s_prepare_buffers:
push %r14
push %r8
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x1a260, %r8
nop
sub $14020, %rbx
mov $0x6162636465666768, %rsi
movq %rsi, (%r8)
nop
nop
inc %rdx
lea addresses_D_ht+0x16c60, %rbx
clflush (%rbx)
and $62625, %rsi
movb (%rbx), %dl
nop
nop
nop
dec %rbp
lea addresses_normal_ht+0x1adac, %r14
nop
nop
nop
nop
nop
add $2721, %r9
mov (%r14), %bx
nop
and $59234, %rbp
lea addresses_WC_ht+0x3c60, %r8
cmp $53145, %rbx
movl $0x61626364, (%r8)
nop
nop
nop
cmp $19381, %r9
lea addresses_D_ht+0x1825c, %rsi
lea addresses_WT_ht+0x1e860, %rdi
nop
nop
dec %rbx
mov $112, %rcx
rep movsb
nop
cmp %rbp, %rbp
lea addresses_A_ht+0xdc60, %rdx
nop
nop
nop
inc %r14
movw $0x6162, (%rdx)
nop
nop
nop
nop
and %r9, %r9
lea addresses_normal_ht+0x5cc, %r14
nop
nop
nop
nop
nop
add $21416, %rcx
vmovups (%r14), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $1, %xmm4, %rdx
sub $65063, %r9
lea addresses_UC_ht+0xb562, %r8
nop
nop
nop
sub $47389, %r14
movw $0x6162, (%r8)
nop
and $25413, %rsi
lea addresses_A_ht+0x1ca78, %rdx
clflush (%rdx)
nop
nop
nop
nop
xor %r8, %r8
mov $0x6162636465666768, %r9
movq %r9, %xmm6
and $0xffffffffffffffc0, %rdx
movntdq %xmm6, (%rdx)
inc %rsi
lea addresses_WT_ht+0x3c26, %rsi
lea addresses_UC_ht+0x1aaa4, %rdi
nop
nop
nop
nop
nop
add %r9, %r9
mov $72, %rcx
rep movsq
nop
nop
cmp %r14, %r14
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r8
pop %r14
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r9
push %rbx
push %rcx
// Store
mov $0x478b1c0000000460, %r11
nop
nop
nop
sub $55317, %rcx
mov $0x5152535455565758, %r9
movq %r9, (%r11)
nop
nop
add $55548, %r13
// Faulty Load
mov $0x478b1c0000000460, %r12
nop
nop
nop
sub $11585, %rcx
mov (%r12), %r13d
lea oracles, %r9
and $0xff, %r13
shlq $12, %r13
mov (%r9,%r13,1), %r13
pop %rcx
pop %rbx
pop %r9
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': True, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_NC', 'same': True, 'AVXalign': False, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_NC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 6}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': True, 'type': 'addresses_D_ht', 'same': True, 'AVXalign': False, 'congruent': 6}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 0}, 'dst': {'same': True, 'type': 'addresses_WT_ht', 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': True, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': True, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 0}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 2}}
{'e0': 3, '00': 241, '58': 21585}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 00 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; A144876: Maximal number of distinct polyominoes into which an n X n square can be divided.
; Submitted by Jon Maiga
; 1,2,4,5,8,10,13,16,19,22,26,30,34,38
mov $2,$0
mul $0,2
mov $1,$0
lpb $1
pow $0,2
mul $1,2
mov $3,$1
mov $1,1
mul $3,2
lpe
add $0,$3
mul $0,2
div $0,63
add $0,$2
add $0,1
|
START:
NOP
LI R1 0XBF
SLL R1 R1 0X00
LI R3 0XBF
SLL R3 R3 0X00
ADDIU R3 0X02
MFPC R7
ADDIU R7 0X02
B TESTR
NOP
LW R3 R2 0x00
MFPC R7
ADDIU R7 0X02
B TESTW
NOP
SW R1 R2 0x00
B START
NOP
;测试8251是否能写
TESTW:
LI R6 0x00BF
SLL R6 R6 0x0000
ADDIU R6 0x0001
LW R6 R0 0x0000
LI R6 0x0001
AND R0 R6
BEQZ R0 TESTW ;BF01&1=0 则等待
NOP
JR R7
NOP
;测试键盘是否能读
TESTR:
LI R6 0x00BF
SLL R6 R6 0x0000
ADDIU R6 0x0003
LW R6 R0 0x0000
LI R6 0x0001
AND R0 R6
BEQZ R0 TESTR ;BF01&2=0 则等待
NOP
JR R7
NOP
|
; A225007: Number of n X 5 0..1 arrays with rows unimodal and columns nondecreasing.
; 16,86,296,791,1792,3612,6672,11517,18832,29458,44408,64883,92288,128248,174624,233529,307344,398734,510664,646415,809600,1004180,1234480,1505205,1821456,2188746,2613016,3100651,3658496,4293872,5014592,5828977
mov $2,$0
mov $3,$0
add $3,1
lpb $3
mov $0,$2
sub $3,1
sub $0,$3
mul $0,2
add $0,2
mov $4,1
mov $5,4
add $5,$0
bin $5,4
lpb $0
sub $0,2
pow $0,2
add $5,$4
lpe
add $1,$5
lpe
|
MOV E, 00000001b
ADD D, E |
importbin k9.bin 0 5400 k0
importbin k8.bin 0 5400 k1
importbin k7.bin 0 5400 k2
importbin k6.bin 0 5400 k3
importbin k5.bin 0 5400 k4
importbin k4.bin 0 5400 k5
importbin k3.bin 0 5400 k6
importbin k2.bin 0 5400 k7
importbin k1.bin 0 5400 k8
importbin k0.bin 0 5400 k9
init:
cls
spr 0x5A3C ; 120x90
bgc 0x2 ; gray
ldi r0, 10
ldi r2, 100
ldi r3, 75
loop:
subi r0, 1
jc end
mov r1, r0
muli r1, 5400
addi r1, k0
drw r2, r3, r1
wait:
ldi r4, 10
wait_loop:
subi r4, 1
jc wait_end
vblnk
jmp wait_loop
wait_end:
jmp loop
end:
ldi r4, 30
end_loop:
subi r4, 1
jc init
vblnk
jmp end_loop |
Name: zel_chra.asm
Type: file
Size: 53641
Last-Modified: '2016-05-13T04:36:32Z'
SHA-1: A8F804975C1F2FBEFDA28299E02E38345F0015AF
Description: null
|
SECTION code_clib
PUBLIC generic_console_cls
PUBLIC generic_console_printc
PUBLIC generic_console_scrollup
PUBLIC generic_console_set_ink
PUBLIC generic_console_set_paper
PUBLIC generic_console_set_attribute
PUBLIC generic_console_xypos
EXTERN CONSOLE_COLUMNS
EXTERN CONSOLE_ROWS
;EXTERN generic_console_font32
;EXTERN generic_console_udg32
;EXTERN generic_console_flags
;EXTERN conio_map_colour
INCLUDE "target/m100/def/romcalls.def"
generic_console_set_paper:
generic_console_set_attribute:
ret
generic_console_set_ink:
ret
generic_console_scrollup:
push bc
push de
ld bc,$0808
call generic_console_xypos
ld a,13
ROMCALL
defw CHROUT
ld a,10
ROMCALL
defw CHROUT
pop de
pop bc
ret
generic_console_cls:
ROMCALL
defw CLS
ret
; c = x
; b = y
; a = d character to print
; e = raw
generic_console_printc:
call generic_console_xypos
ld a,d
ROMCALL
defw CHROUT
ret
; Entry: b = row
; c = column
; Exit: hl = address
generic_console_xypos:
ld a,c
inc a
ld ($f63a),a ; CSRY
ld a,b
inc a
ld ($f639),a ; CSRX
ret
|
; A122512: Expansion of 1/(1 - x^2 - 2 x^3 + x^4).
; Submitted by Christian Krause
; 1,0,1,2,0,4,3,2,11,4,12,24,9,44,45,38,124,84,155,294,199,520,632,624,1473,1368,2089,3690,3352,6500,8643,9514,18291,20300,28676,47368,50985,84420,117045,139022,234900,288692,395899,619470,738383,1122576,1581424
mov $1,1
lpb $0
sub $0,1
add $2,$1
add $4,1
add $3,$4
add $1,$3
add $4,$2
sub $2,$4
add $3,$4
sub $4,$3
add $3,$4
lpe
mov $0,$2
add $0,1
|
; A245328: Denominators in recursive bijection from positive integers to positive rationals (the bijection is f(1) = 1, f(2n) = 1/(f(n)+1), f(2n+1) = f(n)+1).
; Submitted by Jamie Morken(s4)
; 1,2,1,3,2,3,1,5,3,5,2,4,3,4,1,8,5,8,3,7,5,7,2,7,4,7,3,5,4,5,1,13,8,13,5,11,8,11,3,12,7,12,5,9,7,9,2,11,7,11,4,10,7,10,3,9,5,9,4,6,5,6,1,21,13,21,8,18,13,18,5,19,11,19,8,14,11,14,3,19,12,19,7,17,12,17,5,16,9,16,7,11,9,11,2,18,11,18,7,15
mul $0,2
add $0,2
mov $2,1
lpb $0
div $0,2
sub $2,$3
mov $3,9
add $3,$0
mod $3,2
mov $4,$2
add $2,$1
mul $3,$4
add $1,$3
lpe
mov $0,$1
|
; THIS PROGRAM IS TO CALCULATE WEIGHTED SUM
; WHEN A VALUE IS 2 AND WEIGHT IS 6 THEN
; WEIGHTED SUM IS 2*6 = 12
; TOTAL SUM MUST BE LESS THAN 10 TO SEE OUTPUT CORRECTLY
.MODEL SMALL
.STACK 100H
.DATA
VALUE DB ?
DATA1 DB ?
MSG DB 0AH, 0DH, "WEIGHTED SUM: $",
SUM DW ?
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
MOV CX, 3
COUNT_GRADE:
MOV AH, 1
INT 21H
SUB AL, 48
MOV VALUE, AL
INT 21H
SUB AL, 48
MOV DATA1, AL
MOV AL, VALUE
MUL DATA1
ADD SUM, AX
DEC CX
JNZ COUNT_GRADE
MOV AH, 9
LEA DX, MSG
INT 21H
MOV AH, 2
MOV DX, SUM
ADD DX, '0'
INT 21H
; RETURN TO OS
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAIN |
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r14
push %r8
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x152ed, %r12
nop
add $45369, %rax
mov $0x6162636465666768, %r13
movq %r13, (%r12)
nop
add %r14, %r14
lea addresses_normal_ht+0x1d71d, %r12
nop
nop
nop
inc %r14
movb (%r12), %r8b
nop
dec %r12
lea addresses_D_ht+0x38fd, %rsi
lea addresses_WC_ht+0x373d, %rdi
nop
nop
nop
nop
nop
and %r14, %r14
mov $107, %rcx
rep movsq
nop
nop
nop
xor $28001, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r14
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r14
push %r15
push %rax
push %rbx
push %rdi
// Store
lea addresses_D+0x2f3d, %rdi
cmp $1367, %r14
mov $0x5152535455565758, %r15
movq %r15, %xmm5
vmovups %ymm5, (%rdi)
nop
nop
xor $15875, %r14
// Load
lea addresses_WC+0x19ae5, %r14
nop
nop
nop
nop
nop
add $12488, %rbx
movb (%r14), %r11b
nop
nop
xor $5964, %r14
// Store
lea addresses_A+0x191fd, %rdi
nop
nop
nop
inc %r11
movw $0x5152, (%rdi)
and $51706, %r10
// Store
lea addresses_WT+0x130dd, %rax
sub %r11, %r11
movb $0x51, (%rax)
nop
nop
add %rdi, %rdi
// Load
lea addresses_D+0x1e1bd, %r15
nop
nop
cmp %rdi, %rdi
mov (%r15), %bx
nop
nop
xor %rax, %rax
// Faulty Load
lea addresses_normal+0xcf3d, %r11
nop
sub $42657, %r15
movups (%r11), %xmm4
vpextrq $0, %xmm4, %r14
lea oracles, %rax
and $0xff, %r14
shlq $12, %r14
mov (%rax,%r14,1), %r14
pop %rdi
pop %rbx
pop %rax
pop %r15
pop %r14
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 6, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 5, 'same': False, 'type': 'addresses_WT'}, 'OP': 'STOR'}
{'src': {'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 7, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
; A177756: Number of ways to place 3 nonattacking bishops on an n X n toroidal board.
; 0,0,6,128,600,2688,7350,19968,42336,89600,163350,297600,490776,809088,1242150,1906688,2774400,4036608,5633766,7862400,10613400,14326400,18818646,24718848,31740000,40754688,51333750,64658048,80110296,99254400,121230150,148070400,178607616,215441408,257022150,306626688,362237400,427932288,501127926,586841600,681813600,792153600,913801686,1054128768,1208136600,1384642688,1577557350,1797347328,2036662656,2307840000,2602083750,2933840000,3292664856,3695372928,4129651350,4614962688,5136885600,5717831168,6341010486,7032105600,7771680600,8589033600,9461781126,10423205888,11447654400,12572786688,13769334150,15079751808,16470787416,17990134400,19600164150,21354278400,23210054496,25227099648,27357753750,29668354688,32105535000,34742917248,37520929446,40521062400,43677014400,47078758400,50652708966,54497966208,58533077400,62866946688,67409640150,72280575488,77380692576,82840665600,88551631350,94656297600,101035288536,107844157568,114952273350,122528882688,130431321600,138843414528,147609652806,156929360000
pow $0,2
mov $2,$0
sub $2,1
mov $1,$2
pow $1,2
div $2,4
add $2,1
mul $1,$2
div $1,3
mul $1,2
mov $0,$1
|
SECTION code_clib
PUBLIC pixeladdress
EXTERN base_graphics
;
; $Id: pixladdr.asm,v 1.7 2016/04/23 21:05:46 dom Exp $
;
; ******************************************************************
;
; Get absolute pixel address in map of virtual (x,y) coordinate.
;
; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995
;
; in: hl = (x,y) coordinate of pixel (h,l)
;
; out: de = address of pixel byte
; a = bit number of byte where pixel is to be placed
; fz = 1 if bit number is 0 of pixel position
;
; registers changed after return:
; ......hl/ixiy same
; afbcde../.... different
;
.pixeladdress
ld b,l
srl b
srl b
srl b ; linedist = y div 8 * 256
ld a,h
and @11111000 ; rowdist = x div 8 * 8
ld c,a ; bc = linedist + rowdist
ld a,l
and @00000111 ; coldist = y mod 8
ld de,(base_graphics) ; pointer to base of graphics area
ld e,a ; coldist = graphicsarea + coldist
ld a,h
ex de,hl
add hl,bc ; bytepos = linedist + rowdist + coldist
ex de,hl
and @00000111 ; a = x mod 8
xor @00000111 ; a = 7 - a
ret
|
/*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <type_traits>
#include <boost/preprocessor/punctuation/remove_parens.hpp>
#define GT_META_DELEGATE_TO_LAZY(fun, signature, args) \
template <BOOST_PP_REMOVE_PARENS(signature)> \
using fun = typename lazy::fun<BOOST_PP_REMOVE_PARENS(args)>::type
/**
* NVCC bug workaround: sizeof... works incorrectly within template alias context.
*/
#if defined(__CUDACC_VER_MAJOR__) && \
(__CUDACC_VER_MAJOR__ < 10 || (__CUDACC_VER_MAJOR__ == 10 && __CUDACC_VER_MINOR__ < 2))
namespace gridtools {
namespace meta {
template <class... Ts>
struct sizeof_3_dots : std::integral_constant<std::size_t, sizeof...(Ts)> {};
} // namespace meta
} // namespace gridtools
#define GT_SIZEOF_3_DOTS(Ts) ::gridtools::meta::sizeof_3_dots<Ts...>::value
#else
#define GT_SIZEOF_3_DOTS(Ts) sizeof...(Ts)
#endif
|
; A305889: a(n) = 3*a(n-2) + a(n-4), a(0)=a(1)=0, a(2)=1, a(3)=2.
; Submitted by Jamie Morken(s4)
; 0,0,1,2,3,6,10,20,33,66,109,218,360,720,1189,2378,3927,7854,12970,25940,42837,85674,141481,282962,467280,934560,1543321,3086642,5097243,10194486,16835050,33670100,55602393,111204786,183642229,367284458,606529080,1213058160,2003229469,4006458938,6616217487,13232434974,21851881930,43703763860,72171863277,144343726554,238367471761,476734943522,787274278560,1574548557120,2600190307441,5200380614882,8587845200883,17175690401766,28363725910090,56727451820180,93679022931153,187358045862306
sub $0,1
lpb $0
sub $0,1
mov $1,1
add $1,$2
add $3,$2
sub $3,$0
add $2,$3
trn $2,$0
add $2,$1
sub $1,$0
mov $3,$1
lpe
mov $0,$3
|
; A203476: v(n+1)/v(n), where v=A203475.
; Submitted by Christian Krause
; 5,130,8500,1051076,211255200,62840245000,25959932960000,14224928867370000,9986120745657472000,8740787543400204500000,9333385482079885824000000,11942338721669302523305000000,18038821394494464638896640000000
add $0,1
mov $3,$0
add $0,1
pow $0,2
mov $2,1
mov $4,1
lpb $3
mul $1,$3
mul $4,$3
add $1,$4
mul $1,$3
mul $2,$0
mov $4,$2
add $2,$1
sub $3,1
lpe
mov $0,$2
|
; A136691: Final nonzero digit of n! in base 4.
; Submitted by Jon Maiga
; 1,1,2,2,2,2,1,3,2,2,3,1,3,3,2,2,2,2,3,1,1,1,2,2,3,3,2,2,2,2,1,3,2,2,3,1,1,1,2,2,1,1,2,2,2,2,3,1,3,3,2,2,2,2,3,1,2,2,3,1,3,3,2,2,2,2,3,1,1,1,2,2,1,1,2,2,2,2,3,1,1,1,2,2,2,2,1,3,2,2,1,3,1,1,2,2,3,3,2,2
trn $0,1
seq $0,55204 ; Squarefree part of n!: n! divided by its largest square divisor.
mod $0,4
|
; A168992: Number of reduced words of length n in Coxeter group on 27 generators S_i with relations (S_i)^2 = (S_i S_j)^23 = I.
; 1,27,702,18252,474552,12338352,320797152,8340725952,216858874752,5638330743552,146596599332352,3811511582641152,99099301148669952,2576581829865418752,66991127576500887552,1741769316989023076352
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,26
lpe
mov $0,$2
div $0,26
|
/*
* false_driven_enumerator.hpp
*
* Copyright (c) 2018, Ueda Laboratory LMNtal Group
* <lmntal@ueda.info.waseda.ac.jp> All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the Ueda Laboratory LMNtal Group nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SLIM_VM_INTERPRET_FALSE_DRIVEN_ENUMERATOR_HPP
#define SLIM_VM_INTERPRET_FALSE_DRIVEN_ENUMERATOR_HPP
#include "../react_context.hpp"
#include "interpreter.hpp"
#include "verifier/runtime_status.h"
/**
* 失敗駆動ループの候補を返すためのfunctional object
*/
template <typename InputIterator, typename value_type>
struct false_driven_enumerator_get_candidate;
template <typename InputIterator>
struct false_driven_enumerator_get_candidate<InputIterator, LmnRegister> {
LmnRegister operator()(InputIterator &iter) { return (*iter); }
};
template <typename InputIterator>
struct false_driven_enumerator_get_candidate<InputIterator,
std::function<LmnRegister(void)>> {
LmnRegister operator()(InputIterator &iter) { return (*iter)(); }
};
/**
* 失敗駆動ループの実装の
* スタックフレームがポップされるときに呼ばれるコールバックで
* 必要なら(失敗駆動ループするなら)次の候補をレジスタに設定し、スタックに積む
* これ単体では役に立たない!
*/
template <typename InputIterator> struct false_driven_enumerator {
using value_type = typename InputIterator::value_type;
size_t reg_idx;
InputIterator begin;
InputIterator end;
LmnRuleInstr instr;
/**
* コンストラクタ
*
* @param instr ループ時に再開する命令列のアドレス
* @param reg_idx 次の候補を設定するレジスタのインデックス
* @param begin 列挙する候補の最初の要素を指すイテレータ
* @param end 最終候補の次の要素を指すイテレータ
*/
false_driven_enumerator(LmnRuleInstr instr, size_t reg_idx,
InputIterator begin, InputIterator end)
: instr(instr), reg_idx(reg_idx), begin(begin), end(end) {}
slim::vm::interpreter::command_result operator()(slim::vm::interpreter &itr, bool result) {
if(!lmn_env.history_management || record_list.atoms.size() == 0) {
// 成功ならループしないで終了
if (result)
return slim::vm::interpreter::command_result::Success;
// 候補がなくなったら終了
if (this->begin == this->end)
return slim::vm::interpreter::command_result::Failure;
// 命令列の巻き戻し
itr.instr = this->instr;
// 候補を再設定
itr.rc->reg(this->reg_idx) =
false_driven_enumerator_get_candidate<InputIterator, value_type>()(this->begin);
// 次の候補の準備
++this->begin;
} else { // else内が履歴管理用アトムを用いた場合の挙動になる.
int rule_number = record_list.get_rule_number();
if(result) {
if(record_list.get_delete_flag(record_list.get_rule_number())) {
// delete
} else {
record_list.loop_back(rule_number, this->reg_idx);
}
/*
ここを変える(TO DO)
ルールが適用したらループを一回増やすのではなく, アトムが追加されたらループを一回増やすようにしたい-> NEWATOMなどで追加できるが....
--use-swaplinkを用いると, 中間命令でそのようなことが起きないので実行が失敗に終わってしまう. ゆえに放置
*/
record_list.loop_flag[rule_number][reg_idx-1] = true;
return slim::vm::interpreter::command_result::Success;
}
// 候補がなくなったら終了
if(this->begin == this->end) {
if(record_list.get_delete_flag(record_list.get_rule_number())) {
// delete
} else {
if(record_list.loop_flag[rule_number][reg_idx-1]) {
record_list.loop_flag[rule_number][reg_idx-1] = false;
record_list.atoms[rule_number][this->reg_idx-1]->go_head();
return slim::vm::interpreter::command_result::Success;
}
if(this->reg_idx != 1) record_list.atoms[rule_number][this->reg_idx-1]->go_head();
}
return slim::vm::interpreter::command_result::Failure;
}
// 命令列の巻き戻し
itr.instr = this->instr;
// findatomoptを使うときだけiteratorを移動させる
// 候補を再設定
itr.rc->reg(this->reg_idx) =
false_driven_enumerator_get_candidate<InputIterator, value_type>()(this->begin);
// 次の候補の準備
++this->begin;
if(!record_list.get_delete_flag(record_list.get_rule_number())){
record_list.atoms[rule_number][this->reg_idx-1]->record_forward();
while(record_list.atoms[rule_number][this->reg_idx-1]->get_record()->next->record_flag) {
if(this->begin == this->end) {
if(record_list.loop_flag[rule_number][reg_idx-1]) {
record_list.loop_flag[rule_number][reg_idx-1] = false;
record_list.atoms[rule_number][this->reg_idx-1]->go_head();
record_list.start_flag[rule_number] = true;
return slim::vm::interpreter::command_result::Success;
}
if(this->reg_idx != 1) record_list.atoms[rule_number][this->reg_idx-1]->go_head();
return slim::vm::interpreter::command_result::Failure;
}
++this->begin;
record_list.atoms[rule_number][this->reg_idx-1]->record_forward();
}
}
}
profile_backtrack();
return slim::vm::interpreter::command_result::Trial;
}
};
/**
* 既存のイテレータから失敗駆動ループを作る
*/
template <typename InputIterator, typename... Args>
false_driven_enumerator<InputIterator>
make_false_driven_enumerator(slim::vm::interpreter &iter, LmnRuleInstr instr, size_t reg_idx,
InputIterator begin, InputIterator end) {
return false_driven_enumerator<InputIterator>(instr, reg_idx, begin, end);
}
#endif /* SLIM_VM_INTERPRET_FALSE_DRIVEN_ENUMERATOR_HPP */
|
# ------------------------------------------------------------------------------
# Gnu Assembler "Hello World!"
# Writes "Hello, World" to the console using only system calls. Runs on 64-bit
# Linux only. To assemble and run:
#
# gcc -c hello.s && ld hello.o && ./a.out
#
# or
#
# gcc -nostdlib hello.s && ./a.out
# ------------------------------------------------------------------------------
.global _start
.text
_start:
# write(1, message, 13)
mov $1, %rax # system call 1 is write
mov $1, %rdi # file handle 1 is stdout
mov $message, %rsi # address of string to output
mov $13, %rdx # number of bytes
syscall # invoke operating system to do the write
# exit(0)
mov $60, %rax # system call 60 is exit
xor %rdi, %rdi # we want return code 0
syscall # invoke operating system to exit
message:
.ascii "Hello, world\n"
|
; Copyright © 2021, VideoLAN and dav1d authors
; Copyright © 2021, Two Orioles, LLC
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this
; list of conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
; ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%include "config.asm"
%include "ext/x86/x86inc.asm"
SECTION_RODATA
; dav1d_obmc_masks[] << 9
obmc_masks: dw 0, 0, 9728, 0, 12800, 7168, 2560, 0
dw 14336, 11264, 8192, 5632, 3584, 1536, 0, 0
dw 15360, 13824, 12288, 10752, 9216, 7680, 6144, 5120
dw 4096, 3072, 2048, 1536, 0, 0, 0, 0
dw 15872, 14848, 14336, 13312, 12288, 11776, 10752, 10240
dw 9728, 8704, 8192, 7168, 6656, 6144, 5632, 4608
dw 4096, 3584, 3072, 2560, 2048, 2048, 1536, 1024
blend_shuf: db 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 2, 3, 2, 3
spel_h_shufA: db 0, 1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 9
spel_h_shufB: db 4, 5, 6, 7, 6, 7, 8, 9, 8, 9, 10, 11, 10, 11, 12, 13
spel_h_shuf2: db 0, 1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7, 8, 9
spel_s_shuf2: db 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7
spel_s_shuf8: db 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15
unpckw: db 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15
rescale_mul: dd 0, 1, 2, 3
resize_shuf: db 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7
db 8, 9, 10, 11, 12, 13, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15
bdct_lb_q: times 8 db 0
times 8 db 4
times 8 db 8
times 8 db 12
pw_2: times 8 dw 2
pw_16: times 4 dw 16
prep_mul: times 4 dw 16
times 8 dw 4
pw_64: times 8 dw 64
pw_256: times 8 dw 256
pw_2048: times 4 dw 2048
bidir_mul: times 4 dw 2048
pw_8192: times 8 dw 8192
pw_27615: times 8 dw 27615
pw_32766: times 8 dw 32766
pw_m512: times 8 dw -512
pd_63: times 4 dd 63
pd_64: times 4 dd 64
pd_512: times 4 dd 512
pd_m524256: times 4 dd -524256 ; -8192 << 6 + 32
pd_0x3ff: times 4 dd 0x3ff
pd_0x4000: times 4 dd 0x4000
pq_0x400000: times 2 dq 0x400000
pq_0x40000000: times 2 dq 0x40000000
pd_65538: times 2 dd 65538
put_bilin_h_rnd: times 4 dw 8
times 4 dw 10
s_8tap_h_rnd: times 2 dd 2
times 2 dd 8
put_s_8tap_v_rnd: times 2 dd 512
times 2 dd 128
s_8tap_h_sh: dd 2, 4
put_s_8tap_v_sh: dd 10, 8
bidir_rnd: times 4 dw -16400
times 4 dw -16388
put_8tap_h_rnd: dd 34, 34, 40, 40
prep_8tap_1d_rnd: times 2 dd 8 - (8192 << 4)
prep_8tap_2d_rnd: times 4 dd 32 - (8192 << 5)
warp8x8_shift: dd 11, 13
warp8x8_rnd1: dd 1024, 1024, 4096, 4096
warp8x8_rnd2: times 4 dw 4096
times 4 dw 16384
warp8x8t_rnd: times 2 dd 16384 - (8192 << 15)
%macro BIDIR_JMP_TABLE 2-*
%xdefine %1_%2_table (%%table - 2*%3)
%xdefine %%base %1_%2_table
%xdefine %%prefix mangle(private_prefix %+ _%1_16bpc_%2)
%%table:
%rep %0 - 2
dd %%prefix %+ .w%3 - %%base
%rotate 1
%endrep
%endmacro
BIDIR_JMP_TABLE avg, ssse3, 4, 8, 16, 32, 64, 128
BIDIR_JMP_TABLE w_avg, ssse3, 4, 8, 16, 32, 64, 128
BIDIR_JMP_TABLE mask, ssse3, 4, 8, 16, 32, 64, 128
BIDIR_JMP_TABLE w_mask_420, ssse3, 4, 8, 16, 32, 64, 128
BIDIR_JMP_TABLE w_mask_422, ssse3, 4, 8, 16, 32, 64, 128
BIDIR_JMP_TABLE w_mask_444, ssse3, 4, 8, 16, 32, 64, 128
BIDIR_JMP_TABLE blend, ssse3, 4, 8, 16, 32
BIDIR_JMP_TABLE blend_v, ssse3, 2, 4, 8, 16, 32
BIDIR_JMP_TABLE blend_h, ssse3, 2, 4, 8, 16, 32, 64, 128
%macro BASE_JMP_TABLE 3-*
%xdefine %1_%2_table (%%table - %3)
%xdefine %%base %1_%2
%%table:
%rep %0 - 2
dw %%base %+ _w%3 - %%base
%rotate 1
%endrep
%endmacro
%xdefine put_ssse3 mangle(private_prefix %+ _put_bilin_16bpc_ssse3.put)
%xdefine prep_ssse3 mangle(private_prefix %+ _prep_bilin_16bpc_ssse3.prep)
BASE_JMP_TABLE put, ssse3, 2, 4, 8, 16, 32, 64, 128
BASE_JMP_TABLE prep, ssse3, 4, 8, 16, 32, 64, 128
%macro SCALED_JMP_TABLE 2-*
%xdefine %1_%2_table (%%table - %3)
%xdefine %%base mangle(private_prefix %+ _%1_16bpc_%2)
%%table:
%rep %0 - 2
dw %%base %+ .w%3 - %%base
%rotate 1
%endrep
%rotate 2
%%dy_1024:
%xdefine %1_%2_dy1_table (%%dy_1024 - %3)
%rep %0 - 2
dw %%base %+ .dy1_w%3 - %%base
%rotate 1
%endrep
%rotate 2
%%dy_2048:
%xdefine %1_%2_dy2_table (%%dy_2048 - %3)
%rep %0 - 2
dw %%base %+ .dy2_w%3 - %%base
%rotate 1
%endrep
%endmacro
SCALED_JMP_TABLE put_8tap_scaled, ssse3, 2, 4, 8, 16, 32, 64, 128
SCALED_JMP_TABLE prep_8tap_scaled, ssse3, 4, 8, 16, 32, 64, 128
cextern mc_subpel_filters
%define subpel_filters (mangle(private_prefix %+ _mc_subpel_filters)-8)
cextern mc_warp_filter
cextern resize_filter
SECTION .text
%if UNIX64
DECLARE_REG_TMP 7
%else
DECLARE_REG_TMP 5
%endif
INIT_XMM ssse3
cglobal put_bilin_16bpc, 4, 7, 0, dst, ds, src, ss, w, h, mxy
%define base t0-put_ssse3
mov mxyd, r6m ; mx
LEA t0, put_ssse3
movifnidn wd, wm
test mxyd, mxyd
jnz .h
mov mxyd, r7m ; my
test mxyd, mxyd
jnz .v
.put:
tzcnt wd, wd
movzx wd, word [base+put_ssse3_table+wq*2]
add wq, t0
movifnidn hd, hm
jmp wq
.put_w2:
mov r4d, [srcq+ssq*0]
mov r6d, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
mov [dstq+dsq*0], r4d
mov [dstq+dsq*1], r6d
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .put_w2
RET
.put_w4:
movq m0, [srcq+ssq*0]
movq m1, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
movq [dstq+dsq*0], m0
movq [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .put_w4
RET
.put_w8:
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
mova [dstq+dsq*0], m0
mova [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .put_w8
RET
.put_w16:
movu m0, [srcq+ssq*0+16*0]
movu m1, [srcq+ssq*0+16*1]
movu m2, [srcq+ssq*1+16*0]
movu m3, [srcq+ssq*1+16*1]
lea srcq, [srcq+ssq*2]
mova [dstq+dsq*0+16*0], m0
mova [dstq+dsq*0+16*1], m1
mova [dstq+dsq*1+16*0], m2
mova [dstq+dsq*1+16*1], m3
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .put_w16
RET
.put_w32:
movu m0, [srcq+16*0]
movu m1, [srcq+16*1]
movu m2, [srcq+16*2]
movu m3, [srcq+16*3]
add srcq, ssq
mova [dstq+16*0], m0
mova [dstq+16*1], m1
mova [dstq+16*2], m2
mova [dstq+16*3], m3
add dstq, dsq
dec hd
jg .put_w32
RET
.put_w64:
movu m0, [srcq+16*0]
movu m1, [srcq+16*1]
movu m2, [srcq+16*2]
movu m3, [srcq+16*3]
mova [dstq+16*0], m0
mova [dstq+16*1], m1
mova [dstq+16*2], m2
mova [dstq+16*3], m3
movu m0, [srcq+16*4]
movu m1, [srcq+16*5]
movu m2, [srcq+16*6]
movu m3, [srcq+16*7]
add srcq, ssq
mova [dstq+16*4], m0
mova [dstq+16*5], m1
mova [dstq+16*6], m2
mova [dstq+16*7], m3
add dstq, dsq
dec hd
jg .put_w64
RET
.put_w128:
add srcq, 16*8
add dstq, 16*8
.put_w128_loop:
movu m0, [srcq-16*8]
movu m1, [srcq-16*7]
movu m2, [srcq-16*6]
movu m3, [srcq-16*5]
mova [dstq-16*8], m0
mova [dstq-16*7], m1
mova [dstq-16*6], m2
mova [dstq-16*5], m3
movu m0, [srcq-16*4]
movu m1, [srcq-16*3]
movu m2, [srcq-16*2]
movu m3, [srcq-16*1]
mova [dstq-16*4], m0
mova [dstq-16*3], m1
mova [dstq-16*2], m2
mova [dstq-16*1], m3
movu m0, [srcq+16*0]
movu m1, [srcq+16*1]
movu m2, [srcq+16*2]
movu m3, [srcq+16*3]
mova [dstq+16*0], m0
mova [dstq+16*1], m1
mova [dstq+16*2], m2
mova [dstq+16*3], m3
movu m0, [srcq+16*4]
movu m1, [srcq+16*5]
movu m2, [srcq+16*6]
movu m3, [srcq+16*7]
add srcq, ssq
mova [dstq+16*4], m0
mova [dstq+16*5], m1
mova [dstq+16*6], m2
mova [dstq+16*7], m3
add dstq, dsq
dec hd
jg .put_w128_loop
RET
.h:
movd m5, mxyd
mov mxyd, r7m ; my
mova m4, [base+pw_16]
pshufb m5, [base+pw_256]
psubw m4, m5
test mxyd, mxyd
jnz .hv
; 12-bit is rounded twice so we can't use the same pmulhrsw approach as .v
mov r6d, r8m ; bitdepth_max
shr r6d, 11
movddup m3, [base+put_bilin_h_rnd+r6*8]
movifnidn hd, hm
sub wd, 8
jg .h_w16
je .h_w8
cmp wd, -4
je .h_w4
.h_w2:
movq m1, [srcq+ssq*0]
movhps m1, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
pmullw m0, m4, m1
psrlq m1, 16
pmullw m1, m5
paddw m0, m3
paddw m0, m1
psrlw m0, 4
movd [dstq+dsq*0], m0
punpckhqdq m0, m0
movd [dstq+dsq*1], m0
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .h_w2
RET
.h_w4:
movq m0, [srcq+ssq*0]
movhps m0, [srcq+ssq*1]
movq m1, [srcq+ssq*0+2]
movhps m1, [srcq+ssq*1+2]
lea srcq, [srcq+ssq*2]
pmullw m0, m4
pmullw m1, m5
paddw m0, m3
paddw m0, m1
psrlw m0, 4
movq [dstq+dsq*0], m0
movhps [dstq+dsq*1], m0
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .h_w4
RET
.h_w8:
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*0+2]
pmullw m0, m4
pmullw m1, m5
paddw m0, m3
paddw m0, m1
movu m1, [srcq+ssq*1]
movu m2, [srcq+ssq*1+2]
lea srcq, [srcq+ssq*2]
pmullw m1, m4
pmullw m2, m5
paddw m1, m3
paddw m1, m2
psrlw m0, 4
psrlw m1, 4
mova [dstq+dsq*0], m0
mova [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .h_w8
RET
.h_w16:
lea srcq, [srcq+wq*2]
lea dstq, [dstq+wq*2]
neg wq
.h_w16_loop0:
mov r6, wq
.h_w16_loop:
movu m0, [srcq+r6*2+ 0]
movu m1, [srcq+r6*2+ 2]
pmullw m0, m4
pmullw m1, m5
paddw m0, m3
paddw m0, m1
movu m1, [srcq+r6*2+16]
movu m2, [srcq+r6*2+18]
pmullw m1, m4
pmullw m2, m5
paddw m1, m3
paddw m1, m2
psrlw m0, 4
psrlw m1, 4
mova [dstq+r6*2+16*0], m0
mova [dstq+r6*2+16*1], m1
add r6, 16
jl .h_w16_loop
add srcq, ssq
add dstq, dsq
dec hd
jg .h_w16_loop0
RET
.v:
shl mxyd, 11
movd m5, mxyd
pshufb m5, [base+pw_256]
movifnidn hd, hm
cmp wd, 4
jg .v_w8
je .v_w4
.v_w2:
movd m0, [srcq+ssq*0]
.v_w2_loop:
movd m1, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
punpcklqdq m2, m0, m1
movd m0, [srcq+ssq*0]
punpcklqdq m1, m0
psubw m1, m2
pmulhrsw m1, m5
paddw m1, m2
movd [dstq+dsq*0], m1
punpckhqdq m1, m1
movd [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .v_w2_loop
RET
.v_w4:
movq m0, [srcq+ssq*0]
.v_w4_loop:
movq m1, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
punpcklqdq m2, m0, m1
movq m0, [srcq+ssq*0]
punpcklqdq m1, m0
psubw m1, m2
pmulhrsw m1, m5
paddw m1, m2
movq [dstq+dsq*0], m1
movhps [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .v_w4_loop
RET
.v_w8:
%if ARCH_X86_64
%if WIN64
push r7
%endif
shl wd, 5
mov r7, srcq
lea r6d, [wq+hq-256]
mov r4, dstq
%else
mov r6, srcq
%endif
.v_w8_loop0:
movu m0, [srcq+ssq*0]
.v_w8_loop:
movu m3, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
psubw m1, m3, m0
pmulhrsw m1, m5
paddw m1, m0
movu m0, [srcq+ssq*0]
psubw m2, m0, m3
pmulhrsw m2, m5
paddw m2, m3
mova [dstq+dsq*0], m1
mova [dstq+dsq*1], m2
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .v_w8_loop
%if ARCH_X86_64
add r7, 16
add r4, 16
movzx hd, r6b
mov srcq, r7
mov dstq, r4
sub r6d, 1<<8
%else
mov dstq, dstmp
add r6, 16
mov hd, hm
add dstq, 16
mov srcq, r6
mov dstmp, dstq
sub wd, 8
%endif
jg .v_w8_loop0
%if WIN64
pop r7
%endif
RET
.hv:
WIN64_SPILL_XMM 8
shl mxyd, 11
mova m3, [base+pw_2]
movd m6, mxyd
mova m7, [base+pw_8192]
pshufb m6, [base+pw_256]
test dword r8m, 0x800
jnz .hv_12bpc
psllw m4, 2
psllw m5, 2
mova m7, [base+pw_2048]
.hv_12bpc:
movifnidn hd, hm
cmp wd, 4
jg .hv_w8
je .hv_w4
.hv_w2:
movddup m0, [srcq+ssq*0]
pshufhw m1, m0, q0321
pmullw m0, m4
pmullw m1, m5
paddw m0, m3
paddw m0, m1
psrlw m0, 2
.hv_w2_loop:
movq m2, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
movhps m2, [srcq+ssq*0]
pmullw m1, m4, m2
psrlq m2, 16
pmullw m2, m5
paddw m1, m3
paddw m1, m2
psrlw m1, 2 ; 1 _ 2 _
shufpd m2, m0, m1, 0x01 ; 0 _ 1 _
mova m0, m1
psubw m1, m2
paddw m1, m1
pmulhw m1, m6
paddw m1, m2
pmulhrsw m1, m7
movd [dstq+dsq*0], m1
punpckhqdq m1, m1
movd [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .hv_w2_loop
RET
.hv_w4:
movddup m0, [srcq+ssq*0]
movddup m1, [srcq+ssq*0+2]
pmullw m0, m4
pmullw m1, m5
paddw m0, m3
paddw m0, m1
psrlw m0, 2
.hv_w4_loop:
movq m1, [srcq+ssq*1]
movq m2, [srcq+ssq*1+2]
lea srcq, [srcq+ssq*2]
movhps m1, [srcq+ssq*0]
movhps m2, [srcq+ssq*0+2]
pmullw m1, m4
pmullw m2, m5
paddw m1, m3
paddw m1, m2
psrlw m1, 2 ; 1 2
shufpd m2, m0, m1, 0x01 ; 0 1
mova m0, m1
psubw m1, m2
paddw m1, m1
pmulhw m1, m6
paddw m1, m2
pmulhrsw m1, m7
movq [dstq+dsq*0], m1
movhps [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .hv_w4_loop
RET
.hv_w8:
%if ARCH_X86_64
%if WIN64
push r7
%endif
shl wd, 5
lea r6d, [wq+hq-256]
mov r4, srcq
mov r7, dstq
%else
mov r6, srcq
%endif
.hv_w8_loop0:
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*0+2]
pmullw m0, m4
pmullw m1, m5
paddw m0, m3
paddw m0, m1
psrlw m0, 2
.hv_w8_loop:
movu m1, [srcq+ssq*1]
movu m2, [srcq+ssq*1+2]
lea srcq, [srcq+ssq*2]
pmullw m1, m4
pmullw m2, m5
paddw m1, m3
paddw m1, m2
psrlw m1, 2
psubw m2, m1, m0
paddw m2, m2
pmulhw m2, m6
paddw m2, m0
pmulhrsw m2, m7
mova [dstq+dsq*0], m2
movu m0, [srcq+ssq*0]
movu m2, [srcq+ssq*0+2]
pmullw m0, m4
pmullw m2, m5
paddw m0, m3
paddw m0, m2
psrlw m0, 2
psubw m2, m0, m1
paddw m2, m2
pmulhw m2, m6
paddw m2, m1
pmulhrsw m2, m7
mova [dstq+dsq*1], m2
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .hv_w8_loop
%if ARCH_X86_64
add r4, 16
add r7, 16
movzx hd, r6b
mov srcq, r4
mov dstq, r7
sub r6d, 1<<8
%else
mov dstq, dstmp
add r6, 16
mov hd, hm
add dstq, 16
mov srcq, r6
mov dstmp, dstq
sub wd, 8
%endif
jg .hv_w8_loop0
%if WIN64
pop r7
%endif
RET
cglobal prep_bilin_16bpc, 4, 7, 0, tmp, src, stride, w, h, mxy, stride3
%define base r6-prep_ssse3
movifnidn mxyd, r5m ; mx
LEA r6, prep_ssse3
movifnidn hd, hm
test mxyd, mxyd
jnz .h
mov mxyd, r6m ; my
test mxyd, mxyd
jnz .v
.prep:
tzcnt wd, wd
movzx wd, word [base+prep_ssse3_table+wq*2]
mov r5d, r7m ; bitdepth_max
mova m5, [base+pw_8192]
add wq, r6
shr r5d, 11
movddup m4, [base+prep_mul+r5*8]
lea stride3q, [strideq*3]
jmp wq
.prep_w4:
movq m0, [srcq+strideq*0]
movhps m0, [srcq+strideq*1]
movq m1, [srcq+strideq*2]
movhps m1, [srcq+stride3q ]
lea srcq, [srcq+strideq*4]
pmullw m0, m4
pmullw m1, m4
psubw m0, m5
psubw m1, m5
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
add tmpq, 16*2
sub hd, 4
jg .prep_w4
RET
.prep_w8:
movu m0, [srcq+strideq*0]
movu m1, [srcq+strideq*1]
movu m2, [srcq+strideq*2]
movu m3, [srcq+stride3q ]
lea srcq, [srcq+strideq*4]
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
mova [tmpq+16*2], m2
mova [tmpq+16*3], m3
add tmpq, 16*4
sub hd, 4
jg .prep_w8
RET
.prep_w16:
movu m0, [srcq+strideq*0+16*0]
movu m1, [srcq+strideq*0+16*1]
movu m2, [srcq+strideq*1+16*0]
movu m3, [srcq+strideq*1+16*1]
lea srcq, [srcq+strideq*2]
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
mova [tmpq+16*2], m2
mova [tmpq+16*3], m3
add tmpq, 16*4
sub hd, 2
jg .prep_w16
RET
.prep_w32:
movu m0, [srcq+16*0]
movu m1, [srcq+16*1]
movu m2, [srcq+16*2]
movu m3, [srcq+16*3]
add srcq, strideq
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
mova [tmpq+16*2], m2
mova [tmpq+16*3], m3
add tmpq, 16*4
dec hd
jg .prep_w32
RET
.prep_w64:
movu m0, [srcq+16*0]
movu m1, [srcq+16*1]
movu m2, [srcq+16*2]
movu m3, [srcq+16*3]
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
mova [tmpq+16*2], m2
mova [tmpq+16*3], m3
movu m0, [srcq+16*4]
movu m1, [srcq+16*5]
movu m2, [srcq+16*6]
movu m3, [srcq+16*7]
add srcq, strideq
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*4], m0
mova [tmpq+16*5], m1
mova [tmpq+16*6], m2
mova [tmpq+16*7], m3
add tmpq, 16*8
dec hd
jg .prep_w64
RET
.prep_w128:
movu m0, [srcq+16* 0]
movu m1, [srcq+16* 1]
movu m2, [srcq+16* 2]
movu m3, [srcq+16* 3]
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
mova [tmpq+16*2], m2
mova [tmpq+16*3], m3
movu m0, [srcq+16* 4]
movu m1, [srcq+16* 5]
movu m2, [srcq+16* 6]
movu m3, [srcq+16* 7]
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq+16*4], m0
mova [tmpq+16*5], m1
mova [tmpq+16*6], m2
mova [tmpq+16*7], m3
movu m0, [srcq+16* 8]
movu m1, [srcq+16* 9]
movu m2, [srcq+16*10]
movu m3, [srcq+16*11]
add tmpq, 16*16
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq-16*8], m0
mova [tmpq-16*7], m1
mova [tmpq-16*6], m2
mova [tmpq-16*5], m3
movu m0, [srcq+16*12]
movu m1, [srcq+16*13]
movu m2, [srcq+16*14]
movu m3, [srcq+16*15]
add srcq, strideq
REPX {pmullw x, m4}, m0, m1, m2, m3
REPX {psubw x, m5}, m0, m1, m2, m3
mova [tmpq-16*4], m0
mova [tmpq-16*3], m1
mova [tmpq-16*2], m2
mova [tmpq-16*1], m3
dec hd
jg .prep_w128
RET
.h:
movd m4, mxyd
mov mxyd, r6m ; my
mova m3, [base+pw_16]
pshufb m4, [base+pw_256]
mova m5, [base+pw_32766]
psubw m3, m4
test dword r7m, 0x800
jnz .h_12bpc
psllw m3, 2
psllw m4, 2
.h_12bpc:
test mxyd, mxyd
jnz .hv
sub wd, 8
je .h_w8
jg .h_w16
.h_w4:
movq m0, [srcq+strideq*0]
movhps m0, [srcq+strideq*1]
movq m1, [srcq+strideq*0+2]
movhps m1, [srcq+strideq*1+2]
lea srcq, [srcq+strideq*2]
pmullw m0, m3
pmullw m1, m4
psubw m0, m5
paddw m0, m1
psraw m0, 2
mova [tmpq], m0
add tmpq, 16
sub hd, 2
jg .h_w4
RET
.h_w8:
movu m0, [srcq+strideq*0]
movu m1, [srcq+strideq*0+2]
pmullw m0, m3
pmullw m1, m4
psubw m0, m5
paddw m0, m1
movu m1, [srcq+strideq*1]
movu m2, [srcq+strideq*1+2]
lea srcq, [srcq+strideq*2]
pmullw m1, m3
pmullw m2, m4
psubw m1, m5
paddw m1, m2
psraw m0, 2
psraw m1, 2
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
add tmpq, 16*2
sub hd, 2
jg .h_w8
RET
.h_w16:
lea srcq, [srcq+wq*2]
neg wq
.h_w16_loop0:
mov r6, wq
.h_w16_loop:
movu m0, [srcq+r6*2+ 0]
movu m1, [srcq+r6*2+ 2]
pmullw m0, m3
pmullw m1, m4
psubw m0, m5
paddw m0, m1
movu m1, [srcq+r6*2+16]
movu m2, [srcq+r6*2+18]
pmullw m1, m3
pmullw m2, m4
psubw m1, m5
paddw m1, m2
psraw m0, 2
psraw m1, 2
mova [tmpq+16*0], m0
mova [tmpq+16*1], m1
add tmpq, 16*2
add r6, 16
jl .h_w16_loop
add srcq, strideq
dec hd
jg .h_w16_loop0
RET
.v:
movd m4, mxyd
mova m3, [base+pw_16]
pshufb m4, [base+pw_256]
mova m5, [base+pw_32766]
psubw m3, m4
test dword r7m, 0x800
jnz .v_12bpc
psllw m3, 2
psllw m4, 2
.v_12bpc:
cmp wd, 8
je .v_w8
jg .v_w16
.v_w4:
movq m0, [srcq+strideq*0]
.v_w4_loop:
movq m2, [srcq+strideq*1]
lea srcq, [srcq+strideq*2]
punpcklqdq m1, m0, m2 ; 0 1
movq m0, [srcq+strideq*0]
punpcklqdq m2, m0 ; 1 2
pmullw m1, m3
pmullw m2, m4
psubw m1, m5
paddw m1, m2
psraw m1, 2
mova [tmpq], m1
add tmpq, 16
sub hd, 2
jg .v_w4_loop
RET
.v_w8:
movu m0, [srcq+strideq*0]
.v_w8_loop:
movu m2, [srcq+strideq*1]
lea srcq, [srcq+strideq*2]
pmullw m0, m3
pmullw m1, m4, m2
psubw m0, m5
paddw m1, m0
movu m0, [srcq+strideq*0]
psraw m1, 2
pmullw m2, m3
mova [tmpq+16*0], m1
pmullw m1, m4, m0
psubw m2, m5
paddw m1, m2
psraw m1, 2
mova [tmpq+16*1], m1
add tmpq, 16*2
sub hd, 2
jg .v_w8_loop
RET
.v_w16:
%if WIN64
push r7
%endif
mov r5, srcq
%if ARCH_X86_64
lea r6d, [wq*4-32]
mov wd, wd
lea r6d, [hq+r6*8]
mov r7, tmpq
%else
mov r6d, wd
%endif
.v_w16_loop0:
movu m0, [srcq+strideq*0]
.v_w16_loop:
movu m2, [srcq+strideq*1]
lea srcq, [srcq+strideq*2]
pmullw m0, m3
pmullw m1, m4, m2
psubw m0, m5
paddw m1, m0
movu m0, [srcq+strideq*0]
psraw m1, 2
pmullw m2, m3
mova [tmpq+wq*0], m1
pmullw m1, m4, m0
psubw m2, m5
paddw m1, m2
psraw m1, 2
mova [tmpq+wq*2], m1
lea tmpq, [tmpq+wq*4]
sub hd, 2
jg .v_w16_loop
%if ARCH_X86_64
add r5, 16
add r7, 16
movzx hd, r6b
mov srcq, r5
mov tmpq, r7
sub r6d, 1<<8
%else
mov tmpq, tmpmp
add r5, 16
mov hd, hm
add tmpq, 16
mov srcq, r5
mov tmpmp, tmpq
sub r6d, 8
%endif
jg .v_w16_loop0
%if WIN64
pop r7
%endif
RET
.hv:
WIN64_SPILL_XMM 7
shl mxyd, 11
movd m6, mxyd
pshufb m6, [base+pw_256]
cmp wd, 8
je .hv_w8
jg .hv_w16
.hv_w4:
movddup m0, [srcq+strideq*0]
movddup m1, [srcq+strideq*0+2]
pmullw m0, m3
pmullw m1, m4
psubw m0, m5
paddw m0, m1
psraw m0, 2
.hv_w4_loop:
movq m1, [srcq+strideq*1]
movq m2, [srcq+strideq*1+2]
lea srcq, [srcq+strideq*2]
movhps m1, [srcq+strideq*0]
movhps m2, [srcq+strideq*0+2]
pmullw m1, m3
pmullw m2, m4
psubw m1, m5
paddw m1, m2
psraw m1, 2 ; 1 2
shufpd m2, m0, m1, 0x01 ; 0 1
mova m0, m1
psubw m1, m2
pmulhrsw m1, m6
paddw m1, m2
mova [tmpq], m1
add tmpq, 16
sub hd, 2
jg .hv_w4_loop
RET
.hv_w8:
movu m0, [srcq+strideq*0]
movu m1, [srcq+strideq*0+2]
pmullw m0, m3
pmullw m1, m4
psubw m0, m5
paddw m0, m1
psraw m0, 2
.hv_w8_loop:
movu m1, [srcq+strideq*1]
movu m2, [srcq+strideq*1+2]
lea srcq, [srcq+strideq*2]
pmullw m1, m3
pmullw m2, m4
psubw m1, m5
paddw m1, m2
psraw m1, 2
psubw m2, m1, m0
pmulhrsw m2, m6
paddw m2, m0
mova [tmpq+16*0], m2
movu m0, [srcq+strideq*0]
movu m2, [srcq+strideq*0+2]
pmullw m0, m3
pmullw m2, m4
psubw m0, m5
paddw m0, m2
psraw m0, 2
psubw m2, m0, m1
pmulhrsw m2, m6
paddw m2, m1
mova [tmpq+16*1], m2
add tmpq, 16*2
sub hd, 2
jg .hv_w8_loop
RET
.hv_w16:
%if WIN64
push r7
%endif
mov r5, srcq
%if ARCH_X86_64
lea r6d, [wq*4-32]
mov wd, wd
lea r6d, [hq+r6*8]
mov r7, tmpq
%else
mov r6d, wd
%endif
.hv_w16_loop0:
movu m0, [srcq+strideq*0]
movu m1, [srcq+strideq*0+2]
pmullw m0, m3
pmullw m1, m4
psubw m0, m5
paddw m0, m1
psraw m0, 2
.hv_w16_loop:
movu m1, [srcq+strideq*1]
movu m2, [srcq+strideq*1+2]
lea srcq, [srcq+strideq*2]
pmullw m1, m3
pmullw m2, m4
psubw m1, m5
paddw m1, m2
psraw m1, 2
psubw m2, m1, m0
pmulhrsw m2, m6
paddw m2, m0
mova [tmpq+wq*0], m2
movu m0, [srcq+strideq*0]
movu m2, [srcq+strideq*0+2]
pmullw m0, m3
pmullw m2, m4
psubw m0, m5
paddw m0, m2
psraw m0, 2
psubw m2, m0, m1
pmulhrsw m2, m6
paddw m2, m1
mova [tmpq+wq*2], m2
lea tmpq, [tmpq+wq*4]
sub hd, 2
jg .hv_w16_loop
%if ARCH_X86_64
add r5, 16
add r7, 16
movzx hd, r6b
mov srcq, r5
mov tmpq, r7
sub r6d, 1<<8
%else
mov tmpq, tmpmp
add r5, 16
mov hd, hm
add tmpq, 16
mov srcq, r5
mov tmpmp, tmpq
sub r6d, 8
%endif
jg .hv_w16_loop0
%if WIN64
pop r7
%endif
RET
; int8_t subpel_filters[5][15][8]
%assign FILTER_REGULAR (0*15 << 16) | 3*15
%assign FILTER_SMOOTH (1*15 << 16) | 4*15
%assign FILTER_SHARP (2*15 << 16) | 3*15
%macro FN 4 ; prefix, type, type_h, type_v
cglobal %1_%2_16bpc
mov t0d, FILTER_%3
%ifidn %3, %4
mov t1d, t0d
%else
mov t1d, FILTER_%4
%endif
%ifnidn %2, regular ; skip the jump in the last filter
jmp mangle(private_prefix %+ _%1_16bpc %+ SUFFIX)
%endif
%endmacro
%if ARCH_X86_32
DECLARE_REG_TMP 1, 2, 6
%elif WIN64
DECLARE_REG_TMP 4, 5, 8
%else
DECLARE_REG_TMP 7, 8, 8
%endif
%define PUT_8TAP_FN FN put_8tap,
PUT_8TAP_FN sharp, SHARP, SHARP
PUT_8TAP_FN sharp_smooth, SHARP, SMOOTH
PUT_8TAP_FN smooth_sharp, SMOOTH, SHARP
PUT_8TAP_FN smooth, SMOOTH, SMOOTH
PUT_8TAP_FN sharp_regular, SHARP, REGULAR
PUT_8TAP_FN regular_sharp, REGULAR, SHARP
PUT_8TAP_FN smooth_regular, SMOOTH, REGULAR
PUT_8TAP_FN regular_smooth, REGULAR, SMOOTH
PUT_8TAP_FN regular, REGULAR, REGULAR
%if ARCH_X86_32
cglobal put_8tap_16bpc, 0, 7, 8, dst, ds, src, ss, w, h, mx, my
%define mxb r0b
%define mxd r0
%define mxq r0
%define myb r1b
%define myd r1
%define myq r1
%define m8 [esp+16*0]
%define m9 [esp+16*1]
%define m10 [esp+16*2]
%define m11 [esp+16*3]
%define m12 [esp+16*4]
%define m13 [esp+16*5]
%define m14 [esp+16*6]
%define m15 [esp+16*7]
%else
cglobal put_8tap_16bpc, 4, 9, 0, dst, ds, src, ss, w, h, mx, my
%endif
%define base t2-put_ssse3
imul mxd, mxm, 0x010101
add mxd, t0d ; 8tap_h, mx, 4tap_h
imul myd, mym, 0x010101
add myd, t1d ; 8tap_v, my, 4tap_v
LEA t2, put_ssse3
movifnidn wd, wm
movifnidn srcq, srcmp
movifnidn ssq, ssmp
movifnidn hd, hm
test mxd, 0xf00
jnz .h
test myd, 0xf00
jnz .v
tzcnt wd, wd
movzx wd, word [base+put_ssse3_table+wq*2]
movifnidn dstq, dstmp
movifnidn dsq, dsmp
add wq, t2
%if WIN64
pop r8
pop r7
%endif
jmp wq
.h:
test myd, 0xf00
jnz .hv
mov myd, r8m
movd m5, r8m
shr myd, 11
movddup m4, [base+put_8tap_h_rnd+myq*8]
movifnidn dsq, dsmp
pshufb m5, [base+pw_256]
cmp wd, 4
jg .h_w8
movzx mxd, mxb
lea srcq, [srcq-2]
movq m3, [base+subpel_filters+mxq*8]
movifnidn dstq, dstmp
punpcklbw m3, m3
psraw m3, 8 ; sign-extend
je .h_w4
.h_w2:
mova m2, [base+spel_h_shuf2]
pshufd m3, m3, q2121
.h_w2_loop:
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
pshufb m0, m2
pshufb m1, m2
pmaddwd m0, m3
pmaddwd m1, m3
phaddd m0, m1
paddd m0, m4
psrad m0, 6
packssdw m0, m0
pxor m1, m1
pminsw m0, m5
pmaxsw m0, m1
movd [dstq+dsq*0], m0
pshuflw m0, m0, q3232
movd [dstq+dsq*1], m0
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .h_w2_loop
RET
.h_w4:
WIN64_SPILL_XMM 8
mova m6, [base+spel_h_shufA]
mova m7, [base+spel_h_shufB]
pshufd m2, m3, q1111
pshufd m3, m3, q2222
.h_w4_loop:
movu m1, [srcq]
add srcq, ssq
pshufb m0, m1, m6 ; 0 1 1 2 2 3 3 4
pshufb m1, m7 ; 2 3 3 4 4 5 5 6
pmaddwd m0, m2
pmaddwd m1, m3
paddd m0, m4
paddd m0, m1
psrad m0, 6
packssdw m0, m0
pxor m1, m1
pminsw m0, m5
pmaxsw m0, m1
movq [dstq], m0
add dstq, dsq
dec hd
jg .h_w4_loop
RET
.h_w8:
%if WIN64
%assign stack_offset stack_offset - stack_size_padded
WIN64_SPILL_XMM 12
%endif
shr mxd, 16
movq m3, [base+subpel_filters+mxq*8]
movifnidn dstq, dstmp
mova m6, [base+spel_h_shufA]
mova m7, [base+spel_h_shufB]
%if UNIX64
mov wd, wd
%endif
lea srcq, [srcq+wq*2]
punpcklbw m3, m3
lea dstq, [dstq+wq*2]
psraw m3, 8
neg wq
%if ARCH_X86_32
ALLOC_STACK -16*4
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
mova m8, m0
mova m9, m1
mova m10, m2
mova m11, m3
%else
pshufd m8, m3, q0000
pshufd m9, m3, q1111
pshufd m10, m3, q2222
pshufd m11, m3, q3333
%endif
.h_w8_loop0:
mov r6, wq
.h_w8_loop:
movu m0, [srcq+r6*2- 6]
movu m1, [srcq+r6*2+ 2]
pshufb m2, m0, m6 ; 0 1 1 2 2 3 3 4
pshufb m0, m7 ; 2 3 3 4 4 5 5 6
pmaddwd m2, m8 ; abcd0
pmaddwd m0, m9 ; abcd1
pshufb m3, m1, m6 ; 4 5 5 6 6 7 7 8
pshufb m1, m7 ; 6 7 7 8 8 9 9 a
paddd m2, m4
paddd m0, m2
pmaddwd m2, m10, m3 ; abcd2
pmaddwd m3, m8 ; efgh0
paddd m0, m2
pmaddwd m2, m11, m1 ; abcd3
pmaddwd m1, m9 ; efgh1
paddd m0, m2
movu m2, [srcq+r6*2+10]
paddd m3, m4
paddd m1, m3
pshufb m3, m2, m6 ; 8 9 9 a a b b c
pshufb m2, m7 ; a b b c c d d e
pmaddwd m3, m10 ; efgh2
pmaddwd m2, m11 ; efgh3
paddd m1, m3
paddd m1, m2
psrad m0, 6
psrad m1, 6
packssdw m0, m1
pxor m1, m1
pminsw m0, m5
pmaxsw m0, m1
mova [dstq+r6*2], m0
add r6, 8
jl .h_w8_loop
add srcq, ssq
add dstq, dsq
dec hd
jg .h_w8_loop0
RET
.v:
movzx mxd, myb
shr myd, 16
cmp hd, 6
cmovb myd, mxd
movq m3, [base+subpel_filters+myq*8]
%if STACK_ALIGNMENT < 16
%xdefine rstk rsp
%else
%assign stack_offset stack_offset - stack_size_padded
%endif
%if WIN64
WIN64_SPILL_XMM 15
%endif
movd m7, r8m
movifnidn dstq, dstmp
movifnidn dsq, dsmp
punpcklbw m3, m3
pshufb m7, [base+pw_256]
psraw m3, 8 ; sign-extend
%if ARCH_X86_32
ALLOC_STACK -16*7
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
mova m8, m0
mova m9, m1
mova m10, m2
mova m11, m3
%else
pshufd m8, m3, q0000
pshufd m9, m3, q1111
pshufd m10, m3, q2222
pshufd m11, m3, q3333
%endif
lea r6, [ssq*3]
sub srcq, r6
cmp wd, 2
jne .v_w4
.v_w2:
movd m1, [srcq+ssq*0]
movd m4, [srcq+ssq*1]
movd m2, [srcq+ssq*2]
add srcq, r6
movd m5, [srcq+ssq*0]
movd m3, [srcq+ssq*1]
movd m6, [srcq+ssq*2]
add srcq, r6
movd m0, [srcq+ssq*0]
punpckldq m1, m4 ; 0 1
punpckldq m4, m2 ; 1 2
punpckldq m2, m5 ; 2 3
punpckldq m5, m3 ; 3 4
punpckldq m3, m6 ; 4 5
punpckldq m6, m0 ; 5 6
punpcklwd m1, m4 ; 01 12
punpcklwd m2, m5 ; 23 34
punpcklwd m3, m6 ; 45 56
pxor m6, m6
.v_w2_loop:
movd m4, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
pmaddwd m5, m8, m1 ; a0 b0
mova m1, m2
pmaddwd m2, m9 ; a1 b1
paddd m5, m2
mova m2, m3
pmaddwd m3, m10 ; a2 b2
paddd m5, m3
punpckldq m3, m0, m4 ; 6 7
movd m0, [srcq+ssq*0]
punpckldq m4, m0 ; 7 8
punpcklwd m3, m4 ; 67 78
pmaddwd m4, m11, m3 ; a3 b3
paddd m5, m4
psrad m5, 5
packssdw m5, m5
pmaxsw m5, m6
pavgw m5, m6
pminsw m5, m7
movd [dstq+dsq*0], m5
pshuflw m5, m5, q3232
movd [dstq+dsq*1], m5
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .v_w2_loop
RET
.v_w4:
%if ARCH_X86_32
shl wd, 14
%if STACK_ALIGNMENT < 16
mov [esp+4*29], srcq
mov [esp+4*30], dstq
%else
mov srcmp, srcq
%endif
lea wd, [wq+hq-(1<<16)]
%else
shl wd, 6
mov r7, srcq
mov r8, dstq
lea wd, [wq+hq-(1<<8)]
%endif
.v_w4_loop0:
movq m1, [srcq+ssq*0]
movq m2, [srcq+ssq*1]
movq m3, [srcq+ssq*2]
add srcq, r6
movq m4, [srcq+ssq*0]
movq m5, [srcq+ssq*1]
movq m6, [srcq+ssq*2]
add srcq, r6
movq m0, [srcq+ssq*0]
punpcklwd m1, m2 ; 01
punpcklwd m2, m3 ; 12
punpcklwd m3, m4 ; 23
punpcklwd m4, m5 ; 34
punpcklwd m5, m6 ; 45
punpcklwd m6, m0 ; 56
%if ARCH_X86_32
jmp .v_w4_loop_start
.v_w4_loop:
mova m1, m12
mova m2, m13
mova m3, m14
.v_w4_loop_start:
pmaddwd m1, m8 ; a0
pmaddwd m2, m8 ; b0
mova m12, m3
mova m13, m4
pmaddwd m3, m9 ; a1
pmaddwd m4, m9 ; b1
paddd m1, m3
paddd m2, m4
mova m14, m5
mova m4, m6
pmaddwd m5, m10 ; a2
pmaddwd m6, m10 ; b2
paddd m1, m5
paddd m2, m6
movq m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
punpcklwd m5, m0, m6 ; 67
movq m0, [srcq+ssq*0]
pmaddwd m3, m11, m5 ; a3
punpcklwd m6, m0 ; 78
paddd m1, m3
pmaddwd m3, m11, m6 ; b3
paddd m2, m3
psrad m1, 5
psrad m2, 5
packssdw m1, m2
pxor m2, m2
pmaxsw m1, m2
pavgw m1, m2
pminsw m1, m7
movq [dstq+dsq*0], m1
movhps [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .v_w4_loop
%if STACK_ALIGNMENT < 16
mov srcq, [esp+4*29]
mov dstq, [esp+4*30]
movzx hd, ww
add srcq, 8
add dstq, 8
mov [esp+4*29], srcq
mov [esp+4*30], dstq
%else
mov srcq, srcmp
mov dstq, dstmp
movzx hd, ww
add srcq, 8
add dstq, 8
mov srcmp, srcq
mov dstmp, dstq
%endif
sub wd, 1<<16
%else
.v_w4_loop:
pmaddwd m12, m8, m1 ; a0
pmaddwd m13, m8, m2 ; b0
mova m1, m3
mova m2, m4
pmaddwd m3, m9 ; a1
pmaddwd m4, m9 ; b1
paddd m12, m3
paddd m13, m4
mova m3, m5
mova m4, m6
pmaddwd m5, m10 ; a2
pmaddwd m6, m10 ; b2
paddd m12, m5
paddd m13, m6
movq m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
punpcklwd m5, m0, m6 ; 67
movq m0, [srcq+ssq*0]
pmaddwd m14, m11, m5 ; a3
punpcklwd m6, m0 ; 78
paddd m12, m14
pmaddwd m14, m11, m6 ; b3
paddd m13, m14
psrad m12, 5
psrad m13, 5
packssdw m12, m13
pxor m13, m13
pmaxsw m12, m13
pavgw m12, m13
pminsw m12, m7
movq [dstq+dsq*0], m12
movhps [dstq+dsq*1], m12
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .v_w4_loop
add r7, 8
add r8, 8
movzx hd, wb
mov srcq, r7
mov dstq, r8
sub wd, 1<<8
%endif
jg .v_w4_loop0
RET
.hv:
%if STACK_ALIGNMENT < 16
%xdefine rstk rsp
%else
%assign stack_offset stack_offset - stack_size_padded
%endif
%if ARCH_X86_32
movd m4, r8m
mova m6, [base+pd_512]
pshufb m4, [base+pw_256]
%else
%if WIN64
ALLOC_STACK 16*6, 16
%endif
movd m15, r8m
pshufb m15, [base+pw_256]
%endif
cmp wd, 4
jg .hv_w8
movzx mxd, mxb
je .hv_w4
movq m0, [base+subpel_filters+mxq*8]
movzx mxd, myb
shr myd, 16
cmp hd, 6
cmovb myd, mxd
movq m3, [base+subpel_filters+myq*8]
%if ARCH_X86_32
mov dstq, dstmp
mov dsq, dsmp
mova m5, [base+spel_h_shuf2]
ALLOC_STACK -16*8
%else
mova m6, [base+pd_512]
mova m9, [base+spel_h_shuf2]
%endif
pshuflw m0, m0, q2121
pxor m7, m7
punpcklbw m7, m0
punpcklbw m3, m3
psraw m3, 8 ; sign-extend
test dword r8m, 0x800
jz .hv_w2_10bpc
psraw m7, 2
psllw m3, 2
.hv_w2_10bpc:
lea r6, [ssq*3]
sub srcq, 2
sub srcq, r6
%if ARCH_X86_32
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
mova m9, m5
mova m11, m0
mova m12, m1
mova m13, m2
mova m14, m3
mova m15, m4
%else
pshufd m11, m3, q0000
pshufd m12, m3, q1111
pshufd m13, m3, q2222
pshufd m14, m3, q3333
%endif
movu m2, [srcq+ssq*0]
movu m3, [srcq+ssq*1]
movu m1, [srcq+ssq*2]
add srcq, r6
movu m4, [srcq+ssq*0]
%if ARCH_X86_32
REPX {pshufb x, m5}, m2, m3, m1, m4
%else
REPX {pshufb x, m9}, m2, m3, m1, m4
%endif
REPX {pmaddwd x, m7}, m2, m3, m1, m4
phaddd m2, m3 ; 0 1
phaddd m1, m4 ; 2 3
movu m3, [srcq+ssq*1]
movu m4, [srcq+ssq*2]
add srcq, r6
movu m0, [srcq+ssq*0]
%if ARCH_X86_32
REPX {pshufb x, m5}, m3, m4, m0
%else
REPX {pshufb x, m9}, m3, m4, m0
%endif
REPX {pmaddwd x, m7}, m3, m4, m0
phaddd m3, m4 ; 4 5
phaddd m0, m0 ; 6 6
REPX {paddd x, m6}, m2, m1, m3, m0
REPX {psrad x, 10}, m2, m1, m3, m0
packssdw m2, m1 ; 0 1 2 3
packssdw m3, m0 ; 4 5 6 _
palignr m4, m3, m2, 4 ; 1 2 3 4
pshufd m5, m3, q0321 ; 5 6 _ _
punpcklwd m1, m2, m4 ; 01 12
punpckhwd m2, m4 ; 23 34
punpcklwd m3, m5 ; 45 56
.hv_w2_loop:
movu m4, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
movu m5, [srcq+ssq*0]
pshufb m4, m9
pshufb m5, m9
pmaddwd m4, m7
pmaddwd m5, m7
phaddd m4, m5
pmaddwd m5, m11, m1 ; a0 b0
mova m1, m2
pmaddwd m2, m12 ; a1 b1
paddd m5, m2
mova m2, m3
pmaddwd m3, m13 ; a2 b2
paddd m5, m3
paddd m4, m6
psrad m4, 10 ; 7 8
packssdw m0, m4
pshufd m3, m0, q2103
punpckhwd m3, m0 ; 67 78
mova m0, m4
pmaddwd m4, m14, m3 ; a3 b3
paddd m5, m6
paddd m5, m4
psrad m5, 10
packssdw m5, m5
pxor m4, m4
pminsw m5, m15
pmaxsw m5, m4
movd [dstq+dsq*0], m5
pshuflw m5, m5, q3232
movd [dstq+dsq*1], m5
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .hv_w2_loop
RET
.hv_w8:
shr mxd, 16
.hv_w4:
movq m2, [base+subpel_filters+mxq*8]
movzx mxd, myb
shr myd, 16
cmp hd, 6
cmovb myd, mxd
movq m3, [base+subpel_filters+myq*8]
%if ARCH_X86_32
%if STACK_ALIGNMENT < 16
%xdefine rstk rsp
%else
%assign stack_offset stack_offset - stack_size_padded
%endif
mov dstq, dstmp
mov dsq, dsmp
mova m0, [base+spel_h_shufA]
mova m1, [base+spel_h_shufB]
ALLOC_STACK -16*15
mova m8, m0
mova m9, m1
mova m14, m6
%else
mova m8, [base+spel_h_shufA]
mova m9, [base+spel_h_shufB]
%endif
pxor m0, m0
punpcklbw m0, m2
punpcklbw m3, m3
psraw m3, 8
test dword r8m, 0x800
jz .hv_w4_10bpc
psraw m0, 2
psllw m3, 2
.hv_w4_10bpc:
lea r6, [ssq*3]
sub srcq, 6
sub srcq, r6
%if ARCH_X86_32
%define tmp esp+16*8
shl wd, 14
%if STACK_ALIGNMENT < 16
mov [esp+4*61], srcq
mov [esp+4*62], dstq
%else
mov srcmp, srcq
%endif
mova [tmp+16*5], m4
lea wd, [wq+hq-(1<<16)]
pshufd m1, m0, q0000
pshufd m2, m0, q1111
pshufd m5, m0, q2222
pshufd m0, m0, q3333
mova m10, m1
mova m11, m2
mova m12, m5
mova m13, m0
%else
%if WIN64
%define tmp rsp
%else
%define tmp rsp-104 ; red zone
%endif
shl wd, 6
mov r7, srcq
mov r8, dstq
lea wd, [wq+hq-(1<<8)]
pshufd m10, m0, q0000
pshufd m11, m0, q1111
pshufd m12, m0, q2222
pshufd m13, m0, q3333
mova [tmp+16*5], m15
%endif
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
mova [tmp+16*1], m0
mova [tmp+16*2], m1
mova [tmp+16*3], m2
mova [tmp+16*4], m3
%macro PUT_8TAP_HV_H 4-5 m14 ; dst/src+0, src+8, tmp, shift, [pd_512]
pshufb m%3, m%1, m8 ; 0 1 1 2 2 3 3 4
pshufb m%1, m9 ; 2 3 3 4 4 5 5 6
pmaddwd m%3, m10
pmaddwd m%1, m11
paddd m%3, %5
paddd m%1, m%3
pshufb m%3, m%2, m8 ; 4 5 5 6 6 7 7 8
pshufb m%2, m9 ; 6 7 7 8 8 9 9 a
pmaddwd m%3, m12
pmaddwd m%2, m13
paddd m%1, m%3
paddd m%1, m%2
psrad m%1, %4
%endmacro
.hv_w4_loop0:
%if ARCH_X86_64
mova m14, [pd_512]
%endif
movu m4, [srcq+ssq*0+0]
movu m1, [srcq+ssq*0+8]
movu m5, [srcq+ssq*1+0]
movu m2, [srcq+ssq*1+8]
movu m6, [srcq+ssq*2+0]
movu m3, [srcq+ssq*2+8]
add srcq, r6
PUT_8TAP_HV_H 4, 1, 0, 10
PUT_8TAP_HV_H 5, 2, 0, 10
PUT_8TAP_HV_H 6, 3, 0, 10
movu m7, [srcq+ssq*0+0]
movu m2, [srcq+ssq*0+8]
movu m1, [srcq+ssq*1+0]
movu m3, [srcq+ssq*1+8]
PUT_8TAP_HV_H 7, 2, 0, 10
PUT_8TAP_HV_H 1, 3, 0, 10
movu m2, [srcq+ssq*2+0]
movu m3, [srcq+ssq*2+8]
add srcq, r6
PUT_8TAP_HV_H 2, 3, 0, 10
packssdw m4, m7 ; 0 3
packssdw m5, m1 ; 1 4
movu m0, [srcq+ssq*0+0]
movu m1, [srcq+ssq*0+8]
PUT_8TAP_HV_H 0, 1, 3, 10
packssdw m6, m2 ; 2 5
packssdw m7, m0 ; 3 6
punpcklwd m1, m4, m5 ; 01
punpckhwd m4, m5 ; 34
punpcklwd m2, m5, m6 ; 12
punpckhwd m5, m6 ; 45
punpcklwd m3, m6, m7 ; 23
punpckhwd m6, m7 ; 56
%if ARCH_X86_32
jmp .hv_w4_loop_start
.hv_w4_loop:
mova m1, [tmp+16*6]
mova m2, m15
.hv_w4_loop_start:
mova m7, [tmp+16*1]
pmaddwd m1, m7 ; a0
pmaddwd m2, m7 ; b0
mova m7, [tmp+16*2]
mova [tmp+16*6], m3
pmaddwd m3, m7 ; a1
mova m15, m4
pmaddwd m4, m7 ; b1
mova m7, [tmp+16*3]
paddd m1, m3
paddd m2, m4
mova m3, m5
pmaddwd m5, m7 ; a2
mova m4, m6
pmaddwd m6, m7 ; b2
paddd m1, m5
paddd m2, m6
movu m7, [srcq+ssq*1+0]
movu m5, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
PUT_8TAP_HV_H 7, 5, 6, 10
packssdw m0, m7 ; 6 7
mova [tmp+16*0], m0
movu m0, [srcq+ssq*0+0]
movu m5, [srcq+ssq*0+8]
PUT_8TAP_HV_H 0, 5, 6, 10
mova m6, [tmp+16*0]
packssdw m7, m0 ; 7 8
punpcklwd m5, m6, m7 ; 67
punpckhwd m6, m7 ; 78
pmaddwd m7, m5, [tmp+16*4]
paddd m1, m7 ; a3
pmaddwd m7, m6, [tmp+16*4]
paddd m2, m7 ; b3
psrad m1, 9
psrad m2, 9
packssdw m1, m2
pxor m7, m7
pmaxsw m1, m7
pavgw m7, m1
pminsw m7, [tmp+16*5]
movq [dstq+dsq*0], m7
movhps [dstq+dsq*1], m7
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .hv_w4_loop
%if STACK_ALIGNMENT < 16
mov srcq, [esp+4*61]
mov dstq, [esp+4*62]
add srcq, 8
add dstq, 8
mov [esp+4*61], srcq
mov [esp+4*62], dstq
%else
mov srcq, srcmp
mov dstq, dstmp
add srcq, 8
add dstq, 8
mov srcmp, srcq
mov dstmp, dstq
%endif
movzx hd, ww
sub wd, 1<<16
%else
.hv_w4_loop:
mova m15, [tmp+16*1]
pmaddwd m14, m15, m1 ; a0
pmaddwd m15, m2 ; b0
mova m7, [tmp+16*2]
mova m1, m3
pmaddwd m3, m7 ; a1
mova m2, m4
pmaddwd m4, m7 ; b1
mova m7, [tmp+16*3]
paddd m14, m3
paddd m15, m4
mova m3, m5
pmaddwd m5, m7 ; a2
mova m4, m6
pmaddwd m6, m7 ; b2
paddd m14, m5
paddd m15, m6
movu m7, [srcq+ssq*1+0]
movu m5, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
PUT_8TAP_HV_H 7, 5, 6, 10, [pd_512]
packssdw m0, m7 ; 6 7
mova [tmp+16*0], m0
movu m0, [srcq+ssq*0+0]
movu m5, [srcq+ssq*0+8]
PUT_8TAP_HV_H 0, 5, 6, 10, [pd_512]
mova m6, [tmp+16*0]
packssdw m7, m0 ; 7 8
punpcklwd m5, m6, m7 ; 67
punpckhwd m6, m7 ; 78
pmaddwd m7, m5, [tmp+16*4]
paddd m14, m7 ; a3
pmaddwd m7, m6, [tmp+16*4]
paddd m15, m7 ; b3
psrad m14, 9
psrad m15, 9
packssdw m14, m15
pxor m7, m7
pmaxsw m14, m7
pavgw m7, m14
pminsw m7, [tmp+16*5]
movq [dstq+dsq*0], m7
movhps [dstq+dsq*1], m7
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .hv_w4_loop
add r7, 8
add r8, 8
movzx hd, wb
mov srcq, r7
mov dstq, r8
sub wd, 1<<8
%endif
jg .hv_w4_loop0
RET
%undef tmp
%if ARCH_X86_32
DECLARE_REG_TMP 2, 1, 6, 4
%elif WIN64
DECLARE_REG_TMP 6, 4, 7, 4
%else
DECLARE_REG_TMP 6, 7, 7, 8
%endif
%define PREP_8TAP_FN FN prep_8tap,
PREP_8TAP_FN sharp, SHARP, SHARP
PREP_8TAP_FN sharp_smooth, SHARP, SMOOTH
PREP_8TAP_FN smooth_sharp, SMOOTH, SHARP
PREP_8TAP_FN smooth, SMOOTH, SMOOTH
PREP_8TAP_FN sharp_regular, SHARP, REGULAR
PREP_8TAP_FN regular_sharp, REGULAR, SHARP
PREP_8TAP_FN smooth_regular, SMOOTH, REGULAR
PREP_8TAP_FN regular_smooth, REGULAR, SMOOTH
PREP_8TAP_FN regular, REGULAR, REGULAR
%if ARCH_X86_32
cglobal prep_8tap_16bpc, 0, 7, 8, tmp, src, ss, w, h, mx, my
%define mxb r0b
%define mxd r0
%define mxq r0
%define myb r2b
%define myd r2
%define myq r2
%else
cglobal prep_8tap_16bpc, 4, 8, 0, tmp, src, ss, w, h, mx, my
%endif
%define base t2-prep_ssse3
imul mxd, mxm, 0x010101
add mxd, t0d ; 8tap_h, mx, 4tap_h
imul myd, mym, 0x010101
add myd, t1d ; 8tap_v, my, 4tap_v
LEA t2, prep_ssse3
movifnidn wd, wm
movifnidn srcq, srcmp
test mxd, 0xf00
jnz .h
movifnidn hd, hm
test myd, 0xf00
jnz .v
tzcnt wd, wd
mov myd, r7m ; bitdepth_max
movzx wd, word [base+prep_ssse3_table+wq*2]
mova m5, [base+pw_8192]
shr myd, 11
add wq, t2
movddup m4, [base+prep_mul+myq*8]
movifnidn ssq, ssmp
movifnidn tmpq, tmpmp
lea r6, [ssq*3]
%if WIN64
pop r7
%endif
jmp wq
.h:
test myd, 0xf00
jnz .hv
movifnidn ssq, r2mp
movifnidn hd, r4m
movddup m5, [base+prep_8tap_1d_rnd]
cmp wd, 4
jne .h_w8
movzx mxd, mxb
movq m0, [base+subpel_filters+mxq*8]
mova m3, [base+spel_h_shufA]
mova m4, [base+spel_h_shufB]
movifnidn tmpq, tmpmp
sub srcq, 2
WIN64_SPILL_XMM 8
punpcklbw m0, m0
psraw m0, 8
test dword r7m, 0x800
jnz .h_w4_12bpc
psllw m0, 2
.h_w4_12bpc:
pshufd m6, m0, q1111
pshufd m7, m0, q2222
.h_w4_loop:
movu m1, [srcq+ssq*0]
movu m2, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
pshufb m0, m1, m3 ; 0 1 1 2 2 3 3 4
pshufb m1, m4 ; 2 3 3 4 4 5 5 6
pmaddwd m0, m6
pmaddwd m1, m7
paddd m0, m5
paddd m0, m1
pshufb m1, m2, m3
pshufb m2, m4
pmaddwd m1, m6
pmaddwd m2, m7
paddd m1, m5
paddd m1, m2
psrad m0, 4
psrad m1, 4
packssdw m0, m1
mova [tmpq], m0
add tmpq, 16
sub hd, 2
jg .h_w4_loop
RET
.h_w8:
WIN64_SPILL_XMM 11
shr mxd, 16
movq m2, [base+subpel_filters+mxq*8]
mova m4, [base+spel_h_shufA]
mova m6, [base+spel_h_shufB]
movifnidn tmpq, r0mp
add wd, wd
punpcklbw m2, m2
add srcq, wq
psraw m2, 8
add tmpq, wq
neg wq
test dword r7m, 0x800
jnz .h_w8_12bpc
psllw m2, 2
.h_w8_12bpc:
pshufd m7, m2, q0000
%if ARCH_X86_32
ALLOC_STACK -16*3
pshufd m0, m2, q1111
pshufd m1, m2, q2222
pshufd m2, m2, q3333
mova m8, m0
mova m9, m1
mova m10, m2
%else
pshufd m8, m2, q1111
pshufd m9, m2, q2222
pshufd m10, m2, q3333
%endif
.h_w8_loop0:
mov r6, wq
.h_w8_loop:
movu m0, [srcq+r6- 6]
movu m1, [srcq+r6+ 2]
pshufb m2, m0, m4 ; 0 1 1 2 2 3 3 4
pshufb m0, m6 ; 2 3 3 4 4 5 5 6
pmaddwd m2, m7 ; abcd0
pmaddwd m0, m8 ; abcd1
pshufb m3, m1, m4 ; 4 5 5 6 6 7 7 8
pshufb m1, m6 ; 6 7 7 8 8 9 9 a
paddd m2, m5
paddd m0, m2
pmaddwd m2, m9, m3 ; abcd2
pmaddwd m3, m7 ; efgh0
paddd m0, m2
pmaddwd m2, m10, m1 ; abcd3
pmaddwd m1, m8 ; efgh1
paddd m0, m2
movu m2, [srcq+r6+10]
paddd m3, m5
paddd m1, m3
pshufb m3, m2, m4 ; a b b c c d d e
pshufb m2, m6 ; 8 9 9 a a b b c
pmaddwd m3, m9 ; efgh2
pmaddwd m2, m10 ; efgh3
paddd m1, m3
paddd m1, m2
psrad m0, 4
psrad m1, 4
packssdw m0, m1
mova [tmpq+r6], m0
add r6, 16
jl .h_w8_loop
add srcq, ssq
sub tmpq, wq
dec hd
jg .h_w8_loop0
RET
.v:
movzx mxd, myb
shr myd, 16
cmp hd, 4
cmove myd, mxd
movq m3, [base+subpel_filters+myq*8]
%if STACK_ALIGNMENT < 16
%xdefine rstk rsp
%else
%assign stack_offset stack_offset - stack_size_padded
%endif
WIN64_SPILL_XMM 15
movddup m7, [base+prep_8tap_1d_rnd]
movifnidn ssq, r2mp
movifnidn tmpq, r0mp
punpcklbw m3, m3
psraw m3, 8 ; sign-extend
test dword r7m, 0x800
jnz .v_12bpc
psllw m3, 2
.v_12bpc:
%if ARCH_X86_32
ALLOC_STACK -16*7
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
mova m8, m0
mova m9, m1
mova m10, m2
mova m11, m3
%else
pshufd m8, m3, q0000
pshufd m9, m3, q1111
pshufd m10, m3, q2222
pshufd m11, m3, q3333
%endif
lea r6, [ssq*3]
sub srcq, r6
mov r6d, wd
shl wd, 6
mov r5, srcq
%if ARCH_X86_64
mov r7, tmpq
%elif STACK_ALIGNMENT < 16
mov [esp+4*29], tmpq
%endif
lea wd, [wq+hq-(1<<8)]
.v_loop0:
movq m1, [srcq+ssq*0]
movq m2, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
movq m3, [srcq+ssq*0]
movq m4, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
movq m5, [srcq+ssq*0]
movq m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
movq m0, [srcq+ssq*0]
punpcklwd m1, m2 ; 01
punpcklwd m2, m3 ; 12
punpcklwd m3, m4 ; 23
punpcklwd m4, m5 ; 34
punpcklwd m5, m6 ; 45
punpcklwd m6, m0 ; 56
%if ARCH_X86_32
jmp .v_loop_start
.v_loop:
mova m1, m12
mova m2, m13
mova m3, m14
.v_loop_start:
pmaddwd m1, m8 ; a0
pmaddwd m2, m8 ; b0
mova m12, m3
mova m13, m4
pmaddwd m3, m9 ; a1
pmaddwd m4, m9 ; b1
paddd m1, m3
paddd m2, m4
mova m14, m5
mova m4, m6
pmaddwd m5, m10 ; a2
pmaddwd m6, m10 ; b2
paddd m1, m5
paddd m2, m6
movq m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
punpcklwd m5, m0, m6 ; 67
movq m0, [srcq+ssq*0]
pmaddwd m3, m11, m5 ; a3
punpcklwd m6, m0 ; 78
paddd m1, m7
paddd m1, m3
pmaddwd m3, m11, m6 ; b3
paddd m2, m7
paddd m2, m3
psrad m1, 4
psrad m2, 4
packssdw m1, m2
movq [tmpq+r6*0], m1
movhps [tmpq+r6*2], m1
lea tmpq, [tmpq+r6*4]
sub hd, 2
jg .v_loop
%if STACK_ALIGNMENT < 16
mov tmpq, [esp+4*29]
add r5, 8
add tmpq, 8
mov srcq, r5
mov [esp+4*29], tmpq
%else
mov tmpq, tmpmp
add r5, 8
add tmpq, 8
mov srcq, r5
mov tmpmp, tmpq
%endif
%else
.v_loop:
pmaddwd m12, m8, m1 ; a0
pmaddwd m13, m8, m2 ; b0
mova m1, m3
mova m2, m4
pmaddwd m3, m9 ; a1
pmaddwd m4, m9 ; b1
paddd m12, m3
paddd m13, m4
mova m3, m5
mova m4, m6
pmaddwd m5, m10 ; a2
pmaddwd m6, m10 ; b2
paddd m12, m5
paddd m13, m6
movq m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
punpcklwd m5, m0, m6 ; 67
movq m0, [srcq+ssq*0]
pmaddwd m14, m11, m5 ; a3
punpcklwd m6, m0 ; 78
paddd m12, m7
paddd m12, m14
pmaddwd m14, m11, m6 ; b3
paddd m13, m7
paddd m13, m14
psrad m12, 4
psrad m13, 4
packssdw m12, m13
movq [tmpq+r6*0], m12
movhps [tmpq+r6*2], m12
lea tmpq, [tmpq+r6*4]
sub hd, 2
jg .v_loop
add r5, 8
add r7, 8
mov srcq, r5
mov tmpq, r7
%endif
movzx hd, wb
sub wd, 1<<8
jg .v_loop0
RET
.hv:
%if STACK_ALIGNMENT < 16
%xdefine rstk rsp
%else
%assign stack_offset stack_offset - stack_size_padded
%endif
movzx t3d, mxb
shr mxd, 16
cmp wd, 4
cmove mxd, t3d
movifnidn hd, r4m
movq m2, [base+subpel_filters+mxq*8]
movzx mxd, myb
shr myd, 16
cmp hd, 4
cmove myd, mxd
movq m3, [base+subpel_filters+myq*8]
%if ARCH_X86_32
mov ssq, r2mp
mov tmpq, r0mp
mova m0, [base+spel_h_shufA]
mova m1, [base+spel_h_shufB]
mova m4, [base+prep_8tap_2d_rnd]
ALLOC_STACK -16*14
mova m8, m0
mova m9, m1
mova m14, m4
%else
%if WIN64
ALLOC_STACK 16*6, 16
%endif
mova m8, [base+spel_h_shufA]
mova m9, [base+spel_h_shufB]
%endif
pxor m0, m0
punpcklbw m0, m2
punpcklbw m3, m3
psraw m0, 4
psraw m3, 8
test dword r7m, 0x800
jz .hv_10bpc
psraw m0, 2
.hv_10bpc:
lea r6, [ssq*3]
sub srcq, 6
sub srcq, r6
mov r6d, wd
shl wd, 6
mov r5, srcq
%if ARCH_X86_32
%define tmp esp+16*8
%if STACK_ALIGNMENT < 16
mov [esp+4*61], tmpq
%endif
pshufd m1, m0, q0000
pshufd m2, m0, q1111
pshufd m5, m0, q2222
pshufd m0, m0, q3333
mova m10, m1
mova m11, m2
mova m12, m5
mova m13, m0
%else
%if WIN64
%define tmp rsp
%else
%define tmp rsp-88 ; red zone
%endif
mov r7, tmpq
pshufd m10, m0, q0000
pshufd m11, m0, q1111
pshufd m12, m0, q2222
pshufd m13, m0, q3333
%endif
lea wd, [wq+hq-(1<<8)]
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
mova [tmp+16*1], m0
mova [tmp+16*2], m1
mova [tmp+16*3], m2
mova [tmp+16*4], m3
.hv_loop0:
%if ARCH_X86_64
mova m14, [prep_8tap_2d_rnd]
%endif
movu m4, [srcq+ssq*0+0]
movu m1, [srcq+ssq*0+8]
movu m5, [srcq+ssq*1+0]
movu m2, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
movu m6, [srcq+ssq*0+0]
movu m3, [srcq+ssq*0+8]
PUT_8TAP_HV_H 4, 1, 0, 6
PUT_8TAP_HV_H 5, 2, 0, 6
PUT_8TAP_HV_H 6, 3, 0, 6
movu m7, [srcq+ssq*1+0]
movu m2, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
movu m1, [srcq+ssq*0+0]
movu m3, [srcq+ssq*0+8]
PUT_8TAP_HV_H 7, 2, 0, 6
PUT_8TAP_HV_H 1, 3, 0, 6
movu m2, [srcq+ssq*1+0]
movu m3, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
PUT_8TAP_HV_H 2, 3, 0, 6
packssdw m4, m7 ; 0 3
packssdw m5, m1 ; 1 4
movu m0, [srcq+ssq*0+0]
movu m1, [srcq+ssq*0+8]
PUT_8TAP_HV_H 0, 1, 3, 6
packssdw m6, m2 ; 2 5
packssdw m7, m0 ; 3 6
punpcklwd m1, m4, m5 ; 01
punpckhwd m4, m5 ; 34
punpcklwd m2, m5, m6 ; 12
punpckhwd m5, m6 ; 45
punpcklwd m3, m6, m7 ; 23
punpckhwd m6, m7 ; 56
%if ARCH_X86_32
jmp .hv_loop_start
.hv_loop:
mova m1, [tmp+16*5]
mova m2, m15
.hv_loop_start:
mova m7, [tmp+16*1]
pmaddwd m1, m7 ; a0
pmaddwd m2, m7 ; b0
mova m7, [tmp+16*2]
mova [tmp+16*5], m3
pmaddwd m3, m7 ; a1
mova m15, m4
pmaddwd m4, m7 ; b1
mova m7, [tmp+16*3]
paddd m1, m14
paddd m2, m14
paddd m1, m3
paddd m2, m4
mova m3, m5
pmaddwd m5, m7 ; a2
mova m4, m6
pmaddwd m6, m7 ; b2
paddd m1, m5
paddd m2, m6
movu m7, [srcq+ssq*1+0]
movu m5, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
PUT_8TAP_HV_H 7, 5, 6, 6
packssdw m0, m7 ; 6 7
mova [tmp+16*0], m0
movu m0, [srcq+ssq*0+0]
movu m5, [srcq+ssq*0+8]
PUT_8TAP_HV_H 0, 5, 6, 6
mova m6, [tmp+16*0]
packssdw m7, m0 ; 7 8
punpcklwd m5, m6, m7 ; 67
punpckhwd m6, m7 ; 78
pmaddwd m7, m5, [tmp+16*4]
paddd m1, m7 ; a3
pmaddwd m7, m6, [tmp+16*4]
paddd m2, m7 ; b3
psrad m1, 6
psrad m2, 6
packssdw m1, m2
movq [tmpq+r6*0], m1
movhps [tmpq+r6*2], m1
lea tmpq, [tmpq+r6*4]
sub hd, 2
jg .hv_loop
%if STACK_ALIGNMENT < 16
mov tmpq, [esp+4*61]
add r5, 8
add tmpq, 8
mov srcq, r5
mov [esp+4*61], tmpq
%else
mov tmpq, tmpmp
add r5, 8
add tmpq, 8
mov srcq, r5
mov tmpmp, tmpq
%endif
%else
.hv_loop:
mova m15, [tmp+16*1]
mova m7, [prep_8tap_2d_rnd]
pmaddwd m14, m15, m1 ; a0
pmaddwd m15, m2 ; b0
paddd m14, m7
paddd m15, m7
mova m7, [tmp+16*2]
mova m1, m3
pmaddwd m3, m7 ; a1
mova m2, m4
pmaddwd m4, m7 ; b1
mova m7, [tmp+16*3]
paddd m14, m3
paddd m15, m4
mova m3, m5
pmaddwd m5, m7 ; a2
mova m4, m6
pmaddwd m6, m7 ; b2
paddd m14, m5
paddd m15, m6
movu m7, [srcq+ssq*1+0]
movu m5, [srcq+ssq*1+8]
lea srcq, [srcq+ssq*2]
PUT_8TAP_HV_H 7, 5, 6, 6, [prep_8tap_2d_rnd]
packssdw m0, m7 ; 6 7
mova [tmp+16*0], m0
movu m0, [srcq+ssq*0+0]
movu m5, [srcq+ssq*0+8]
PUT_8TAP_HV_H 0, 5, 6, 6, [prep_8tap_2d_rnd]
mova m6, [tmp+16*0]
packssdw m7, m0 ; 7 8
punpcklwd m5, m6, m7 ; 67
punpckhwd m6, m7 ; 78
pmaddwd m7, m5, [tmp+16*4]
paddd m14, m7 ; a3
pmaddwd m7, m6, [tmp+16*4]
paddd m15, m7 ; b3
psrad m14, 6
psrad m15, 6
packssdw m14, m15
movq [tmpq+r6*0], m14
movhps [tmpq+r6*2], m14
lea tmpq, [tmpq+r6*4]
sub hd, 2
jg .hv_loop
add r5, 8
add r7, 8
mov srcq, r5
mov tmpq, r7
%endif
movzx hd, wb
sub wd, 1<<8
jg .hv_loop0
RET
%undef tmp
%macro movifprep 2
%if isprep
mov %1, %2
%endif
%endmacro
%macro SAVE_REG 1
%xdefine r%1_save r%1
%xdefine r%1q_save r%1q
%xdefine r%1d_save r%1d
%if ARCH_X86_32
%define r%1m_save [rstk+stack_offset+(%1+1)*4]
%endif
%endmacro
%macro LOAD_REG 1
%xdefine r%1 r%1_save
%xdefine r%1q r%1q_save
%xdefine r%1d r%1d_save
%if ARCH_X86_32
%define r%1m r%1m_save
%endif
%undef r%1d_save
%undef r%1q_save
%undef r%1_save
%endmacro
%macro REMAP_REG 2-3
%xdefine r%1 r%2
%xdefine r%1q r%2q
%xdefine r%1d r%2d
%if ARCH_X86_32
%if %3 == 0
%xdefine r%1m r%2m
%else
%define r%1m [rstk+stack_offset+(%1+1)*4]
%endif
%endif
%endmacro
%macro MCT_8TAP_SCALED_REMAP_REGS_TO_PREV 0
%if isprep
%if ARCH_X86_64
SAVE_REG 14
%assign %%i 14
%rep 14
%assign %%j %%i-1
REMAP_REG %%i, %%j
%assign %%i %%i-1
%endrep
%else
SAVE_REG 5
%assign %%i 5
%rep 5
%assign %%j %%i-1
REMAP_REG %%i, %%j, 0
%assign %%i %%i-1
%endrep
%endif
%endif
%endmacro
%macro MCT_8TAP_SCALED_REMAP_REGS_TO_DEFAULT 0
%if isprep
%assign %%i 1
%if ARCH_X86_64
%rep 13
%assign %%j %%i+1
REMAP_REG %%i, %%j
%assign %%i %%i+1
%endrep
LOAD_REG 14
%else
%rep 4
%assign %%j %%i+1
REMAP_REG %%i, %%j, 1
%assign %%i %%i+1
%endrep
LOAD_REG 5
%endif
%endif
%endmacro
%macro MC_8TAP_SCALED_RET 0-1 1 ; leave_mapping_unchanged
MCT_8TAP_SCALED_REMAP_REGS_TO_DEFAULT
RET
%if %1
MCT_8TAP_SCALED_REMAP_REGS_TO_PREV
%endif
%endmacro
%if ARCH_X86_32
%macro MC_4TAP_SCALED_H 1 ; dst_mem
movu m7, [srcq+ssq*0]
movu m2, [srcq+ssq*1]
movu m5, [r4 +ssq*0]
movu m6, [r4 +ssq*1]
lea srcq, [srcq+ssq*2]
lea r4, [r4 +ssq*2]
REPX {pshufb x, m12}, m7, m2
REPX {pmaddwd x, m13}, m7, m2
REPX {pshufb x, m14}, m5, m6
REPX {pmaddwd x, m15}, m5, m6
phaddd m7, m5
phaddd m2, m6
mova m5, [esp+0x00]
movd m6, [esp+0x10]
paddd m7, m5
paddd m2, m5
psrad m7, m6
psrad m2, m6
packssdw m7, m2
mova [stk+%1], m7
%endmacro
%endif
%if ARCH_X86_64
%macro MC_8TAP_SCALED_H 8 ; dst, tmp[0-6]
movu m%1, [srcq+ r4*2]
movu m%2, [srcq+ r6*2]
movu m%3, [srcq+ r7*2]
movu m%4, [srcq+ r9*2]
movu m%5, [srcq+r10*2]
movu m%6, [srcq+r11*2]
movu m%7, [srcq+r13*2]
movu m%8, [srcq+ rX*2]
add srcq, ssq
pmaddwd m%1, [stk+0x10]
pmaddwd m%2, [stk+0x20]
pmaddwd m%3, [stk+0x30]
pmaddwd m%4, [stk+0x40]
pmaddwd m%5, [stk+0x50]
pmaddwd m%6, [stk+0x60]
pmaddwd m%7, [stk+0x70]
pmaddwd m%8, [stk+0x80]
phaddd m%1, m%2
phaddd m%3, m%4
phaddd m%5, m%6
phaddd m%7, m%8
phaddd m%1, m%3
phaddd m%5, m%7
paddd m%1, hround
paddd m%5, hround
psrad m%1, m12
psrad m%5, m12
packssdw m%1, m%5
%endmacro
%else
%macro MC_8TAP_SCALED_H 2-3 1 ; weights_mem_start, h_mem, load_fh_offsets
%if %3 == 1
mov r0, [stk+ 0]
mov rX, [stk+ 4]
mov r4, [stk+ 8]
mov r5, [stk+12]
%endif
movu m0, [srcq+r0*2]
movu m1, [srcq+rX*2]
movu m2, [srcq+r4*2]
movu m3, [srcq+r5*2]
mov r0, [stk+16]
mov rX, [stk+20]
mov r4, [stk+24]
mov r5, [stk+28]
pmaddwd m0, [stk+%1+0x00]
pmaddwd m1, [stk+%1+0x10]
pmaddwd m2, [stk+%1+0x20]
pmaddwd m3, [stk+%1+0x30]
phaddd m0, m1
phaddd m2, m3
movu m4, [srcq+r0*2]
movu m5, [srcq+rX*2]
movu m6, [srcq+r4*2]
movu m7, [srcq+r5*2]
add srcq, ssq
pmaddwd m4, [stk+%1+0xa0]
pmaddwd m5, [stk+%1+0xb0]
pmaddwd m6, [stk+%1+0xc0]
pmaddwd m7, [stk+%1+0xd0]
phaddd m4, m5
phaddd m6, m7
phaddd m0, m2
phaddd m4, m6
paddd m0, hround
paddd m4, hround
psrad m0, m12
psrad m4, m12
packssdw m0, m4
%if %2 != 0
mova [stk+%2], m0
%endif
%endmacro
%endif
%macro MC_8TAP_SCALED 1
%ifidn %1, put
%assign isput 1
%assign isprep 0
%if ARCH_X86_64
%if required_stack_alignment <= STACK_ALIGNMENT
cglobal put_8tap_scaled_16bpc, 2, 15, 16, 0x1c0, dst, ds, src, ss, w, h, mx, my, dx, dy, pxmax
%else
cglobal put_8tap_scaled_16bpc, 2, 14, 16, 0x1c0, dst, ds, src, ss, w, h, mx, my, dx, dy, pxmax
%endif
%else ; ARCH_X86_32
%if required_stack_alignment <= STACK_ALIGNMENT
cglobal put_8tap_scaled_16bpc, 0, 7, 8, 0x200, dst, ds, src, ss, w, h, mx, my, dx, dy, pxmax
%else
cglobal put_8tap_scaled_16bpc, 0, 7, 8, -0x200-0x30, dst, ds, src, ss, w, h, mx, my, dx, dy, pxmax
%endif
%endif
%xdefine base_reg r12
%else ; prep
%assign isput 0
%assign isprep 1
%if ARCH_X86_64
%if required_stack_alignment <= STACK_ALIGNMENT
cglobal prep_8tap_scaled_16bpc, 2, 15, 16, 0x1c0, tmp, src, ss, w, h, mx, my, dx, dy, pxmax
%xdefine tmp_stridem r14q
%else
cglobal prep_8tap_scaled_16bpc, 2, 14, 16, 0x1c0, tmp, src, ss, w, h, mx, my, dx, dy, pxmax
%define tmp_stridem qword [stk+0x138]
%endif
%xdefine base_reg r11
%else ; ARCH_X86_32
%if required_stack_alignment <= STACK_ALIGNMENT
cglobal prep_8tap_scaled_16bpc, 0, 7, 8, 0x200, tmp, src, ss, w, h, mx, my, dx, dy, pxmax
%else
cglobal prep_8tap_scaled_16bpc, 0, 6, 8, 0x200, tmp, src, ss, w, h, mx, my, dx, dy, pxmax
%endif
%define tmp_stridem dword [stk+0x138]
%endif
%endif
%if ARCH_X86_32
mov [esp+0x1f0], t0d
mov [esp+0x1f4], t1d
%if isput && required_stack_alignment > STACK_ALIGNMENT
mov dstd, dstm
mov dsd, dsm
mov srcd, srcm
mov ssd, ssm
mov hd, hm
mov r4, mxm
%define r0m [esp+0x200]
%define dsm [esp+0x204]
%define dsmp dsm
%define r1m dsm
%define r2m [esp+0x208]
%define ssm [esp+0x20c]
%define r3m ssm
%define hm [esp+0x210]
%define mxm [esp+0x214]
mov r0m, dstd
mov dsm, dsd
mov r2m, srcd
mov ssm, ssd
mov hm, hd
mov r0, mym
mov r1, dxm
mov r2, dym
%define mym [esp+0x218]
%define dxm [esp+0x21c]
%define dym [esp+0x220]
mov mxm, r4
mov mym, r0
mov dxm, r1
mov dym, r2
tzcnt wd, wm
%endif
%if isput
mov r3, pxmaxm
%define pxmaxm r3
%else
mov r2, pxmaxm
%endif
%if isprep && required_stack_alignment > STACK_ALIGNMENT
%xdefine base_reg r5
%else
%xdefine base_reg r6
%endif
%endif
LEA base_reg, %1_8tap_scaled_16bpc_ssse3
%xdefine base base_reg-%1_8tap_scaled_16bpc_ssse3
%if ARCH_X86_64 || isprep || required_stack_alignment <= STACK_ALIGNMENT
tzcnt wd, wm
%endif
%if ARCH_X86_64
%if isput
mov r7d, pxmaxm
%endif
%else
%define m8 m0
%define m9 m1
%define m14 m4
%define m15 m3
%endif
movd m8, dxm
movd m14, mxm
%if isput
movd m15, pxmaxm
%endif
pshufd m8, m8, q0000
pshufd m14, m14, q0000
%if isput
pshuflw m15, m15, q0000
punpcklqdq m15, m15
%endif
%if isprep
%if UNIX64
mov r5d, t0d
DECLARE_REG_TMP 5, 7
%endif
%if ARCH_X86_64
mov r6d, pxmaxm
%endif
%endif
%if ARCH_X86_64
mov dyd, dym
%endif
%if isput
%if WIN64
mov r8d, hm
DEFINE_ARGS dst, ds, src, ss, w, _, _, my, h, dy, ss3
%define hm r5m
%define dxm r8m
%elif ARCH_X86_64
DEFINE_ARGS dst, ds, src, ss, w, h, _, my, dx, dy, ss3
%define hm r6m
%else
%endif
%if ARCH_X86_64
%if required_stack_alignment > STACK_ALIGNMENT
%define dsm [rsp+0x138]
%define rX r1
%define rXd r1d
%else
%define dsm dsq
%define rX r14
%define rXd r14d
%endif
%else
%define rX r1
%endif
%else ; prep
%if WIN64
mov r7d, hm
DEFINE_ARGS tmp, src, ss, w, _, _, my, h, dy, ss3
%define hm r4m
%define dxm r7m
%elif ARCH_X86_64
DEFINE_ARGS tmp, src, ss, w, h, _, my, dx, dy, ss3
%xdefine hm r7m
%endif
MCT_8TAP_SCALED_REMAP_REGS_TO_PREV
%if ARCH_X86_64
%define rX r14
%define rXd r14d
%else
%define rX r3
%endif
%endif
%if ARCH_X86_64
shr r7d, 11
mova m10, [base+pd_0x3ff]
movddup m11, [base+s_8tap_h_rnd+r7*8]
movd m12, [base+s_8tap_h_sh+r7*4]
%if isput
movddup m13, [base+put_s_8tap_v_rnd+r7*8]
movd m7, [base+put_s_8tap_v_sh+r7*4]
%define pxmaxm [rsp]
mova pxmaxm, m15
punpcklqdq m12, m7
%endif
lea ss3q, [ssq*3]
movzx r7d, t1b
shr t1d, 16
cmp hd, 6
cmovs t1d, r7d
sub srcq, ss3q
%else
%define m10 [base+pd_0x3ff]
%define m11 [esp+0x00]
%define m12 [esp+0x10]
shr r3, 11
movddup m1, [base+s_8tap_h_rnd+r3*8]
movd m2, [base+s_8tap_h_sh+r3*4]
%if isput
%define m13 [esp+0x20]
%define pxmaxm [esp+0x30]
%define stk esp+0x40
movddup m5, [base+put_s_8tap_v_rnd+r3*8]
movd m6, [base+put_s_8tap_v_sh+r3*4]
mova pxmaxm, m15
punpcklqdq m2, m6
mova m13, m5
%else
%define m13 [base+pd_m524256]
%endif
mov ssd, ssm
mova m11, m1
mova m12, m2
MCT_8TAP_SCALED_REMAP_REGS_TO_DEFAULT
mov r1, [esp+0x1f4]
lea r0, [ssd*3]
movzx r2, r1b
shr r1, 16
cmp dword hm, 6
cmovs r1, r2
mov [esp+0x1f4], r1
%if isprep
mov r1, r1m
%endif
mov r2, r2m
sub srcq, r0
MCT_8TAP_SCALED_REMAP_REGS_TO_PREV
%define ss3q r0
%define myd r4
%define dyd dword dym
%define hd dword hm
%endif
cmp dyd, 1024
je .dy1
cmp dyd, 2048
je .dy2
movzx wd, word [base+%1_8tap_scaled_ssse3_table+wq*2]
add wq, base_reg
jmp wq
%if isput
.w2:
%if ARCH_X86_64
mov myd, mym
movzx t0d, t0b
sub srcq, 2
movd m15, t0d
%else
movzx r4, byte [esp+0x1f0]
sub srcq, 2
movd m15, r4
%endif
pxor m9, m9
punpckldq m9, m8
paddd m14, m9 ; mx+dx*[0-1]
%if ARCH_X86_64
mova m9, [base+pd_0x4000]
%endif
pshufd m15, m15, q0000
pand m8, m14, m10
psrld m8, 6
paddd m15, m8
movd r4d, m15
pshufd m15, m15, q0321
%if ARCH_X86_64
movd r6d, m15
%else
movd r3d, m15
%endif
mova m5, [base+bdct_lb_q]
mova m6, [base+spel_s_shuf2]
movd m15, [base+subpel_filters+r4*8+2]
%if ARCH_X86_64
movd m7, [base+subpel_filters+r6*8+2]
%else
movd m7, [base+subpel_filters+r3*8+2]
%endif
pxor m2, m2
pcmpeqd m8, m2
psrld m14, 10
paddd m14, m14
%if ARCH_X86_32
mov r3, r3m
pshufb m14, m5
paddb m14, m6
mova [stk], m14
SWAP m5, m0
SWAP m6, m3
%define m15 m6
%endif
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*1]
movu m2, [srcq+ssq*2]
movu m3, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
punpckldq m15, m7
%if ARCH_X86_64
pshufb m14, m5
paddb m14, m6
pand m9, m8
pandn m8, m15
SWAP m15, m8
por m15, m9
movu m4, [srcq+ssq*0]
movu m5, [srcq+ssq*1]
movu m6, [srcq+ssq*2]
movu m7, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
%else
pand m7, m5, [base+pd_0x4000]
pandn m5, m15
por m5, m7
%define m15 m5
%endif
punpcklbw m15, m15
psraw m15, 8
REPX {pshufb x, m14}, m0, m1, m2, m3
REPX {pmaddwd x, m15}, m0, m1, m2, m3
%if ARCH_X86_64
REPX {pshufb x, m14}, m4, m5, m6, m7
REPX {pmaddwd x, m15}, m4, m5, m6, m7
phaddd m0, m1
phaddd m2, m3
phaddd m4, m5
phaddd m6, m7
REPX {paddd x, m11}, m0, m2, m4, m6
REPX {psrad x, m12}, m0, m2, m4, m6
packssdw m0, m2 ; 0 1 2 3
packssdw m4, m6 ; 4 5 6 7
SWAP m1, m4
%else
mova [stk+0x10], m15
phaddd m0, m1
phaddd m2, m3
movu m1, [srcq+ssq*0]
movu m7, [srcq+ssq*1]
movu m6, [srcq+ssq*2]
movu m3, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
REPX {pshufb x, m14}, m1, m7, m6, m3
REPX {pmaddwd x, m15}, m1, m7, m6, m3
phaddd m1, m7
phaddd m6, m3
REPX {paddd x, m11}, m0, m2, m1, m6
REPX {psrad x, m12}, m0, m2, m1, m6
packssdw m0, m2
packssdw m1, m6
%define m14 [stk+0x00]
%define m15 [stk+0x10]
%endif
palignr m2, m1, m0, 4 ; 1 2 3 4
punpcklwd m3, m0, m2 ; 01 12
punpckhwd m0, m2 ; 23 34
pshufd m5, m1, q0321 ; 5 6 7 _
punpcklwd m2, m1, m5 ; 45 56
punpckhwd m4, m1, m5 ; 67 __
%if ARCH_X86_32
mov myd, mym
mov r0, r0m
mova [stk+0x20], m3
mova [stk+0x30], m0
mova [stk+0x40], m2
mova [stk+0x50], m4
%endif
.w2_loop:
and myd, 0x3ff
%if ARCH_X86_64
mov r6d, 64 << 24
mov r4d, myd
shr r4d, 6
lea r4d, [t1+r4]
cmovnz r6q, [base+subpel_filters+r4*8]
movq m10, r6q
punpcklbw m10, m10
psraw m10, 8
pshufd m7, m10, q0000
pshufd m8, m10, q1111
pmaddwd m5, m3, m7
pmaddwd m6, m0, m8
pshufd m9, m10, q2222
pshufd m10, m10, q3333
pmaddwd m7, m2, m9
pmaddwd m8, m4, m10
paddd m5, m6
paddd m7, m8
%else
mov r1, [esp+0x1f4]
xor r3, r3
mov r5, myd
shr r5, 6
lea r1, [r1+r5]
mov r5, 64 << 24
cmovnz r3, [base+subpel_filters+r1*8+4]
cmovnz r5, [base+subpel_filters+r1*8+0]
movd m6, r3
movd m7, r5
punpckldq m7, m6
punpcklbw m7, m7
psraw m7, 8
pshufd m5, m7, q0000
pshufd m6, m7, q1111
pmaddwd m3, m5
pmaddwd m0, m6
pshufd m5, m7, q2222
pshufd m7, m7, q3333
pmaddwd m2, m5
pmaddwd m4, m7
paddd m3, m0
paddd m2, m4
SWAP m5, m3
SWAP m7, m2
%define m8 m3
%endif
paddd m5, m13
pshufd m6, m12, q1032
pxor m8, m8
paddd m5, m7
psrad m5, m6
packssdw m5, m5
pmaxsw m5, m8
pminsw m5, pxmaxm
movd [dstq], m5
add dstq, dsmp
dec hd
jz .ret
%if ARCH_X86_64
add myd, dyd
%else
add myd, dym
%endif
test myd, ~0x3ff
%if ARCH_X86_32
SWAP m3, m5
SWAP m2, m7
mova m3, [stk+0x20]
mova m0, [stk+0x30]
mova m2, [stk+0x40]
mova m4, [stk+0x50]
%endif
jz .w2_loop
%if ARCH_X86_32
mov r3, r3m
%endif
movu m5, [srcq]
test myd, 0x400
jz .w2_skip_line
add srcq, ssq
shufps m3, m0, q1032 ; 01 12
shufps m0, m2, q1032 ; 23 34
shufps m2, m4, q1032 ; 45 56
pshufb m5, m14
pmaddwd m5, m15
phaddd m5, m5
paddd m5, m11
psrad m5, m12
packssdw m5, m5
palignr m4, m5, m1, 12
punpcklqdq m1, m4, m4 ; 6 7 6 7
punpcklwd m4, m1, m5 ; 67 __
%if ARCH_X86_32
mova [stk+0x20], m3
mova [stk+0x30], m0
mova [stk+0x40], m2
mova [stk+0x50], m4
%endif
jmp .w2_loop
.w2_skip_line:
movu m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
mova m3, m0 ; 01 12
mova m0, m2 ; 23 34
pshufb m5, m14
pshufb m6, m14
pmaddwd m5, m15
pmaddwd m6, m15
phaddd m5, m6
paddd m5, m11
psrad m5, m12
packssdw m5, m5 ; 6 7 6 7
punpckhqdq m1, m5 ; 4 5 6 7
pshufd m5, m1, q0321 ; 5 6 7 _
punpcklwd m2, m1, m5 ; 45 56
punpckhwd m4, m1, m5 ; 67 __
%if ARCH_X86_32
mova [stk+0x20], m3
mova [stk+0x30], m0
mova [stk+0x40], m2
mova [stk+0x50], m4
%endif
jmp .w2_loop
%endif
INIT_XMM ssse3
.w4:
%if ARCH_X86_64
mov myd, mym
mova [rsp+0x10], m11
mova [rsp+0x20], m12
%if isput
mova [rsp+0x30], m13
%endif
movzx t0d, t0b
sub srcq, 2
movd m15, t0d
%else
%define m8 m0
%xdefine m14 m4
%define m15 m3
movzx r4, byte [esp+0x1f0]
sub srcq, 2
movd m15, r4
%endif
pmaddwd m8, [base+rescale_mul]
%if ARCH_X86_64
mova m9, [base+pd_0x4000]
%else
%define m9 [base+pd_0x4000]
%endif
pshufd m15, m15, q0000
paddd m14, m8 ; mx+dx*[0-3]
pand m0, m14, m10
psrld m0, 6
paddd m15, m0
pshufd m7, m15, q1032
%if ARCH_X86_64
movd r4d, m15
movd r11d, m7
pshufd m15, m15, q0321
pshufd m7, m7, q0321
movd r6d, m15
movd r13d, m7
mova m10, [base+bdct_lb_q+ 0]
mova m11, [base+bdct_lb_q+16]
movd m13, [base+subpel_filters+ r4*8+2]
movd m2, [base+subpel_filters+ r6*8+2]
movd m15, [base+subpel_filters+r11*8+2]
movd m4, [base+subpel_filters+r13*8+2]
%else
movd r0, m15
movd r4, m7
pshufd m15, m15, q0321
pshufd m7, m7, q0321
movd rX, m15
movd r5, m7
mova m5, [base+bdct_lb_q+ 0]
mova m6, [base+bdct_lb_q+16]
movd m1, [base+subpel_filters+r0*8+2]
movd m2, [base+subpel_filters+rX*8+2]
movd m3, [base+subpel_filters+r4*8+2]
movd m7, [base+subpel_filters+r5*8+2]
movifprep r3, r3m
SWAP m4, m7
%define m10 m5
%define m11 m6
%define m12 m1
%define m13 m1
%endif
psrld m14, 10
paddd m14, m14
punpckldq m13, m2
punpckldq m15, m4
punpcklqdq m13, m15
pxor m2, m2
pcmpeqd m0, m2
%if ARCH_X86_64
pand m9, m0
%else
pand m2, m9, m0
%define m9 m2
SWAP m7, m4
%endif
pandn m0, m13
%if ARCH_X86_64
SWAP m13, m0
%else
%define m13 m0
%endif
por m13, m9
punpckhbw m15, m13, m13
punpcklbw m13, m13
psraw m15, 8
psraw m13, 8
pshufb m12, m14, m10
pshufb m14, m11
mova m10, [base+spel_s_shuf2]
movd r4d, m14
shr r4d, 24
%if ARCH_X86_32
mova [stk+0x20], m13
mova [stk+0x30], m15
pxor m2, m2
%endif
pshufb m7, m14, m2
psubb m14, m7
paddb m12, m10
paddb m14, m10
%if ARCH_X86_64
lea r6, [r4+ssq*1]
lea r11, [r4+ssq*2]
lea r13, [r4+ss3q ]
movu m7, [srcq+ssq*0]
movu m9, [srcq+ssq*1]
movu m8, [srcq+ssq*2]
movu m10, [srcq+ss3q ]
movu m1, [srcq+r4 ]
movu m3, [srcq+r6 ]
movu m2, [srcq+r11 ]
movu m4, [srcq+r13 ]
lea srcq, [srcq+ssq*4]
REPX {pshufb x, m12}, m7, m9, m8, m10
REPX {pmaddwd x, m13}, m7, m9, m8, m10
REPX {pshufb x, m14}, m1, m2, m3, m4
REPX {pmaddwd x, m15}, m1, m2, m3, m4
mova m5, [rsp+0x10]
movd xm6, [rsp+0x20]
phaddd m7, m1
phaddd m9, m3
phaddd m8, m2
phaddd m10, m4
movu m1, [srcq+ssq*0]
movu m2, [srcq+ssq*1]
movu m3, [srcq+ssq*2]
movu m4, [srcq+ss3q ]
REPX {paddd x, m5}, m7, m9, m8, m10
REPX {psrad x, xm6}, m7, m9, m8, m10
packssdw m7, m9 ; 0 1
packssdw m8, m10 ; 2 3
movu m0, [srcq+r4 ]
movu m9, [srcq+r6 ]
movu m10, [srcq+r11 ]
movu m11, [srcq+r13 ]
lea srcq, [srcq+ssq*4]
REPX {pshufb x, m12}, m1, m2, m3, m4
REPX {pmaddwd x, m13}, m1, m2, m3, m4
REPX {pshufb x, m14}, m0, m9, m10, m11
REPX {pmaddwd x, m15}, m0, m9, m10, m11
phaddd m1, m0
phaddd m2, m9
phaddd m3, m10
phaddd m4, m11
REPX {paddd x, m5}, m1, m2, m3, m4
REPX {psrad x, xm6}, m1, m2, m3, m4
packssdw m1, m2 ; 4 5
packssdw m3, m4 ; 6 7
SWAP m9, m1
shufps m4, m7, m8, q1032 ; 1 2
shufps m5, m8, m9, q1032 ; 3 4
shufps m6, m9, m3, q1032 ; 5 6
pshufd m10, m3, q1032 ; 7 _
punpcklwd m0, m7, m4 ; 01
punpckhwd m7, m4 ; 12
punpcklwd m1, m8, m5 ; 23
punpckhwd m8, m5 ; 34
punpcklwd m2, m9, m6 ; 45
punpckhwd m9, m6 ; 56
punpcklwd m3, m10 ; 67
mova [rsp+0x40], m7
mova [rsp+0x50], m8
mova [rsp+0x60], m9
%else
mova [stk+0x00], m12
mova [stk+0x10], m14
add r4, srcq
MC_4TAP_SCALED_H 0x40 ; 0 1
MC_4TAP_SCALED_H 0x50 ; 2 3
MC_4TAP_SCALED_H 0x60 ; 4 5
MC_4TAP_SCALED_H 0x70 ; 6 7
mova m4, [stk+0x40]
mova m5, [stk+0x50]
mova m6, [stk+0x60]
mova m7, [stk+0x70]
mov [stk+0xc0], r4
shufps m1, m4, m5, q1032 ; 1 2
shufps m2, m5, m6, q1032 ; 3 4
shufps m3, m6, m7, q1032 ; 5 6
pshufd m0, m7, q1032 ; 7 _
mova [stk+0xb0], m0
punpcklwd m0, m4, m1 ; 01
punpckhwd m4, m1 ; 12
punpcklwd m1, m5, m2 ; 23
punpckhwd m5, m2 ; 34
punpcklwd m2, m6, m3 ; 45
punpckhwd m6, m3 ; 56
punpcklwd m3, m7, [stk+0xb0] ; 67
mov myd, mym
mov r0, r0m
mova [stk+0x40], m0 ; 01
mova [stk+0x50], m1 ; 23
mova [stk+0x60], m2 ; 45
mova [stk+0x70], m3 ; 67
mova [stk+0x80], m4 ; 12
mova [stk+0x90], m5 ; 34
mova [stk+0xa0], m6 ; 56
%define m12 [stk+0x00]
%define m14 [stk+0x10]
%define m13 [stk+0x20]
%define m15 [stk+0x30]
%define hrnd_mem [esp+0x00]
%define hsh_mem [esp+0x10]
%if isput
%define vrnd_mem [esp+0x20]
%else
%define vrnd_mem [base+pd_m524256]
%endif
%endif
.w4_loop:
and myd, 0x3ff
%if ARCH_X86_64
mov r11d, 64 << 24
mov r13d, myd
shr r13d, 6
lea r13d, [t1+r13]
cmovnz r11q, [base+subpel_filters+r13*8]
movq m9, r11q
punpcklbw m9, m9
psraw m9, 8
pshufd m7, m9, q0000
pshufd m8, m9, q1111
pmaddwd m4, m0, m7
pmaddwd m5, m1, m8
pshufd m7, m9, q2222
pshufd m9, m9, q3333
pmaddwd m6, m2, m7
pmaddwd m8, m3, m9
%if isput
movd m9, [rsp+0x28]
%define vrnd_mem [rsp+0x30]
%else
%define vrnd_mem [base+pd_m524256]
%endif
paddd m4, m5
paddd m6, m8
paddd m4, m6
paddd m4, vrnd_mem
%else
mov mym, myd
mov r5, [esp+0x1f4]
xor r3, r3
shr r4, 6
lea r5, [r5+r4]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+r5*8+0]
cmovnz r3, [base+subpel_filters+r5*8+4]
movd m7, r4
movd m6, r3
punpckldq m7, m6
punpcklbw m7, m7
psraw m7, 8
pshufd m4, m7, q0000
pshufd m5, m7, q1111
pshufd m6, m7, q2222
pshufd m7, m7, q3333
pmaddwd m0, m4
pmaddwd m1, m5
pmaddwd m2, m6
pmaddwd m3, m7
%if isput
movd m4, [esp+0x18]
%endif
paddd m0, m1
paddd m2, m3
paddd m0, vrnd_mem
paddd m0, m2
SWAP m4, m0
%define m9 m0
%endif
%if isput
pxor m5, m5
psrad m4, m9
packssdw m4, m4
pmaxsw m4, m5
pminsw m4, pxmaxm
movq [dstq], m4
add dstq, dsmp
%else
psrad m4, 6
packssdw m4, m4
movq [tmpq], m4
add tmpq, 8
%endif
dec hd
jz .ret
%if ARCH_X86_64
add myd, dyd
test myd, ~0x3ff
jz .w4_loop
mova m8, [rsp+0x10]
movd m9, [rsp+0x20]
movu m4, [srcq]
movu m5, [srcq+r4]
test myd, 0x400
jz .w4_skip_line
mova m0, [rsp+0x40]
mova [rsp+0x40], m1
mova m1, [rsp+0x50]
mova [rsp+0x50], m2
mova m2, [rsp+0x60]
mova [rsp+0x60], m3
pshufb m4, m12
pshufb m5, m14
pmaddwd m4, m13
pmaddwd m5, m15
phaddd m4, m5
paddd m4, m8
psrad m4, m9
packssdw m4, m4
punpcklwd m3, m10, m4
mova m10, m4
add srcq, ssq
jmp .w4_loop
.w4_skip_line:
movu m6, [srcq+ssq*1]
movu m7, [srcq+r6]
mova m0, [rsp+0x50]
mova m11, [rsp+0x60]
pshufb m4, m12
pshufb m6, m12
pshufb m5, m14
pshufb m7, m14
pmaddwd m4, m13
pmaddwd m6, m13
pmaddwd m5, m15
pmaddwd m7, m15
mova [rsp+0x40], m0
mova [rsp+0x50], m11
phaddd m4, m5
phaddd m6, m7
paddd m4, m8
paddd m6, m8
psrad m4, m9
psrad m6, m9
packssdw m4, m6
punpcklwd m9, m10, m4
mova [rsp+0x60], m9
pshufd m10, m4, q1032
mova m0, m1
mova m1, m2
mova m2, m3
punpcklwd m3, m4, m10
lea srcq, [srcq+ssq*2]
jmp .w4_loop
%else
SWAP m0, m4
mov myd, mym
mov r3, r3m
add myd, dym
test myd, ~0x3ff
jnz .w4_next_line
mova m0, [stk+0x40]
mova m1, [stk+0x50]
mova m2, [stk+0x60]
mova m3, [stk+0x70]
jmp .w4_loop
.w4_next_line:
mov r5, [stk+0xc0]
movu m4, [srcq]
movu m5, [r5]
test myd, 0x400
jz .w4_skip_line
add [stk+0xc0], ssq
mova m0, [stk+0x80]
mova m3, [stk+0x50]
mova [stk+0x40], m0
mova [stk+0x80], m3
mova m1, [stk+0x90]
mova m6, [stk+0x60]
mova [stk+0x50], m1
mova [stk+0x90], m6
mova m2, [stk+0xa0]
mova m7, [stk+0x70]
mova [stk+0x60], m2
mova [stk+0xa0], m7
pshufb m4, m12
pshufb m5, m14
pmaddwd m4, m13
pmaddwd m5, m15
phaddd m4, m5
paddd m4, hrnd_mem
psrad m4, hsh_mem
packssdw m4, m4
punpcklwd m3, [stk+0xb0], m4
mova [stk+0xb0], m4
mova [stk+0x70], m3
add srcq, ssq
jmp .w4_loop
.w4_skip_line:
movu m6, [srcq+ssq*1]
movu m7, [r5 +ssq*1]
lea r5, [r5 +ssq*2]
mov [stk+0xc0], r5
mova m0, [stk+0x50]
mova m1, [stk+0x60]
mova m2, [stk+0x70]
mova m3, [stk+0x90]
pshufb m4, m12
pshufb m6, m12
pshufb m5, m14
pshufb m7, m14
pmaddwd m4, m13
pmaddwd m6, m13
pmaddwd m5, m15
pmaddwd m7, m15
mova [stk+0x40], m0
mova [stk+0x50], m1
mova [stk+0x60], m2
mova [stk+0x80], m3
phaddd m4, m5
phaddd m6, m7
mova m5, [stk+0xa0]
mova m7, [stk+0xb0]
paddd m4, hrnd_mem
paddd m6, hrnd_mem
psrad m4, hsh_mem
psrad m6, hsh_mem
packssdw m4, m6
punpcklwd m7, m4
pshufd m6, m4, q1032
mova [stk+0x90], m5
mova [stk+0xa0], m7
mova [stk+0xb0], m6
punpcklwd m3, m4, m6
mova [stk+0x70], m3
lea srcq, [srcq+ssq*2]
jmp .w4_loop
%endif
INIT_XMM ssse3
%if ARCH_X86_64
%define stk rsp+0x20
%endif
.w8:
mov dword [stk+0xf0], 1
movifprep tmp_stridem, 16
jmp .w_start
.w16:
mov dword [stk+0xf0], 2
movifprep tmp_stridem, 32
jmp .w_start
.w32:
mov dword [stk+0xf0], 4
movifprep tmp_stridem, 64
jmp .w_start
.w64:
mov dword [stk+0xf0], 8
movifprep tmp_stridem, 128
jmp .w_start
.w128:
mov dword [stk+0xf0], 16
movifprep tmp_stridem, 256
.w_start:
%if ARCH_X86_64
%ifidn %1, put
movifnidn dsm, dsq
%endif
mova [rsp+0x10], m11
%define hround m11
shr t0d, 16
movd m15, t0d
%if isprep
mova m13, [base+pd_m524256]
%endif
%else
%define hround [esp+0x00]
%define m12 [esp+0x10]
%define m10 [base+pd_0x3ff]
%define m8 m0
%xdefine m14 m4
%define m15 m3
%if isprep
%define ssq ssm
%endif
mov r4, [esp+0x1f0]
shr r4, 16
movd m15, r4
mov r0, r0m
mov myd, mym
%endif
sub srcq, 6
pslld m7, m8, 2 ; dx*4
pmaddwd m8, [base+rescale_mul] ; dx*[0-3]
pshufd m15, m15, q0000
paddd m14, m8 ; mx+dx*[0-3]
mova [stk+0x100], m7
mova [stk+0x120], m15
mov [stk+0x0f8], srcq
mov [stk+0x130], r0q ; dstq / tmpq
%if ARCH_X86_64 && UNIX64
mov hm, hd
%elif ARCH_X86_32
mov r5, hm
mov [stk+0x0f4], myd
mov [stk+0x134], r5
%endif
jmp .hloop
.hloop_prep:
dec dword [stk+0x0f0]
jz .ret
%if ARCH_X86_64
add qword [stk+0x130], 16
mov hd, hm
%else
add dword [stk+0x130], 16
mov myd, [stk+0x0f4]
mov r5, [stk+0x134]
mov r0, [stk+0x130]
%endif
mova m7, [stk+0x100]
mova m14, [stk+0x110]
%if ARCH_X86_64
mova m10, [base+pd_0x3ff]
mova m11, [rsp+0x10]
%endif
mova m15, [stk+0x120]
mov srcq, [stk+0x0f8]
%if ARCH_X86_64
mov r0q, [stk+0x130] ; dstq / tmpq
%else
mov mym, myd
mov hm, r5
mov r0m, r0
mov r3, r3m
%endif
paddd m14, m7
.hloop:
%if ARCH_X86_64
mova m9, [base+pq_0x40000000]
%else
%define m9 [base+pq_0x40000000]
%endif
pxor m1, m1
psrld m2, m14, 10
mova [stk], m2
pand m6, m14, m10
psrld m6, 6
paddd m5, m15, m6
pcmpeqd m6, m1
pshufd m2, m5, q1032
%if ARCH_X86_64
movd r4d, m5
movd r6d, m2
pshufd m5, m5, q0321
pshufd m2, m2, q0321
movd r7d, m5
movd r9d, m2
movq m0, [base+subpel_filters+r4*8]
movq m1, [base+subpel_filters+r6*8]
movhps m0, [base+subpel_filters+r7*8]
movhps m1, [base+subpel_filters+r9*8]
%else
movd r0, m5
movd rX, m2
pshufd m5, m5, q0321
pshufd m2, m2, q0321
movd r4, m5
movd r5, m2
movq m0, [base+subpel_filters+r0*8]
movq m1, [base+subpel_filters+rX*8]
movhps m0, [base+subpel_filters+r4*8]
movhps m1, [base+subpel_filters+r5*8]
%endif
paddd m14, m7 ; mx+dx*[4-7]
pand m5, m14, m10
psrld m5, 6
paddd m15, m5
pxor m2, m2
pcmpeqd m5, m2
mova [stk+0x110], m14
pshufd m4, m15, q1032
%if ARCH_X86_64
movd r10d, m15
movd r11d, m4
pshufd m15, m15, q0321
pshufd m4, m4, q0321
movd r13d, m15
movd rXd, m4
movq m2, [base+subpel_filters+r10*8]
movq m3, [base+subpel_filters+r11*8]
movhps m2, [base+subpel_filters+r13*8]
movhps m3, [base+subpel_filters+ rX*8]
psrld m14, 10
movq r11, m14
punpckhqdq m14, m14
movq rX, m14
mov r10d, r11d
shr r11, 32
mov r13d, rXd
shr rX, 32
mov r4d, [stk+ 0]
mov r6d, [stk+ 4]
mov r7d, [stk+ 8]
mov r9d, [stk+12]
pshufd m4, m6, q1100
pshufd m6, m6, q3322
pshufd m14, m5, q1100
pshufd m5, m5, q3322
pand m7, m9, m4
pand m8, m9, m6
pand m15, m9, m14
pand m9, m9, m5
pandn m4, m0
pandn m6, m1
pandn m14, m2
pandn m5, m3
por m7, m4
por m8, m6
por m15, m14
por m9, m5
punpcklbw m0, m7, m7
punpckhbw m7, m7
punpcklbw m1, m8, m8
punpckhbw m8, m8
psraw m0, 8
psraw m7, 8
psraw m1, 8
psraw m8, 8
punpcklbw m2, m15, m15
punpckhbw m15, m15
punpcklbw m3, m9, m9
punpckhbw m9, m9
psraw m2, 8
psraw m15, 8
psraw m3, 8
psraw m9, 8
mova [stk+0x10], m0
mova [stk+0x20], m7
mova [stk+0x30], m1
mova [stk+0x40], m8
mova [stk+0x50], m2
mova [stk+0x60], m15
mova [stk+0x70], m3
mova [stk+0x80], m9
MC_8TAP_SCALED_H 1, 2, 3, 4, 5, 6, 9, 10 ; 0
mova [stk+0x90], m1
MC_8TAP_SCALED_H 2, 3, 4, 5, 6, 1, 9, 10 ; 1
mova [stk+0xa0], m2
MC_8TAP_SCALED_H 3, 4, 5, 6, 1, 2, 9, 10 ; 2
mova [stk+0xb0], m3
MC_8TAP_SCALED_H 4, 5, 6, 1, 2, 3, 9, 10 ; 3
mova [stk+0xc0], m4
MC_8TAP_SCALED_H 5, 6, 1, 2, 3, 4, 9, 10 ; 4
mova [stk+0xd0], m5
MC_8TAP_SCALED_H 6, 1, 2, 3, 4, 5, 9, 10 ; 5
MC_8TAP_SCALED_H 7, 1, 2, 3, 4, 5, 9, 10 ; 6
MC_8TAP_SCALED_H 8, 1, 2, 3, 4, 5, 9, 10 ; 7
mova m5, [stk+0xd0]
mova m1, [stk+0x90]
mova m2, [stk+0xa0]
mova m3, [stk+0xb0]
mova m9, [stk+0xc0]
mov myd, mym
mov dyd, dym
punpcklwd m4, m5, m6 ; 45a
punpckhwd m5, m6 ; 45b
punpcklwd m6, m7, m8 ; 67a
punpckhwd m7, m8 ; 67b
punpcklwd m0, m1, m2 ; 01a
punpckhwd m1, m2 ; 01b
punpcklwd m2, m3, m9 ; 23a
punpckhwd m3, m9 ; 23b
mova [stk+0x90], m4
mova [stk+0xa0], m5
mova [stk+0xb0], m6
mova [stk+0xc0], m7
%define hround [rsp+0x10]
.vloop:
and myd, 0x3ff
mov r6d, 64 << 24
mov r4d, myd
shr r4d, 6
lea r4d, [t1+r4]
cmovnz r6q, [base+subpel_filters+r4*8]
movq m11, r6q
punpcklbw m11, m11
psraw m11, 8
pshufd m5, m11, q0000
pshufd m7, m11, q1111
pshufd m10, m11, q2222
pshufd m11, m11, q3333
pmaddwd m4, m5, m0
pmaddwd m5, m5, m1
pmaddwd m6, m7, m2
pmaddwd m7, m7, m3
paddd m4, m13
paddd m5, m13
paddd m4, m6
paddd m5, m7
pmaddwd m6, [stk+0x90], m10
pmaddwd m7, [stk+0xa0], m10
pmaddwd m8, [stk+0xb0], m11
pmaddwd m9, [stk+0xc0], m11
paddd m4, m6
paddd m5, m7
%if isput
pshufd m6, m12, q1032
%endif
paddd m4, m8
paddd m5, m9
%else
movd r0, m15
movd rX, m4
pshufd m15, m15, q0321
pshufd m4, m4, q0321
movd r4, m15
movd r5, m4
mova m14, [stk+0x110]
movq m2, [base+subpel_filters+r0*8]
movq m3, [base+subpel_filters+rX*8]
movhps m2, [base+subpel_filters+r4*8]
movhps m3, [base+subpel_filters+r5*8]
psrld m14, 10
mova [stk+16], m14
mov r0, [stk+ 0]
mov rX, [stk+ 4]
mov r4, [stk+ 8]
mov r5, [stk+12]
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
pshufd m4, m6, q1100
pshufd m6, m6, q3322
pshufd m7, m5, q1100
pshufd m5, m5, q3322
pand m0, m9, m4
pand m1, m9, m6
pand m2, m9, m7
pand m3, m9, m5
pandn m4, [stk+0x20]
pandn m6, [stk+0x30]
pandn m7, [stk+0x40]
pandn m5, [stk+0x50]
por m0, m4
por m1, m6
por m2, m7
por m3, m5
punpcklbw m4, m0, m0
punpckhbw m0, m0
punpcklbw m5, m1, m1
punpckhbw m1, m1
psraw m4, 8
psraw m0, 8
psraw m5, 8
psraw m1, 8
punpcklbw m6, m2, m2
punpckhbw m2, m2
punpcklbw m7, m3, m3
punpckhbw m3, m3
psraw m6, 8
psraw m2, 8
psraw m7, 8
psraw m3, 8
mova [stk+0x0a0], m4
mova [stk+0x0b0], m0
mova [stk+0x0c0], m5
mova [stk+0x0d0], m1
mova [stk+0x140], m6
mova [stk+0x150], m2
mova [stk+0x160], m7
mova [stk+0x170], m3
MC_8TAP_SCALED_H 0xa0, 0x20, 0 ; 0
MC_8TAP_SCALED_H 0xa0, 0x30 ; 1
MC_8TAP_SCALED_H 0xa0, 0x40 ; 2
MC_8TAP_SCALED_H 0xa0, 0x50 ; 3
MC_8TAP_SCALED_H 0xa0, 0x60 ; 4
MC_8TAP_SCALED_H 0xa0, 0x70 ; 5
MC_8TAP_SCALED_H 0xa0, 0x80 ; 6
MC_8TAP_SCALED_H 0xa0, 0x90 ; 7
mova m5, [stk+0x60]
mova m6, [stk+0x70]
mova m7, [stk+0x80]
mova m0, [stk+0x90]
mov myd, mym
punpcklwd m4, m5, m6 ; 45a
punpckhwd m5, m6 ; 45b
punpcklwd m6, m7, m0 ; 67a
punpckhwd m7, m0 ; 67b
mova [stk+0x60], m4
mova [stk+0x70], m5
mova [stk+0x80], m6
mova [stk+0x90], m7
mova m1, [stk+0x20]
mova m2, [stk+0x30]
mova m3, [stk+0x40]
mova m4, [stk+0x50]
punpcklwd m0, m1, m2 ; 01a
punpckhwd m1, m2 ; 01b
punpcklwd m2, m3, m4 ; 23a
punpckhwd m3, m4 ; 23b
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
.vloop:
mov r0, r0m
mov r5, [esp+0x1f4]
and myd, 0x3ff
mov mym, myd
xor r3, r3
shr r4, 6
lea r5, [r5+r4]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+r5*8+0]
cmovnz r3, [base+subpel_filters+r5*8+4]
movd m7, r4
movd m6, r3
punpckldq m7, m6
punpcklbw m7, m7
psraw m7, 8
pshufd m4, m7, q0000
pshufd m5, m7, q1111
pmaddwd m0, m4
pmaddwd m1, m4
pmaddwd m2, m5
pmaddwd m3, m5
pshufd m6, m7, q2222
pshufd m7, m7, q3333
paddd m0, m2
paddd m1, m3
pmaddwd m2, [stk+0x60], m6
pmaddwd m3, [stk+0x70], m6
pmaddwd m4, [stk+0x80], m7
pmaddwd m5, [stk+0x90], m7
%if isput
movd m6, [esp+0x18]
%endif
paddd m0, m2
paddd m1, m3
paddd m0, vrnd_mem
paddd m1, vrnd_mem
paddd m4, m0
paddd m5, m1
%endif
%ifidn %1, put
psrad m4, m6
psrad m5, m6
packssdw m4, m5
pxor m7, m7
pmaxsw m4, m7
pminsw m4, pxmaxm
mova [dstq], m4
add dstq, dsm
%else
psrad m4, 6
psrad m5, 6
packssdw m4, m5
mova [tmpq], m4
add tmpq, tmp_stridem
%endif
dec hd
jz .hloop_prep
%if ARCH_X86_64
add myd, dyd
test myd, ~0x3ff
jz .vloop
test myd, 0x400
mov [stk+0x140], myd
mov r4d, [stk+ 0]
mov r6d, [stk+ 4]
mov r7d, [stk+ 8]
mov r9d, [stk+12]
jz .skip_line
mova m14, [base+unpckw]
movu m8, [srcq+r10*2]
movu m9, [srcq+r11*2]
movu m10, [srcq+r13*2]
movu m11, [srcq+ rX*2]
movu m4, [srcq+ r4*2]
movu m5, [srcq+ r6*2]
movu m6, [srcq+ r7*2]
movu m7, [srcq+ r9*2]
add srcq, ssq
mov myd, [stk+0x140]
mov dyd, dym
pshufd m15, m14, q1032
pshufb m0, m14 ; 0a 1a
pshufb m1, m14 ; 0b 1b
pshufb m2, m15 ; 3a 2a
pshufb m3, m15 ; 3b 2b
pmaddwd m8, [stk+0x50]
pmaddwd m9, [stk+0x60]
pmaddwd m10, [stk+0x70]
pmaddwd m11, [stk+0x80]
pmaddwd m4, [stk+0x10]
pmaddwd m5, [stk+0x20]
pmaddwd m6, [stk+0x30]
pmaddwd m7, [stk+0x40]
phaddd m8, m9
phaddd m10, m11
mova m11, hround
phaddd m4, m5
phaddd m6, m7
phaddd m8, m10
phaddd m4, m6
paddd m4, m11
paddd m8, m11
psrad m4, m12
psrad m8, m12
packssdw m4, m8
pshufb m5, [stk+0x90], m14 ; 4a 5a
pshufb m6, [stk+0xa0], m14 ; 4b 5b
pshufb m7, [stk+0xb0], m15 ; 7a 6a
pshufb m8, [stk+0xc0], m15 ; 7b 6b
punpckhwd m0, m2 ; 12a
punpckhwd m1, m3 ; 12b
punpcklwd m2, m5 ; 34a
punpcklwd m3, m6 ; 34b
punpckhwd m5, m7 ; 56a
punpckhwd m6, m8 ; 56b
punpcklwd m7, m4 ; 78a
punpckhqdq m4, m4
punpcklwd m8, m4 ; 78b
mova [stk+0x90], m5
mova [stk+0xa0], m6
mova [stk+0xb0], m7
mova [stk+0xc0], m8
jmp .vloop
.skip_line:
MC_8TAP_SCALED_H 4, 8, 5, 6, 7, 9, 10, 11
MC_8TAP_SCALED_H 8, 5, 6, 7, 9, 0, 10, 11
mov myd, [stk+0x140]
mov dyd, dym
mova m0, m2 ; 01a
mova m1, m3 ; 01b
mova m2, [stk+0x90] ; 23a
mova m3, [stk+0xa0] ; 23b
mova m5, [stk+0xb0] ; 45a
mova m6, [stk+0xc0] ; 45b
punpcklwd m7, m4, m8 ; 67a
punpckhwd m4, m8 ; 67b
mova [stk+0x90], m5
mova [stk+0xa0], m6
mova [stk+0xb0], m7
mova [stk+0xc0], m4
%else
mov r0m, r0
mov myd, mym
mov r3, r3m
add myd, dym
test myd, ~0x3ff
mov mym, myd
jnz .next_line
mova m0, [stk+0x20]
mova m1, [stk+0x30]
mova m2, [stk+0x40]
mova m3, [stk+0x50]
jmp .vloop
.next_line:
test myd, 0x400
mov r0, [stk+ 0]
mov rX, [stk+ 4]
mov r4, [stk+ 8]
mov r5, [stk+12]
jz .skip_line
MC_8TAP_SCALED_H 0xa0, 0xe0, 0 ; 8
mova m7, [base+unpckw]
pshufd m4, m7, q1032
pshufb m0, [stk+0x20], m7 ; 0a 1a
pshufb m1, [stk+0x30], m7 ; 0b 1b
pshufb m2, [stk+0x40], m4 ; 3a 2a
pshufb m3, [stk+0x50], m4 ; 3b 2b
pshufb m5, [stk+0x60], m7 ; 4a 5a
pshufb m6, [stk+0x70], m7 ; 4b 5b
pshufb m7, [stk+0x80], m4 ; 7a 6a
punpckhwd m0, m2 ; 12a
punpckhwd m1, m3 ; 12b
punpcklwd m2, m5 ; 34a
punpcklwd m3, m6 ; 34b
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
punpckhwd m5, m7 ; 56a
mova [stk+0x60], m5
pshufb m5, [stk+0x90], m4 ; 7b 6b
punpcklwd m7, [stk+0xe0] ; 78a
punpckhwd m6, m5 ; 56b
mova [stk+0x70], m6
movq m6, [stk+0xe8]
mova [stk+0x80], m7
punpcklwd m5, m6
mov myd, mym
mova [stk+0x90], m5
jmp .vloop
.skip_line:
MC_8TAP_SCALED_H 0xa0, 0xe0, 0 ; 8
MC_8TAP_SCALED_H 0xa0, 0 ; 9
mova m7, [stk+0xe0]
mova m2, [stk+0x60] ; 23a
mova m3, [stk+0x70] ; 23b
mova m4, [stk+0x80] ; 45a
mova m5, [stk+0x90] ; 45b
punpcklwd m6, m7, m0 ; 67a
punpckhwd m7, m0 ; 67b
mova m0, [stk+0x40] ; 01a
mova m1, [stk+0x50] ; 01b
mov myd, mym
mova [stk+0x40], m2
mova [stk+0x50], m3
mova [stk+0x60], m4
mova [stk+0x70], m5
mova [stk+0x80], m6
mova [stk+0x90], m7
mova [stk+0x20], m0
mova [stk+0x30], m1
%endif
jmp .vloop
INIT_XMM ssse3
.dy1:
movzx wd, word [base+%1_8tap_scaled_ssse3_dy1_table+wq*2]
add wq, base_reg
jmp wq
%if isput
.dy1_w2:
%if ARCH_X86_64
mov myd, mym
movzx t0d, t0b
sub srcq, 2
movd m15, t0d
%else
%define m8 m0
%define m9 m1
%define m14 m4
%define m15 m3
%define m11 [esp+0x00]
%define m12 [esp+0x10]
%define m13 [esp+0x20]
movzx r5, byte [esp+0x1f0]
sub srcq, 2
movd m15, r5
mov r1, r1m
%endif
pxor m9, m9
punpckldq m9, m8
paddd m14, m9 ; mx+dx*[0-1]
%if ARCH_X86_64
mova m9, [base+pd_0x4000]
%endif
pshufd m15, m15, q0000
pand m8, m14, m10
psrld m8, 6
paddd m15, m8
movd r4d, m15
pshufd m15, m15, q0321
%if ARCH_X86_64
movd r6d, m15
%else
movd r3d, m15
%endif
mova m5, [base+bdct_lb_q]
mova m6, [base+spel_s_shuf2]
movd m15, [base+subpel_filters+r4*8+2]
%if ARCH_X86_64
movd m7, [base+subpel_filters+r6*8+2]
%else
movd m7, [base+subpel_filters+r3*8+2]
%endif
pxor m2, m2
pcmpeqd m8, m2
psrld m14, 10
paddd m14, m14
%if ARCH_X86_32
mov r3, r3m
pshufb m14, m5
paddb m14, m6
mova [stk], m14
SWAP m5, m0
SWAP m6, m3
%define m15 m6
%endif
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*1]
movu m2, [srcq+ssq*2]
movu m3, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
punpckldq m15, m7
%if ARCH_X86_64
pshufb m14, m5
paddb m14, m6
pand m9, m8
pandn m8, m15
SWAP m15, m8
por m15, m9
movu m4, [srcq+ssq*0]
movu m5, [srcq+ssq*1]
movu m6, [srcq+ssq*2]
add srcq, ss3q
shr myd, 6
mov r4d, 64 << 24
lea myd, [t1+myq]
cmovnz r4q, [base+subpel_filters+myq*8]
%else
pand m7, m5, [base+pd_0x4000]
pandn m5, m15
por m5, m7
%define m15 m5
mov myd, mym
mov r5, [esp+0x1f4]
xor r3, r3
shr myd, 6
lea r5, [r5+myd]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+r5*8+0]
cmovnz r3, [base+subpel_filters+r5*8+4]
mov [stk+0x20], r3
mov r3, r3m
%endif
punpcklbw m15, m15
psraw m15, 8
REPX {pshufb x, m14}, m0, m1, m2, m3
REPX {pmaddwd x, m15}, m0, m1, m2, m3
%if ARCH_X86_64
REPX {pshufb x, m14}, m4, m5, m6
REPX {pmaddwd x, m15}, m4, m5, m6
phaddd m0, m1
phaddd m2, m3
phaddd m4, m5
phaddd m6, m6
REPX {paddd x, m11}, m0, m2, m4, m6
REPX {psrad x, m12}, m0, m2, m4, m6
packssdw m0, m2 ; 0 1 2 3
packssdw m4, m6 ; 4 5 6
SWAP m1, m4
movq m10, r4
%else
mova [stk+0x10], m15
phaddd m0, m1
phaddd m2, m3
movu m1, [srcq+ssq*0]
movu m7, [srcq+ssq*1]
movu m6, [srcq+ssq*2]
add srcq, ss3q
REPX {pshufb x, m14}, m1, m7, m6
REPX {pmaddwd x, m15}, m1, m7, m6
%define m14 [stk+0x00]
%define m15 [stk+0x10]
phaddd m1, m7
phaddd m6, m6
REPX {paddd x, m11}, m0, m2, m1, m6
REPX {psrad x, m12}, m0, m2, m1, m6
packssdw m0, m2
packssdw m1, m6
%define m8 m6
%define m9 m4
%define m10 m5
movd m10, r4
movd m9, [stk+0x20]
punpckldq m10, m9
%endif
punpcklbw m10, m10
psraw m10, 8
pshufd m7, m10, q0000
pshufd m8, m10, q1111
pshufd m9, m10, q2222
pshufd m10, m10, q3333
%if ARCH_X86_32
mova [stk+0x50], m7
mova [stk+0x60], m8
mova [stk+0x70], m9
mova [stk+0x80], m10
%define m7 [stk+0x50]
%define m8 [stk+0x60]
%define m9 [stk+0x70]
%define m10 [stk+0x80]
%endif
palignr m2, m1, m0, 4 ; 1 2 3 4
punpcklwd m3, m0, m2 ; 01 12
punpckhwd m0, m2 ; 23 34
pshufd m4, m1, q2121 ; 5 6 5 6
punpcklwd m2, m1, m4 ; 45 56
%if ARCH_X86_32
mov r0, r0m
%endif
.dy1_w2_loop:
movu m1, [srcq+ssq*0]
movu m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
pmaddwd m5, m3, m7
mova m3, m0
pmaddwd m0, m8
pshufb m1, m14
pshufb m6, m14
pmaddwd m1, m15
pmaddwd m6, m15
phaddd m1, m6
paddd m1, m11
psrad m1, m12
packssdw m1, m1
paddd m5, m0
mova m0, m2
pmaddwd m2, m9
paddd m5, m2
palignr m2, m1, m4, 12
punpcklwd m2, m1 ; 67 78
pmaddwd m4, m2, m10
paddd m5, m13
paddd m5, m4
pxor m6, m6
mova m4, m1
pshufd m1, m12, q1032
psrad m5, m1
packssdw m5, m5
pmaxsw m5, m6
pminsw m5, pxmaxm
movd [dstq+dsq*0], m5
pshuflw m5, m5, q1032
movd [dstq+dsq*1], m5
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .dy1_w2_loop
RET
%endif
INIT_XMM ssse3
.dy1_w4:
%if ARCH_X86_64
mov myd, mym
mova [rsp+0x10], m11
mova [rsp+0x20], m12
%if isput
mova [rsp+0x30], m13
%define vrnd_mem [rsp+0x30]
%define stk rsp+0x40
%else
%define vrnd_mem [base+pd_m524256]
%define stk rsp+0x30
%endif
movzx t0d, t0b
sub srcq, 2
movd m15, t0d
%else
%define m10 [base+pd_0x3ff]
%define m9 [base+pd_0x4000]
%define m8 m0
%xdefine m14 m4
%define m15 m3
%if isprep
%define ssq r3
%endif
movzx r5, byte [esp+0x1f0]
sub srcq, 2
movd m15, r5
%endif
pmaddwd m8, [base+rescale_mul]
%if ARCH_X86_64
mova m9, [base+pd_0x4000]
%endif
pshufd m15, m15, q0000
paddd m14, m8 ; mx+dx*[0-3]
pand m0, m14, m10
psrld m0, 6
paddd m15, m0
pshufd m7, m15, q1032
%if ARCH_X86_64
movd r4d, m15
movd r11d, m7
pshufd m15, m15, q0321
pshufd m7, m7, q0321
movd r6d, m15
movd r13d, m7
mova m10, [base+bdct_lb_q+ 0]
mova m11, [base+bdct_lb_q+16]
movd m13, [base+subpel_filters+ r4*8+2]
movd m2, [base+subpel_filters+ r6*8+2]
movd m15, [base+subpel_filters+r11*8+2]
movd m4, [base+subpel_filters+r13*8+2]
%else
movd r0, m15
movd r4, m7
pshufd m15, m15, q0321
pshufd m7, m7, q0321
movd rX, m15
movd r5, m7
mova m5, [base+bdct_lb_q+ 0]
mova m6, [base+bdct_lb_q+16]
movd m1, [base+subpel_filters+r0*8+2]
movd m2, [base+subpel_filters+rX*8+2]
movd m3, [base+subpel_filters+r4*8+2]
movd m7, [base+subpel_filters+r5*8+2]
SWAP m4, m7
%if isprep
mov r3, r3m
%endif
%define m10 m5
%define m11 m6
%define m12 m1
%define m13 m1
%endif
psrld m14, 10
paddd m14, m14
punpckldq m13, m2
punpckldq m15, m4
punpcklqdq m13, m15
pxor m2, m2
pcmpeqd m0, m2
%if ARCH_X86_64
pand m9, m0
%else
pand m2, m9, m0
%define m9 m2
SWAP m7, m4
%endif
pandn m0, m13
%if ARCH_X86_64
SWAP m13, m0
%else
%define m13 m0
%endif
por m13, m9
punpckhbw m15, m13, m13
punpcklbw m13, m13
psraw m15, 8
psraw m13, 8
pshufb m12, m14, m10
pshufb m14, m11
mova m10, [base+spel_s_shuf2]
movd r4d, m14
shr r4d, 24
%if ARCH_X86_32
mova [stk+0x40], m13
mova [stk+0x50], m15
pxor m2, m2
%endif
pshufb m7, m14, m2
psubb m14, m7
paddb m12, m10
paddb m14, m10
%if ARCH_X86_64
lea r6, [r4+ssq*1]
lea r11, [r4+ssq*2]
lea r13, [r4+ss3q ]
movu m7, [srcq+ssq*0]
movu m9, [srcq+ssq*1]
movu m8, [srcq+ssq*2]
movu m10, [srcq+ss3q ]
movu m1, [srcq+r4 ]
movu m3, [srcq+r6 ]
movu m2, [srcq+r11 ]
movu m4, [srcq+r13 ]
lea srcq, [srcq+ssq*4]
REPX {pshufb x, m12}, m7, m9, m8, m10
REPX {pmaddwd x, m13}, m7, m9, m8, m10
REPX {pshufb x, m14}, m1, m3, m2, m4
REPX {pmaddwd x, m15}, m1, m3, m2, m4
mova m5, [rsp+0x10]
movd xm6, [rsp+0x20]
phaddd m7, m1
phaddd m9, m3
phaddd m8, m2
phaddd m10, m4
movu m1, [srcq+ssq*0]
movu m2, [srcq+ssq*1]
movu m3, [srcq+ssq*2]
REPX {paddd x, m5}, m7, m9, m8, m10
REPX {psrad x, xm6}, m7, m9, m8, m10
packssdw m7, m9 ; 0 1
packssdw m8, m10 ; 2 3
movu m0, [srcq+r4 ]
movu m9, [srcq+r6 ]
movu m10, [srcq+r11 ]
add srcq, ss3q
REPX {pshufb x, m12}, m1, m2, m3
REPX {pmaddwd x, m13}, m1, m2, m3
REPX {pshufb x, m14}, m0, m9, m10
REPX {pmaddwd x, m15}, m0, m9, m10
phaddd m1, m0
phaddd m2, m9
phaddd m3, m10
shr myd, 6
mov r13d, 64 << 24
lea myd, [t1+myq]
cmovnz r13q, [base+subpel_filters+myq*8]
REPX {paddd x, m5}, m1, m2, m3
REPX {psrad x, xm6}, m1, m2, m3
packssdw m1, m2 ; 4 5
packssdw m3, m3 ; 6 6
SWAP m9, m1
shufps m4, m7, m8, q1032 ; 1 2
shufps m5, m8, m9, q1032 ; 3 4
shufps m6, m9, m3, q1032 ; 5 6
punpcklwd m0, m7, m4 ; 01
punpckhwd m7, m4 ; 12
punpcklwd m1, m8, m5 ; 23
punpckhwd m8, m5 ; 34
punpcklwd m2, m9, m6 ; 45
punpckhwd m9, m6 ; 56
movq m10, r13
mova [stk+0x00], m1
mova [stk+0x10], m8
mova [stk+0x20], m2
mova [stk+0x30], m9
mova [stk+0x40], m3
%define hrnd_mem [rsp+0x10]
%define hsh_mem [rsp+0x20]
%define vsh_mem [rsp+0x28]
%if isput
%define vrnd_mem [rsp+0x30]
%else
%define vrnd_mem [base+pd_m524256]
%endif
%else
mova [stk+0x20], m12
mova [stk+0x30], m14
add r4, srcq
MC_4TAP_SCALED_H 0x60 ; 0 1
MC_4TAP_SCALED_H 0x70 ; 2 3
MC_4TAP_SCALED_H 0x80 ; 4 5
movu m7, [srcq]
movu m2, [r4]
add srcq, ssq
add r4, ssq
mov [stk+0xb0], r4
pshufb m7, m12
pshufb m2, m14
pmaddwd m7, m13
pmaddwd m2, m15
phaddd m7, m2
paddd m7, [esp+0x00]
psrad m7, [esp+0x10]
packssdw m7, m7 ; 6 6
mova m4, [stk+0x60]
mova m5, [stk+0x70]
mova m6, [stk+0x80]
mov myd, mym
mov rX, [esp+0x1f4]
xor r5, r5
shr myd, 6
lea rX, [rX+myd]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+rX*8+0]
cmovnz r5, [base+subpel_filters+rX*8+4]
mov r3, r3m
shufps m1, m4, m5, q1032 ; 1 2
shufps m2, m5, m6, q1032 ; 3 4
shufps m3, m6, m7, q1032 ; 5 6
mova [stk+0xa0], m7
punpcklwd m0, m4, m1 ; 01
punpckhwd m4, m1 ; 12
punpcklwd m1, m5, m2 ; 23
punpckhwd m5, m2 ; 34
punpcklwd m2, m6, m3 ; 45
punpckhwd m6, m3 ; 56
movd m7, r4
movd m3, r5
mov r0, r0m
%if isput
mov r1, r1m
%endif
mov r4, [stk+0xb0]
mova [stk+0xc0], m4 ; 12
mova [stk+0x60], m1 ; 23
mova [stk+0x70], m2 ; 45
mova [stk+0x80], m5 ; 34
mova [stk+0x90], m6 ; 56
%define m12 [stk+0x20]
%define m14 [stk+0x30]
%define m13 [stk+0x40]
%define m15 [stk+0x50]
%define hrnd_mem [esp+0x00]
%define hsh_mem [esp+0x10]
%define vsh_mem [esp+0x18]
%if isput
%define vrnd_mem [esp+0x20]
%else
%define vrnd_mem [base+pd_m524256]
%endif
%define m10 m7
punpckldq m10, m3
%endif
punpcklbw m10, m10
psraw m10, 8
pshufd m3, m10, q0000
pshufd m4, m10, q1111
pshufd m5, m10, q2222
pshufd m10, m10, q3333
%if ARCH_X86_32
%xdefine m8 m3
%xdefine m9 m6
%xdefine m11 m5
%xdefine m6 m4
mova [stk+0x100], m3
mova [stk+0x110], m4
mova [stk+0x120], m5
mova [stk+0x130], m10
%define m3 [stk+0x100]
%define m4 [stk+0x110]
%define m5 [stk+0x120]
%define m10 [stk+0x130]
mova m7, [stk+0xc0]
mova m8, [stk+0x80]
%endif
.dy1_w4_loop:
movu m11, [srcq+ssq*0]
movu m6, [srcq+ssq*1]
pmaddwd m0, m3
pmaddwd m7, m3
pmaddwd m1, m4
pmaddwd m8, m4
pmaddwd m2, m5
pmaddwd m9, m5
paddd m1, m0
paddd m8, m7
%if ARCH_X86_64
movu m0, [srcq+r4]
movu m7, [srcq+r6]
%else
movu m0, [r4+ssq*0]
movu m7, [r4+ssq*1]
lea r4, [r4+ssq*2]
%endif
lea srcq, [srcq+ssq*2]
paddd m1, m2
paddd m8, m9
pshufb m11, m12
pshufb m6, m12
pmaddwd m11, m13
pmaddwd m6, m13
pshufb m0, m14
pshufb m7, m14
pmaddwd m0, m15
pmaddwd m7, m15
phaddd m11, m0
phaddd m6, m7
paddd m11, hrnd_mem
paddd m6, hrnd_mem
psrad m11, hsh_mem
psrad m6, hsh_mem
packssdw m11, m6 ; 7 8
%if ARCH_X86_64
shufps m9, [stk+0x40], m11, q1032 ; 6 7
mova m0, [stk+0x00]
mova [stk+0x40], m11
%else
shufps m9, [stk+0xa0], m11, q1032 ; 6 7
mova m0, [stk+0x60]
mova [stk+0xa0], m11
%endif
punpcklwd m2, m9, m11 ; 67
punpckhwd m9, m11 ; 78
pmaddwd m6, m2, m10
pmaddwd m7, m9, m10
%if isput
movd m11, vsh_mem
%endif
paddd m1, vrnd_mem
paddd m8, vrnd_mem
paddd m1, m6
paddd m8, m7
%if ARCH_X86_64
mova m7, [stk+0x10]
%else
mova m7, [stk+0x80]
%endif
%if isput
psrad m1, m11
psrad m8, m11
%else
psrad m1, 6
psrad m8, 6
%endif
packssdw m1, m8
%if ARCH_X86_64
mova m8, [stk+0x30]
%else
mova m8, [stk+0x90]
%endif
%if isput
pxor m6, m6
pmaxsw m1, m6
pminsw m1, pxmaxm
movq [dstq+dsq*0], m1
movhps [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
%else
mova [tmpq], m1
add tmpq, 16
%endif
%if ARCH_X86_64
mova m1, [stk+0x20]
mova [stk+0x10], m8
mova [stk+0x00], m1
mova [stk+0x20], m2
mova [stk+0x30], m9
%else
mova m1, [stk+0x70]
mova [stk+0x80], m8
mova [stk+0x60], m1
mova [stk+0x70], m2
mova [stk+0x90], m9
%endif
sub hd, 2
jg .dy1_w4_loop
MC_8TAP_SCALED_RET ; why not jz .ret?
INIT_XMM ssse3
.dy1_w8:
mov dword [stk+0xf0], 1
movifprep tmp_stridem, 16
jmp .dy1_w_start
.dy1_w16:
mov dword [stk+0xf0], 2
movifprep tmp_stridem, 32
jmp .dy1_w_start
.dy1_w32:
mov dword [stk+0xf0], 4
movifprep tmp_stridem, 64
jmp .dy1_w_start
.dy1_w64:
mov dword [stk+0xf0], 8
movifprep tmp_stridem, 128
jmp .dy1_w_start
.dy1_w128:
mov dword [stk+0xf0], 16
movifprep tmp_stridem, 256
.dy1_w_start:
mov myd, mym
%if ARCH_X86_64
%ifidn %1, put
movifnidn dsm, dsq
%endif
mova [rsp+0x10], m11
mova [rsp+0x20], m12
%define hround m11
%if isput
mova [rsp+0x30], m13
%else
mova m13, [base+pd_m524256]
%endif
shr t0d, 16
shr myd, 6
mov r4d, 64 << 24
lea myd, [t1+myq]
cmovnz r4q, [base+subpel_filters+myq*8]
movd m15, t0d
%else
%define hround [esp+0x00]
%define m12 [esp+0x10]
%define m10 [base+pd_0x3ff]
%define m8 m0
%xdefine m14 m4
%xdefine m15 m3
%if isprep
%define ssq ssm
%endif
mov r5, [esp+0x1f0]
mov r3, [esp+0x1f4]
shr r5, 16
movd m15, r5
xor r5, r5
shr myd, 6
lea r3, [r3+myd]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+r3*8+0]
cmovnz r5, [base+subpel_filters+r3*8+4]
mov r0, r0m
mov r3, r3m
%endif
sub srcq, 6
pslld m7, m8, 2 ; dx*4
pmaddwd m8, [base+rescale_mul] ; dx*[0-3]
pshufd m15, m15, q0000
paddd m14, m8 ; mx+dx*[0-3]
%if ARCH_X86_64
movq m3, r4q
%else
movd m5, r4
movd m6, r5
punpckldq m5, m6
SWAP m3, m5
%endif
punpcklbw m3, m3
psraw m3, 8
mova [stk+0x100], m7
mova [stk+0x120], m15
mov [stk+0x0f8], srcq
mov [stk+0x130], r0q ; dstq / tmpq
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
%if ARCH_X86_64
mova [stk+0x140], m0
mova [stk+0x150], m1
mova [stk+0x160], m2
mova [stk+0x170], m3
%if UNIX64
mov hm, hd
%endif
%else
mova [stk+0x180], m0
mova [stk+0x190], m1
mova [stk+0x1a0], m2
mova [stk+0x1b0], m3
SWAP m5, m3
mov r5, hm
mov [stk+0x134], r5
%endif
jmp .dy1_hloop
.dy1_hloop_prep:
dec dword [stk+0x0f0]
jz .ret
%if ARCH_X86_64
add qword [stk+0x130], 16
mov hd, hm
%else
add dword [stk+0x130], 16
mov r5, [stk+0x134]
mov r0, [stk+0x130]
%endif
mova m7, [stk+0x100]
mova m14, [stk+0x110]
%if ARCH_X86_64
mova m10, [base+pd_0x3ff]
mova m11, [rsp+0x10]
%endif
mova m15, [stk+0x120]
mov srcq, [stk+0x0f8]
%if ARCH_X86_64
mov r0q, [stk+0x130] ; dstq / tmpq
%else
mov hm, r5
mov r0m, r0
mov r3, r3m
%endif
paddd m14, m7
.dy1_hloop:
%if ARCH_X86_64
mova m9, [base+pq_0x40000000]
%else
%define m9 [base+pq_0x40000000]
%endif
pxor m1, m1
psrld m2, m14, 10
mova [stk], m2
pand m6, m14, m10
psrld m6, 6
paddd m5, m15, m6
pcmpeqd m6, m1
pshufd m2, m5, q1032
%if ARCH_X86_64
movd r4d, m5
movd r6d, m2
pshufd m5, m5, q0321
pshufd m2, m2, q0321
movd r7d, m5
movd r9d, m2
movq m0, [base+subpel_filters+r4*8]
movq m1, [base+subpel_filters+r6*8]
movhps m0, [base+subpel_filters+r7*8]
movhps m1, [base+subpel_filters+r9*8]
%else
movd r0, m5
movd rX, m2
pshufd m5, m5, q0321
pshufd m2, m2, q0321
movd r4, m5
movd r5, m2
movq m0, [base+subpel_filters+r0*8]
movq m1, [base+subpel_filters+rX*8]
movhps m0, [base+subpel_filters+r4*8]
movhps m1, [base+subpel_filters+r5*8]
%endif
paddd m14, m7 ; mx+dx*[4-7]
pand m5, m14, m10
psrld m5, 6
paddd m15, m5
pxor m2, m2
pcmpeqd m5, m2
mova [stk+0x110], m14
pshufd m4, m15, q1032
%if ARCH_X86_64
movd r10d, m15
movd r11d, m4
pshufd m15, m15, q0321
pshufd m4, m4, q0321
movd r13d, m15
movd rXd, m4
movq m2, [base+subpel_filters+r10*8]
movq m3, [base+subpel_filters+r11*8]
movhps m2, [base+subpel_filters+r13*8]
movhps m3, [base+subpel_filters+ rX*8]
psrld m14, 10
movq r11, m14
punpckhqdq m14, m14
movq rX, m14
mov r10d, r11d
shr r11, 32
mov r13d, rXd
shr rX, 32
mov r4d, [stk+ 0]
mov r6d, [stk+ 4]
mov r7d, [stk+ 8]
mov r9d, [stk+12]
pshufd m4, m6, q1100
pshufd m6, m6, q3322
pshufd m14, m5, q1100
pshufd m5, m5, q3322
pand m7, m9, m4
pand m8, m9, m6
pand m15, m9, m14
pand m9, m9, m5
pandn m4, m0
pandn m6, m1
pandn m14, m2
pandn m5, m3
por m7, m4
por m8, m6
por m15, m14
por m9, m5
punpcklbw m0, m7, m7
punpckhbw m7, m7
punpcklbw m1, m8, m8
punpckhbw m8, m8
psraw m0, 8
psraw m7, 8
psraw m1, 8
psraw m8, 8
punpcklbw m2, m15, m15
punpckhbw m15, m15
punpcklbw m3, m9, m9
punpckhbw m9, m9
psraw m2, 8
psraw m15, 8
psraw m3, 8
psraw m9, 8
mova [stk+0x10], m0
mova [stk+0x20], m7
mova [stk+0x30], m1
mova [stk+0x40], m8
mova [stk+0x50], m2
mova [stk+0x60], m15
mova [stk+0x70], m3
mova [stk+0x80], m9
MC_8TAP_SCALED_H 1, 2, 3, 4, 5, 6, 9, 10 ; 0
mova [stk+0x90], m1
MC_8TAP_SCALED_H 2, 3, 4, 5, 6, 1, 9, 10 ; 1
mova [stk+0xa0], m2
MC_8TAP_SCALED_H 3, 4, 5, 6, 1, 2, 9, 10 ; 2
mova [stk+0xb0], m3
MC_8TAP_SCALED_H 4, 5, 6, 1, 2, 3, 9, 10 ; 3
mova [stk+0xc0], m4
MC_8TAP_SCALED_H 5, 6, 1, 2, 3, 4, 9, 10 ; 4
mova [stk+0xd0], m5
MC_8TAP_SCALED_H 6, 1, 2, 3, 4, 5, 9, 10 ; 5
MC_8TAP_SCALED_H 7, 1, 2, 3, 4, 5, 9, 10 ; 6
MC_8TAP_SCALED_H 8, 1, 2, 3, 4, 5, 9, 10 ; 7
mova m5, [stk+0xd0]
mova m1, [stk+0x90]
mova m2, [stk+0xa0]
mova m3, [stk+0xb0]
mova m9, [stk+0xc0]
punpcklwd m4, m5, m6 ; 45a
punpckhwd m5, m6 ; 45b
punpcklwd m6, m7, m8 ; 67a
punpckhwd m7, m8 ; 67b
punpcklwd m0, m1, m2 ; 01a
punpckhwd m1, m2 ; 01b
punpcklwd m2, m3, m9 ; 23a
punpckhwd m3, m9 ; 23b
mova m10, [stk+0x140]
mova m11, [stk+0x150]
mova m14, [stk+0x160]
mova m15, [stk+0x170]
mova [stk+0x90], m4
mova [stk+0xa0], m5
mova [stk+0xb0], m6
mova [stk+0xc0], m7
%define hround [rsp+0x10]
%define shift [rsp+0x20]
%if isput
%define vround [rsp+0x30]
%else
%define vround [base+pd_m524256]
%endif
.dy1_vloop:
pmaddwd m4, m0, m10
pmaddwd m5, m1, m10
pmaddwd m6, m2, m11
pmaddwd m7, m3, m11
paddd m4, m13
paddd m5, m13
paddd m4, m6
paddd m5, m7
pmaddwd m6, [stk+0x90], m14
pmaddwd m7, [stk+0xa0], m14
pmaddwd m8, [stk+0xb0], m15
pmaddwd m9, [stk+0xc0], m15
paddd m4, m6
paddd m5, m7
%if isput
pshufd m6, m12, q1032
%endif
paddd m4, m8
paddd m5, m9
%else
movd r0, m15
movd rX, m4
pshufd m15, m15, q0321
pshufd m4, m4, q0321
movd r4, m15
movd r5, m4
mova m14, [stk+0x110]
movq m2, [base+subpel_filters+r0*8]
movq m3, [base+subpel_filters+rX*8]
movhps m2, [base+subpel_filters+r4*8]
movhps m3, [base+subpel_filters+r5*8]
psrld m14, 10
mova [stk+16], m14
mov r0, [stk+ 0]
mov rX, [stk+ 4]
mov r4, [stk+ 8]
mov r5, [stk+12]
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
pshufd m4, m6, q1100
pshufd m6, m6, q3322
pshufd m7, m5, q1100
pshufd m5, m5, q3322
pand m0, m9, m4
pand m1, m9, m6
pand m2, m9, m7
pand m3, m9, m5
pandn m4, [stk+0x20]
pandn m6, [stk+0x30]
pandn m7, [stk+0x40]
pandn m5, [stk+0x50]
por m0, m4
por m1, m6
por m2, m7
por m3, m5
punpcklbw m4, m0, m0
punpckhbw m0, m0
punpcklbw m5, m1, m1
punpckhbw m1, m1
psraw m4, 8
psraw m0, 8
psraw m5, 8
psraw m1, 8
punpcklbw m6, m2, m2
punpckhbw m2, m2
punpcklbw m7, m3, m3
punpckhbw m3, m3
psraw m6, 8
psraw m2, 8
psraw m7, 8
psraw m3, 8
mova [stk+0x0a0], m4
mova [stk+0x0b0], m0
mova [stk+0x0c0], m5
mova [stk+0x0d0], m1
mova [stk+0x140], m6
mova [stk+0x150], m2
mova [stk+0x160], m7
mova [stk+0x170], m3
MC_8TAP_SCALED_H 0xa0, 0x20, 0 ; 0
MC_8TAP_SCALED_H 0xa0, 0x30 ; 1
MC_8TAP_SCALED_H 0xa0, 0x40 ; 2
MC_8TAP_SCALED_H 0xa0, 0x50 ; 3
MC_8TAP_SCALED_H 0xa0, 0x60 ; 4
MC_8TAP_SCALED_H 0xa0, 0x70 ; 5
MC_8TAP_SCALED_H 0xa0, 0x80 ; 6
MC_8TAP_SCALED_H 0xa0, 0x90 ; 7
mova m5, [stk+0x60]
mova m6, [stk+0x70]
mova m7, [stk+0x80]
mova m0, [stk+0x90]
mov r0, r0m
punpcklwd m4, m5, m6 ; 45a
punpckhwd m5, m6 ; 45b
punpcklwd m6, m7, m0 ; 67a
punpckhwd m7, m0 ; 67b
mova [stk+0x60], m4
mova [stk+0x70], m5
mova [stk+0x80], m6
mova [stk+0x90], m7
mova m1, [stk+0x20]
mova m2, [stk+0x30]
mova m3, [stk+0x40]
mova m4, [stk+0x50]
punpcklwd m0, m1, m2 ; 01a
punpckhwd m1, m2 ; 01b
punpcklwd m2, m3, m4 ; 23a
punpckhwd m3, m4 ; 23b
mova m4, [stk+0x180]
mova m5, [stk+0x190]
mova m6, [stk+0x1a0]
mova m7, [stk+0x1b0]
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
.dy1_vloop:
pmaddwd m0, m4
pmaddwd m1, m4
pmaddwd m2, m5
pmaddwd m3, m5
paddd m0, m2
paddd m1, m3
pmaddwd m2, [stk+0x60], m6
pmaddwd m3, [stk+0x70], m6
pmaddwd m4, [stk+0x80], m7
pmaddwd m5, [stk+0x90], m7
%if isput
movd m6, [esp+0x18]
%endif
paddd m0, m2
paddd m1, m3
paddd m0, vrnd_mem
paddd m1, vrnd_mem
paddd m4, m0
paddd m5, m1
%endif
%ifidn %1, put
psrad m4, m6
psrad m5, m6
packssdw m4, m5
pxor m7, m7
pmaxsw m4, m7
pminsw m4, pxmaxm
mova [dstq], m4
add dstq, dsm
%else
psrad m4, 6
psrad m5, 6
packssdw m4, m5
mova [tmpq], m4
add tmpq, tmp_stridem
%endif
dec hd
jz .dy1_hloop_prep
%if ARCH_X86_64
movu m8, [srcq+r10*2]
movu m9, [srcq+r11*2]
movu m12, [srcq+r13*2]
movu m13, [srcq+ rX*2]
movu m4, [srcq+ r4*2]
movu m5, [srcq+ r6*2]
movu m6, [srcq+ r7*2]
movu m7, [srcq+ r9*2]
add srcq, ssq
pmaddwd m8, [stk+0x50]
pmaddwd m9, [stk+0x60]
pmaddwd m12, [stk+0x70]
pmaddwd m13, [stk+0x80]
pmaddwd m4, [stk+0x10]
pmaddwd m5, [stk+0x20]
pmaddwd m6, [stk+0x30]
pmaddwd m7, [stk+0x40]
phaddd m8, m9
phaddd m12, m13
mova m9, [base+unpckw]
mova m13, hround
phaddd m4, m5
phaddd m6, m7
phaddd m8, m12
phaddd m4, m6
pshufd m5, m9, q1032
pshufb m0, m9 ; 0a 1a
pshufb m1, m9 ; 0b 1b
pshufb m2, m5 ; 3a 2a
pshufb m3, m5 ; 3b 2b
mova m12, shift
paddd m4, m13
paddd m8, m13
psrad m4, m12
psrad m8, m12
packssdw m4, m8
pshufb m6, [stk+0x90], m9 ; 4a 5a
pshufb m7, [stk+0xa0], m9 ; 4b 5b
pshufb m8, [stk+0xb0], m5 ; 7a 6a
pshufb m13, [stk+0xc0], m5 ; 7b 6b
punpckhwd m0, m2 ; 12a
punpckhwd m1, m3 ; 12b
punpcklwd m2, m6 ; 34a
punpcklwd m3, m7 ; 34b
punpckhwd m6, m8 ; 56a
punpckhwd m7, m13 ; 56b
punpcklwd m8, m4 ; 78a
punpckhqdq m4, m4
punpcklwd m13, m4 ; 78b
mova [stk+0x90], m6
mova [stk+0xa0], m7
mova [stk+0xb0], m8
mova [stk+0xc0], m13
mova m13, vround
%else
mov r0m, r0
mov r3, r3m
mov r0, [stk+ 0]
mov rX, [stk+ 4]
mov r4, [stk+ 8]
mov r5, [stk+12]
MC_8TAP_SCALED_H 0xa0, 0xe0, 0 ; 8
mova m7, [base+unpckw]
pshufd m4, m7, q1032
pshufb m0, [stk+0x20], m7 ; 0a 1a
pshufb m1, [stk+0x30], m7 ; 0b 1b
pshufb m2, [stk+0x40], m4 ; 3a 2a
pshufb m3, [stk+0x50], m4 ; 3b 2b
pshufb m5, [stk+0x60], m7 ; 4a 5a
pshufb m6, [stk+0x70], m7 ; 4b 5b
pshufb m7, [stk+0x80], m4 ; 7a 6a
punpckhwd m0, m2 ; 12a
punpckhwd m1, m3 ; 12b
punpcklwd m2, m5 ; 34a
punpcklwd m3, m6 ; 34b
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
punpckhwd m5, m7 ; 56a
mova [stk+0x60], m5
pshufb m5, [stk+0x90], m4 ; 7b 6b
punpcklwd m7, [stk+0xe0] ; 78a
mova m4, [stk+0x180]
punpckhwd m6, m5 ; 56b
mova [stk+0x70], m6
movq m6, [stk+0xe8]
mova [stk+0x80], m7
mova m7, [stk+0x1b0]
punpcklwd m5, m6
mova m6, [stk+0x1a0]
mova [stk+0x90], m5
mova m5, [stk+0x190]
mov r0, r0m
%endif
jmp .dy1_vloop
INIT_XMM ssse3
%if ARCH_X86_64
%define stk rsp+0x20
%endif
.dy2:
movzx wd, word [base+%1_8tap_scaled_ssse3_dy2_table+wq*2]
add wq, base_reg
jmp wq
%if isput
.dy2_w2:
%if ARCH_X86_64
mov myd, mym
mova [rsp+0x10], m13
%define vrnd_mem [rsp+0x10]
movzx t0d, t0b
sub srcq, 2
movd m15, t0d
%else
%define m8 m0
%define m9 m1
%define m14 m4
%define m15 m3
%define m11 [esp+0x00]
%define m12 [esp+0x10]
%define vrnd_mem [esp+0x20]
mov r1, r1m
movzx r5, byte [esp+0x1f0]
sub srcq, 2
movd m15, r5
%endif
pxor m9, m9
punpckldq m9, m8
paddd m14, m9 ; mx+dx*[0-1]
%if ARCH_X86_64
mova m9, [base+pd_0x4000]
%endif
pshufd m15, m15, q0000
pand m8, m14, m10
psrld m8, 6
paddd m15, m8
movd r4d, m15
pshufd m15, m15, q0321
%if ARCH_X86_64
movd r6d, m15
%else
movd r3d, m15
%endif
mova m5, [base+bdct_lb_q]
mova m6, [base+spel_s_shuf2]
movd m15, [base+subpel_filters+r4*8+2]
%if ARCH_X86_64
movd m7, [base+subpel_filters+r6*8+2]
%else
movd m7, [base+subpel_filters+r3*8+2]
%endif
pxor m2, m2
pcmpeqd m8, m2
psrld m14, 10
paddd m14, m14
%if ARCH_X86_32
mov r3, r3m
pshufb m14, m5
paddb m14, m6
mova [stk], m14
SWAP m5, m0
SWAP m6, m3
%define m15 m6
%endif
movu m0, [srcq+ssq*0]
movu m1, [srcq+ssq*2]
movu m2, [srcq+ssq*4]
punpckldq m15, m7
%if ARCH_X86_64
pshufb m14, m5
paddb m14, m6
pand m9, m8
pandn m8, m15
SWAP m15, m8
por m15, m9
movu m4, [srcq+ssq*1]
movu m5, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
movu m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
shr myd, 6
mov r4d, 64 << 24
lea myd, [t1+myq]
cmovnz r4q, [base+subpel_filters+myq*8]
%else
pand m7, m5, [base+pd_0x4000]
pandn m5, m15
por m5, m7
%define m15 m5
mov myd, mym
mov r5, [esp+0x1f4]
xor r3, r3
shr myd, 6
lea r5, [r5+myd]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+r5*8+0]
cmovnz r3, [base+subpel_filters+r5*8+4]
mov [stk+0x20], r3
mov r3, r3m
%endif
punpcklbw m15, m15
psraw m15, 8
REPX {pshufb x, m14}, m0, m1, m2
REPX {pmaddwd x, m15}, m0, m1, m2
%if ARCH_X86_64
REPX {pshufb x, m14}, m4, m5, m6
REPX {pmaddwd x, m15}, m4, m5, m6
phaddd m0, m1
phaddd m1, m2
phaddd m4, m5
phaddd m5, m6
REPX {paddd x, m11}, m0, m1, m4, m5
REPX {psrad x, m12}, m0, m1, m4, m5
packssdw m0, m1 ; 0 2 2 4
packssdw m4, m5 ; 1 3 3 5
SWAP m2, m4
movq m10, r4
%else
mova [stk+0x10], m15
phaddd m0, m1
phaddd m1, m2
movu m2, [srcq+ssq*1]
movu m7, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
movu m6, [srcq+ssq*1]
lea srcq, [srcq+ssq*2]
REPX {pshufb x, m14}, m2, m7, m6
REPX {pmaddwd x, m15}, m2, m7, m6
%define m14 [stk+0x00]
%define m15 [stk+0x10]
phaddd m2, m7
phaddd m7, m6
REPX {paddd x, m11}, m0, m1, m2, m7
REPX {psrad x, m12}, m0, m1, m2, m7
packssdw m0, m1
packssdw m2, m7
%define m8 m6
%define m9 m4
%define m10 m5
movd m10, r4
movd m9, [stk+0x20]
punpckldq m10, m9
%endif
punpcklbw m10, m10
psraw m10, 8
pshufd m7, m10, q0000
pshufd m8, m10, q1111
pshufd m9, m10, q2222
pshufd m10, m10, q3333
%if ARCH_X86_32
mova [stk+0x50], m7
mova [stk+0x60], m8
mova [stk+0x70], m9
mova [stk+0x80], m10
%xdefine m13 m7
%define m7 [stk+0x50]
%define m8 [stk+0x60]
%define m9 [stk+0x70]
%define m10 [stk+0x80]
%endif
punpcklwd m1, m0, m2 ; 01 23
punpckhwd m3, m0, m2 ; 23 45
%if ARCH_X86_32
mov r4, r0m
%define dstq r4
mova [stk+0x20], m3
mova [stk+0x30], m0
%endif
.dy2_w2_loop:
movu m4, [srcq+ssq*0]
movu m5, [srcq+ssq*1]
movu m6, [srcq+ssq*2]
movu m13, [srcq+ss3q ]
lea srcq, [srcq+ssq*4]
pmaddwd m3, m8
REPX {pshufb x, m14}, m4, m5, m6, m13
REPX {pmaddwd x, m15}, m4, m5, m6, m13
phaddd m4, m5
phaddd m6, m13
pmaddwd m5, m1, m7
paddd m4, m11
paddd m6, m11
psrad m4, m12
psrad m6, m12
packssdw m4, m6 ; 6 7 8 9
paddd m5, m3
pshufd m3, m4, q2200
pshufd m4, m4, q3311
palignr m3, m0, 12 ; 4 6 6 8
palignr m4, m2, 12 ; 5 7 7 9
mova m0, m3
mova m2, m4
punpcklwd m1, m3, m4
punpckhwd m3, m4
pmaddwd m6, m1, m9
pmaddwd m4, m3, m10
paddd m5, vrnd_mem
paddd m6, m4
paddd m5, m6
pshufd m4, m12, q1032
pxor m6, m6
psrad m5, m4
packssdw m5, m5
pmaxsw m5, m6
pminsw m5, pxmaxm
movd [dstq+dsq*0], m5
pshuflw m5, m5, q1032
movd [dstq+dsq*1], m5
lea dstq, [dstq+dsq*2]
sub hd, 2
jg .dy2_w2_loop
RET
%endif
INIT_XMM ssse3
.dy2_w4:
%if ARCH_X86_64
mov myd, mym
mova [rsp+0x10], m11
mova [rsp+0x20], m12
%if isput
mova [rsp+0x30], m13
%define vrnd_mem [rsp+0x30]
%define stk rsp+0x40
%else
%define vrnd_mem [base+pd_m524256]
%define stk rsp+0x30
%endif
movzx t0d, t0b
sub srcq, 2
movd m15, t0d
%else
%define m10 [base+pd_0x3ff]
%define m9 [base+pd_0x4000]
%define m8 m0
%xdefine m14 m4
%define m15 m3
%if isprep
%define ssq r3
%endif
movzx r5, byte [esp+0x1f0]
sub srcq, 2
movd m15, r5
%endif
pmaddwd m8, [base+rescale_mul]
%if ARCH_X86_64
mova m9, [base+pd_0x4000]
%endif
pshufd m15, m15, q0000
paddd m14, m8 ; mx+dx*[0-3]
pand m0, m14, m10
psrld m0, 6
paddd m15, m0
pshufd m7, m15, q1032
%if ARCH_X86_64
movd r4d, m15
movd r11d, m7
pshufd m15, m15, q0321
pshufd m7, m7, q0321
movd r6d, m15
movd r13d, m7
mova m10, [base+bdct_lb_q+ 0]
mova m11, [base+bdct_lb_q+16]
movd m13, [base+subpel_filters+ r4*8+2]
movd m2, [base+subpel_filters+ r6*8+2]
movd m15, [base+subpel_filters+r11*8+2]
movd m4, [base+subpel_filters+r13*8+2]
%else
movd r1, m15
movd r4, m7
pshufd m15, m15, q0321
pshufd m7, m7, q0321
movd r3, m15
movd r5, m7
mova m5, [base+bdct_lb_q+ 0]
mova m6, [base+bdct_lb_q+16]
movd m1, [base+subpel_filters+r1*8+2]
movd m2, [base+subpel_filters+r3*8+2]
movd m3, [base+subpel_filters+r4*8+2]
movd m7, [base+subpel_filters+r5*8+2]
SWAP m4, m7
mov r3, r3m
%if isprep
lea ss3q, [ssq*3]
%endif
%define m10 m5
%define m11 m6
%define m12 m1
%define m13 m1
%endif
psrld m14, 10
paddd m14, m14
punpckldq m13, m2
punpckldq m15, m4
punpcklqdq m13, m15
pxor m2, m2
pcmpeqd m0, m2
%if ARCH_X86_64
pand m9, m0
%else
pand m2, m9, m0
%define m9 m2
SWAP m7, m4
%endif
pandn m0, m13
%if ARCH_X86_64
SWAP m13, m0
%else
%define m13 m0
%endif
por m13, m9
punpckhbw m15, m13, m13
punpcklbw m13, m13
psraw m15, 8
psraw m13, 8
pshufb m12, m14, m10
pshufb m14, m11
mova m10, [base+spel_s_shuf2]
movd r4d, m14
shr r4d, 24
%if ARCH_X86_32
mova [stk+0x40], m13
mova [stk+0x50], m15
pxor m2, m2
%endif
pshufb m7, m14, m2
psubb m14, m7
paddb m12, m10
paddb m14, m10
%if ARCH_X86_64
lea r6, [r4+ssq*1]
lea r11, [r4+ssq*2]
lea r13, [r4+ss3q ]
movu m1, [srcq+ssq*0]
movu m8, [srcq+ssq*2]
movu m9, [srcq+ssq*1]
movu m10, [srcq+ss3q ]
movu m7, [srcq+r4 ]
movu m2, [srcq+r11 ]
movu m3, [srcq+r6 ]
movu m4, [srcq+r13 ]
lea srcq, [srcq+ssq*4]
REPX {pshufb x, m12}, m1, m9, m8, m10
REPX {pmaddwd x, m13}, m1, m9, m8, m10
REPX {pshufb x, m14}, m7, m3, m2, m4
REPX {pmaddwd x, m15}, m7, m3, m2, m4
mova m5, [rsp+0x10]
movd xm6, [rsp+0x20]
phaddd m1, m7
phaddd m8, m2
phaddd m9, m3
phaddd m10, m4
movu m2, [srcq+ssq*0]
movu m3, [srcq+ssq*1]
REPX {paddd x, m5}, m1, m9, m8, m10
REPX {psrad x, xm6}, m1, m9, m8, m10
packssdw m1, m8 ; 0 2
packssdw m9, m10 ; 1 3
movu m0, [srcq+r4 ]
movu m8, [srcq+r6 ]
lea srcq, [srcq+ssq*2]
REPX {pshufb x, m12}, m2, m3
REPX {pmaddwd x, m13}, m2, m3
REPX {pshufb x, m14}, m0, m8
REPX {pmaddwd x, m15}, m0, m8
phaddd m2, m0
phaddd m3, m8
shr myd, 6
mov r9d, 64 << 24
lea myd, [t1+myq]
cmovnz r9q, [base+subpel_filters+myq*8]
REPX {paddd x, m5}, m2, m3
REPX {psrad x, xm6}, m2, m3
packssdw m2, m3 ; 4 5
pshufd m3, m2, q1032 ; 5 _
punpcklwd m0, m1, m9 ; 01
punpckhwd m1, m9 ; 23
punpcklwd m2, m3 ; 45
movq m10, r9
%define hrnd_mem [rsp+0x10]
%define hsh_mem [rsp+0x20]
%define vsh_mem [rsp+0x28]
%if isput
%define vrnd_mem [rsp+0x30]
%else
%define vrnd_mem [base+pd_m524256]
%endif
%else
mova [stk+0x20], m12
mova [stk+0x30], m14
add r4, srcq
MC_4TAP_SCALED_H 0x60 ; 0 1
MC_4TAP_SCALED_H 0x70 ; 2 3
MC_4TAP_SCALED_H 0x80 ; 4 5
mov [stk+0xe0], r4
mova m3, [base+spel_s_shuf8]
mova m0, [stk+0x60]
mova m1, [stk+0x70]
mova m2, [stk+0x80]
mov myd, mym
mov rX, [esp+0x1f4]
xor r5, r5
shr myd, 6
lea rX, [rX+myd]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+rX*8+0]
cmovnz r5, [base+subpel_filters+rX*8+4]
mov r3, r3m
pshufb m0, m3 ; 01
pshufb m1, m3 ; 23
pshufb m2, m3 ; 45
movd m7, r4
movd m4, r5
mov r5, r0m
%if isput
mov r1, r1m
%endif
mov r4, [stk+0xe0]
%define dstq r5
%define tmpq r5
%define m12 [stk+0x20]
%define m14 [stk+0x30]
%define m13 [stk+0x40]
%define m15 [stk+0x50]
%define hrnd_mem [esp+0x00]
%define hsh_mem [esp+0x10]
%define vsh_mem [esp+0x18]
%if isput
%define vrnd_mem [esp+0x20]
%else
%define vrnd_mem [base+pd_m524256]
%endif
%define m10 m7
punpckldq m10, m4
%endif
punpcklbw m10, m10
psraw m10, 8
pshufd m3, m10, q0000
pshufd m4, m10, q1111
pshufd m5, m10, q2222
pshufd m10, m10, q3333
%if ARCH_X86_32
%xdefine m8 m3
%xdefine m9 m6
%xdefine m11 m5
%xdefine m6 m4
mova [stk+0x100], m3
mova [stk+0x110], m4
mova [stk+0x120], m5
mova [stk+0x130], m10
%define m3 [stk+0x100]
%define m4 [stk+0x110]
%define m5 [stk+0x120]
%define m10 [stk+0x130]
%endif
.dy2_w4_loop:
pmaddwd m8, m0, m3
pmaddwd m9, m1, m3
mova m0, m2
pmaddwd m1, m4
pmaddwd m11, m2, m4
paddd m8, vrnd_mem
paddd m9, vrnd_mem
pmaddwd m2, m5
paddd m8, m1
paddd m9, m11
paddd m8, m2
movu m6, [srcq+ssq*0]
movu m1, [srcq+ssq*2]
%if ARCH_X86_64
movu m11, [srcq+r4 ]
movu m2, [srcq+r11]
%else
movu m11, [r4+ssq*0]
movu m2, [r4+ssq*2]
%endif
pshufb m6, m12
pshufb m1, m12
pmaddwd m6, m13
pmaddwd m1, m13
pshufb m11, m14
pshufb m2, m14
pmaddwd m11, m15
pmaddwd m2, m15
phaddd m6, m11
phaddd m1, m2
paddd m6, hrnd_mem
paddd m1, hrnd_mem
psrad m6, hsh_mem
psrad m1, hsh_mem
movu m7, [srcq+ssq*1]
movu m11, [srcq+ss3q ]
packssdw m6, m1 ; 6 8
%if ARCH_X86_64
movu m2, [srcq+r6 ]
movu m1, [srcq+r13]
%else
movu m2, [r4+ssq*1]
movu m1, [r4+ss3q ]
%endif
pshufb m7, m12
pshufb m11, m12
pmaddwd m7, m13
pmaddwd m11, m13
pshufb m2, m14
pshufb m1, m14
pmaddwd m2, m15
pmaddwd m1, m15
phaddd m7, m2
phaddd m11, m1
paddd m7, hrnd_mem
paddd m11, hrnd_mem
psrad m7, hsh_mem
psrad m11, hsh_mem
packssdw m7, m11 ; 7 9
%if ARCH_X86_32
lea r4, [r4+ssq*4]
%endif
lea srcq, [srcq+ssq*4]
punpcklwd m1, m6, m7 ; 67
punpckhwd m6, m7 ; 89
mova m2, m6
pmaddwd m11, m1, m5
pmaddwd m7, m1, m10
pmaddwd m6, m10
paddd m9, m11
%if isput
movd m11, vsh_mem
%endif
paddd m8, m7
paddd m9, m6
%if isput
psrad m8, m11
psrad m9, m11
packssdw m8, m9
pxor m7, m7
pmaxsw m8, m7
pminsw m8, pxmaxm
movq [dstq+dsq*0], m8
movhps [dstq+dsq*1], m8
lea dstq, [dstq+dsq*2]
%else
psrad m8, 6
psrad m9, 6
packssdw m8, m9
mova [tmpq], m8
add tmpq, 16
%endif
sub hd, 2
jg .dy2_w4_loop
MC_8TAP_SCALED_RET ; why not jz .ret?
INIT_XMM ssse3
.dy2_w8:
mov dword [stk+0xf0], 1
movifprep tmp_stridem, 16
jmp .dy2_w_start
.dy2_w16:
mov dword [stk+0xf0], 2
movifprep tmp_stridem, 32
jmp .dy2_w_start
.dy2_w32:
mov dword [stk+0xf0], 4
movifprep tmp_stridem, 64
jmp .dy2_w_start
.dy2_w64:
mov dword [stk+0xf0], 8
movifprep tmp_stridem, 128
jmp .dy2_w_start
.dy2_w128:
mov dword [stk+0xf0], 16
movifprep tmp_stridem, 256
.dy2_w_start:
mov myd, mym
%if ARCH_X86_64
%ifidn %1, put
movifnidn dsm, dsq
%endif
mova [rsp+0x10], m11
mova [rsp+0x20], m12
%define hround m11
%if isput
mova [rsp+0x30], m13
%else
mova m13, [base+pd_m524256]
%endif
shr t0d, 16
shr myd, 6
mov r4d, 64 << 24
lea myd, [t1+myq]
cmovnz r4q, [base+subpel_filters+myq*8]
movd m15, t0d
%else
%define hround [esp+0x00]
%define m12 [esp+0x10]
%define m10 [base+pd_0x3ff]
%define m8 m0
%xdefine m14 m4
%xdefine m15 m3
%if isput
%define dstq r0
%else
%define tmpq r0
%define ssq ssm
%endif
mov r5, [esp+0x1f0]
mov r3, [esp+0x1f4]
shr r5, 16
movd m15, r5
xor r5, r5
shr myd, 6
lea r3, [r3+myd]
mov r4, 64 << 24
cmovnz r4, [base+subpel_filters+r3*8+0]
cmovnz r5, [base+subpel_filters+r3*8+4]
mov r0, r0m
mov r3, r3m
%endif
sub srcq, 6
pslld m7, m8, 2 ; dx*4
pmaddwd m8, [base+rescale_mul] ; dx*[0-3]
pshufd m15, m15, q0000
paddd m14, m8 ; mx+dx*[0-3]
%if ARCH_X86_64
movq m3, r4q
%else
movd m5, r4
movd m6, r5
punpckldq m5, m6
SWAP m3, m5
%endif
punpcklbw m3, m3
psraw m3, 8
mova [stk+0x100], m7
mova [stk+0x120], m15
mov [stk+0x0f8], srcq
mov [stk+0x130], r0q ; dstq / tmpq
pshufd m0, m3, q0000
pshufd m1, m3, q1111
pshufd m2, m3, q2222
pshufd m3, m3, q3333
%if ARCH_X86_64
mova [stk+0x140], m0
mova [stk+0x150], m1
mova [stk+0x160], m2
mova [stk+0x170], m3
%if UNIX64
mov hm, hd
%endif
%else
mova [stk+0x180], m0
mova [stk+0x190], m1
mova [stk+0x1a0], m2
mova [stk+0x1b0], m3
SWAP m5, m3
mov r5, hm
mov [stk+0x134], r5
%endif
jmp .dy2_hloop
.dy2_hloop_prep:
dec dword [stk+0x0f0]
jz .ret
%if ARCH_X86_64
add qword [stk+0x130], 16
mov hd, hm
%else
add dword [stk+0x130], 16
mov r5, [stk+0x134]
mov r0, [stk+0x130]
%endif
mova m7, [stk+0x100]
mova m14, [stk+0x110]
%if ARCH_X86_64
mova m10, [base+pd_0x3ff]
mova m11, [rsp+0x10]
%endif
mova m15, [stk+0x120]
mov srcq, [stk+0x0f8]
%if ARCH_X86_64
mov r0q, [stk+0x130] ; dstq / tmpq
%else
mov hm, r5
mov r0m, r0
mov r3, r3m
%endif
paddd m14, m7
.dy2_hloop:
%if ARCH_X86_64
mova m9, [base+pq_0x40000000]
%else
%define m9 [base+pq_0x40000000]
%endif
pxor m1, m1
psrld m2, m14, 10
mova [stk], m2
pand m6, m14, m10
psrld m6, 6
paddd m5, m15, m6
pcmpeqd m6, m1
pshufd m2, m5, q1032
%if ARCH_X86_64
movd r4d, m5
movd r6d, m2
pshufd m5, m5, q0321
pshufd m2, m2, q0321
movd r7d, m5
movd r9d, m2
movq m0, [base+subpel_filters+r4*8]
movq m1, [base+subpel_filters+r6*8]
movhps m0, [base+subpel_filters+r7*8]
movhps m1, [base+subpel_filters+r9*8]
%else
movd r0, m5
movd rX, m2
pshufd m5, m5, q0321
pshufd m2, m2, q0321
movd r4, m5
movd r5, m2
movq m0, [base+subpel_filters+r0*8]
movq m1, [base+subpel_filters+rX*8]
movhps m0, [base+subpel_filters+r4*8]
movhps m1, [base+subpel_filters+r5*8]
%endif
paddd m14, m7 ; mx+dx*[4-7]
pand m5, m14, m10
psrld m5, 6
paddd m15, m5
pxor m2, m2
pcmpeqd m5, m2
mova [stk+0x110], m14
pshufd m4, m15, q1032
%if ARCH_X86_64
movd r10d, m15
movd r11d, m4
pshufd m15, m15, q0321
pshufd m4, m4, q0321
movd r13d, m15
movd rXd, m4
movq m2, [base+subpel_filters+r10*8]
movq m3, [base+subpel_filters+r11*8]
movhps m2, [base+subpel_filters+r13*8]
movhps m3, [base+subpel_filters+ rX*8]
psrld m14, 10
movq r11, m14
punpckhqdq m14, m14
movq rX, m14
mov r10d, r11d
shr r11, 32
mov r13d, rXd
shr rX, 32
mov r4d, [stk+ 0]
mov r6d, [stk+ 4]
mov r7d, [stk+ 8]
mov r9d, [stk+12]
pshufd m4, m6, q1100
pshufd m6, m6, q3322
pshufd m14, m5, q1100
pshufd m5, m5, q3322
pand m7, m9, m4
pand m8, m9, m6
pand m15, m9, m14
pand m9, m9, m5
pandn m4, m0
pandn m6, m1
pandn m14, m2
pandn m5, m3
por m7, m4
por m8, m6
por m15, m14
por m9, m5
punpcklbw m0, m7, m7
punpckhbw m7, m7
punpcklbw m1, m8, m8
punpckhbw m8, m8
psraw m0, 8
psraw m7, 8
psraw m1, 8
psraw m8, 8
punpcklbw m2, m15, m15
punpckhbw m15, m15
punpcklbw m3, m9, m9
punpckhbw m9, m9
psraw m2, 8
psraw m15, 8
psraw m3, 8
psraw m9, 8
mova [stk+0x10], m0
mova [stk+0x20], m7
mova [stk+0x30], m1
mova [stk+0x40], m8
mova [stk+0x50], m2
mova [stk+0x60], m15
mova [stk+0x70], m3
mova [stk+0x80], m9
MC_8TAP_SCALED_H 1, 2, 3, 4, 5, 6, 9, 10 ; 0
mova [stk+0x90], m1
MC_8TAP_SCALED_H 2, 3, 4, 5, 6, 1, 9, 10 ; 1
mova [stk+0xa0], m2
MC_8TAP_SCALED_H 3, 4, 5, 6, 1, 2, 9, 10 ; 2
mova [stk+0xb0], m3
MC_8TAP_SCALED_H 4, 5, 6, 1, 2, 3, 9, 10 ; 3
mova [stk+0xc0], m4
MC_8TAP_SCALED_H 5, 6, 1, 2, 3, 4, 9, 10 ; 4
mova [stk+0xd0], m5
MC_8TAP_SCALED_H 6, 1, 2, 3, 4, 5, 9, 10 ; 5
MC_8TAP_SCALED_H 7, 1, 2, 3, 4, 5, 9, 10 ; 6
MC_8TAP_SCALED_H 8, 1, 2, 3, 4, 5, 9, 10 ; 7
mova m5, [stk+0xd0]
mova m1, [stk+0x90]
mova m2, [stk+0xa0]
mova m3, [stk+0xb0]
mova m9, [stk+0xc0]
punpcklwd m4, m5, m6 ; 45a
punpckhwd m5, m6 ; 45b
punpcklwd m6, m7, m8 ; 67a
punpckhwd m7, m8 ; 67b
punpcklwd m0, m1, m2 ; 01a
punpckhwd m1, m2 ; 01b
punpcklwd m2, m3, m9 ; 23a
punpckhwd m3, m9 ; 23b
mova m10, [stk+0x140]
mova m11, [stk+0x150]
mova m14, [stk+0x160]
mova m15, [stk+0x170]
mova [stk+0x90], m4
mova [stk+0xa0], m5
mova [stk+0xb0], m6
mova [stk+0xc0], m7
%define hround [rsp+0x10]
%define shift [rsp+0x20]
%if isput
%define vround [rsp+0x30]
%else
%define vround [base+pd_m524256]
%endif
.dy2_vloop:
pmaddwd m4, m0, m10
pmaddwd m5, m1, m10
pmaddwd m6, m2, m11
pmaddwd m7, m3, m11
paddd m4, m13
paddd m5, m13
paddd m4, m6
paddd m5, m7
pmaddwd m6, [stk+0x90], m14
pmaddwd m7, [stk+0xa0], m14
pmaddwd m8, [stk+0xb0], m15
pmaddwd m9, [stk+0xc0], m15
paddd m4, m6
paddd m5, m7
%if isput
pshufd m6, m12, q1032
%endif
paddd m4, m8
paddd m5, m9
%else
movd r0, m15
movd rX, m4
pshufd m15, m15, q0321
pshufd m4, m4, q0321
movd r4, m15
movd r5, m4
mova m14, [stk+0x110]
movq m2, [base+subpel_filters+r0*8]
movq m3, [base+subpel_filters+rX*8]
movhps m2, [base+subpel_filters+r4*8]
movhps m3, [base+subpel_filters+r5*8]
psrld m14, 10
mova [stk+16], m14
mov r0, [stk+ 0]
mov rX, [stk+ 4]
mov r4, [stk+ 8]
mov r5, [stk+12]
mova [stk+0x20], m0
mova [stk+0x30], m1
mova [stk+0x40], m2
mova [stk+0x50], m3
pshufd m4, m6, q1100
pshufd m6, m6, q3322
pshufd m7, m5, q1100
pshufd m5, m5, q3322
pand m0, m9, m4
pand m1, m9, m6
pand m2, m9, m7
pand m3, m9, m5
pandn m4, [stk+0x20]
pandn m6, [stk+0x30]
pandn m7, [stk+0x40]
pandn m5, [stk+0x50]
por m0, m4
por m1, m6
por m2, m7
por m3, m5
punpcklbw m4, m0, m0
punpckhbw m0, m0
punpcklbw m5, m1, m1
punpckhbw m1, m1
psraw m4, 8
psraw m0, 8
psraw m5, 8
psraw m1, 8
punpcklbw m6, m2, m2
punpckhbw m2, m2
punpcklbw m7, m3, m3
punpckhbw m3, m3
psraw m6, 8
psraw m2, 8
psraw m7, 8
psraw m3, 8
mova [stk+0x0a0], m4
mova [stk+0x0b0], m0
mova [stk+0x0c0], m5
mova [stk+0x0d0], m1
mova [stk+0x140], m6
mova [stk+0x150], m2
mova [stk+0x160], m7
mova [stk+0x170], m3
MC_8TAP_SCALED_H 0xa0, 0x20, 0 ; 0
MC_8TAP_SCALED_H 0xa0, 0x30 ; 1
MC_8TAP_SCALED_H 0xa0, 0x40 ; 2
MC_8TAP_SCALED_H 0xa0, 0x50 ; 3
MC_8TAP_SCALED_H 0xa0, 0x60 ; 4
MC_8TAP_SCALED_H 0xa0, 0x70 ; 5
MC_8TAP_SCALED_H 0xa0, 0x80 ; 6
MC_8TAP_SCALED_H 0xa0, 0x90 ; 7
mova m5, [stk+0x60]
mova m6, [stk+0x70]
mova m7, [stk+0x80]
mova m0, [stk+0x90]
mov r0, r0m
punpcklwd m4, m5, m6 ; 45a
punpckhwd m5, m6 ; 45b
punpcklwd m6, m7, m0 ; 67a
punpckhwd m7, m0 ; 67b
mova [stk+0x60], m4
mova [stk+0x70], m5
mova [stk+0x80], m6
mova [stk+0x90], m7
mova m1, [stk+0x20]
mova m2, [stk+0x30]
mova m3, [stk+0x40]
mova m4, [stk+0x50]
punpcklwd m0, m1, m2 ; 01a
punpckhwd m1, m2 ; 01b
punpcklwd m2, m3, m4 ; 23a
punpckhwd m3, m4 ; 23b
mova m4, [stk+0x180]
mova m5, [stk+0x190]
mova m6, [stk+0x1a0]
mova m7, [stk+0x1b0]
mova [stk+0x40], m2
mova [stk+0x50], m3
.dy2_vloop:
pmaddwd m0, m4
pmaddwd m1, m4
pmaddwd m2, m5
pmaddwd m3, m5
paddd m0, m2
paddd m1, m3
pmaddwd m2, [stk+0x60], m6
pmaddwd m3, [stk+0x70], m6
pmaddwd m4, [stk+0x80], m7
pmaddwd m5, [stk+0x90], m7
%if isput
movd m6, [esp+0x18]
%endif
paddd m0, m2
paddd m1, m3
paddd m0, vrnd_mem
paddd m1, vrnd_mem
paddd m4, m0
paddd m5, m1
%endif
%ifidn %1, put
psrad m4, m6
psrad m5, m6
packssdw m4, m5
pxor m7, m7
pmaxsw m4, m7
pminsw m4, pxmaxm
mova [dstq], m4
add dstq, dsm
%else
psrad m4, 6
psrad m5, 6
packssdw m4, m5
mova [tmpq], m4
add tmpq, tmp_stridem
%endif
dec hd
jz .dy2_hloop_prep
%if ARCH_X86_64
MC_8TAP_SCALED_H 4, 8, 5, 6, 7, 9, 0, 1
mova [stk+0xd0], m4
MC_8TAP_SCALED_H 8, 5, 6, 7, 9, 4, 0, 1
mova m4, [stk+0xd0]
mova m0, m2 ; 01a
mova m1, m3 ; 01b
mova m2, [stk+0x90] ; 23a
mova m3, [stk+0xa0] ; 23b
mova m5, [stk+0xb0] ; 45a
mova m6, [stk+0xc0] ; 45b
punpcklwd m7, m4, m8 ; 67a
punpckhwd m4, m8 ; 67b
mova [stk+0x90], m5
mova [stk+0xa0], m6
mova [stk+0xb0], m7
mova [stk+0xc0], m4
%else
mov r0m, r0
mov r3, r3m
MC_8TAP_SCALED_H 0xa0, 0xe0 ; 8
MC_8TAP_SCALED_H 0xa0, 0 ; 9
mova m7, [stk+0xe0]
mova m2, [stk+0x60] ; 23a
mova m3, [stk+0x70] ; 23b
mova m4, [stk+0x80] ; 45a
mova m5, [stk+0x90] ; 45b
punpcklwd m6, m7, m0 ; 67a
punpckhwd m7, m0 ; 67b
mova m0, [stk+0x40] ; 01a
mova m1, [stk+0x50] ; 01b
mova [stk+0x40], m2
mova [stk+0x50], m3
mova [stk+0x60], m4
mova [stk+0x70], m5
mova m4, [stk+0x180]
mova m5, [stk+0x190]
mova [stk+0x80], m6
mova [stk+0x90], m7
mova m6, [stk+0x1a0]
mova m7, [stk+0x1b0]
mov r0, r0m
%endif
jmp .dy2_vloop
INIT_XMM ssse3
.ret:
MC_8TAP_SCALED_RET 0
%if ARCH_X86_32 && !isprep && required_stack_alignment > STACK_ALIGNMENT
%define r0m [rstk+stack_offset+ 4]
%define r1m [rstk+stack_offset+ 8]
%define r2m [rstk+stack_offset+12]
%define r3m [rstk+stack_offset+16]
%endif
%undef isput
%undef isprep
%endmacro
%macro BILIN_SCALED_FN 1
cglobal %1_bilin_scaled_16bpc
mov t0d, (5*15 << 16) | 5*15
mov t1d, (5*15 << 16) | 5*15
jmp mangle(private_prefix %+ _%1_8tap_scaled_16bpc %+ SUFFIX)
%endmacro
%if WIN64
DECLARE_REG_TMP 6, 5
%elif ARCH_X86_64
DECLARE_REG_TMP 6, 8
%else
DECLARE_REG_TMP 1, 2
%endif
BILIN_SCALED_FN put
FN put_8tap_scaled, sharp, SHARP, SHARP
FN put_8tap_scaled, sharp_smooth, SHARP, SMOOTH
FN put_8tap_scaled, smooth_sharp, SMOOTH, SHARP
FN put_8tap_scaled, smooth, SMOOTH, SMOOTH
FN put_8tap_scaled, sharp_regular, SHARP, REGULAR
FN put_8tap_scaled, regular_sharp, REGULAR, SHARP
FN put_8tap_scaled, smooth_regular, SMOOTH, REGULAR
FN put_8tap_scaled, regular_smooth, REGULAR, SMOOTH
FN put_8tap_scaled, regular, REGULAR, REGULAR
MC_8TAP_SCALED put
%if WIN64
DECLARE_REG_TMP 5, 4
%elif ARCH_X86_64
DECLARE_REG_TMP 6, 7
%else
DECLARE_REG_TMP 1, 2
%endif
BILIN_SCALED_FN prep
FN prep_8tap_scaled, sharp, SHARP, SHARP
FN prep_8tap_scaled, sharp_smooth, SHARP, SMOOTH
FN prep_8tap_scaled, smooth_sharp, SMOOTH, SHARP
FN prep_8tap_scaled, smooth, SMOOTH, SMOOTH
FN prep_8tap_scaled, sharp_regular, SHARP, REGULAR
FN prep_8tap_scaled, regular_sharp, REGULAR, SHARP
FN prep_8tap_scaled, smooth_regular, SMOOTH, REGULAR
FN prep_8tap_scaled, regular_smooth, REGULAR, SMOOTH
FN prep_8tap_scaled, regular, REGULAR, REGULAR
MC_8TAP_SCALED prep
%if ARCH_X86_64
DECLARE_REG_TMP 6
%else
DECLARE_REG_TMP 2
%endif
%if ARCH_X86_64
; warp8x8t spills one less xmm register than warp8x8 on WIN64, compensate that
; by allocating 16 bytes more stack space so that stack offsets match up.
%if WIN64 && STACK_ALIGNMENT == 16
%assign stksz 16*14
%else
%assign stksz 16*13
%endif
cglobal warp_affine_8x8t_16bpc, 4, 13, 9, stksz, dst, ds, src, ss, delta, \
mx, tmp, alpha, beta, \
filter, my, gamma, cnt
%assign stack_size_padded_8x8t stack_size_padded
%else
cglobal warp_affine_8x8t_16bpc, 0, 7, 8, -16*17, alpha, gamma, src, tmp, \
filter, mx, my
%define m8 [esp+16*13]
%define m9 [esp+16*14]
%define cntd dword [esp+4*63]
%define dstq tmpq
%define dsq 0
%if STACK_ALIGNMENT < 16
%define dstm [esp+4*65]
%define dsm [esp+4*66]
%else
%define dstm r0m
%define dsm r1m
%endif
%endif
%define base filterq-$$
mov t0d, r7m
LEA filterq, $$
shr t0d, 11
%if ARCH_X86_64
movddup m8, [base+warp8x8t_rnd]
%else
movddup m1, [base+warp8x8t_rnd]
mov r1, r1m
add r1, r1
mova m8, m1
mov r1m, r1 ; ds *= 2
%endif
call mangle(private_prefix %+ _warp_affine_8x8_16bpc_ssse3).main
jmp .start
.loop:
%if ARCH_X86_64
lea dstq, [dstq+dsq*4]
%else
add dstq, dsm
mov dstm, dstq
%endif
call mangle(private_prefix %+ _warp_affine_8x8_16bpc_ssse3).main2
.start:
%if ARCH_X86_32
mov dstq, dstm
%endif
paddd m1, m8
paddd m2, m8
psrad m1, 15
psrad m2, 15
packssdw m1, m2
mova [dstq+dsq*0], m1
call mangle(private_prefix %+ _warp_affine_8x8_16bpc_ssse3).main3
%if ARCH_X86_32
mov dstq, dstm
add dstq, dsm
%endif
paddd m1, m8
paddd m2, m8
psrad m1, 15
psrad m2, 15
packssdw m1, m2
mova [dstq+dsq*2], m1
dec cntd
jg .loop
RET
%if ARCH_X86_64
cglobal warp_affine_8x8_16bpc, 4, 13, 10, 16*13, dst, ds, src, ss, delta, \
mx, tmp, alpha, beta, \
filter, my, gamma, cnt
ASSERT stack_size_padded == stack_size_padded_8x8t
%else
cglobal warp_affine_8x8_16bpc, 0, 7, 8, -16*17, alpha, gamma, src, tmp, \
filter, mx, my
%endif
mov t0d, r7m
LEA filterq, $$
shr t0d, 11
%if ARCH_X86_64
movddup m8, [base+warp8x8_rnd2+t0*8]
movd m9, r7m ; pixel_max
pshufb m9, [base+pw_256]
%else
movddup m1, [base+warp8x8_rnd2+t0*8]
movd m2, r7m ; pixel_max
pshufb m2, [base+pw_256]
mova m8, m1
mova m9, m2
%endif
call .main
jmp .start
.loop:
%if ARCH_X86_64
lea dstq, [dstq+dsq*2]
%else
add dstq, dsm
mov dstm, dstq
%endif
call .main2
.start:
%if ARCH_X86_32
mov dstq, dstm
%endif
psrad m1, 16
psrad m2, 16
packssdw m1, m2
pmaxsw m1, m6
pmulhrsw m1, m8
pminsw m1, m9
mova [dstq+dsq*0], m1
call .main3
%if ARCH_X86_32
mov dstq, dstm
add dstq, dsm
%endif
psrad m1, 16
psrad m2, 16
packssdw m1, m2
pmaxsw m1, m6
pmulhrsw m1, m8
pminsw m1, m9
mova [dstq+dsq*1], m1
dec cntd
jg .loop
RET
ALIGN function_align
.main:
; Stack args offset by one (r4m -> r5m etc.) due to call
%if WIN64
mov deltaq, r5m
mov mxd, r6m
%endif
movd m0, [base+warp8x8_shift+t0*4]
movddup m7, [base+warp8x8_rnd1+t0*8]
add filterq, mc_warp_filter-$$
%if ARCH_X86_64
movsx alphad, word [deltaq+2*0]
movsx betad, word [deltaq+2*1]
movsx gammad, word [deltaq+2*2]
movsx deltad, word [deltaq+2*3]
lea tmpq, [ssq*3]
add mxd, 512+(64<<10)
sub srcq, tmpq ; src -= ss*3
imul tmpd, alphad, -7
mov myd, r7m
add betad, tmpd ; beta -= alpha*7
imul tmpd, gammad, -7
add myd, 512+(64<<10)
mov cntd, 4
add deltad, tmpd ; delta -= gamma*7
%else
%if STACK_ALIGNMENT < 16
%assign stack_offset stack_offset - gprsize
%endif
mov r3d, r5m ; abcd
%if STACK_ALIGNMENT < 16
mov r0, r1m ; dst
mov r1, r2m ; ds
mov [esp+gprsize+4*65], r0
mov [esp+gprsize+4*66], r1
%endif
movsx alphad, word [r3+2*0]
movsx r2d, word [r3+2*1]
movsx gammad, word [r3+2*2]
movsx r3d, word [r3+2*3]
imul r5d, alphad, -7
add r2d, r5d ; beta -= alpha*7
imul r5d, gammad, -7
mov [esp+gprsize+4*60], r2d
add r3d, r5d ; delta -= gamma*7
mov [esp+gprsize+4*61], r3d
mov r3d, r4m ; ss
mov srcq, r3m
mov mxd, r6m
mov myd, r7m
mov dword [esp+gprsize+4*63], 4 ; cnt
mov [esp+gprsize+4*62], r3
lea r3, [r3*3]
add mxd, 512+(64<<10)
add myd, 512+(64<<10)
sub srcq, r3 ; src -= ss*3
%if STACK_ALIGNMENT < 16
%assign stack_offset stack_offset + gprsize
%endif
%endif
mova [rsp+gprsize], m0
pxor m6, m6
call .h
mova m5, m0
call .h
punpcklwd m1, m5, m0 ; 01
punpckhwd m5, m0
mova [rsp+gprsize+16* 1], m1
mova [rsp+gprsize+16* 4], m5
mova m5, m0
call .h
punpcklwd m1, m5, m0 ; 12
punpckhwd m5, m0
mova [rsp+gprsize+16* 7], m1
mova [rsp+gprsize+16*10], m5
mova m5, m0
call .h
punpcklwd m1, m5, m0 ; 23
punpckhwd m5, m0
mova [rsp+gprsize+16* 2], m1
mova [rsp+gprsize+16* 5], m5
mova m5, m0
call .h
punpcklwd m1, m5, m0 ; 34
punpckhwd m5, m0
mova [rsp+gprsize+16* 8], m1
mova [rsp+gprsize+16*11], m5
mova m5, m0
call .h
punpcklwd m1, m5, m0 ; 45
punpckhwd m5, m0
mova [rsp+gprsize+16* 3], m1
mova [rsp+gprsize+16* 6], m5
mova m5, m0
call .h
punpcklwd m1, m5, m0 ; 56
punpckhwd m5, m0
mova [rsp+gprsize+16* 9], m1
mova [rsp+gprsize+16*12], m5
mova m5, m0
.main2:
call .h
%macro WARP_V 6 ; 01l, 23l, 45l, 01h, 23h, 45h
lea tmpd, [myq+gammaq]
shr myd, 10
movq m4, [filterq+myq*8] ; a
lea myd, [tmpq+gammaq]
shr tmpd, 10
movq m2, [filterq+tmpq*8] ; b
lea tmpd, [myq+gammaq]
shr myd, 10
movq m3, [filterq+myq*8] ; c
lea myd, [tmpq+gammaq]
shr tmpd, 10
movq m1, [filterq+tmpq*8] ; d
lea tmpd, [myq+gammaq]
shr myd, 10
punpcklwd m4, m2
punpcklwd m3, m1
punpckldq m2, m4, m3
punpckhdq m4, m3
punpcklbw m1, m6, m2 ; a0 a1 b0 b1 c0 c1 d0 d1 << 8
pmaddwd m1, [rsp+gprsize+16*%1]
punpckhbw m3, m6, m2 ; a2 a3 b2 b3 c2 c3 d2 d3 << 8
mova m2, [rsp+gprsize+16*%2]
pmaddwd m3, m2
mova [rsp+gprsize+16*%1], m2
paddd m1, m3
punpcklbw m3, m6, m4 ; a4 a5 b4 b5 c4 c5 d4 d5 << 8
mova m2, [rsp+gprsize+16*%3]
pmaddwd m3, m2
mova [rsp+gprsize+16*%2], m2
paddd m1, m3
punpcklwd m3, m5, m0 ; 67
punpckhbw m2, m6, m4 ; a6 a7 b6 b7 c6 c7 d6 d7 << 8
pmaddwd m2, m3
mova [rsp+gprsize+16*%3], m3
paddd m1, m2
movq m4, [filterq+myq*8] ; e
lea myd, [tmpq+gammaq]
shr tmpd, 10
movq m3, [filterq+tmpq*8] ; f
lea tmpd, [myq+gammaq]
shr myd, 10
movq m2, [filterq+myq*8] ; g
%if ARCH_X86_64
lea myd, [tmpq+deltaq] ; my += delta
%else
mov myd, [esp+gprsize+4*61]
add myd, tmpd
%endif
shr tmpd, 10
punpcklwd m4, m3
movq m3, [filterq+tmpq*8] ; h
punpcklwd m2, m3
punpckldq m3, m4, m2
punpckhdq m4, m2
punpcklbw m2, m6, m3 ; e0 e1 f0 f1 g0 g1 h0 h1 << 8
pmaddwd m2, [rsp+gprsize+16*%4]
punpckhbw m6, m3 ; e2 e3 f2 f3 g2 g3 h2 h3 << 8
mova m3, [rsp+gprsize+16*%5]
pmaddwd m6, m3
mova [rsp+gprsize+16*%4], m3
pxor m3, m3
paddd m2, m6
punpcklbw m3, m4 ; e4 e5 f4 f5 g4 g5 h4 h5 << 8
mova m6, [rsp+gprsize+16*%6]
pmaddwd m3, m6
mova [rsp+gprsize+16*%5], m6
punpckhwd m5, m0
pxor m6, m6
paddd m2, m3
punpckhbw m3, m6, m4 ; e6 e7 f6 f7 g6 g7 h6 h7 << 8
pmaddwd m3, m5
mova [rsp+gprsize+16*%6], m5
mova m5, m0
paddd m2, m3
%endmacro
WARP_V 1, 2, 3, 4, 5, 6
ret
.main3:
call .h
WARP_V 7, 8, 9, 10, 11, 12
ret
ALIGN function_align
.h:
lea tmpd, [mxq+alphaq]
shr mxd, 10
movq m3, [filterq+mxq*8]
punpcklbw m0, m6, m3
movu m3, [srcq-6]
pmaddwd m0, m3 ; 0
lea mxd, [tmpq+alphaq]
shr tmpd, 10
movq m3, [filterq+tmpq*8]
punpcklbw m2, m6, m3
movu m3, [srcq-4]
pmaddwd m2, m3 ; 1
lea tmpd, [mxq+alphaq]
shr mxd, 10
movq m3, [filterq+mxq*8]
phaddd m0, m2 ; 0 1
punpcklbw m2, m6, m3
movu m3, [srcq-2]
pmaddwd m2, m3 ; 2
lea mxd, [tmpq+alphaq]
shr tmpd, 10
movq m3, [filterq+tmpq*8]
punpcklbw m1, m6, m3
movu m3, [srcq+0]
pmaddwd m1, m3 ; 3
lea tmpd, [mxq+alphaq]
shr mxd, 10
movq m3, [filterq+mxq*8]
phaddd m2, m1 ; 2 3
punpcklbw m1, m6, m3
movu m3, [srcq+2]
pmaddwd m1, m3 ; 4
lea mxd, [tmpq+alphaq]
shr tmpd, 10
movq m3, [filterq+tmpq*8]
phaddd m0, m2 ; 0 1 2 3
punpcklbw m2, m6, m3
movu m3, [srcq+4]
pmaddwd m2, m3 ; 5
lea tmpd, [mxq+alphaq]
shr mxd, 10
movq m3, [filterq+mxq*8]
phaddd m1, m2 ; 4 5
punpcklbw m2, m6, m3
movu m3, [srcq+6]
pmaddwd m2, m3 ; 6
%if ARCH_X86_64
lea mxd, [tmpq+betaq] ; mx += beta
%else
mov mxd, [esp+gprsize*2+4*60]
add mxd, tmpd
%endif
shr tmpd, 10
movq m3, [filterq+tmpq*8]
punpcklbw m4, m6, m3
movu m3, [srcq+8]
%if ARCH_X86_64
add srcq, ssq
%else
add srcq, [esp+gprsize*2+4*62]
%endif
pmaddwd m3, m4 ; 7
phaddd m2, m3 ; 6 7
phaddd m1, m2 ; 4 5 6 7
paddd m0, m7
paddd m1, m7
psrad m0, [rsp+gprsize*2]
psrad m1, [rsp+gprsize*2]
packssdw m0, m1
ret
%macro BIDIR_FN 0
call .main
jmp wq
.w4_loop:
call .main
lea dstq, [dstq+strideq*2]
.w4:
movq [dstq+strideq*0], m0
movhps [dstq+strideq*1], m0
lea dstq, [dstq+strideq*2]
movq [dstq+strideq*0], m1
movhps [dstq+strideq*1], m1
sub hd, 4
jg .w4_loop
.ret:
RET
.w8_loop:
call .main
lea dstq, [dstq+strideq*2]
.w8:
mova [dstq+strideq*0], m0
mova [dstq+strideq*1], m1
sub hd, 2
jne .w8_loop
RET
.w16_loop:
call .main
add dstq, strideq
.w16:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
dec hd
jg .w16_loop
RET
.w32_loop:
call .main
add dstq, strideq
.w32:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
call .main
mova [dstq+16*2], m0
mova [dstq+16*3], m1
dec hd
jg .w32_loop
RET
.w64_loop:
call .main
add dstq, strideq
.w64:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
call .main
mova [dstq+16*2], m0
mova [dstq+16*3], m1
call .main
mova [dstq+16*4], m0
mova [dstq+16*5], m1
call .main
mova [dstq+16*6], m0
mova [dstq+16*7], m1
dec hd
jg .w64_loop
RET
.w128_loop:
call .main
add dstq, strideq
.w128:
mova [dstq+16* 0], m0
mova [dstq+16* 1], m1
call .main
mova [dstq+16* 2], m0
mova [dstq+16* 3], m1
call .main
mova [dstq+16* 4], m0
mova [dstq+16* 5], m1
call .main
mova [dstq+16* 6], m0
mova [dstq+16* 7], m1
call .main
mova [dstq+16* 8], m0
mova [dstq+16* 9], m1
call .main
mova [dstq+16*10], m0
mova [dstq+16*11], m1
call .main
mova [dstq+16*12], m0
mova [dstq+16*13], m1
call .main
mova [dstq+16*14], m0
mova [dstq+16*15], m1
dec hd
jg .w128_loop
RET
%endmacro
%if UNIX64
DECLARE_REG_TMP 7
%else
DECLARE_REG_TMP 5
%endif
cglobal avg_16bpc, 4, 7, 4, dst, stride, tmp1, tmp2, w, h
%define base r6-avg_ssse3_table
LEA r6, avg_ssse3_table
tzcnt wd, wm
mov t0d, r6m ; pixel_max
movsxd wq, [r6+wq*4]
shr t0d, 11
movddup m2, [base+bidir_rnd+t0*8]
movddup m3, [base+bidir_mul+t0*8]
movifnidn hd, hm
add wq, r6
BIDIR_FN
ALIGN function_align
.main:
mova m0, [tmp1q+16*0]
paddsw m0, [tmp2q+16*0]
mova m1, [tmp1q+16*1]
paddsw m1, [tmp2q+16*1]
add tmp1q, 16*2
add tmp2q, 16*2
pmaxsw m0, m2
pmaxsw m1, m2
psubsw m0, m2
psubsw m1, m2
pmulhw m0, m3
pmulhw m1, m3
ret
cglobal w_avg_16bpc, 4, 7, 8, dst, stride, tmp1, tmp2, w, h
%define base r6-w_avg_ssse3_table
LEA r6, w_avg_ssse3_table
tzcnt wd, wm
mov t0d, r6m ; weight
movd m6, r7m ; pixel_max
movddup m5, [base+pd_65538]
movsxd wq, [r6+wq*4]
pshufb m6, [base+pw_256]
add wq, r6
lea r6d, [t0-16]
shl t0d, 16
sub t0d, r6d ; 16-weight, weight
paddw m5, m6
mov r6d, t0d
shl t0d, 2
test dword r7m, 0x800
cmovnz r6d, t0d
movifnidn hd, hm
movd m4, r6d
pslld m5, 7
pxor m7, m7
pshufd m4, m4, q0000
BIDIR_FN
ALIGN function_align
.main:
mova m2, [tmp1q+16*0]
mova m0, [tmp2q+16*0]
punpckhwd m3, m0, m2
punpcklwd m0, m2
mova m2, [tmp1q+16*1]
mova m1, [tmp2q+16*1]
add tmp1q, 16*2
add tmp2q, 16*2
pmaddwd m3, m4
pmaddwd m0, m4
paddd m3, m5
paddd m0, m5
psrad m3, 8
psrad m0, 8
packssdw m0, m3
punpckhwd m3, m1, m2
punpcklwd m1, m2
pmaddwd m3, m4
pmaddwd m1, m4
paddd m3, m5
paddd m1, m5
psrad m3, 8
psrad m1, 8
packssdw m1, m3
pminsw m0, m6
pminsw m1, m6
pmaxsw m0, m7
pmaxsw m1, m7
ret
%if ARCH_X86_64
cglobal mask_16bpc, 4, 7, 9, dst, stride, tmp1, tmp2, w, h, mask
%else
cglobal mask_16bpc, 4, 7, 8, dst, stride, tmp1, tmp2, w, mask
%define hd dword r5m
%define m8 [base+pw_64]
%endif
%define base r6-mask_ssse3_table
LEA r6, mask_ssse3_table
tzcnt wd, wm
mov t0d, r7m ; pixel_max
shr t0d, 11
movsxd wq, [r6+wq*4]
movddup m6, [base+bidir_rnd+t0*8]
movddup m7, [base+bidir_mul+t0*8]
%if ARCH_X86_64
mova m8, [base+pw_64]
movifnidn hd, hm
%endif
add wq, r6
mov maskq, r6mp
BIDIR_FN
ALIGN function_align
.main:
movq m3, [maskq+8*0]
mova m0, [tmp1q+16*0]
mova m4, [tmp2q+16*0]
pxor m5, m5
punpcklbw m3, m5
punpckhwd m2, m0, m4
punpcklwd m0, m4
psubw m1, m8, m3
punpckhwd m4, m3, m1 ; m, 64-m
punpcklwd m3, m1
pmaddwd m2, m4 ; tmp1 * m + tmp2 * (64-m)
pmaddwd m0, m3
movq m3, [maskq+8*1]
mova m1, [tmp1q+16*1]
mova m4, [tmp2q+16*1]
add maskq, 8*2
add tmp1q, 16*2
add tmp2q, 16*2
psrad m2, 5
psrad m0, 5
packssdw m0, m2
punpcklbw m3, m5
punpckhwd m2, m1, m4
punpcklwd m1, m4
psubw m5, m8, m3
punpckhwd m4, m3, m5 ; m, 64-m
punpcklwd m3, m5
pmaddwd m2, m4 ; tmp1 * m + tmp2 * (64-m)
pmaddwd m1, m3
psrad m2, 5
psrad m1, 5
packssdw m1, m2
pmaxsw m0, m6
pmaxsw m1, m6
psubsw m0, m6
psubsw m1, m6
pmulhw m0, m7
pmulhw m1, m7
ret
cglobal w_mask_420_16bpc, 4, 7, 12, dst, stride, tmp1, tmp2, w, h, mask
%define base t0-w_mask_420_ssse3_table
LEA t0, w_mask_420_ssse3_table
tzcnt wd, wm
mov r6d, r8m ; pixel_max
movd m0, r7m ; sign
shr r6d, 11
movsxd wq, [t0+wq*4]
%if ARCH_X86_64
mova m8, [base+pw_27615] ; ((64 - 38) << 10) + 1023 - 32
mova m9, [base+pw_64]
movddup m10, [base+bidir_rnd+r6*8]
movddup m11, [base+bidir_mul+r6*8]
%else
mova m1, [base+pw_27615] ; ((64 - 38) << 10) + 1023 - 32
mova m2, [base+pw_64]
movddup m3, [base+bidir_rnd+r6*8]
movddup m4, [base+bidir_mul+r6*8]
ALLOC_STACK -16*4
mova [rsp+16*0], m1
mova [rsp+16*1], m2
mova [rsp+16*2], m3
mova [rsp+16*3], m4
%define m8 [rsp+gprsize+16*0]
%define m9 [rsp+gprsize+16*1]
%define m10 [rsp+gprsize+16*2]
%define m11 [rsp+gprsize+16*3]
%endif
movd m7, [base+pw_2]
psubw m7, m0
pshufb m7, [base+pw_256]
add wq, t0
movifnidn hd, r5m
mov maskq, r6mp
call .main
jmp wq
.w4_loop:
call .main
lea dstq, [dstq+strideq*2]
add maskq, 4
.w4:
movq [dstq+strideq*0], m0
phaddw m2, m3
movhps [dstq+strideq*1], m0
phaddd m2, m2
lea dstq, [dstq+strideq*2]
paddw m2, m7
movq [dstq+strideq*0], m1
psrlw m2, 2
movhps [dstq+strideq*1], m1
packuswb m2, m2
movd [maskq], m2
sub hd, 4
jg .w4_loop
RET
.w8_loop:
call .main
lea dstq, [dstq+strideq*2]
add maskq, 4
.w8:
mova [dstq+strideq*0], m0
paddw m2, m3
phaddw m2, m2
mova [dstq+strideq*1], m1
paddw m2, m7
psrlw m2, 2
packuswb m2, m2
movd [maskq], m2
sub hd, 2
jg .w8_loop
RET
.w16_loop:
call .main
lea dstq, [dstq+strideq*2]
add maskq, 8
.w16:
mova [dstq+strideq*1+16*0], m2
mova [dstq+strideq*0+16*0], m0
mova [dstq+strideq*1+16*1], m3
mova [dstq+strideq*0+16*1], m1
call .main
paddw m2, [dstq+strideq*1+16*0]
paddw m3, [dstq+strideq*1+16*1]
mova [dstq+strideq*1+16*0], m0
phaddw m2, m3
mova [dstq+strideq*1+16*1], m1
paddw m2, m7
psrlw m2, 2
packuswb m2, m2
movq [maskq], m2
sub hd, 2
jg .w16_loop
RET
.w32_loop:
call .main
lea dstq, [dstq+strideq*2]
add maskq, 16
.w32:
mova [dstq+strideq*1+16*0], m2
mova [dstq+strideq*0+16*0], m0
mova [dstq+strideq*1+16*1], m3
mova [dstq+strideq*0+16*1], m1
call .main
mova [dstq+strideq*0+16*2], m0
phaddw m2, m3
mova [dstq+strideq*1+16*3], m2
mova [dstq+strideq*0+16*3], m1
call .main
paddw m2, [dstq+strideq*1+16*0]
paddw m3, [dstq+strideq*1+16*1]
mova [dstq+strideq*1+16*0], m0
phaddw m2, m3
mova [dstq+strideq*1+16*2], m2
mova [dstq+strideq*1+16*1], m1
call .main
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16*2]
paddw m2, [dstq+strideq*1+16*3]
mova [dstq+strideq*1+16*2], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16*3], m1
packuswb m3, m2
mova [maskq], m3
sub hd, 2
jg .w32_loop
RET
.w64_loop:
call .main
lea dstq, [dstq+strideq*2]
add maskq, 16*2
.w64:
mova [dstq+strideq*1+16*1], m2
mova [dstq+strideq*0+16*0], m0
mova [dstq+strideq*1+16*2], m3
mova [dstq+strideq*0+16*1], m1
call .main
mova [dstq+strideq*1+16*3], m2
mova [dstq+strideq*0+16*2], m0
mova [dstq+strideq*1+16*4], m3
mova [dstq+strideq*0+16*3], m1
call .main
mova [dstq+strideq*1+16*5], m2
mova [dstq+strideq*0+16*4], m0
mova [dstq+strideq*1+16*6], m3
mova [dstq+strideq*0+16*5], m1
call .main
mova [dstq+strideq*0+16*6], m0
phaddw m2, m3
mova [dstq+strideq*1+16*7], m2
mova [dstq+strideq*0+16*7], m1
call .main
paddw m2, [dstq+strideq*1+16*1]
paddw m3, [dstq+strideq*1+16*2]
mova [dstq+strideq*1+16*0], m0
phaddw m2, m3
mova [dstq+strideq*1+16*2], m2
mova [dstq+strideq*1+16*1], m1
call .main
paddw m2, [dstq+strideq*1+16*3]
paddw m3, [dstq+strideq*1+16*4]
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16*2]
mova [dstq+strideq*1+16*2], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16*3], m1
packuswb m3, m2
mova [maskq+16*0], m3
call .main
paddw m2, [dstq+strideq*1+16*5]
paddw m3, [dstq+strideq*1+16*6]
mova [dstq+strideq*1+16*4], m0
phaddw m2, m3
mova [dstq+strideq*1+16*6], m2
mova [dstq+strideq*1+16*5], m1
call .main
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16*6]
paddw m2, [dstq+strideq*1+16*7]
mova [dstq+strideq*1+16*6], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16*7], m1
packuswb m3, m2
mova [maskq+16*1], m3
sub hd, 2
jg .w64_loop
RET
.w128_loop:
call .main
lea dstq, [dstq+strideq*2]
add maskq, 16*4
.w128:
mova [dstq+strideq*1+16* 1], m2
mova [dstq+strideq*0+16* 0], m0
mova [dstq+strideq*1+16* 2], m3
mova [dstq+strideq*0+16* 1], m1
call .main
mova [dstq+strideq*1+16* 3], m2
mova [dstq+strideq*0+16* 2], m0
mova [dstq+strideq*1+16* 4], m3
mova [dstq+strideq*0+16* 3], m1
call .main
mova [dstq+strideq*1+16* 5], m2
mova [dstq+strideq*0+16* 4], m0
mova [dstq+strideq*1+16* 6], m3
mova [dstq+strideq*0+16* 5], m1
call .main
mova [dstq+strideq*1+16* 7], m2
mova [dstq+strideq*0+16* 6], m0
mova [dstq+strideq*1+16* 8], m3
mova [dstq+strideq*0+16* 7], m1
call .main
mova [dstq+strideq*1+16* 9], m2
mova [dstq+strideq*0+16* 8], m0
mova [dstq+strideq*1+16*10], m3
mova [dstq+strideq*0+16* 9], m1
call .main
mova [dstq+strideq*1+16*11], m2
mova [dstq+strideq*0+16*10], m0
mova [dstq+strideq*1+16*12], m3
mova [dstq+strideq*0+16*11], m1
call .main
mova [dstq+strideq*1+16*13], m2
mova [dstq+strideq*0+16*12], m0
mova [dstq+strideq*1+16*14], m3
mova [dstq+strideq*0+16*13], m1
call .main
mova [dstq+strideq*0+16*14], m0
phaddw m2, m3
mova [dstq+strideq*1+16*15], m2
mova [dstq+strideq*0+16*15], m1
call .main
paddw m2, [dstq+strideq*1+16* 1]
paddw m3, [dstq+strideq*1+16* 2]
mova [dstq+strideq*1+16* 0], m0
phaddw m2, m3
mova [dstq+strideq*1+16* 2], m2
mova [dstq+strideq*1+16* 1], m1
call .main
paddw m2, [dstq+strideq*1+16* 3]
paddw m3, [dstq+strideq*1+16* 4]
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16* 2]
mova [dstq+strideq*1+16* 2], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16* 3], m1
packuswb m3, m2
mova [maskq+16*0], m3
call .main
paddw m2, [dstq+strideq*1+16* 5]
paddw m3, [dstq+strideq*1+16* 6]
mova [dstq+strideq*1+16* 4], m0
phaddw m2, m3
mova [dstq+strideq*1+16* 6], m2
mova [dstq+strideq*1+16* 5], m1
call .main
paddw m2, [dstq+strideq*1+16* 7]
paddw m3, [dstq+strideq*1+16* 8]
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16* 6]
mova [dstq+strideq*1+16* 6], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16* 7], m1
packuswb m3, m2
mova [maskq+16*1], m3
call .main
paddw m2, [dstq+strideq*1+16* 9]
paddw m3, [dstq+strideq*1+16*10]
mova [dstq+strideq*1+16* 8], m0
phaddw m2, m3
mova [dstq+strideq*1+16*10], m2
mova [dstq+strideq*1+16* 9], m1
call .main
paddw m2, [dstq+strideq*1+16*11]
paddw m3, [dstq+strideq*1+16*12]
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16*10]
mova [dstq+strideq*1+16*10], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16*11], m1
packuswb m3, m2
mova [maskq+16*2], m3
call .main
paddw m2, [dstq+strideq*1+16*13]
paddw m3, [dstq+strideq*1+16*14]
mova [dstq+strideq*1+16*12], m0
phaddw m2, m3
mova [dstq+strideq*1+16*14], m2
mova [dstq+strideq*1+16*13], m1
call .main
phaddw m2, m3
paddw m3, m7, [dstq+strideq*1+16*14]
paddw m2, [dstq+strideq*1+16*15]
mova [dstq+strideq*1+16*14], m0
paddw m2, m7
psrlw m3, 2
psrlw m2, 2
mova [dstq+strideq*1+16*15], m1
packuswb m3, m2
mova [maskq+16*3], m3
sub hd, 2
jg .w128_loop
RET
ALIGN function_align
.main:
%macro W_MASK 2 ; dst/tmp_offset, mask
mova m%1, [tmp1q+16*%1]
mova m%2, [tmp2q+16*%1]
punpcklwd m4, m%2, m%1
punpckhwd m5, m%2, m%1
psubsw m%1, m%2
pabsw m%1, m%1
psubusw m6, m8, m%1
psrlw m6, 10 ; 64-m
psubw m%2, m9, m6 ; m
punpcklwd m%1, m6, m%2
punpckhwd m6, m%2
pmaddwd m%1, m4
pmaddwd m6, m5
psrad m%1, 5
psrad m6, 5
packssdw m%1, m6
pmaxsw m%1, m10
psubsw m%1, m10
pmulhw m%1, m11
%endmacro
W_MASK 0, 2
W_MASK 1, 3
add tmp1q, 16*2
add tmp2q, 16*2
ret
cglobal w_mask_422_16bpc, 4, 7, 12, dst, stride, tmp1, tmp2, w, h, mask
%define base t0-w_mask_422_ssse3_table
LEA t0, w_mask_422_ssse3_table
tzcnt wd, wm
mov r6d, r8m ; pixel_max
movd m7, r7m ; sign
shr r6d, 11
movsxd wq, [t0+wq*4]
%if ARCH_X86_64
mova m8, [base+pw_27615]
mova m9, [base+pw_64]
movddup m10, [base+bidir_rnd+r6*8]
movddup m11, [base+bidir_mul+r6*8]
%else
mova m1, [base+pw_27615]
mova m2, [base+pw_64]
movddup m3, [base+bidir_rnd+r6*8]
movddup m4, [base+bidir_mul+r6*8]
ALLOC_STACK -16*4
mova [rsp+16*0], m1
mova [rsp+16*1], m2
mova [rsp+16*2], m3
mova [rsp+16*3], m4
%endif
pxor m0, m0
add wq, t0
pshufb m7, m0
movifnidn hd, r5m
mov maskq, r6mp
call .main
jmp wq
.w4_loop:
call .main
lea dstq, [dstq+strideq*2]
.w4:
movq [dstq+strideq*0], m0
movhps [dstq+strideq*1], m0
lea dstq, [dstq+strideq*2]
movq [dstq+strideq*0], m1
movhps [dstq+strideq*1], m1
sub hd, 4
jg .w4_loop
.end:
RET
.w8_loop:
call .main
lea dstq, [dstq+strideq*2]
.w8:
mova [dstq+strideq*0], m0
mova [dstq+strideq*1], m1
sub hd, 2
jg .w8_loop
.w8_end:
RET
.w16_loop:
call .main
lea dstq, [dstq+strideq*2]
.w16:
mova [dstq+strideq*0+16*0], m0
mova [dstq+strideq*0+16*1], m1
call .main
mova [dstq+strideq*1+16*0], m0
mova [dstq+strideq*1+16*1], m1
sub hd, 2
jg .w16_loop
RET
.w32_loop:
call .main
add dstq, strideq
.w32:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
call .main
mova [dstq+16*2], m0
mova [dstq+16*3], m1
dec hd
jg .w32_loop
RET
.w64_loop:
call .main
add dstq, strideq
.w64:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
call .main
mova [dstq+16*2], m0
mova [dstq+16*3], m1
call .main
mova [dstq+16*4], m0
mova [dstq+16*5], m1
call .main
mova [dstq+16*6], m0
mova [dstq+16*7], m1
dec hd
jg .w64_loop
RET
.w128_loop:
call .main
add dstq, strideq
.w128:
mova [dstq+16* 0], m0
mova [dstq+16* 1], m1
call .main
mova [dstq+16* 2], m0
mova [dstq+16* 3], m1
call .main
mova [dstq+16* 4], m0
mova [dstq+16* 5], m1
call .main
mova [dstq+16* 6], m0
mova [dstq+16* 7], m1
call .main
mova [dstq+16* 8], m0
mova [dstq+16* 9], m1
call .main
mova [dstq+16*10], m0
mova [dstq+16*11], m1
call .main
mova [dstq+16*12], m0
mova [dstq+16*13], m1
call .main
mova [dstq+16*14], m0
mova [dstq+16*15], m1
dec hd
jg .w128_loop
RET
ALIGN function_align
.main:
W_MASK 0, 2
W_MASK 1, 3
phaddw m2, m3
add tmp1q, 16*2
add tmp2q, 16*2
packuswb m2, m2
pxor m3, m3
psubb m2, m7
pavgb m2, m3
movq [maskq], m2
add maskq, 8
ret
cglobal w_mask_444_16bpc, 4, 7, 12, dst, stride, tmp1, tmp2, w, h, mask
%define base t0-w_mask_444_ssse3_table
LEA t0, w_mask_444_ssse3_table
tzcnt wd, wm
mov r6d, r8m ; pixel_max
shr r6d, 11
movsxd wq, [t0+wq*4]
%if ARCH_X86_64
mova m8, [base+pw_27615]
mova m9, [base+pw_64]
movddup m10, [base+bidir_rnd+r6*8]
movddup m11, [base+bidir_mul+r6*8]
%else
mova m1, [base+pw_27615]
mova m2, [base+pw_64]
movddup m3, [base+bidir_rnd+r6*8]
movddup m7, [base+bidir_mul+r6*8]
ALLOC_STACK -16*3
mova [rsp+16*0], m1
mova [rsp+16*1], m2
mova [rsp+16*2], m3
%define m11 m7
%endif
add wq, t0
movifnidn hd, r5m
mov maskq, r6mp
call .main
jmp wq
.w4_loop:
call .main
lea dstq, [dstq+strideq*2]
.w4:
movq [dstq+strideq*0], m0
movhps [dstq+strideq*1], m0
lea dstq, [dstq+strideq*2]
movq [dstq+strideq*0], m1
movhps [dstq+strideq*1], m1
sub hd, 4
jg .w4_loop
.end:
RET
.w8_loop:
call .main
lea dstq, [dstq+strideq*2]
.w8:
mova [dstq+strideq*0], m0
mova [dstq+strideq*1], m1
sub hd, 2
jg .w8_loop
.w8_end:
RET
.w16_loop:
call .main
lea dstq, [dstq+strideq*2]
.w16:
mova [dstq+strideq*0+16*0], m0
mova [dstq+strideq*0+16*1], m1
call .main
mova [dstq+strideq*1+16*0], m0
mova [dstq+strideq*1+16*1], m1
sub hd, 2
jg .w16_loop
RET
.w32_loop:
call .main
add dstq, strideq
.w32:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
call .main
mova [dstq+16*2], m0
mova [dstq+16*3], m1
dec hd
jg .w32_loop
RET
.w64_loop:
call .main
add dstq, strideq
.w64:
mova [dstq+16*0], m0
mova [dstq+16*1], m1
call .main
mova [dstq+16*2], m0
mova [dstq+16*3], m1
call .main
mova [dstq+16*4], m0
mova [dstq+16*5], m1
call .main
mova [dstq+16*6], m0
mova [dstq+16*7], m1
dec hd
jg .w64_loop
RET
.w128_loop:
call .main
add dstq, strideq
.w128:
mova [dstq+16* 0], m0
mova [dstq+16* 1], m1
call .main
mova [dstq+16* 2], m0
mova [dstq+16* 3], m1
call .main
mova [dstq+16* 4], m0
mova [dstq+16* 5], m1
call .main
mova [dstq+16* 6], m0
mova [dstq+16* 7], m1
call .main
mova [dstq+16* 8], m0
mova [dstq+16* 9], m1
call .main
mova [dstq+16*10], m0
mova [dstq+16*11], m1
call .main
mova [dstq+16*12], m0
mova [dstq+16*13], m1
call .main
mova [dstq+16*14], m0
mova [dstq+16*15], m1
dec hd
jg .w128_loop
RET
ALIGN function_align
.main:
W_MASK 0, 2
W_MASK 1, 3
packuswb m2, m3
add tmp1q, 16*2
add tmp2q, 16*2
mova [maskq], m2
add maskq, 16
ret
; (a * (64 - m) + b * m + 32) >> 6
; = (((b - a) * m + 32) >> 6) + a
; = (((b - a) * (m << 9) + 16384) >> 15) + a
; except m << 9 overflows int16_t when m == 64 (which is possible),
; but if we negate m it works out (-64 << 9 == -32768).
; = (((a - b) * (m * -512) + 16384) >> 15) + a
cglobal blend_16bpc, 3, 7, 8, dst, stride, tmp, w, h, mask, stride3
%define base r6-blend_ssse3_table
LEA r6, blend_ssse3_table
tzcnt wd, wm
movifnidn hd, hm
movsxd wq, [r6+wq*4]
movifnidn maskq, maskmp
mova m7, [base+pw_m512]
add wq, r6
lea stride3q, [strideq*3]
pxor m6, m6
jmp wq
.w4:
mova m5, [maskq]
movq m0, [dstq+strideq*0]
movhps m0, [dstq+strideq*1]
movq m1, [dstq+strideq*2]
movhps m1, [dstq+stride3q ]
psubw m2, m0, [tmpq+16*0]
psubw m3, m1, [tmpq+16*1]
add maskq, 16
add tmpq, 32
punpcklbw m4, m5, m6
punpckhbw m5, m6
pmullw m4, m7
pmullw m5, m7
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
movq [dstq+strideq*0], m0
movhps [dstq+strideq*1], m0
movq [dstq+strideq*2], m1
movhps [dstq+stride3q ], m1
lea dstq, [dstq+strideq*4]
sub hd, 4
jg .w4
RET
.w8:
mova m5, [maskq]
mova m0, [dstq+strideq*0]
mova m1, [dstq+strideq*1]
psubw m2, m0, [tmpq+16*0]
psubw m3, m1, [tmpq+16*1]
add maskq, 16
add tmpq, 32
punpcklbw m4, m5, m6
punpckhbw m5, m6
pmullw m4, m7
pmullw m5, m7
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
mova [dstq+strideq*0], m0
mova [dstq+strideq*1], m1
lea dstq, [dstq+strideq*2]
sub hd, 2
jg .w8
RET
.w16:
mova m5, [maskq]
mova m0, [dstq+16*0]
mova m1, [dstq+16*1]
psubw m2, m0, [tmpq+16*0]
psubw m3, m1, [tmpq+16*1]
add maskq, 16
add tmpq, 32
punpcklbw m4, m5, m6
punpckhbw m5, m6
pmullw m4, m7
pmullw m5, m7
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
mova [dstq+16*0], m0
mova [dstq+16*1], m1
add dstq, strideq
dec hd
jg .w16
RET
.w32:
mova m5, [maskq+16*0]
mova m0, [dstq+16*0]
mova m1, [dstq+16*1]
psubw m2, m0, [tmpq+16*0]
psubw m3, m1, [tmpq+16*1]
punpcklbw m4, m5, m6
punpckhbw m5, m6
pmullw m4, m7
pmullw m5, m7
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
mova [dstq+16*0], m0
mova [dstq+16*1], m1
mova m5, [maskq+16*1]
mova m0, [dstq+16*2]
mova m1, [dstq+16*3]
psubw m2, m0, [tmpq+16*2]
psubw m3, m1, [tmpq+16*3]
add maskq, 32
add tmpq, 64
punpcklbw m4, m5, m6
punpckhbw m5, m6
pmullw m4, m7
pmullw m5, m7
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
mova [dstq+16*2], m0
mova [dstq+16*3], m1
add dstq, strideq
dec hd
jg .w32
RET
cglobal blend_v_16bpc, 3, 6, 6, dst, stride, tmp, w, h
%define base r5-blend_v_ssse3_table
LEA r5, blend_v_ssse3_table
tzcnt wd, wm
movifnidn hd, hm
movsxd wq, [r5+wq*4]
add wq, r5
jmp wq
.w2:
movd m4, [base+obmc_masks+2*2]
.w2_loop:
movd m0, [dstq+strideq*0]
movd m2, [tmpq+4*0]
movd m1, [dstq+strideq*1]
movd m3, [tmpq+4*1]
add tmpq, 4*2
psubw m2, m0
psubw m3, m1
pmulhrsw m2, m4
pmulhrsw m3, m4
paddw m0, m2
paddw m1, m3
movd [dstq+strideq*0], m0
movd [dstq+strideq*1], m1
lea dstq, [dstq+strideq*2]
sub hd, 2
jg .w2_loop
RET
.w4:
movddup m2, [base+obmc_masks+4*2]
.w4_loop:
movq m0, [dstq+strideq*0]
movhps m0, [dstq+strideq*1]
mova m1, [tmpq]
add tmpq, 8*2
psubw m1, m0
pmulhrsw m1, m2
paddw m0, m1
movq [dstq+strideq*0], m0
movhps [dstq+strideq*1], m0
lea dstq, [dstq+strideq*2]
sub hd, 2
jg .w4_loop
RET
.w8:
mova m4, [base+obmc_masks+8*2]
.w8_loop:
mova m0, [dstq+strideq*0]
mova m2, [tmpq+16*0]
mova m1, [dstq+strideq*1]
mova m3, [tmpq+16*1]
add tmpq, 16*2
psubw m2, m0
psubw m3, m1
pmulhrsw m2, m4
pmulhrsw m3, m4
paddw m0, m2
paddw m1, m3
mova [dstq+strideq*0], m0
mova [dstq+strideq*1], m1
lea dstq, [dstq+strideq*2]
sub hd, 2
jg .w8_loop
RET
.w16:
mova m4, [base+obmc_masks+16*2]
movq m5, [base+obmc_masks+16*3]
.w16_loop:
mova m0, [dstq+16*0]
mova m2, [tmpq+16*0]
mova m1, [dstq+16*1]
mova m3, [tmpq+16*1]
add tmpq, 16*2
psubw m2, m0
psubw m3, m1
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
mova [dstq+16*0], m0
mova [dstq+16*1], m1
add dstq, strideq
dec hd
jg .w16_loop
RET
.w32:
%if WIN64
movaps [rsp+8], m6
%endif
mova m4, [base+obmc_masks+16*4]
mova m5, [base+obmc_masks+16*5]
mova m6, [base+obmc_masks+16*6]
.w32_loop:
mova m0, [dstq+16*0]
mova m2, [tmpq+16*0]
mova m1, [dstq+16*1]
mova m3, [tmpq+16*1]
psubw m2, m0
psubw m3, m1
pmulhrsw m2, m4
pmulhrsw m3, m5
paddw m0, m2
mova m2, [dstq+16*2]
paddw m1, m3
mova m3, [tmpq+16*2]
add tmpq, 16*4
psubw m3, m2
pmulhrsw m3, m6
paddw m2, m3
mova [dstq+16*0], m0
mova [dstq+16*1], m1
mova [dstq+16*2], m2
add dstq, strideq
dec hd
jg .w32_loop
%if WIN64
movaps m6, [rsp+8]
%endif
RET
%macro BLEND_H_ROW 2-3 0; dst_off, tmp_off, inc_tmp
mova m0, [dstq+16*(%1+0)]
mova m2, [tmpq+16*(%2+0)]
mova m1, [dstq+16*(%1+1)]
mova m3, [tmpq+16*(%2+1)]
%if %3
add tmpq, 16*%3
%endif
psubw m2, m0
psubw m3, m1
pmulhrsw m2, m5
pmulhrsw m3, m5
paddw m0, m2
paddw m1, m3
mova [dstq+16*(%1+0)], m0
mova [dstq+16*(%1+1)], m1
%endmacro
cglobal blend_h_16bpc, 3, 7, 6, dst, ds, tmp, w, h, mask
%define base r6-blend_h_ssse3_table
LEA r6, blend_h_ssse3_table
tzcnt wd, wm
mov hd, hm
movsxd wq, [r6+wq*4]
movddup m4, [base+blend_shuf]
lea maskq, [base+obmc_masks+hq*2]
lea hd, [hq*3]
add wq, r6
shr hd, 2 ; h * 3/4
lea maskq, [maskq+hq*2]
neg hq
jmp wq
.w2:
movd m0, [dstq+dsq*0]
movd m2, [dstq+dsq*1]
movd m3, [maskq+hq*2]
movq m1, [tmpq]
add tmpq, 4*2
punpckldq m0, m2
punpcklwd m3, m3
psubw m1, m0
pmulhrsw m1, m3
paddw m0, m1
movd [dstq+dsq*0], m0
psrlq m0, 32
movd [dstq+dsq*1], m0
lea dstq, [dstq+dsq*2]
add hq, 2
jl .w2
RET
.w4:
mova m3, [base+blend_shuf]
.w4_loop:
movq m0, [dstq+dsq*0]
movhps m0, [dstq+dsq*1]
movd m2, [maskq+hq*2]
mova m1, [tmpq]
add tmpq, 8*2
psubw m1, m0
pshufb m2, m3
pmulhrsw m1, m2
paddw m0, m1
movq [dstq+dsq*0], m0
movhps [dstq+dsq*1], m0
lea dstq, [dstq+dsq*2]
add hq, 2
jl .w4_loop
RET
.w8:
movddup m5, [base+blend_shuf+8]
%if WIN64
movaps [rsp+ 8], m6
movaps [rsp+24], m7
%endif
.w8_loop:
movd m7, [maskq+hq*2]
mova m0, [dstq+dsq*0]
mova m2, [tmpq+16*0]
mova m1, [dstq+dsq*1]
mova m3, [tmpq+16*1]
add tmpq, 16*2
pshufb m6, m7, m4
psubw m2, m0
pshufb m7, m5
psubw m3, m1
pmulhrsw m2, m6
pmulhrsw m3, m7
paddw m0, m2
paddw m1, m3
mova [dstq+dsq*0], m0
mova [dstq+dsq*1], m1
lea dstq, [dstq+dsq*2]
add hq, 2
jl .w8_loop
%if WIN64
movaps m6, [rsp+ 8]
movaps m7, [rsp+24]
%endif
RET
.w16:
movd m5, [maskq+hq*2]
pshufb m5, m4
BLEND_H_ROW 0, 0, 2
add dstq, dsq
inc hq
jl .w16
RET
.w32:
movd m5, [maskq+hq*2]
pshufb m5, m4
BLEND_H_ROW 0, 0
BLEND_H_ROW 2, 2, 4
add dstq, dsq
inc hq
jl .w32
RET
.w64:
movd m5, [maskq+hq*2]
pshufb m5, m4
BLEND_H_ROW 0, 0
BLEND_H_ROW 2, 2
BLEND_H_ROW 4, 4
BLEND_H_ROW 6, 6, 8
add dstq, dsq
inc hq
jl .w64
RET
.w128:
movd m5, [maskq+hq*2]
pshufb m5, m4
BLEND_H_ROW 0, 0
BLEND_H_ROW 2, 2
BLEND_H_ROW 4, 4
BLEND_H_ROW 6, 6, 16
BLEND_H_ROW 8, -8
BLEND_H_ROW 10, -6
BLEND_H_ROW 12, -4
BLEND_H_ROW 14, -2
add dstq, dsq
inc hq
jl .w128
RET
; emu_edge args:
; const intptr_t bw, const intptr_t bh, const intptr_t iw, const intptr_t ih,
; const intptr_t x, const intptr_t y, pixel *dst, const ptrdiff_t dst_stride,
; const pixel *ref, const ptrdiff_t ref_stride
;
; bw, bh total filled size
; iw, ih, copied block -> fill bottom, right
; x, y, offset in bw/bh -> fill top, left
cglobal emu_edge_16bpc, 10, 13, 1, bw, bh, iw, ih, x, \
y, dst, dstride, src, sstride, \
bottomext, rightext, blk
; we assume that the buffer (stride) is larger than width, so we can
; safely overwrite by a few bytes
%if ARCH_X86_64
%define reg_zero r12q
%define reg_tmp r10
%define reg_src srcq
%define reg_bottomext bottomextq
%define reg_rightext rightextq
%define reg_blkm r9m
%else
%define reg_zero r6
%define reg_tmp r0
%define reg_src r1
%define reg_bottomext r0
%define reg_rightext r1
%define reg_blkm r2m
%endif
;
; ref += iclip(y, 0, ih - 1) * PXSTRIDE(ref_stride)
xor reg_zero, reg_zero
lea reg_tmp, [ihq-1]
cmp yq, ihq
cmovs reg_tmp, yq
test yq, yq
cmovs reg_tmp, reg_zero
%if ARCH_X86_64
imul reg_tmp, sstrideq
add srcq, reg_tmp
%else
imul reg_tmp, sstridem
mov reg_src, srcm
add reg_src, reg_tmp
%endif
;
; ref += iclip(x, 0, iw - 1)
lea reg_tmp, [iwq-1]
cmp xq, iwq
cmovs reg_tmp, xq
test xq, xq
cmovs reg_tmp, reg_zero
lea reg_src, [reg_src+reg_tmp*2]
%if ARCH_X86_32
mov srcm, reg_src
%endif
;
; bottom_ext = iclip(y + bh - ih, 0, bh - 1)
%if ARCH_X86_32
mov r1, r1m ; restore bh
%endif
lea reg_bottomext, [yq+bhq]
sub reg_bottomext, ihq
lea r3, [bhq-1]
cmovs reg_bottomext, reg_zero
;
DEFINE_ARGS bw, bh, iw, ih, x, \
topext, dst, dstride, src, sstride, \
bottomext, rightext, blk
; top_ext = iclip(-y, 0, bh - 1)
neg topextq
cmovs topextq, reg_zero
cmp reg_bottomext, bhq
cmovns reg_bottomext, r3
cmp topextq, bhq
cmovg topextq, r3
%if ARCH_X86_32
mov r4m, reg_bottomext
;
; right_ext = iclip(x + bw - iw, 0, bw - 1)
mov r0, r0m ; restore bw
%endif
lea reg_rightext, [xq+bwq]
sub reg_rightext, iwq
lea r2, [bwq-1]
cmovs reg_rightext, reg_zero
DEFINE_ARGS bw, bh, iw, ih, leftext, \
topext, dst, dstride, src, sstride, \
bottomext, rightext, blk
; left_ext = iclip(-x, 0, bw - 1)
neg leftextq
cmovs leftextq, reg_zero
cmp reg_rightext, bwq
cmovns reg_rightext, r2
%if ARCH_X86_32
mov r3m, r1
%endif
cmp leftextq, bwq
cmovns leftextq, r2
%undef reg_zero
%undef reg_tmp
%undef reg_src
%undef reg_bottomext
%undef reg_rightext
DEFINE_ARGS bw, centerh, centerw, dummy, leftext, \
topext, dst, dstride, src, sstride, \
bottomext, rightext, blk
; center_h = bh - top_ext - bottom_ext
%if ARCH_X86_64
lea r3, [bottomextq+topextq]
sub centerhq, r3
%else
mov r1, centerhm ; restore r1
sub centerhq, topextq
sub centerhq, r4m
mov r1m, centerhq
%endif
;
; blk += top_ext * PXSTRIDE(dst_stride)
mov r2, topextq
%if ARCH_X86_64
imul r2, dstrideq
%else
mov r6, r6m ; restore dstq
imul r2, dstridem
%endif
add dstq, r2
mov reg_blkm, dstq ; save pointer for ext
;
; center_w = bw - left_ext - right_ext
mov centerwq, bwq
%if ARCH_X86_64
lea r3, [rightextq+leftextq]
sub centerwq, r3
%else
sub centerwq, r3m
sub centerwq, leftextq
%endif
; vloop Macro
%macro v_loop 3 ; need_left_ext, need_right_ext, suffix
%if ARCH_X86_64
%define reg_tmp r12
%else
%define reg_tmp r0
%endif
.v_loop_%3:
%if ARCH_X86_32
mov r0, r0m
mov r1, r1m
%endif
%if %1
; left extension
%if ARCH_X86_64
movd m0, [srcq]
%else
mov r3, srcm
movd m0, [r3]
%endif
pshuflw m0, m0, q0000
punpcklqdq m0, m0
xor r3, r3
.left_loop_%3:
mova [dstq+r3*2], m0
add r3, mmsize/2
cmp r3, leftextq
jl .left_loop_%3
; body
lea reg_tmp, [dstq+leftextq*2]
%endif
xor r3, r3
.body_loop_%3:
%if ARCH_X86_64
movu m0, [srcq+r3*2]
%else
mov r1, srcm
movu m0, [r1+r3*2]
%endif
%if %1
movu [reg_tmp+r3*2], m0
%else
movu [dstq+r3*2], m0
%endif
add r3, mmsize/2
cmp r3, centerwq
jl .body_loop_%3
%if %2
; right extension
%if %1
lea reg_tmp, [reg_tmp+centerwq*2]
%else
lea reg_tmp, [dstq+centerwq*2]
%endif
%if ARCH_X86_64
movd m0, [srcq+centerwq*2-2]
%else
mov r3, srcm
movd m0, [r3+centerwq*2-2]
%endif
pshuflw m0, m0, q0000
punpcklqdq m0, m0
xor r3, r3
.right_loop_%3:
movu [reg_tmp+r3*2], m0
add r3, mmsize/2
%if ARCH_X86_64
cmp r3, rightextq
%else
cmp r3, r3m
%endif
jl .right_loop_%3
%endif
%if ARCH_X86_64
add dstq, dstrideq
add srcq, sstrideq
dec centerhq
jg .v_loop_%3
%else
add dstq, dstridem
mov r0, sstridem
add srcm, r0
sub dword centerhm, 1
jg .v_loop_%3
mov r0, r0m ; restore r0
%endif
%endmacro ; vloop MACRO
test leftextq, leftextq
jnz .need_left_ext
%if ARCH_X86_64
test rightextq, rightextq
jnz .need_right_ext
%else
cmp leftextq, r3m ; leftextq == 0
jne .need_right_ext
%endif
v_loop 0, 0, 0
jmp .body_done
;left right extensions
.need_left_ext:
%if ARCH_X86_64
test rightextq, rightextq
%else
mov r3, r3m
test r3, r3
%endif
jnz .need_left_right_ext
v_loop 1, 0, 1
jmp .body_done
.need_left_right_ext:
v_loop 1, 1, 2
jmp .body_done
.need_right_ext:
v_loop 0, 1, 3
.body_done:
; r0 ; bw
; r1 ;; x loop
; r4 ;; y loop
; r5 ; topextq
; r6 ;dstq
; r7 ;dstrideq
; r8 ; srcq
%if ARCH_X86_64
%define reg_dstride dstrideq
%else
%define reg_dstride r2
%endif
;
; bottom edge extension
%if ARCH_X86_64
test bottomextq, bottomextq
jz .top
%else
xor r1, r1
cmp r1, r4m
je .top
%endif
;
%if ARCH_X86_64
mov srcq, dstq
sub srcq, dstrideq
xor r1, r1
%else
mov r3, dstq
mov reg_dstride, dstridem
sub r3, reg_dstride
mov srcm, r3
%endif
;
.bottom_x_loop:
%if ARCH_X86_64
mova m0, [srcq+r1*2]
lea r3, [dstq+r1*2]
mov r4, bottomextq
%else
mov r3, srcm
mova m0, [r3+r1*2]
lea r3, [dstq+r1*2]
mov r4, r4m
%endif
;
.bottom_y_loop:
mova [r3], m0
add r3, reg_dstride
dec r4
jg .bottom_y_loop
add r1, mmsize/2
cmp r1, bwq
jl .bottom_x_loop
.top:
; top edge extension
test topextq, topextq
jz .end
%if ARCH_X86_64
mov srcq, reg_blkm
%else
mov r3, reg_blkm
mov reg_dstride, dstridem
%endif
mov dstq, dstm
xor r1, r1
;
.top_x_loop:
%if ARCH_X86_64
mova m0, [srcq+r1*2]
%else
mov r3, reg_blkm
mova m0, [r3+r1*2]
%endif
lea r3, [dstq+r1*2]
mov r4, topextq
;
.top_y_loop:
mova [r3], m0
add r3, reg_dstride
dec r4
jg .top_y_loop
add r1, mmsize/2
cmp r1, bwq
jl .top_x_loop
.end:
RET
%undef reg_dstride
%undef reg_blkm
%undef reg_tmp
%macro SCRATCH 3
%if ARCH_X86_32
mova [rsp+%3*mmsize], m%1
%define m%2 [rsp+%3*mmsize]
%else
SWAP %1, %2
%endif
%endmacro
%if ARCH_X86_64
cglobal resize_16bpc, 0, 12, 16, 1*16, dst, dst_stride, src, src_stride, \
dst_w, h, src_w, dx, mx0, pxmax
%elif STACK_ALIGNMENT >= 16
cglobal resize_16bpc, 0, 7, 8, 6*16, dst, dst_stride, src, src_stride, \
dst_w, h, src_w, dx, mx0, pxmax
%else
cglobal resize_16bpc, 0, 6, 8, 6*16, dst, dst_stride, src, src_stride, \
dst_w, h, src_w, dx, mx0, pxmax
%endif
movifnidn dstq, dstmp
movifnidn srcq, srcmp
%if STACK_ALIGNMENT >= 16
movifnidn dst_wd, dst_wm
%endif
%if ARCH_X86_64
movifnidn hd, hm
%endif
sub dword mx0m, 4<<14
sub dword src_wm, 8
movd m4, pxmaxm
movd m7, dxm
movd m6, mx0m
movd m5, src_wm
punpcklwd m4, m4
pshufd m4, m4, q0000
pshufd m7, m7, q0000
pshufd m6, m6, q0000
pshufd m5, m5, q0000
mova [rsp+16*3*ARCH_X86_32], m4
%if ARCH_X86_64
DEFINE_ARGS dst, dst_stride, src, src_stride, dst_w, h, x
LEA r7, $$
%define base r7-$$
%else
DEFINE_ARGS dst, dst_stride, src, src_stride, dst_w, x
%define hd dword r5m
%if STACK_ALIGNMENT >= 16
LEA r6, $$
%define base r6-$$
%else
LEA r4, $$
%define base r4-$$
%endif
%endif
%if ARCH_X86_64
mova m12, [base+pd_64]
mova m11, [base+pd_63]
%else
%define m12 [base+pd_64]
%define m11 [base+pd_63]
%endif
pmaddwd m4, m7, [base+rescale_mul] ; dx*[0,1,2,3]
pslld m7, 2 ; dx*4
pslld m5, 14
paddd m6, m4 ; mx+[0..3]*dx
SCRATCH 7, 15, 0
SCRATCH 6, 14, 1
SCRATCH 5, 13, 2
pxor m1, m1
.loop_y:
xor xd, xd
mova m0, m14 ; per-line working version of mx
.loop_x:
pcmpgtd m1, m0
pandn m1, m0
psrad m2, m0, 8 ; filter offset (unmasked)
pcmpgtd m3, m13, m1
pand m1, m3
pandn m3, m13
por m1, m3
psubd m3, m0, m1 ; pshufb offset
psrad m1, 14 ; clipped src_x offset
psrad m3, 14 ; pshufb edge_emu offset
pand m2, m11 ; filter offset (masked)
; load source pixels
%if ARCH_X86_64
movd r8d, m1
pshuflw m1, m1, q3232
movd r9d, m1
punpckhqdq m1, m1
movd r10d, m1
psrlq m1, 32
movd r11d, m1
movu m4, [srcq+r8*2]
movu m5, [srcq+r9*2]
movu m6, [srcq+r10*2]
movu m7, [srcq+r11*2]
; if no emulation is required, we don't need to shuffle or emulate edges
packssdw m3, m3
movq r11, m3
test r11, r11
jz .filter
movsx r8, r11w
sar r11, 16
movsx r9, r11w
sar r11, 16
movsx r10, r11w
sar r11, 16
movu m1, [base+resize_shuf+8+r8*2]
movu m3, [base+resize_shuf+8+r9*2]
movu m8, [base+resize_shuf+8+r10*2]
movu m9, [base+resize_shuf+8+r11*2]
pshufb m4, m1
pshufb m5, m3
pshufb m6, m8
pshufb m7, m9
.filter:
movd r8d, m2
pshuflw m2, m2, q3232
movd r9d, m2
punpckhqdq m2, m2
movd r10d, m2
psrlq m2, 32
movd r11d, m2
movq m8, [base+resize_filter+r8*8]
movq m2, [base+resize_filter+r9*8]
pxor m9, m9
punpcklbw m1, m9, m8
punpcklbw m3, m9, m2
psraw m1, 8
psraw m3, 8
movq m10, [base+resize_filter+r10*8]
movq m2, [base+resize_filter+r11*8]
punpcklbw m8, m9, m10
punpcklbw m9, m2
psraw m8, 8
psraw m9, 8
pmaddwd m4, m1
pmaddwd m5, m3
pmaddwd m6, m8
pmaddwd m7, m9
phaddd m4, m5
%else
movd r3, m1
pshuflw m1, m1, q3232
movd r1, m1
punpckhqdq m1, m1
movu m4, [srcq+r3*2]
movu m5, [srcq+r1*2]
movd r3, m1
psrlq m1, 32
movd r1, m1
movu m6, [srcq+r3*2]
movu m7, [srcq+r1*2]
; if no emulation is required, we don't need to shuffle or emulate edges
pxor m1, m1
pcmpeqb m1, m3
pmovmskb r3d, m1
cmp r3d, 0xffff
je .filter
movd r3, m3
movu m1, [base+resize_shuf+8+r3*2]
pshuflw m3, m3, q3232
movd r1, m3
pshufb m4, m1
movu m1, [base+resize_shuf+8+r1*2]
punpckhqdq m3, m3
movd r3, m3
pshufb m5, m1
movu m1, [base+resize_shuf+8+r3*2]
psrlq m3, 32
movd r1, m3
pshufb m6, m1
movu m1, [base+resize_shuf+8+r1*2]
pshufb m7, m1
.filter:
mova [esp+4*16], m6
mova [esp+5*16], m7
movd r3, m2
pshuflw m2, m2, q3232
movd r1, m2
movq m6, [base+resize_filter+r3*8]
movq m7, [base+resize_filter+r1*8]
pxor m3, m3
punpcklbw m1, m3, m6
punpcklbw m3, m7
psraw m1, 8
psraw m3, 8
pmaddwd m4, m1
pmaddwd m5, m3
punpckhqdq m2, m2
movd r3, m2
psrlq m2, 32
movd r1, m2
phaddd m4, m5
movq m2, [base+resize_filter+r3*8]
movq m5, [base+resize_filter+r1*8]
mova m6, [esp+4*16]
mova m7, [esp+5*16]
pxor m3, m3
punpcklbw m1, m3, m2
punpcklbw m3, m5
psraw m1, 8
psraw m3, 8
pmaddwd m6, m1
pmaddwd m7, m3
%endif
phaddd m6, m7
phaddd m4, m6
pxor m1, m1
psubd m2, m12, m4
psrad m2, 7
packssdw m2, m2
pmaxsw m2, m1
pminsw m2, [rsp+16*3*ARCH_X86_32]
movq [dstq+xq*2], m2
paddd m0, m15
add xd, 4
%if STACK_ALIGNMENT >= 16
cmp xd, dst_wd
%else
cmp xd, dst_wm
%endif
jl .loop_x
add dstq, dst_stridemp
add srcq, src_stridemp
dec hd
jg .loop_y
RET
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.