text stringlengths 1 1.05M |
|---|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "bindings/core/v8/V8DOMActivityLogger.h"
#include "bindings/core/v8/V8Binding.h"
#include "platform/weborigin/KURL.h"
#include "wtf/HashMap.h"
#include "wtf/text/StringHash.h"
#include <memory>
namespace blink {
typedef HashMap<String, std::unique_ptr<V8DOMActivityLogger>> DOMActivityLoggerMapForMainWorld;
typedef HashMap<int, std::unique_ptr<V8DOMActivityLogger>, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int>> DOMActivityLoggerMapForIsolatedWorld;
static DOMActivityLoggerMapForMainWorld& domActivityLoggersForMainWorld()
{
ASSERT(isMainThread());
DEFINE_STATIC_LOCAL(DOMActivityLoggerMapForMainWorld, map, ());
return map;
}
static DOMActivityLoggerMapForIsolatedWorld& domActivityLoggersForIsolatedWorld()
{
ASSERT(isMainThread());
DEFINE_STATIC_LOCAL(DOMActivityLoggerMapForIsolatedWorld, map, ());
return map;
}
void V8DOMActivityLogger::setActivityLogger(int worldId, const String& extensionId, std::unique_ptr<V8DOMActivityLogger> logger)
{
if (worldId)
domActivityLoggersForIsolatedWorld().set(worldId, std::move(logger));
else
domActivityLoggersForMainWorld().set(extensionId, std::move(logger));
}
V8DOMActivityLogger* V8DOMActivityLogger::activityLogger(int worldId, const String& extensionId)
{
if (worldId) {
DOMActivityLoggerMapForIsolatedWorld& loggers = domActivityLoggersForIsolatedWorld();
DOMActivityLoggerMapForIsolatedWorld::iterator it = loggers.find(worldId);
return it == loggers.end() ? 0 : it->value.get();
}
if (extensionId.isEmpty())
return 0;
DOMActivityLoggerMapForMainWorld& loggers = domActivityLoggersForMainWorld();
DOMActivityLoggerMapForMainWorld::iterator it = loggers.find(extensionId);
return it == loggers.end() ? 0 : it->value.get();
}
V8DOMActivityLogger* V8DOMActivityLogger::activityLogger(int worldId, const KURL& url)
{
// extension ID is ignored for worldId != 0.
if (worldId)
return activityLogger(worldId, String());
// To find an activity logger that corresponds to the main world of an
// extension, we need to obtain the extension ID. Extension ID is a hostname
// of a background page's URL.
if (!url.protocolIs("chrome-extension"))
return 0;
return activityLogger(worldId, url.host());
}
V8DOMActivityLogger* V8DOMActivityLogger::currentActivityLogger()
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
if (!isolate->InContext())
return 0;
v8::HandleScope handleScope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
if (context.IsEmpty() || !toDOMWindow(context))
return 0;
V8PerContextData* contextData = ScriptState::from(context)->perContextData();
if (!contextData)
return 0;
return contextData->activityLogger();
}
V8DOMActivityLogger* V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld()
{
v8::Isolate* isolate = v8::Isolate::GetCurrent();
if (!isolate->InContext())
return 0;
v8::HandleScope handleScope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
if (context.IsEmpty() || !toDOMWindow(context))
return 0;
ScriptState* scriptState = ScriptState::from(context);
if (!scriptState->world().isIsolatedWorld())
return 0;
V8PerContextData* contextData = scriptState->perContextData();
if (!contextData)
return 0;
return contextData->activityLogger();
}
} // namespace blink
|
.global s_prepare_buffers
s_prepare_buffers:
push %r9
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0xf699, %rsi
lea addresses_WC_ht+0x3299, %rdi
nop
nop
add $58285, %rdx
mov $86, %rcx
rep movsb
sub $8236, %rbp
lea addresses_WT_ht+0x19699, %r9
nop
nop
nop
nop
nop
inc %rbx
vmovups (%r9), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $0, %xmm6, %rsi
nop
nop
nop
dec %rdx
lea addresses_normal_ht+0xd499, %rbp
clflush (%rbp)
nop
xor $28071, %rdx
vmovups (%rbp), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $0, %xmm6, %rdi
nop
nop
nop
cmp $41547, %r9
lea addresses_D_ht+0xb699, %rbp
nop
add $48656, %r9
mov (%rbp), %edi
nop
nop
xor %rbx, %rbx
lea addresses_D_ht+0x17359, %rbx
nop
nop
nop
xor %rsi, %rsi
movw $0x6162, (%rbx)
nop
nop
nop
nop
inc %rbp
lea addresses_WT_ht+0x1c139, %rbp
nop
nop
nop
nop
nop
dec %rdi
vmovups (%rbp), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $0, %xmm1, %rcx
nop
nop
inc %rbx
lea addresses_D_ht+0x15ef9, %rsi
lea addresses_normal_ht+0xfe89, %rdi
nop
nop
nop
nop
inc %rax
mov $108, %rcx
rep movsw
cmp $52706, %rbx
lea addresses_WC_ht+0x11e6d, %rsi
lea addresses_A_ht+0x10846, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
cmp %rbp, %rbp
mov $92, %rcx
rep movsb
nop
and $28789, %rcx
lea addresses_UC_ht+0x1d7c9, %rcx
nop
lfence
movl $0x61626364, (%rcx)
xor $61894, %rcx
lea addresses_normal_ht+0xfc19, %rdi
nop
nop
nop
nop
nop
xor $64987, %rbp
movb (%rdi), %al
nop
nop
and $39347, %rbp
lea addresses_D_ht+0x15899, %rbx
nop
nop
nop
xor %rcx, %rcx
movb (%rbx), %r9b
nop
nop
nop
inc %rbp
lea addresses_normal_ht+0xfc99, %rbp
nop
nop
cmp $12521, %rbx
and $0xffffffffffffffc0, %rbp
vmovaps (%rbp), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $1, %xmm7, %r9
nop
nop
nop
nop
nop
xor $63202, %rbp
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r9
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r15
push %r9
push %rax
push %rdi
push %rsi
// Store
lea addresses_UC+0x859, %rsi
cmp %r11, %r11
movw $0x5152, (%rsi)
nop
nop
nop
nop
sub %r12, %r12
// Store
mov $0x4c60f0000000a99, %rsi
and %rdi, %rdi
mov $0x5152535455565758, %r12
movq %r12, %xmm5
movups %xmm5, (%rsi)
and %r15, %r15
// Store
mov $0x33db7c00000009a5, %rsi
nop
nop
nop
sub %rdi, %rdi
movb $0x51, (%rsi)
sub %r12, %r12
// Store
lea addresses_WC+0xc019, %r12
nop
nop
nop
nop
dec %rdi
mov $0x5152535455565758, %rax
movq %rax, %xmm0
vmovups %ymm0, (%r12)
add %rax, %rax
// Store
lea addresses_WT+0x2299, %r12
sub $56111, %rdi
mov $0x5152535455565758, %r15
movq %r15, %xmm4
movups %xmm4, (%r12)
nop
nop
xor $32561, %r11
// Store
lea addresses_A+0x19299, %rax
nop
nop
and $29397, %r15
movw $0x5152, (%rax)
nop
sub %rdi, %rdi
// Faulty Load
mov $0x4c60f0000000a99, %r9
nop
nop
nop
and %rdi, %rdi
mov (%r9), %r11
lea oracles, %r12
and $0xff, %r11
shlq $12, %r11
mov (%r12,%r11,1), %r11
pop %rsi
pop %rdi
pop %rax
pop %r9
pop %r15
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 4, 'AVXalign': True, 'NT': True, 'congruent': 10, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': True, 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': True, 'NT': False, 'congruent': 8, 'same': False}}
{'00': 2, '58': 1}
00 00 58
*/
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
; Module Name:
;
; SetJump.Asm
;
; Abstract:
;
; Implementation of SetJump() on x64.
;
;------------------------------------------------------------------------------
%include "Nasm.inc"
DEFAULT REL
SECTION .text
extern ASM_PFX(InternalAssertJumpBuffer)
extern ASM_PFX(PcdGet32 (PcdControlFlowEnforcementPropertyMask))
;------------------------------------------------------------------------------
; UINTN
; EFIAPI
; SetJump (
; OUT BASE_LIBRARY_JUMP_BUFFER *JumpBuffer
; );
;------------------------------------------------------------------------------
global ASM_PFX(SetJump)
ASM_PFX(SetJump):
push rcx
add rsp, -0x20
call ASM_PFX(InternalAssertJumpBuffer)
add rsp, 0x20
pop rcx
pop rdx
xor rax, rax
mov [rcx + 0xF8], rax ; save 0 to SSP
mov eax, [ASM_PFX(PcdGet32 (PcdControlFlowEnforcementPropertyMask))]
test eax, eax
jz CetDone
mov rax, cr4
bt eax, 23 ; check if CET is enabled
jnc CetDone
mov rax, 1
incsspq rax ; to read original SSP
rdsspq rax
mov [rcx + 0xF8], rax ; save SSP
CetDone:
mov [rcx], rbx
mov [rcx + 8], rsp
mov [rcx + 0x10], rbp
mov [rcx + 0x18], rdi
mov [rcx + 0x20], rsi
mov [rcx + 0x28], r12
mov [rcx + 0x30], r13
mov [rcx + 0x38], r14
mov [rcx + 0x40], r15
mov [rcx + 0x48], rdx
; save non-volatile fp registers
stmxcsr [rcx + 0x50]
movdqu [rcx + 0x58], xmm6
movdqu [rcx + 0x68], xmm7
movdqu [rcx + 0x78], xmm8
movdqu [rcx + 0x88], xmm9
movdqu [rcx + 0x98], xmm10
movdqu [rcx + 0xA8], xmm11
movdqu [rcx + 0xB8], xmm12
movdqu [rcx + 0xC8], xmm13
movdqu [rcx + 0xD8], xmm14
movdqu [rcx + 0xE8], xmm15
xor rax, rax
jmp rdx
|
; A130755: Binomial transform of periodic sequence (3, 1, 2).
; 3,4,7,15,32,65,129,256,511,1023,2048,4097,8193,16384,32767,65535,131072,262145,524289,1048576,2097151,4194303,8388608,16777217,33554433,67108864,134217727,268435455,536870912,1073741825,2147483649,4294967296,8589934591,17179869183,34359738368,68719476737,137438953473,274877906944,549755813887,1099511627775,2199023255552,4398046511105,8796093022209,17592186044416,35184372088831,70368744177663,140737488355328,281474976710657,562949953421313,1125899906842624,2251799813685247,4503599627370495,9007199254740992
mov $2,$0
add $2,1
cal $2,282153 ; Expansion of x*(1 - 2*x + 3*x^2)/((1 - x)*(1 - 2*x)*(1 - x + x^2)).
add $1,$2
add $1,2
|
#include "IBlock.h"
namespace CryptoNote {
IBlock::~IBlock() {
}
}
|
/// @file
/// C64 DTV version 2 Registers and Constants
///
/// Sources
/// (J) https://www.c64-wiki.com/wiki/C64DTV_Programming_Guide
/// (H) http://dtvhacking.cbm8bit.com/dtv_wiki/images/d/d9/Dtv_registers_full.txt
// Commodore 64 PRG executable file
.file [name="c64dtv-blittermin.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(main)
.const DTV_FEATURE_ENABLE = 1
/// Bit[0] Force Start Strobe when set
.const DTV_BLIT_FORCE_START = 1
/// Bit[1] Source A Direction Positive when set
.const DTV_BLIT_SRCA_FWD = 2
/// Bit[2] Source B Direction Positive when set
.const DTV_BLIT_SRCB_FWD = 4
/// Bit[3] Destination Direction Positive when set
.const DTV_BLIT_DEST_FWD = 8
/// No transparancy
/// Bit[2]==Bit[1]==0: write in any case
.const DTV_BLIT_TRANSPARANCY_NONE = 0
.const DTV_BLIT_ADD = $30
/// Bit[0] Clear Blitter IRQ
.const DTV_BLIT_CLEAR_IRQ = 1
/// Bit[3] Destination Continue
.const DTV_BLIT_DEST_CONT = 8
/// Bit[0] Busy when set (When reading)
.const DTV_BLIT_STATUS_BUSY = 1
.const SRCA_LEN = 9
/// Feature enables or disables the extra C64 DTV features
.label DTV_FEATURE = $d03f
/// Blitter Source A Start
.label DTV_BLITTER_SRCA_LO = $d320
.label DTV_BLITTER_SRCA_MI = $d321
.label DTV_BLITTER_SRCA_HI = $d322
/// Blitter Source A Modulo
.label DTV_BLITTER_SRCA_MOD_LO = $d323
.label DTV_BLITTER_SRCA_MOD_HI = $d324
/// Blitter Source A Line Length
.label DTV_BLITTER_SRCA_LIN_LO = $d325
.label DTV_BLITTER_SRCA_LIN_HI = $d326
/// Blitter Source A Step ([7:4] integral part, [3:0] fractional part)
.label DTV_BLITTER_SRCA_STEP = $d327
/// Blitter Source B Start
.label DTV_BLITTER_SRCB_LO = $d328
.label DTV_BLITTER_SRCB_MI = $d329
.label DTV_BLITTER_SRCB_HI = $d32a
/// Blitter Source B Modulo
.label DTV_BLITTER_SRCB_MOD_LO = $d32b
.label DTV_BLITTER_SRCB_MOD_HI = $d32c
/// Blitter Source B Line Length
.label DTV_BLITTER_SRCB_LIN_LO = $d32d
.label DTV_BLITTER_SRCB_LIN_HI = $d32e
/// Blitter Source B Step ([7:4] integral part, [3:0] fractional part)
.label DTV_BLITTER_SRCB_STEP = $d32f
/// Blitter Destination Start
.label DTV_BLITTER_DEST_LO = $d330
.label DTV_BLITTER_DEST_MI = $d331
.label DTV_BLITTER_DEST_HI = $d332
/// Blitter Source B Modulo
.label DTV_BLITTER_DEST_MOD_LO = $d333
.label DTV_BLITTER_DEST_MOD_HI = $d334
/// Blitter Source B Line Length
.label DTV_BLITTER_DEST_LIN_LO = $d335
.label DTV_BLITTER_DEST_LIN_HI = $d336
/// Blitter Source B Step ([7:4] integral part, [3:0] fractional part)
.label DTV_BLITTER_DEST_STEP = $d337
/// Blitter Blit Length
.label DTV_BLITTER_LEN_LO = $d338
.label DTV_BLITTER_LEN_HI = $d339
/// Blitter Control
.label DTV_BLITTER_CONTROL = $d33a
/// Blitter Transparency
.label DTV_BLITTER_TRANSPARANCY = $d33b
/// Blitter Control 2
.label DTV_BLITTER_CONTROL2 = $d33f
.label SCREEN = $400
/// Controls the ALU operation
.label DTV_BLITTER_ALU = $d33e
.segment Code
main: {
// *DTV_FEATURE = DTV_FEATURE_ENABLE
lda #DTV_FEATURE_ENABLE
sta DTV_FEATURE
// *DTV_BLITTER_CONTROL2 = DTV_BLIT_CLEAR_IRQ
// Instruct blitter not to continue previous blit
lda #DTV_BLIT_CLEAR_IRQ
sta DTV_BLITTER_CONTROL2
// *DTV_BLITTER_SRCA_LO = BYTE0(SRCA)
lda #<SRCA
sta DTV_BLITTER_SRCA_LO
// *DTV_BLITTER_SRCA_MI = BYTE1(SRCA)
lda #>SRCA
sta DTV_BLITTER_SRCA_MI
// *DTV_BLITTER_SRCA_HI = 0
lda #0
sta DTV_BLITTER_SRCA_HI
// *DTV_BLITTER_SRCA_MOD_LO = 0
sta DTV_BLITTER_SRCA_MOD_LO
// *DTV_BLITTER_SRCA_MOD_HI = 0
sta DTV_BLITTER_SRCA_MOD_HI
// *DTV_BLITTER_SRCA_LIN_LO = BYTE0($100uw)
sta DTV_BLITTER_SRCA_LIN_LO
// *DTV_BLITTER_SRCA_LIN_HI = BYTE1($100uw)
lda #>$100
sta DTV_BLITTER_SRCA_LIN_HI
// *DTV_BLITTER_SRCA_STEP = $10
lda #$10
sta DTV_BLITTER_SRCA_STEP
// *DTV_BLITTER_SRCB_LO = BYTE0(SRCB)
// Step 1.0
lda #<SRCB
sta DTV_BLITTER_SRCB_LO
// *DTV_BLITTER_SRCB_MI = BYTE1(SRCB)
lda #>SRCB
sta DTV_BLITTER_SRCB_MI
// *DTV_BLITTER_SRCB_HI = 0
lda #0
sta DTV_BLITTER_SRCB_HI
// *DTV_BLITTER_SRCB_MOD_LO = 0
sta DTV_BLITTER_SRCB_MOD_LO
// *DTV_BLITTER_SRCB_MOD_HI = 0
sta DTV_BLITTER_SRCB_MOD_HI
// *DTV_BLITTER_SRCB_LIN_LO = BYTE0($100uw)
sta DTV_BLITTER_SRCB_LIN_LO
// *DTV_BLITTER_SRCB_LIN_HI = BYTE1($100uw)
lda #>$100
sta DTV_BLITTER_SRCB_LIN_HI
// *DTV_BLITTER_SRCB_STEP = $00
lda #0
sta DTV_BLITTER_SRCB_STEP
// *DTV_BLITTER_DEST_LO = BYTE0(SCREEN)
// Step 0.0
sta DTV_BLITTER_DEST_LO
// *DTV_BLITTER_DEST_MI = BYTE1(SCREEN)
lda #>SCREEN
sta DTV_BLITTER_DEST_MI
// *DTV_BLITTER_DEST_HI = 0
lda #0
sta DTV_BLITTER_DEST_HI
// *DTV_BLITTER_DEST_MOD_LO = 0
sta DTV_BLITTER_DEST_MOD_LO
// *DTV_BLITTER_DEST_MOD_HI = 0
sta DTV_BLITTER_DEST_MOD_HI
// *DTV_BLITTER_DEST_LIN_LO = BYTE0($100uw)
sta DTV_BLITTER_DEST_LIN_LO
// *DTV_BLITTER_DEST_LIN_HI = BYTE1($100uw)
lda #>$100
sta DTV_BLITTER_DEST_LIN_HI
// *DTV_BLITTER_DEST_STEP = $10
lda #$10
sta DTV_BLITTER_DEST_STEP
// *DTV_BLITTER_LEN_LO = SRCA_LEN
// Step 1.0
lda #SRCA_LEN
sta DTV_BLITTER_LEN_LO
// *DTV_BLITTER_LEN_HI = 0
lda #0
sta DTV_BLITTER_LEN_HI
// *DTV_BLITTER_ALU = DTV_BLIT_ADD
lda #DTV_BLIT_ADD
sta DTV_BLITTER_ALU
// *DTV_BLITTER_TRANSPARANCY = DTV_BLIT_TRANSPARANCY_NONE
lda #DTV_BLIT_TRANSPARANCY_NONE
sta DTV_BLITTER_TRANSPARANCY
// *DTV_BLITTER_CONTROL = DTV_BLIT_FORCE_START | DTV_BLIT_SRCA_FWD | DTV_BLIT_SRCB_FWD| DTV_BLIT_DEST_FWD
// Start blitter
lda #DTV_BLIT_FORCE_START|DTV_BLIT_SRCA_FWD|DTV_BLIT_SRCB_FWD|DTV_BLIT_DEST_FWD
sta DTV_BLITTER_CONTROL
// *DTV_BLITTER_CONTROL2 = DTV_BLIT_DEST_CONT
// Instruct blitter to continue at DEST and restart SRC A/B
lda #DTV_BLIT_DEST_CONT
sta DTV_BLITTER_CONTROL2
ldx #0
// wait til blitter is ready
__b1:
// *DTV_BLITTER_CONTROL2 & DTV_BLIT_STATUS_BUSY
lda #DTV_BLIT_STATUS_BUSY
and DTV_BLITTER_CONTROL2
// while((*DTV_BLITTER_CONTROL2 & DTV_BLIT_STATUS_BUSY)!=0)
cmp #0
bne __b1
// *DTV_BLITTER_CONTROL = DTV_BLIT_FORCE_START | DTV_BLIT_SRCA_FWD | DTV_BLIT_SRCB_FWD| DTV_BLIT_DEST_FWD
// restart
lda #DTV_BLIT_FORCE_START|DTV_BLIT_SRCA_FWD|DTV_BLIT_SRCB_FWD|DTV_BLIT_DEST_FWD
sta DTV_BLITTER_CONTROL
// for( byte r: 0..7 )
inx
cpx #8
bne __b1
// }
rts
}
.segment Data
SRCA: .byte 'c', 'a', 'm', 'e', 'l', 'o', 't', '!', ' '
SRCB: .byte $80
|
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include <bitset>
#include <cassert>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <utility>
#include "modules/timer/include/timer.h"
#include "hebench/api_bridge/api.h"
#include "include/hebench_engine.h"
#include "include/hebench_math_utils.h"
#include "../include/hebench_matmult_o.h"
namespace hebench {
namespace TestHarness {
namespace MatrixMultiply {
namespace Offline {
//----------------------------
// class BenchmarkDescription
//----------------------------
bool BenchmarkDescriptor::m_b_registered = // register the benchmark with the factory
hebench::TestHarness::BenchmarkFactory::registerSupportedBenchmark(std::make_shared<BenchmarkDescriptor>());
bool BenchmarkDescriptor::matchBenchmarkDescriptor(const hebench::APIBridge::BenchmarkDescriptor &bench_desc,
const std::vector<hebench::APIBridge::WorkloadParam> &w_params) const
{
assert(m_b_registered);
// return true if benchmark is supported
bool retval =
BenchmarkDescriptorCategory::matchBenchmarkDescriptor(bench_desc, w_params)
&& (bench_desc.category == hebench::APIBridge::Category::Offline);
return retval;
}
void BenchmarkDescriptor::completeWorkloadDescription(WorkloadDescriptionOutput &output,
const Engine &engine,
const BenchmarkDescription::Backend &backend_desc,
const BenchmarkDescription::Configuration &config) const
{
// finish describing workload
assert(OpParameterCount == 2);
assert(DefaultBatchSize == 100);
BenchmarkDescriptorCategory::completeWorkloadDescription(output, engine, backend_desc, config);
assert(OpParameterCount == output.operation_params_count);
std::stringstream ss;
std::uint64_t batch_sizes[OpParameterCount];
std::array<std::pair<std::uint64_t, std::uint64_t>, OpParameterCount> mat_dims =
fetchMatrixSizes(config.w_params);
std::uint64_t sample_size_fallback =
config.fallback_default_sample_size > 0 ?
config.fallback_default_sample_size :
DefaultBatchSize;
std::uint64_t result_batch_size = computeSampleSizes(batch_sizes,
OpParameterCount,
config.default_sample_sizes,
backend_desc.descriptor,
sample_size_fallback);
// complete header with workload specifics
ss << ", , M = M0 x M1" << std::endl
<< ", , , Rows, Columns, Batch size" << std::endl;
for (std::size_t i = 0; i < OpParameterCount; ++i)
{
ss << ", , M" << i << ", " << mat_dims[i].first << ", " << mat_dims[i].second << ", " << batch_sizes[i] << std::endl;
} // end for
ss << ", , M, " << mat_dims[0].first << ", " << mat_dims[1].second << ", " << result_batch_size << std::endl;
output.workload_header = ss.str();
}
hebench::TestHarness::PartialBenchmark *BenchmarkDescriptor::createBenchmark(std::shared_ptr<Engine> p_engine,
const DescriptionToken &description_token)
{
assert(m_b_registered);
Benchmark *retval = nullptr;
try
{
retval = new Benchmark(p_engine, description_token);
}
catch (...)
{
if (retval)
delete retval;
throw;
}
return retval;
}
void BenchmarkDescriptor::destroyBenchmark(PartialBenchmark *p_bench)
{
assert(m_b_registered);
if (p_bench)
delete p_bench;
}
//-----------------
// class Benchmark
//-----------------
Benchmark::Benchmark(std::shared_ptr<Engine> p_engine,
const IBenchmarkDescriptor::DescriptionToken &description_token) :
BenchmarkOffline(p_engine, description_token)
{
}
void Benchmark::init()
{
hebench::Common::EventTimer timer;
hebench::Common::TimingReportEvent::Ptr p_timing_event;
std::uint64_t batch_sizes[BenchmarkDescriptor::OpParameterCount];
std::stringstream ss;
std::array<std::pair<std::uint64_t, std::uint64_t>, BenchmarkDescriptor::OpParameterCount> mat_dims =
BenchmarkDescriptor::fetchMatrixSizes(this->getBenchmarkConfiguration().w_params);
std::uint64_t sample_size_fallback =
this->getBenchmarkConfiguration().fallback_default_sample_size > 0 ?
this->getBenchmarkConfiguration().fallback_default_sample_size :
BenchmarkDescriptor::DefaultBatchSize;
BenchmarkDescriptor::computeSampleSizes(batch_sizes,
BenchmarkDescriptor::OpParameterCount,
this->getBenchmarkConfiguration().default_sample_sizes,
this->getBackendDescription().descriptor,
sample_size_fallback);
std::cout << IOS_MSG_INFO << hebench::Logging::GlobalLogger::log("Generating workload...") << std::endl;
std::cout << IOS_MSG_INFO << hebench::Logging::GlobalLogger::log("Loading workload data...") << std::endl;
timer.start();
// generates random matrices for input and generates (computes) ground truth
m_data = DataGenerator::create(mat_dims[0].first, mat_dims[0].second, // M0
mat_dims[1].second, // M1
batch_sizes[0], batch_sizes[1],
this->getBackendDescription().descriptor.data_type);
p_timing_event = timer.stop<std::milli>();
ss = std::stringstream();
ss << "Total data loaded: " << m_data->getTotalDataLoaded() << " bytes";
std::cout << IOS_MSG_DONE << hebench::Logging::GlobalLogger::log(ss.str()) << std::endl;
ss = std::stringstream();
ss << "Elapsed wall time: " << p_timing_event->elapsedWallTime<std::milli>() << " ms";
std::cout << IOS_MSG_INFO << hebench::Logging::GlobalLogger::log(ss.str()) << std::endl;
ss = std::stringstream();
ss << "Elapsed CPU time: " << p_timing_event->elapsedCPUTime<std::milli>() << " ms";
std::cout << IOS_MSG_INFO << hebench::Logging::GlobalLogger::log(ss.str()) << std::endl;
}
bool Benchmark::validateResult(IDataLoader::Ptr dataset,
const std::uint64_t *param_data_pack_indices,
const std::vector<hebench::APIBridge::NativeDataBuffer *> &outputs,
hebench::APIBridge::DataType data_type) const
{
assert(dataset->getParameterCount() == BenchmarkDescriptorCategory::OpParameterCount
&& dataset->getResultCount() == BenchmarkDescriptorCategory::OpResultCount);
return BenchmarkOffline::validateResult(dataset, param_data_pack_indices, outputs, data_type);
}
} // namespace Offline
} // namespace MatrixMultiply
} // namespace TestHarness
} // namespace hebench
|
; A021046: Decimal expansion of 1/42.
; 0,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3,8,0,9,5,2,3
add $0,2
mov $1,10
pow $1,$0
mul $1,4
div $1,1680
mod $1,10
mov $0,$1
|
; A096182: Index of first occurrence of n in A095773.
; 1,2,4,6,8,10,13,16,19,22,26,30,34,38,42,46,51,56,61,66,71,76,82,88,94,100,106,112,118,124,130,136,142,148,155,162,169,176,183,190,197,204,211,218,225,232,240,248,256,264,272,280,288,296,304,312,320,328,336
mov $7,$0
mov $9,$0
add $9,1
lpb $9
clr $0,7
mov $0,$7
sub $9,1
sub $0,$9
add $6,2
lpb $0
div $0,2
add $1,3
add $0,$1
mov $6,$1
sub $1,1
lpe
div $0,2
add $6,$0
add $6,1
div $6,2
add $8,$6
lpe
mov $1,$8
|
/*************************************************************************/
/* variant.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "variant.h"
#include "core_string_names.h"
#include "io/marshalls.h"
#include "math_funcs.h"
#include "print_string.h"
#include "resource.h"
#include "scene/gui/control.h"
#include "scene/main/node.h"
#include "variant_parser.h"
String Variant::get_type_name(Variant::Type p_type) {
switch (p_type) {
case NIL: {
return "Nil";
} break;
// atomic types
case BOOL: {
return "bool";
} break;
case INT: {
return "int";
} break;
case REAL: {
return "float";
} break;
case STRING: {
return "String";
} break;
// math types
case VECTOR2: {
return "Vector2";
} break;
case RECT2: {
return "Rect2";
} break;
case TRANSFORM2D: {
return "Transform2D";
} break;
case VECTOR3: {
return "Vector3";
} break;
case PLANE: {
return "Plane";
} break;
/*
case QUAT: {
} break;*/
case RECT3: {
return "Rect3";
} break;
case QUAT: {
return "Quat";
} break;
case BASIS: {
return "Basis";
} break;
case TRANSFORM: {
return "Transform";
} break;
// misc types
case COLOR: {
return "Color";
} break;
case _RID: {
return "RID";
} break;
case OBJECT: {
return "Object";
} break;
case NODE_PATH: {
return "NodePath";
} break;
case DICTIONARY: {
return "Dictionary";
} break;
case ARRAY: {
return "Array";
} break;
// arrays
case POOL_BYTE_ARRAY: {
return "PoolByteArray";
} break;
case POOL_INT_ARRAY: {
return "PoolIntArray";
} break;
case POOL_REAL_ARRAY: {
return "PoolRealArray";
} break;
case POOL_STRING_ARRAY: {
return "PoolStringArray";
} break;
case POOL_VECTOR2_ARRAY: {
return "PoolVector2Array";
} break;
case POOL_VECTOR3_ARRAY: {
return "PoolVector3Array";
} break;
case POOL_COLOR_ARRAY: {
return "PoolColorArray";
} break;
default: {}
}
return "";
}
bool Variant::can_convert(Variant::Type p_type_from, Variant::Type p_type_to) {
if (p_type_from == p_type_to)
return true;
if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything
return true;
if (p_type_from == NIL) {
return (p_type_to == OBJECT);
};
const Type *valid_types = NULL;
const Type *invalid_types = NULL;
switch (p_type_to) {
case BOOL: {
static const Type valid[] = {
INT,
REAL,
STRING,
NIL,
};
valid_types = valid;
} break;
case INT: {
static const Type valid[] = {
BOOL,
REAL,
STRING,
NIL,
};
valid_types = valid;
} break;
case REAL: {
static const Type valid[] = {
BOOL,
INT,
STRING,
NIL,
};
valid_types = valid;
} break;
case STRING: {
static const Type invalid[] = {
OBJECT,
NIL
};
invalid_types = invalid;
} break;
case TRANSFORM2D: {
static const Type valid[] = {
TRANSFORM,
NIL
};
valid_types = valid;
} break;
case QUAT: {
static const Type valid[] = {
BASIS,
NIL
};
valid_types = valid;
} break;
case BASIS: {
static const Type valid[] = {
QUAT,
NIL
};
valid_types = valid;
} break;
case TRANSFORM: {
static const Type valid[] = {
TRANSFORM2D,
QUAT,
BASIS,
NIL
};
valid_types = valid;
} break;
case COLOR: {
static const Type valid[] = {
STRING,
INT,
NIL,
};
valid_types = valid;
} break;
case _RID: {
static const Type valid[] = {
OBJECT,
NIL
};
valid_types = valid;
} break;
case OBJECT: {
static const Type valid[] = {
NIL
};
valid_types = valid;
} break;
case NODE_PATH: {
static const Type valid[] = {
STRING,
NIL
};
valid_types = valid;
} break;
case ARRAY: {
static const Type valid[] = {
POOL_BYTE_ARRAY,
POOL_INT_ARRAY,
POOL_STRING_ARRAY,
POOL_REAL_ARRAY,
POOL_COLOR_ARRAY,
POOL_VECTOR2_ARRAY,
POOL_VECTOR3_ARRAY,
NIL
};
valid_types = valid;
} break;
// arrays
case POOL_BYTE_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_INT_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_REAL_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_STRING_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_VECTOR2_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_VECTOR3_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_COLOR_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
default: {}
}
if (valid_types) {
int i = 0;
while (valid_types[i] != NIL) {
if (p_type_from == valid_types[i])
return true;
i++;
}
} else if (invalid_types) {
int i = 0;
while (invalid_types[i] != NIL) {
if (p_type_from == invalid_types[i])
return false;
i++;
}
return true;
}
return false;
}
bool Variant::can_convert_strict(Variant::Type p_type_from, Variant::Type p_type_to) {
if (p_type_from == p_type_to)
return true;
if (p_type_to == NIL && p_type_from != NIL) //nil can convert to anything
return true;
if (p_type_from == NIL) {
return (p_type_to == OBJECT);
};
const Type *valid_types = NULL;
switch (p_type_to) {
case BOOL: {
static const Type valid[] = {
INT,
REAL,
//STRING,
NIL,
};
valid_types = valid;
} break;
case INT: {
static const Type valid[] = {
BOOL,
REAL,
//STRING,
NIL,
};
valid_types = valid;
} break;
case REAL: {
static const Type valid[] = {
BOOL,
INT,
//STRING,
NIL,
};
valid_types = valid;
} break;
case STRING: {
static const Type valid[] = {
NODE_PATH,
NIL
};
valid_types = valid;
} break;
case TRANSFORM2D: {
static const Type valid[] = {
TRANSFORM,
NIL
};
valid_types = valid;
} break;
case QUAT: {
static const Type valid[] = {
BASIS,
NIL
};
valid_types = valid;
} break;
case BASIS: {
static const Type valid[] = {
QUAT,
NIL
};
valid_types = valid;
} break;
case TRANSFORM: {
static const Type valid[] = {
TRANSFORM2D,
QUAT,
BASIS,
NIL
};
valid_types = valid;
} break;
case COLOR: {
static const Type valid[] = {
STRING,
INT,
NIL,
};
valid_types = valid;
} break;
case _RID: {
static const Type valid[] = {
OBJECT,
NIL
};
valid_types = valid;
} break;
case OBJECT: {
static const Type valid[] = {
NIL
};
valid_types = valid;
} break;
case NODE_PATH: {
static const Type valid[] = {
STRING,
NIL
};
valid_types = valid;
} break;
case ARRAY: {
static const Type valid[] = {
POOL_BYTE_ARRAY,
POOL_INT_ARRAY,
POOL_STRING_ARRAY,
POOL_REAL_ARRAY,
POOL_COLOR_ARRAY,
POOL_VECTOR2_ARRAY,
POOL_VECTOR3_ARRAY,
NIL
};
valid_types = valid;
} break;
// arrays
case POOL_BYTE_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_INT_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_REAL_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_STRING_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_VECTOR2_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_VECTOR3_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
case POOL_COLOR_ARRAY: {
static const Type valid[] = {
ARRAY,
NIL
};
valid_types = valid;
} break;
default: {}
}
if (valid_types) {
int i = 0;
while (valid_types[i] != NIL) {
if (p_type_from == valid_types[i])
return true;
i++;
}
}
return false;
}
bool Variant::operator==(const Variant &p_variant) const {
if (type != p_variant.type) //evaluation of operator== needs to be more strict
return false;
bool v;
Variant r;
evaluate(OP_EQUAL, *this, p_variant, r, v);
return r;
}
bool Variant::operator!=(const Variant &p_variant) const {
if (type != p_variant.type) //evaluation of operator== needs to be more strict
return true;
bool v;
Variant r;
evaluate(OP_NOT_EQUAL, *this, p_variant, r, v);
return r;
}
bool Variant::operator<(const Variant &p_variant) const {
if (type != p_variant.type) //if types differ, then order by type first
return type < p_variant.type;
bool v;
Variant r;
evaluate(OP_LESS, *this, p_variant, r, v);
return r;
}
bool Variant::is_zero() const {
switch (type) {
case NIL: {
return true;
} break;
// atomic types
case BOOL: {
return _data._bool == false;
} break;
case INT: {
return _data._int == 0;
} break;
case REAL: {
return _data._real == 0;
} break;
case STRING: {
return *reinterpret_cast<const String *>(_data._mem) == String();
} break;
// math types
case VECTOR2: {
return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2();
} break;
case RECT2: {
return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2();
} break;
case TRANSFORM2D: {
return *_data._transform2d == Transform2D();
} break;
case VECTOR3: {
return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3();
} break;
case PLANE: {
return *reinterpret_cast<const Plane *>(_data._mem) == Plane();
} break;
/*
case QUAT: {
} break;*/
case RECT3: {
return *_data._rect3 == Rect3();
} break;
case QUAT: {
return *reinterpret_cast<const Quat *>(_data._mem) == Quat();
} break;
case BASIS: {
return *_data._basis == Basis();
} break;
case TRANSFORM: {
return *_data._transform == Transform();
} break;
// misc types
case COLOR: {
return *reinterpret_cast<const Color *>(_data._mem) == Color();
} break;
case _RID: {
return *reinterpret_cast<const RID *>(_data._mem) == RID();
} break;
case OBJECT: {
return _get_obj().obj == NULL;
} break;
case NODE_PATH: {
return reinterpret_cast<const NodePath *>(_data._mem)->is_empty();
} break;
case DICTIONARY: {
return reinterpret_cast<const Dictionary *>(_data._mem)->empty();
} break;
case ARRAY: {
return reinterpret_cast<const Array *>(_data._mem)->empty();
} break;
// arrays
case POOL_BYTE_ARRAY: {
return reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem)->size() == 0;
} break;
case POOL_INT_ARRAY: {
return reinterpret_cast<const PoolVector<int> *>(_data._mem)->size() == 0;
} break;
case POOL_REAL_ARRAY: {
return reinterpret_cast<const PoolVector<real_t> *>(_data._mem)->size() == 0;
} break;
case POOL_STRING_ARRAY: {
return reinterpret_cast<const PoolVector<String> *>(_data._mem)->size() == 0;
} break;
case POOL_VECTOR2_ARRAY: {
return reinterpret_cast<const PoolVector<Vector2> *>(_data._mem)->size() == 0;
} break;
case POOL_VECTOR3_ARRAY: {
return reinterpret_cast<const PoolVector<Vector3> *>(_data._mem)->size() == 0;
} break;
case POOL_COLOR_ARRAY: {
return reinterpret_cast<const PoolVector<Color> *>(_data._mem)->size() == 0;
} break;
default: {}
}
return false;
}
bool Variant::is_one() const {
switch (type) {
case NIL: {
return true;
} break;
// atomic types
case BOOL: {
return _data._bool == true;
} break;
case INT: {
return _data._int == 1;
} break;
case REAL: {
return _data._real == 1;
} break;
case VECTOR2: {
return *reinterpret_cast<const Vector2 *>(_data._mem) == Vector2(1, 1);
} break;
case RECT2: {
return *reinterpret_cast<const Rect2 *>(_data._mem) == Rect2(1, 1, 1, 1);
} break;
case VECTOR3: {
return *reinterpret_cast<const Vector3 *>(_data._mem) == Vector3(1, 1, 1);
} break;
case PLANE: {
return *reinterpret_cast<const Plane *>(_data._mem) == Plane(1, 1, 1, 1);
} break;
case COLOR: {
return *reinterpret_cast<const Color *>(_data._mem) == Color(1, 1, 1, 1);
} break;
default: { return !is_zero(); }
}
return false;
}
void Variant::reference(const Variant &p_variant) {
if (this == &p_variant)
return;
clear();
type = p_variant.type;
switch (p_variant.type) {
case NIL: {
// none
} break;
// atomic types
case BOOL: {
_data._bool = p_variant._data._bool;
} break;
case INT: {
_data._int = p_variant._data._int;
} break;
case REAL: {
_data._real = p_variant._data._real;
} break;
case STRING: {
memnew_placement(_data._mem, String(*reinterpret_cast<const String *>(p_variant._data._mem)));
} break;
// math types
case VECTOR2: {
memnew_placement(_data._mem, Vector2(*reinterpret_cast<const Vector2 *>(p_variant._data._mem)));
} break;
case RECT2: {
memnew_placement(_data._mem, Rect2(*reinterpret_cast<const Rect2 *>(p_variant._data._mem)));
} break;
case TRANSFORM2D: {
_data._transform2d = memnew(Transform2D(*p_variant._data._transform2d));
} break;
case VECTOR3: {
memnew_placement(_data._mem, Vector3(*reinterpret_cast<const Vector3 *>(p_variant._data._mem)));
} break;
case PLANE: {
memnew_placement(_data._mem, Plane(*reinterpret_cast<const Plane *>(p_variant._data._mem)));
} break;
/*
case QUAT: {
} break;*/
case RECT3: {
_data._rect3 = memnew(Rect3(*p_variant._data._rect3));
} break;
case QUAT: {
memnew_placement(_data._mem, Quat(*reinterpret_cast<const Quat *>(p_variant._data._mem)));
} break;
case BASIS: {
_data._basis = memnew(Basis(*p_variant._data._basis));
} break;
case TRANSFORM: {
_data._transform = memnew(Transform(*p_variant._data._transform));
} break;
// misc types
case COLOR: {
memnew_placement(_data._mem, Color(*reinterpret_cast<const Color *>(p_variant._data._mem)));
} break;
case _RID: {
memnew_placement(_data._mem, RID(*reinterpret_cast<const RID *>(p_variant._data._mem)));
} break;
case OBJECT: {
memnew_placement(_data._mem, ObjData(p_variant._get_obj()));
} break;
case NODE_PATH: {
memnew_placement(_data._mem, NodePath(*reinterpret_cast<const NodePath *>(p_variant._data._mem)));
} break;
case DICTIONARY: {
memnew_placement(_data._mem, Dictionary(*reinterpret_cast<const Dictionary *>(p_variant._data._mem)));
} break;
case ARRAY: {
memnew_placement(_data._mem, Array(*reinterpret_cast<const Array *>(p_variant._data._mem)));
} break;
// arrays
case POOL_BYTE_ARRAY: {
memnew_placement(_data._mem, PoolVector<uint8_t>(*reinterpret_cast<const PoolVector<uint8_t> *>(p_variant._data._mem)));
} break;
case POOL_INT_ARRAY: {
memnew_placement(_data._mem, PoolVector<int>(*reinterpret_cast<const PoolVector<int> *>(p_variant._data._mem)));
} break;
case POOL_REAL_ARRAY: {
memnew_placement(_data._mem, PoolVector<real_t>(*reinterpret_cast<const PoolVector<real_t> *>(p_variant._data._mem)));
} break;
case POOL_STRING_ARRAY: {
memnew_placement(_data._mem, PoolVector<String>(*reinterpret_cast<const PoolVector<String> *>(p_variant._data._mem)));
} break;
case POOL_VECTOR2_ARRAY: {
memnew_placement(_data._mem, PoolVector<Vector2>(*reinterpret_cast<const PoolVector<Vector2> *>(p_variant._data._mem)));
} break;
case POOL_VECTOR3_ARRAY: {
memnew_placement(_data._mem, PoolVector<Vector3>(*reinterpret_cast<const PoolVector<Vector3> *>(p_variant._data._mem)));
} break;
case POOL_COLOR_ARRAY: {
memnew_placement(_data._mem, PoolVector<Color>(*reinterpret_cast<const PoolVector<Color> *>(p_variant._data._mem)));
} break;
default: {}
}
}
void Variant::zero() {
switch (type) {
case NIL: break;
case BOOL: this->_data._bool = false; break;
case INT: this->_data._int = 0; break;
case REAL: this->_data._real = 0; break;
case VECTOR2: *reinterpret_cast<Vector2 *>(this->_data._mem) = Vector2(); break;
case RECT2: *reinterpret_cast<Rect2 *>(this->_data._mem) = Rect2(); break;
case VECTOR3: *reinterpret_cast<Vector3 *>(this->_data._mem) = Vector3(); break;
case PLANE: *reinterpret_cast<Plane *>(this->_data._mem) = Plane(); break;
case QUAT: *reinterpret_cast<Quat *>(this->_data._mem) = Quat(); break;
case COLOR: *reinterpret_cast<Color *>(this->_data._mem) = Color(); break;
default: this->clear(); break;
}
}
void Variant::clear() {
switch (type) {
case STRING: {
reinterpret_cast<String *>(_data._mem)->~String();
} break;
/*
// no point, they don't allocate memory
VECTOR3,
PLANE,
QUAT,
COLOR,
VECTOR2,
RECT2
*/
case TRANSFORM2D: {
memdelete(_data._transform2d);
} break;
case RECT3: {
memdelete(_data._rect3);
} break;
case BASIS: {
memdelete(_data._basis);
} break;
case TRANSFORM: {
memdelete(_data._transform);
} break;
// misc types
case NODE_PATH: {
reinterpret_cast<NodePath *>(_data._mem)->~NodePath();
} break;
case OBJECT: {
_get_obj().obj = NULL;
_get_obj().ref.unref();
} break;
case _RID: {
// not much need probably
reinterpret_cast<RID *>(_data._mem)->~RID();
} break;
case DICTIONARY: {
reinterpret_cast<Dictionary *>(_data._mem)->~Dictionary();
} break;
case ARRAY: {
reinterpret_cast<Array *>(_data._mem)->~Array();
} break;
// arrays
case POOL_BYTE_ARRAY: {
reinterpret_cast<PoolVector<uint8_t> *>(_data._mem)->~PoolVector<uint8_t>();
} break;
case POOL_INT_ARRAY: {
reinterpret_cast<PoolVector<int> *>(_data._mem)->~PoolVector<int>();
} break;
case POOL_REAL_ARRAY: {
reinterpret_cast<PoolVector<real_t> *>(_data._mem)->~PoolVector<real_t>();
} break;
case POOL_STRING_ARRAY: {
reinterpret_cast<PoolVector<String> *>(_data._mem)->~PoolVector<String>();
} break;
case POOL_VECTOR2_ARRAY: {
reinterpret_cast<PoolVector<Vector2> *>(_data._mem)->~PoolVector<Vector2>();
} break;
case POOL_VECTOR3_ARRAY: {
reinterpret_cast<PoolVector<Vector3> *>(_data._mem)->~PoolVector<Vector3>();
} break;
case POOL_COLOR_ARRAY: {
reinterpret_cast<PoolVector<Color> *>(_data._mem)->~PoolVector<Color>();
} break;
default: {} /* not needed */
}
type = NIL;
}
Variant::operator signed int() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
Variant::operator unsigned int() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
Variant::operator int64_t() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
/*
Variant::operator long unsigned int() const {
switch( type ) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
};
*/
Variant::operator uint64_t() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
#ifdef NEED_LONG_INT
Variant::operator signed long() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
};
Variant::operator unsigned long() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
};
#endif
Variant::operator signed short() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
Variant::operator unsigned short() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
Variant::operator signed char() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
Variant::operator unsigned char() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1 : 0;
case INT: return _data._int;
case REAL: return _data._real;
case STRING: return operator String().to_int();
default: {
return 0;
}
}
return 0;
}
Variant::operator CharType() const {
return operator unsigned int();
}
Variant::operator float() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1.0 : 0.0;
case INT: return (float)_data._int;
case REAL: return _data._real;
case STRING: return operator String().to_double();
default: {
return 0;
}
}
return 0;
}
Variant::operator double() const {
switch (type) {
case NIL: return 0;
case BOOL: return _data._bool ? 1.0 : 0.0;
case INT: return (double)_data._int;
case REAL: return _data._real;
case STRING: return operator String().to_double();
default: {
return 0;
}
}
return true;
}
Variant::operator StringName() const {
if (type == NODE_PATH) {
return reinterpret_cast<const NodePath *>(_data._mem)->get_sname();
}
return StringName(operator String());
}
struct _VariantStrPair {
String key;
String value;
bool operator<(const _VariantStrPair &p) const {
return key < p.key;
}
};
Variant::operator String() const {
switch (type) {
case NIL: return "Null";
case BOOL: return _data._bool ? "True" : "False";
case INT: return itos(_data._int);
case REAL: return rtos(_data._real);
case STRING: return *reinterpret_cast<const String *>(_data._mem);
case VECTOR2: return "(" + operator Vector2() + ")";
case RECT2: return "(" + operator Rect2() + ")";
case TRANSFORM2D: {
Transform2D mat32 = operator Transform2D();
return "(" + Variant(mat32.elements[0]).operator String() + ", " + Variant(mat32.elements[1]).operator String() + ", " + Variant(mat32.elements[2]).operator String() + ")";
} break;
case VECTOR3: return "(" + operator Vector3() + ")";
case PLANE:
return operator Plane();
//case QUAT:
case RECT3: return operator Rect3();
case QUAT: return "(" + operator Quat() + ")";
case BASIS: {
Basis mat3 = operator Basis();
String mtx("(");
for (int i = 0; i < 3; i++) {
if (i != 0)
mtx += ", ";
mtx += "(";
for (int j = 0; j < 3; j++) {
if (j != 0)
mtx += ", ";
mtx += Variant(mat3.elements[i][j]).operator String();
}
mtx += ")";
}
return mtx + ")";
} break;
case TRANSFORM: return operator Transform();
case NODE_PATH: return operator NodePath();
case COLOR: return String::num(operator Color().r) + "," + String::num(operator Color().g) + "," + String::num(operator Color().b) + "," + String::num(operator Color().a);
case DICTIONARY: {
const Dictionary &d = *reinterpret_cast<const Dictionary *>(_data._mem);
//const String *K=NULL;
String str;
List<Variant> keys;
d.get_key_list(&keys);
Vector<_VariantStrPair> pairs;
for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
_VariantStrPair sp;
sp.key = String(E->get());
sp.value = d[E->get()];
pairs.push_back(sp);
}
pairs.sort();
for (int i = 0; i < pairs.size(); i++) {
if (i > 0)
str += ", ";
str += "(" + pairs[i].key + ":" + pairs[i].value + ")";
}
return str;
} break;
case POOL_VECTOR2_ARRAY: {
PoolVector<Vector2> vec = operator PoolVector<Vector2>();
String str("[");
for (int i = 0; i < vec.size(); i++) {
if (i > 0)
str += ", ";
str = str + Variant(vec[i]);
}
str += "]";
return str;
} break;
case POOL_VECTOR3_ARRAY: {
PoolVector<Vector3> vec = operator PoolVector<Vector3>();
String str("[");
for (int i = 0; i < vec.size(); i++) {
if (i > 0)
str += ", ";
str = str + Variant(vec[i]);
}
str += "]";
return str;
} break;
case POOL_STRING_ARRAY: {
PoolVector<String> vec = operator PoolVector<String>();
String str("[");
for (int i = 0; i < vec.size(); i++) {
if (i > 0)
str += ", ";
str = str + vec[i];
}
str += "]";
return str;
} break;
case POOL_INT_ARRAY: {
PoolVector<int> vec = operator PoolVector<int>();
String str("[");
for (int i = 0; i < vec.size(); i++) {
if (i > 0)
str += ", ";
str = str + itos(vec[i]);
}
str += "]";
return str;
} break;
case POOL_REAL_ARRAY: {
PoolVector<real_t> vec = operator PoolVector<real_t>();
String str("[");
for (int i = 0; i < vec.size(); i++) {
if (i > 0)
str += ", ";
str = str + rtos(vec[i]);
}
str += "]";
return str;
} break;
case ARRAY: {
Array arr = operator Array();
String str("[");
for (int i = 0; i < arr.size(); i++) {
if (i)
str += ", ";
str += String(arr[i]);
};
str += "]";
return str;
} break;
case OBJECT: {
if (_get_obj().obj) {
#ifdef DEBUG_ENABLED
if (ScriptDebugger::get_singleton() && _get_obj().ref.is_null()) {
//only if debugging!
if (!ObjectDB::instance_validate(_get_obj().obj)) {
return "[Deleted Object]";
};
};
#endif
return "[" + _get_obj().obj->get_class() + ":" + itos(_get_obj().obj->get_instance_ID()) + "]";
} else
return "[Object:null]";
} break;
default: {
return "[" + get_type_name(type) + "]";
}
}
return "";
}
Variant::operator Vector2() const {
if (type == VECTOR2)
return *reinterpret_cast<const Vector2 *>(_data._mem);
else if (type == VECTOR3)
return Vector2(reinterpret_cast<const Vector3 *>(_data._mem)->x, reinterpret_cast<const Vector3 *>(_data._mem)->y);
else
return Vector2();
}
Variant::operator Rect2() const {
if (type == RECT2)
return *reinterpret_cast<const Rect2 *>(_data._mem);
else
return Rect2();
}
Variant::operator Vector3() const {
if (type == VECTOR3)
return *reinterpret_cast<const Vector3 *>(_data._mem);
else
return Vector3();
}
Variant::operator Plane() const {
if (type == PLANE)
return *reinterpret_cast<const Plane *>(_data._mem);
else
return Plane();
}
Variant::operator Rect3() const {
if (type == RECT3)
return *_data._rect3;
else
return Rect3();
}
Variant::operator Basis() const {
if (type == BASIS)
return *_data._basis;
else if (type == QUAT)
return *reinterpret_cast<const Quat *>(_data._mem);
else if (type == TRANSFORM)
return _data._transform->basis;
else
return Basis();
}
Variant::operator Quat() const {
if (type == QUAT)
return *reinterpret_cast<const Quat *>(_data._mem);
else if (type == BASIS)
return *_data._basis;
else if (type == TRANSFORM)
return _data._transform->basis;
else
return Quat();
}
Variant::operator Transform() const {
if (type == TRANSFORM)
return *_data._transform;
else if (type == BASIS)
return Transform(*_data._basis, Vector3());
else if (type == QUAT)
return Transform(Basis(*reinterpret_cast<const Quat *>(_data._mem)), Vector3());
else
return Transform();
}
Variant::operator Transform2D() const {
if (type == TRANSFORM2D) {
return *_data._transform2d;
} else if (type == TRANSFORM) {
const Transform &t = *_data._transform;
Transform2D m;
m.elements[0][0] = t.basis.elements[0][0];
m.elements[0][1] = t.basis.elements[1][0];
m.elements[1][0] = t.basis.elements[0][1];
m.elements[1][1] = t.basis.elements[1][1];
m.elements[2][0] = t.origin[0];
m.elements[2][1] = t.origin[1];
return m;
} else
return Transform2D();
}
Variant::operator Color() const {
if (type == COLOR)
return *reinterpret_cast<const Color *>(_data._mem);
else if (type == STRING)
return Color::html(operator String());
else if (type == INT)
return Color::hex(operator int());
else
return Color();
}
Variant::operator NodePath() const {
if (type == NODE_PATH)
return *reinterpret_cast<const NodePath *>(_data._mem);
else if (type == STRING)
return NodePath(operator String());
else
return NodePath();
}
Variant::operator RefPtr() const {
if (type == OBJECT)
return _get_obj().ref;
else
return RefPtr();
}
Variant::operator RID() const {
if (type == _RID)
return *reinterpret_cast<const RID *>(_data._mem);
else if (type == OBJECT && !_get_obj().ref.is_null()) {
return _get_obj().ref.get_rid();
} else if (type == OBJECT && _get_obj().obj) {
Variant::CallError ce;
Variant ret = _get_obj().obj->call(CoreStringNames::get_singleton()->get_rid, NULL, 0, ce);
if (ce.error == Variant::CallError::CALL_OK && ret.get_type() == Variant::_RID) {
return ret;
}
return RID();
} else {
return RID();
}
}
Variant::operator Object *() const {
if (type == OBJECT)
return _get_obj().obj;
else
return NULL;
}
Variant::operator Node *() const {
if (type == OBJECT)
return _get_obj().obj ? _get_obj().obj->cast_to<Node>() : NULL;
else
return NULL;
}
Variant::operator Control *() const {
if (type == OBJECT)
return _get_obj().obj ? _get_obj().obj->cast_to<Control>() : NULL;
else
return NULL;
}
Variant::operator Dictionary() const {
if (type == DICTIONARY)
return *reinterpret_cast<const Dictionary *>(_data._mem);
else
return Dictionary();
}
template <class DA, class SA>
inline DA _convert_array(const SA &p_array) {
DA da;
da.resize(p_array.size());
for (int i = 0; i < p_array.size(); i++) {
da.set(i, Variant(p_array.get(i)));
}
return da;
}
template <class DA>
inline DA _convert_array_from_variant(const Variant &p_variant) {
switch (p_variant.get_type()) {
case Variant::ARRAY: {
return _convert_array<DA, Array>(p_variant.operator Array());
}
case Variant::POOL_BYTE_ARRAY: {
return _convert_array<DA, PoolVector<uint8_t> >(p_variant.operator PoolVector<uint8_t>());
}
case Variant::POOL_INT_ARRAY: {
return _convert_array<DA, PoolVector<int> >(p_variant.operator PoolVector<int>());
}
case Variant::POOL_REAL_ARRAY: {
return _convert_array<DA, PoolVector<real_t> >(p_variant.operator PoolVector<real_t>());
}
case Variant::POOL_STRING_ARRAY: {
return _convert_array<DA, PoolVector<String> >(p_variant.operator PoolVector<String>());
}
case Variant::POOL_VECTOR2_ARRAY: {
return _convert_array<DA, PoolVector<Vector2> >(p_variant.operator PoolVector<Vector2>());
}
case Variant::POOL_VECTOR3_ARRAY: {
return _convert_array<DA, PoolVector<Vector3> >(p_variant.operator PoolVector<Vector3>());
}
case Variant::POOL_COLOR_ARRAY: {
return _convert_array<DA, PoolVector<Color> >(p_variant.operator PoolVector<Color>());
}
default: { return DA(); }
}
return DA();
}
Variant::operator Array() const {
if (type == ARRAY)
return *reinterpret_cast<const Array *>(_data._mem);
else
return _convert_array_from_variant<Array>(*this);
}
Variant::operator PoolVector<uint8_t>() const {
if (type == POOL_BYTE_ARRAY)
return *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<uint8_t> >(*this);
}
Variant::operator PoolVector<int>() const {
if (type == POOL_INT_ARRAY)
return *reinterpret_cast<const PoolVector<int> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<int> >(*this);
}
Variant::operator PoolVector<real_t>() const {
if (type == POOL_REAL_ARRAY)
return *reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<real_t> >(*this);
}
Variant::operator PoolVector<String>() const {
if (type == POOL_STRING_ARRAY)
return *reinterpret_cast<const PoolVector<String> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<String> >(*this);
}
Variant::operator PoolVector<Vector3>() const {
if (type == POOL_VECTOR3_ARRAY)
return *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<Vector3> >(*this);
}
Variant::operator PoolVector<Vector2>() const {
if (type == POOL_VECTOR2_ARRAY)
return *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<Vector2> >(*this);
}
Variant::operator PoolVector<Color>() const {
if (type == POOL_COLOR_ARRAY)
return *reinterpret_cast<const PoolVector<Color> *>(_data._mem);
else
return _convert_array_from_variant<PoolVector<Color> >(*this);
}
/* helpers */
Variant::operator Vector<RID>() const {
Array va = operator Array();
Vector<RID> rids;
rids.resize(va.size());
for (int i = 0; i < rids.size(); i++)
rids[i] = va[i];
return rids;
}
Variant::operator Vector<Vector2>() const {
PoolVector<Vector2> from = operator PoolVector<Vector2>();
Vector<Vector2> to;
int len = from.size();
if (len == 0)
return Vector<Vector2>();
to.resize(len);
PoolVector<Vector2>::Read r = from.read();
Vector2 *w = &to[0];
for (int i = 0; i < len; i++) {
w[i] = r[i];
}
return to;
}
Variant::operator PoolVector<Plane>() const {
Array va = operator Array();
PoolVector<Plane> planes;
int va_size = va.size();
if (va_size == 0)
return planes;
planes.resize(va_size);
PoolVector<Plane>::Write w = planes.write();
for (int i = 0; i < va_size; i++)
w[i] = va[i];
return planes;
}
Variant::operator PoolVector<Face3>() const {
PoolVector<Vector3> va = operator PoolVector<Vector3>();
PoolVector<Face3> faces;
int va_size = va.size();
if (va_size == 0)
return faces;
faces.resize(va_size / 3);
PoolVector<Face3>::Write w = faces.write();
PoolVector<Vector3>::Read r = va.read();
for (int i = 0; i < va_size; i++)
w[i / 3].vertex[i % 3] = r[i];
return faces;
}
Variant::operator Vector<Plane>() const {
Array va = operator Array();
Vector<Plane> planes;
int va_size = va.size();
if (va_size == 0)
return planes;
planes.resize(va_size);
for (int i = 0; i < va_size; i++)
planes[i] = va[i];
return planes;
}
Variant::operator Vector<Variant>() const {
Array from = operator Array();
Vector<Variant> to;
int len = from.size();
to.resize(len);
for (int i = 0; i < len; i++) {
to[i] = from[i];
}
return to;
}
Variant::operator Vector<uint8_t>() const {
PoolVector<uint8_t> from = operator PoolVector<uint8_t>();
Vector<uint8_t> to;
int len = from.size();
to.resize(len);
for (int i = 0; i < len; i++) {
to[i] = from[i];
}
return to;
}
Variant::operator Vector<int>() const {
PoolVector<int> from = operator PoolVector<int>();
Vector<int> to;
int len = from.size();
to.resize(len);
for (int i = 0; i < len; i++) {
to[i] = from[i];
}
return to;
}
Variant::operator Vector<real_t>() const {
PoolVector<real_t> from = operator PoolVector<real_t>();
Vector<real_t> to;
int len = from.size();
to.resize(len);
for (int i = 0; i < len; i++) {
to[i] = from[i];
}
return to;
}
Variant::operator Vector<String>() const {
PoolVector<String> from = operator PoolVector<String>();
Vector<String> to;
int len = from.size();
to.resize(len);
for (int i = 0; i < len; i++) {
to[i] = from[i];
}
return to;
}
Variant::operator Vector<Vector3>() const {
PoolVector<Vector3> from = operator PoolVector<Vector3>();
Vector<Vector3> to;
int len = from.size();
if (len == 0)
return Vector<Vector3>();
to.resize(len);
PoolVector<Vector3>::Read r = from.read();
Vector3 *w = &to[0];
for (int i = 0; i < len; i++) {
w[i] = r[i];
}
return to;
}
Variant::operator Vector<Color>() const {
PoolVector<Color> from = operator PoolVector<Color>();
Vector<Color> to;
int len = from.size();
if (len == 0)
return Vector<Color>();
to.resize(len);
PoolVector<Color>::Read r = from.read();
Color *w = &to[0];
for (int i = 0; i < len; i++) {
w[i] = r[i];
}
return to;
}
Variant::operator Margin() const {
return (Margin) operator int();
}
Variant::operator Orientation() const {
return (Orientation) operator int();
}
Variant::operator IP_Address() const {
if (type == POOL_REAL_ARRAY || type == POOL_INT_ARRAY || type == POOL_BYTE_ARRAY) {
PoolVector<int> addr = operator PoolVector<int>();
if (addr.size() == 4) {
return IP_Address(addr.get(0), addr.get(1), addr.get(2), addr.get(3));
}
}
return IP_Address(operator String());
}
Variant::Variant(bool p_bool) {
type = BOOL;
_data._bool = p_bool;
}
/*
Variant::Variant(long unsigned int p_long) {
type=INT;
_data._int=p_long;
};
*/
Variant::Variant(signed int p_int) {
type = INT;
_data._int = p_int;
}
Variant::Variant(unsigned int p_int) {
type = INT;
_data._int = p_int;
}
#ifdef NEED_LONG_INT
Variant::Variant(signed long p_int) {
type = INT;
_data._int = p_int;
}
Variant::Variant(unsigned long p_int) {
type = INT;
_data._int = p_int;
}
#endif
Variant::Variant(int64_t p_int) {
type = INT;
_data._int = p_int;
}
Variant::Variant(uint64_t p_int) {
type = INT;
_data._int = p_int;
}
Variant::Variant(signed short p_short) {
type = INT;
_data._int = p_short;
}
Variant::Variant(unsigned short p_short) {
type = INT;
_data._int = p_short;
}
Variant::Variant(signed char p_char) {
type = INT;
_data._int = p_char;
}
Variant::Variant(unsigned char p_char) {
type = INT;
_data._int = p_char;
}
Variant::Variant(float p_float) {
type = REAL;
_data._real = p_float;
}
Variant::Variant(double p_double) {
type = REAL;
_data._real = p_double;
}
Variant::Variant(const StringName &p_string) {
type = STRING;
memnew_placement(_data._mem, String(p_string.operator String()));
}
Variant::Variant(const String &p_string) {
type = STRING;
memnew_placement(_data._mem, String(p_string));
}
Variant::Variant(const char *const p_cstring) {
type = STRING;
memnew_placement(_data._mem, String((const char *)p_cstring));
}
Variant::Variant(const CharType *p_wstring) {
type = STRING;
memnew_placement(_data._mem, String(p_wstring));
}
Variant::Variant(const Vector3 &p_vector3) {
type = VECTOR3;
memnew_placement(_data._mem, Vector3(p_vector3));
}
Variant::Variant(const Vector2 &p_vector2) {
type = VECTOR2;
memnew_placement(_data._mem, Vector2(p_vector2));
}
Variant::Variant(const Rect2 &p_rect2) {
type = RECT2;
memnew_placement(_data._mem, Rect2(p_rect2));
}
Variant::Variant(const Plane &p_plane) {
type = PLANE;
memnew_placement(_data._mem, Plane(p_plane));
}
Variant::Variant(const Rect3 &p_aabb) {
type = RECT3;
_data._rect3 = memnew(Rect3(p_aabb));
}
Variant::Variant(const Basis &p_matrix) {
type = BASIS;
_data._basis = memnew(Basis(p_matrix));
}
Variant::Variant(const Quat &p_quat) {
type = QUAT;
memnew_placement(_data._mem, Quat(p_quat));
}
Variant::Variant(const Transform &p_transform) {
type = TRANSFORM;
_data._transform = memnew(Transform(p_transform));
}
Variant::Variant(const Transform2D &p_transform) {
type = TRANSFORM2D;
_data._transform2d = memnew(Transform2D(p_transform));
}
Variant::Variant(const Color &p_color) {
type = COLOR;
memnew_placement(_data._mem, Color(p_color));
}
Variant::Variant(const NodePath &p_node_path) {
type = NODE_PATH;
memnew_placement(_data._mem, NodePath(p_node_path));
}
Variant::Variant(const RefPtr &p_resource) {
type = OBJECT;
memnew_placement(_data._mem, ObjData);
REF ref = p_resource;
_get_obj().obj = ref.ptr();
_get_obj().ref = p_resource;
}
Variant::Variant(const RID &p_rid) {
type = _RID;
memnew_placement(_data._mem, RID(p_rid));
}
Variant::Variant(const Object *p_object) {
type = OBJECT;
memnew_placement(_data._mem, ObjData);
_get_obj().obj = const_cast<Object *>(p_object);
}
Variant::Variant(const Dictionary &p_dictionary) {
type = DICTIONARY;
memnew_placement(_data._mem, (Dictionary)(p_dictionary));
}
Variant::Variant(const Array &p_array) {
type = ARRAY;
memnew_placement(_data._mem, Array(p_array));
}
Variant::Variant(const PoolVector<Plane> &p_array) {
type = ARRAY;
Array *plane_array = memnew_placement(_data._mem, Array);
plane_array->resize(p_array.size());
for (int i = 0; i < p_array.size(); i++) {
plane_array->operator[](i) = Variant(p_array[i]);
}
}
Variant::Variant(const Vector<Plane> &p_array) {
type = ARRAY;
Array *plane_array = memnew_placement(_data._mem, Array);
plane_array->resize(p_array.size());
for (int i = 0; i < p_array.size(); i++) {
plane_array->operator[](i) = Variant(p_array[i]);
}
}
Variant::Variant(const Vector<RID> &p_array) {
type = ARRAY;
Array *rid_array = memnew_placement(_data._mem, Array);
rid_array->resize(p_array.size());
for (int i = 0; i < p_array.size(); i++) {
rid_array->set(i, Variant(p_array[i]));
}
}
Variant::Variant(const Vector<Vector2> &p_array) {
type = NIL;
PoolVector<Vector2> v;
int len = p_array.size();
if (len > 0) {
v.resize(len);
PoolVector<Vector2>::Write w = v.write();
const Vector2 *r = p_array.ptr();
for (int i = 0; i < len; i++)
w[i] = r[i];
}
*this = v;
}
Variant::Variant(const PoolVector<uint8_t> &p_raw_array) {
type = POOL_BYTE_ARRAY;
memnew_placement(_data._mem, PoolVector<uint8_t>(p_raw_array));
}
Variant::Variant(const PoolVector<int> &p_int_array) {
type = POOL_INT_ARRAY;
memnew_placement(_data._mem, PoolVector<int>(p_int_array));
}
Variant::Variant(const PoolVector<real_t> &p_real_array) {
type = POOL_REAL_ARRAY;
memnew_placement(_data._mem, PoolVector<real_t>(p_real_array));
}
Variant::Variant(const PoolVector<String> &p_string_array) {
type = POOL_STRING_ARRAY;
memnew_placement(_data._mem, PoolVector<String>(p_string_array));
}
Variant::Variant(const PoolVector<Vector3> &p_vector3_array) {
type = POOL_VECTOR3_ARRAY;
memnew_placement(_data._mem, PoolVector<Vector3>(p_vector3_array));
}
Variant::Variant(const PoolVector<Vector2> &p_vector2_array) {
type = POOL_VECTOR2_ARRAY;
memnew_placement(_data._mem, PoolVector<Vector2>(p_vector2_array));
}
Variant::Variant(const PoolVector<Color> &p_color_array) {
type = POOL_COLOR_ARRAY;
memnew_placement(_data._mem, PoolVector<Color>(p_color_array));
}
Variant::Variant(const PoolVector<Face3> &p_face_array) {
PoolVector<Vector3> vertices;
int face_count = p_face_array.size();
vertices.resize(face_count * 3);
if (face_count) {
PoolVector<Face3>::Read r = p_face_array.read();
PoolVector<Vector3>::Write w = vertices.write();
for (int i = 0; i < face_count; i++) {
for (int j = 0; j < 3; j++)
w[i * 3 + j] = r[i].vertex[j];
}
r = PoolVector<Face3>::Read();
w = PoolVector<Vector3>::Write();
}
type = NIL;
*this = vertices;
}
/* helpers */
Variant::Variant(const Vector<Variant> &p_array) {
type = NIL;
Array v;
int len = p_array.size();
v.resize(len);
for (int i = 0; i < len; i++)
v.set(i, p_array[i]);
*this = v;
}
Variant::Variant(const Vector<uint8_t> &p_array) {
type = NIL;
PoolVector<uint8_t> v;
int len = p_array.size();
v.resize(len);
for (int i = 0; i < len; i++)
v.set(i, p_array[i]);
*this = v;
}
Variant::Variant(const Vector<int> &p_array) {
type = NIL;
PoolVector<int> v;
int len = p_array.size();
v.resize(len);
for (int i = 0; i < len; i++)
v.set(i, p_array[i]);
*this = v;
}
Variant::Variant(const Vector<real_t> &p_array) {
type = NIL;
PoolVector<real_t> v;
int len = p_array.size();
v.resize(len);
for (int i = 0; i < len; i++)
v.set(i, p_array[i]);
*this = v;
}
Variant::Variant(const Vector<String> &p_array) {
type = NIL;
PoolVector<String> v;
int len = p_array.size();
v.resize(len);
for (int i = 0; i < len; i++)
v.set(i, p_array[i]);
*this = v;
}
Variant::Variant(const Vector<Vector3> &p_array) {
type = NIL;
PoolVector<Vector3> v;
int len = p_array.size();
if (len > 0) {
v.resize(len);
PoolVector<Vector3>::Write w = v.write();
const Vector3 *r = p_array.ptr();
for (int i = 0; i < len; i++)
w[i] = r[i];
}
*this = v;
}
Variant::Variant(const Vector<Color> &p_array) {
type = NIL;
PoolVector<Color> v;
int len = p_array.size();
v.resize(len);
for (int i = 0; i < len; i++)
v.set(i, p_array[i]);
*this = v;
}
void Variant::operator=(const Variant &p_variant) {
reference(p_variant);
}
Variant::Variant(const IP_Address &p_address) {
type = STRING;
memnew_placement(_data._mem, String(p_address));
}
Variant::Variant(const Variant &p_variant) {
type = NIL;
reference(p_variant);
}
/*
Variant::~Variant() {
clear();
}*/
uint32_t Variant::hash() const {
switch (type) {
case NIL: {
return 0;
} break;
case BOOL: {
return _data._bool ? 1 : 0;
} break;
case INT: {
return _data._int;
} break;
case REAL: {
return hash_djb2_one_float(_data._real);
} break;
case STRING: {
return reinterpret_cast<const String *>(_data._mem)->hash();
} break;
// math types
case VECTOR2: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->x);
return hash_djb2_one_float(reinterpret_cast<const Vector2 *>(_data._mem)->y, hash);
} break;
case RECT2: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->position.x);
hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->position.y, hash);
hash = hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.x, hash);
return hash_djb2_one_float(reinterpret_cast<const Rect2 *>(_data._mem)->size.y, hash);
} break;
case TRANSFORM2D: {
uint32_t hash = 5831;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
hash = hash_djb2_one_float(_data._transform2d->elements[i][j], hash);
}
}
return hash;
} break;
case VECTOR3: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->x);
hash = hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->y, hash);
return hash_djb2_one_float(reinterpret_cast<const Vector3 *>(_data._mem)->z, hash);
} break;
case PLANE: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.x);
hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.y, hash);
hash = hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->normal.z, hash);
return hash_djb2_one_float(reinterpret_cast<const Plane *>(_data._mem)->d, hash);
} break;
/*
case QUAT: {
} break;*/
case RECT3: {
uint32_t hash = 5831;
for (int i = 0; i < 3; i++) {
hash = hash_djb2_one_float(_data._rect3->position[i], hash);
hash = hash_djb2_one_float(_data._rect3->size[i], hash);
}
return hash;
} break;
case QUAT: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->x);
hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->y, hash);
hash = hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->z, hash);
return hash_djb2_one_float(reinterpret_cast<const Quat *>(_data._mem)->w, hash);
} break;
case BASIS: {
uint32_t hash = 5831;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
hash = hash_djb2_one_float(_data._basis->elements[i][j], hash);
}
}
return hash;
} break;
case TRANSFORM: {
uint32_t hash = 5831;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
hash = hash_djb2_one_float(_data._transform->basis.elements[i][j], hash);
}
hash = hash_djb2_one_float(_data._transform->origin[i], hash);
}
return hash;
} break;
// misc types
case COLOR: {
uint32_t hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->r);
hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->g, hash);
hash = hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->b, hash);
return hash_djb2_one_float(reinterpret_cast<const Color *>(_data._mem)->a, hash);
} break;
case _RID: {
return hash_djb2_one_64(reinterpret_cast<const RID *>(_data._mem)->get_id());
} break;
case OBJECT: {
return hash_djb2_one_64(make_uint64_t(_get_obj().obj));
} break;
case NODE_PATH: {
return reinterpret_cast<const NodePath *>(_data._mem)->hash();
} break;
case DICTIONARY: {
return reinterpret_cast<const Dictionary *>(_data._mem)->hash();
} break;
case ARRAY: {
const Array &arr = *reinterpret_cast<const Array *>(_data._mem);
return arr.hash();
} break;
case POOL_BYTE_ARRAY: {
const PoolVector<uint8_t> &arr = *reinterpret_cast<const PoolVector<uint8_t> *>(_data._mem);
int len = arr.size();
PoolVector<uint8_t>::Read r = arr.read();
return hash_djb2_buffer((uint8_t *)&r[0], len);
} break;
case POOL_INT_ARRAY: {
const PoolVector<int> &arr = *reinterpret_cast<const PoolVector<int> *>(_data._mem);
int len = arr.size();
PoolVector<int>::Read r = arr.read();
return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(int));
} break;
case POOL_REAL_ARRAY: {
const PoolVector<real_t> &arr = *reinterpret_cast<const PoolVector<real_t> *>(_data._mem);
int len = arr.size();
PoolVector<real_t>::Read r = arr.read();
return hash_djb2_buffer((uint8_t *)&r[0], len * sizeof(real_t));
} break;
case POOL_STRING_ARRAY: {
uint32_t hash = 5831;
const PoolVector<String> &arr = *reinterpret_cast<const PoolVector<String> *>(_data._mem);
int len = arr.size();
PoolVector<String>::Read r = arr.read();
for (int i = 0; i < len; i++) {
hash = hash_djb2_one_32(r[i].hash(), hash);
}
return hash;
} break;
case POOL_VECTOR2_ARRAY: {
uint32_t hash = 5831;
const PoolVector<Vector2> &arr = *reinterpret_cast<const PoolVector<Vector2> *>(_data._mem);
int len = arr.size();
PoolVector<Vector2>::Read r = arr.read();
for (int i = 0; i < len; i++) {
hash = hash_djb2_one_float(r[i].x, hash);
hash = hash_djb2_one_float(r[i].y, hash);
}
return hash;
} break;
case POOL_VECTOR3_ARRAY: {
uint32_t hash = 5831;
const PoolVector<Vector3> &arr = *reinterpret_cast<const PoolVector<Vector3> *>(_data._mem);
int len = arr.size();
PoolVector<Vector3>::Read r = arr.read();
for (int i = 0; i < len; i++) {
hash = hash_djb2_one_float(r[i].x, hash);
hash = hash_djb2_one_float(r[i].y, hash);
hash = hash_djb2_one_float(r[i].z, hash);
}
return hash;
} break;
case POOL_COLOR_ARRAY: {
uint32_t hash = 5831;
const PoolVector<Color> &arr = *reinterpret_cast<const PoolVector<Color> *>(_data._mem);
int len = arr.size();
PoolVector<Color>::Read r = arr.read();
for (int i = 0; i < len; i++) {
hash = hash_djb2_one_float(r[i].r, hash);
hash = hash_djb2_one_float(r[i].g, hash);
hash = hash_djb2_one_float(r[i].b, hash);
hash = hash_djb2_one_float(r[i].a, hash);
}
return hash;
} break;
default: {}
}
return 0;
}
#define hash_compare_scalar(p_lhs, p_rhs) \
((p_lhs) == (p_rhs)) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs))
#define hash_compare_vector2(p_lhs, p_rhs) \
(hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
(hash_compare_scalar((p_lhs).y, (p_rhs).y))
#define hash_compare_vector3(p_lhs, p_rhs) \
(hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
(hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \
(hash_compare_scalar((p_lhs).z, (p_rhs).z))
#define hash_compare_quat(p_lhs, p_rhs) \
(hash_compare_scalar((p_lhs).x, (p_rhs).x)) && \
(hash_compare_scalar((p_lhs).y, (p_rhs).y)) && \
(hash_compare_scalar((p_lhs).z, (p_rhs).z)) && \
(hash_compare_scalar((p_lhs).w, (p_rhs).w))
#define hash_compare_color(p_lhs, p_rhs) \
(hash_compare_scalar((p_lhs).r, (p_rhs).r)) && \
(hash_compare_scalar((p_lhs).g, (p_rhs).g)) && \
(hash_compare_scalar((p_lhs).b, (p_rhs).b)) && \
(hash_compare_scalar((p_lhs).a, (p_rhs).a))
#define hash_compare_pool_array(p_lhs, p_rhs, p_type, p_compare_func) \
const PoolVector<p_type> &l = *reinterpret_cast<const PoolVector<p_type> *>(p_lhs); \
const PoolVector<p_type> &r = *reinterpret_cast<const PoolVector<p_type> *>(p_rhs); \
\
if (l.size() != r.size()) \
return false; \
\
PoolVector<p_type>::Read lr = l.read(); \
PoolVector<p_type>::Read rr = r.read(); \
\
for (int i = 0; i < l.size(); ++i) { \
if (!p_compare_func((lr[i]), (rr[i]))) \
return false; \
} \
\
return true
bool Variant::hash_compare(const Variant &p_variant) const {
if (type != p_variant.type)
return false;
switch (type) {
case REAL: {
return hash_compare_scalar(_data._real, p_variant._data._real);
} break;
case VECTOR2: {
const Vector2 *l = reinterpret_cast<const Vector2 *>(_data._mem);
const Vector2 *r = reinterpret_cast<const Vector2 *>(p_variant._data._mem);
return hash_compare_vector2(*l, *r);
} break;
case RECT2: {
const Rect2 *l = reinterpret_cast<const Rect2 *>(_data._mem);
const Rect2 *r = reinterpret_cast<const Rect2 *>(p_variant._data._mem);
return (hash_compare_vector2(l->position, r->position)) &&
(hash_compare_vector2(l->size, r->size));
} break;
case TRANSFORM2D: {
Transform2D *l = _data._transform2d;
Transform2D *r = p_variant._data._transform2d;
for (int i = 0; i < 3; i++) {
if (!(hash_compare_vector2(l->elements[i], r->elements[i])))
return false;
}
return true;
} break;
case VECTOR3: {
const Vector3 *l = reinterpret_cast<const Vector3 *>(_data._mem);
const Vector3 *r = reinterpret_cast<const Vector3 *>(p_variant._data._mem);
return hash_compare_vector3(*l, *r);
} break;
case PLANE: {
const Plane *l = reinterpret_cast<const Plane *>(_data._mem);
const Plane *r = reinterpret_cast<const Plane *>(p_variant._data._mem);
return (hash_compare_vector3(l->normal, r->normal)) &&
(hash_compare_scalar(l->d, r->d));
} break;
case RECT3: {
const Rect3 *l = _data._rect3;
const Rect3 *r = p_variant._data._rect3;
return (hash_compare_vector3(l->position, r->position) &&
(hash_compare_vector3(l->size, r->size)));
} break;
case QUAT: {
const Quat *l = reinterpret_cast<const Quat *>(_data._mem);
const Quat *r = reinterpret_cast<const Quat *>(p_variant._data._mem);
return hash_compare_quat(*l, *r);
} break;
case BASIS: {
const Basis *l = _data._basis;
const Basis *r = p_variant._data._basis;
for (int i = 0; i < 3; i++) {
if (!(hash_compare_vector3(l->elements[i], r->elements[i])))
return false;
}
return true;
} break;
case TRANSFORM: {
const Transform *l = _data._transform;
const Transform *r = p_variant._data._transform;
for (int i = 0; i < 3; i++) {
if (!(hash_compare_vector3(l->basis.elements[i], r->basis.elements[i])))
return false;
}
return hash_compare_vector3(l->origin, r->origin);
} break;
case COLOR: {
const Color *l = reinterpret_cast<const Color *>(_data._mem);
const Color *r = reinterpret_cast<const Color *>(p_variant._data._mem);
return hash_compare_color(*l, *r);
} break;
case ARRAY: {
const Array &l = *(reinterpret_cast<const Array *>(_data._mem));
const Array &r = *(reinterpret_cast<const Array *>(p_variant._data._mem));
if (l.size() != r.size())
return false;
for (int i = 0; i < l.size(); ++i) {
if (!l[i].hash_compare(r[i]))
return false;
}
return true;
} break;
case POOL_REAL_ARRAY: {
hash_compare_pool_array(_data._mem, p_variant._data._mem, real_t, hash_compare_scalar);
} break;
case POOL_VECTOR2_ARRAY: {
hash_compare_pool_array(_data._mem, p_variant._data._mem, Vector2, hash_compare_vector2);
} break;
case POOL_VECTOR3_ARRAY: {
hash_compare_pool_array(_data._mem, p_variant._data._mem, Vector3, hash_compare_vector3);
} break;
case POOL_COLOR_ARRAY: {
hash_compare_pool_array(_data._mem, p_variant._data._mem, Color, hash_compare_color);
} break;
default:
bool v;
Variant r;
evaluate(OP_EQUAL, *this, p_variant, r, v);
return r;
}
return false;
}
bool Variant::is_ref() const {
return type == OBJECT && !_get_obj().ref.is_null();
}
Vector<Variant> varray() {
return Vector<Variant>();
}
Vector<Variant> varray(const Variant &p_arg1) {
Vector<Variant> v;
v.push_back(p_arg1);
return v;
}
Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2) {
Vector<Variant> v;
v.push_back(p_arg1);
v.push_back(p_arg2);
return v;
}
Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3) {
Vector<Variant> v;
v.push_back(p_arg1);
v.push_back(p_arg2);
v.push_back(p_arg3);
return v;
}
Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4) {
Vector<Variant> v;
v.push_back(p_arg1);
v.push_back(p_arg2);
v.push_back(p_arg3);
v.push_back(p_arg4);
return v;
}
Vector<Variant> varray(const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5) {
Vector<Variant> v;
v.push_back(p_arg1);
v.push_back(p_arg2);
v.push_back(p_arg3);
v.push_back(p_arg4);
v.push_back(p_arg5);
return v;
}
void Variant::static_assign(const Variant &p_variant) {
}
bool Variant::is_shared() const {
switch (type) {
case OBJECT: return true;
case ARRAY: return true;
case DICTIONARY: return true;
default: {}
}
return false;
}
Variant Variant::call(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
int argc = 0;
for (int i = 0; i < VARIANT_ARG_MAX; i++) {
if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
CallError error;
Variant ret = call(p_method, argptr, argc, error);
switch (error.error) {
case CallError::CALL_ERROR_INVALID_ARGUMENT: {
String err = "Invalid type for argument #" + itos(error.argument) + ", expected '" + Variant::get_type_name(error.expected) + "'.";
ERR_PRINT(err.utf8().get_data());
} break;
case CallError::CALL_ERROR_INVALID_METHOD: {
String err = "Invalid method '" + p_method + "' for type '" + Variant::get_type_name(type) + "'.";
ERR_PRINT(err.utf8().get_data());
} break;
case CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: {
String err = "Too many arguments for method '" + p_method + "'";
ERR_PRINT(err.utf8().get_data());
} break;
default: {}
}
return ret;
}
void Variant::construct_from_string(const String &p_string, Variant &r_value, ObjectConstruct p_obj_construct, void *p_construct_ud) {
r_value = Variant();
}
String Variant::get_construct_string() const {
String vars;
VariantWriter::write_to_string(*this, vars);
return vars;
}
String Variant::get_call_error_text(Object *p_base, const StringName &p_method, const Variant **p_argptrs, int p_argcount, const Variant::CallError &ce) {
String err_text;
if (ce.error == Variant::CallError::CALL_ERROR_INVALID_ARGUMENT) {
int errorarg = ce.argument;
err_text = "Cannot convert argument " + itos(errorarg + 1) + " from " + Variant::get_type_name(p_argptrs[errorarg]->get_type()) + " to " + Variant::get_type_name(ce.expected) + ".";
} else if (ce.error == Variant::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS) {
err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + ".";
} else if (ce.error == Variant::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS) {
err_text = "Method expected " + itos(ce.argument) + " arguments, but called with " + itos(p_argcount) + ".";
} else if (ce.error == Variant::CallError::CALL_ERROR_INVALID_METHOD) {
err_text = "Method not found.";
} else if (ce.error == Variant::CallError::CALL_ERROR_INSTANCE_IS_NULL) {
err_text = "Instance is null";
} else if (ce.error == Variant::CallError::CALL_OK) {
return "Call OK";
}
String class_name = p_base->get_class();
Ref<Script> script = p_base->get_script();
if (script.is_valid() && script->get_path().is_resource_file()) {
class_name += "(" + script->get_path().get_file() + ")";
}
return "'" + class_name + "::" + String(p_method) + "': " + err_text;
}
String vformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) {
Array args;
if (p1.get_type() != Variant::NIL) {
args.push_back(p1);
if (p2.get_type() != Variant::NIL) {
args.push_back(p2);
if (p3.get_type() != Variant::NIL) {
args.push_back(p3);
if (p4.get_type() != Variant::NIL) {
args.push_back(p4);
if (p5.get_type() != Variant::NIL) {
args.push_back(p5);
}
}
}
}
}
bool error = false;
String fmt = p_text.sprintf(args, &error);
ERR_FAIL_COND_V(error, String());
return fmt;
}
|
;
; jidctint.asm - accurate integer IDCT (MMX)
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
; Copyright (C) 2016, 2020, D. R. Commander.
;
; Based on the 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
;
; This file contains a slower but more accurate integer implementation of the
; inverse DCT (Discrete Cosine Transform). The following code is based
; directly on the IJG's original jidctint.c; see the jidctint.c for
; more details.
%include "jsimdext.inc"
%include "jdct.inc"
; --------------------------------------------------------------------------
%define CONST_BITS 13
%define PASS1_BITS 2
%define DESCALE_P1 (CONST_BITS - PASS1_BITS)
%define DESCALE_P2 (CONST_BITS + PASS1_BITS + 3)
%if CONST_BITS == 13
F_0_298 equ 2446 ; FIX(0.298631336)
F_0_390 equ 3196 ; FIX(0.390180644)
F_0_541 equ 4433 ; FIX(0.541196100)
F_0_765 equ 6270 ; FIX(0.765366865)
F_0_899 equ 7373 ; FIX(0.899976223)
F_1_175 equ 9633 ; FIX(1.175875602)
F_1_501 equ 12299 ; FIX(1.501321110)
F_1_847 equ 15137 ; FIX(1.847759065)
F_1_961 equ 16069 ; FIX(1.961570560)
F_2_053 equ 16819 ; FIX(2.053119869)
F_2_562 equ 20995 ; FIX(2.562915447)
F_3_072 equ 25172 ; FIX(3.072711026)
%else
; NASM cannot do compile-time arithmetic on floating-point constants.
%define DESCALE(x, n) (((x) + (1 << ((n) - 1))) >> (n))
F_0_298 equ DESCALE( 320652955, 30 - CONST_BITS) ; FIX(0.298631336)
F_0_390 equ DESCALE( 418953276, 30 - CONST_BITS) ; FIX(0.390180644)
F_0_541 equ DESCALE( 581104887, 30 - CONST_BITS) ; FIX(0.541196100)
F_0_765 equ DESCALE( 821806413, 30 - CONST_BITS) ; FIX(0.765366865)
F_0_899 equ DESCALE( 966342111, 30 - CONST_BITS) ; FIX(0.899976223)
F_1_175 equ DESCALE(1262586813, 30 - CONST_BITS) ; FIX(1.175875602)
F_1_501 equ DESCALE(1612031267, 30 - CONST_BITS) ; FIX(1.501321110)
F_1_847 equ DESCALE(1984016188, 30 - CONST_BITS) ; FIX(1.847759065)
F_1_961 equ DESCALE(2106220350, 30 - CONST_BITS) ; FIX(1.961570560)
F_2_053 equ DESCALE(2204520673, 30 - CONST_BITS) ; FIX(2.053119869)
F_2_562 equ DESCALE(2751909506, 30 - CONST_BITS) ; FIX(2.562915447)
F_3_072 equ DESCALE(3299298341, 30 - CONST_BITS) ; FIX(3.072711026)
%endif
; --------------------------------------------------------------------------
SECTION SEG_CONST
alignz 32
GLOBAL_DATA(jconst_idct_islow_mmx)
EXTN(jconst_idct_islow_mmx):
PW_F130_F054 times 2 dw (F_0_541 + F_0_765), F_0_541
PW_F054_MF130 times 2 dw F_0_541, (F_0_541 - F_1_847)
PW_MF078_F117 times 2 dw (F_1_175 - F_1_961), F_1_175
PW_F117_F078 times 2 dw F_1_175, (F_1_175 - F_0_390)
PW_MF060_MF089 times 2 dw (F_0_298 - F_0_899), -F_0_899
PW_MF089_F060 times 2 dw -F_0_899, (F_1_501 - F_0_899)
PW_MF050_MF256 times 2 dw (F_2_053 - F_2_562), -F_2_562
PW_MF256_F050 times 2 dw -F_2_562, (F_3_072 - F_2_562)
PD_DESCALE_P1 times 2 dd 1 << (DESCALE_P1 - 1)
PD_DESCALE_P2 times 2 dd 1 << (DESCALE_P2 - 1)
PB_CENTERJSAMP times 8 db CENTERJSAMPLE
alignz 32
; --------------------------------------------------------------------------
SECTION SEG_TEXT
BITS 32
;
; Perform dequantization and inverse DCT on one block of coefficients.
;
; GLOBAL(void)
; jsimd_idct_islow_mmx(void *dct_table, JCOEFPTR coef_block,
; JSAMPARRAY output_buf, JDIMENSION output_col)
;
%define dct_table(b) (b) + 8 ; jpeg_component_info *compptr
%define coef_block(b) (b) + 12 ; JCOEFPTR coef_block
%define output_buf(b) (b) + 16 ; JSAMPARRAY output_buf
%define output_col(b) (b) + 20 ; JDIMENSION output_col
%define original_ebp ebp + 0
%define wk(i) ebp - (WK_NUM - (i)) * SIZEOF_MMWORD
; mmword wk[WK_NUM]
%define WK_NUM 12
%define workspace wk(0) - DCTSIZE2 * SIZEOF_JCOEF
; JCOEF workspace[DCTSIZE2]
align 32
GLOBAL_FUNCTION(jsimd_idct_islow_mmx)
EXTN(jsimd_idct_islow_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, [workspace]
push ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
get_GOT ebx ; get GOT address
; ---- Pass 1: process columns from input, store into work array.
; mov eax, [original_ebp]
mov edx, POINTER [dct_table(eax)] ; quantptr
mov esi, JCOEFPTR [coef_block(eax)] ; inptr
lea edi, [workspace] ; JCOEF *wsptr
mov ecx, DCTSIZE/4 ; ctr
alignx 16, 7
.columnloop:
%ifndef NO_ZERO_COLUMN_TEST_ISLOW_MMX
mov eax, dword [DWBLOCK(1,0,esi,SIZEOF_JCOEF)]
or eax, dword [DWBLOCK(2,0,esi,SIZEOF_JCOEF)]
jnz short .columnDCT
movq mm0, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(2,0,esi,SIZEOF_JCOEF)]
por mm0, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
por mm1, MMWORD [MMBLOCK(4,0,esi,SIZEOF_JCOEF)]
por mm0, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
por mm1, MMWORD [MMBLOCK(6,0,esi,SIZEOF_JCOEF)]
por mm0, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
por mm1, mm0
packsswb mm1, mm1
movd eax, mm1
test eax, eax
jnz short .columnDCT
; -- AC terms all zero
movq mm0, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
pmullw mm0, MMWORD [MMBLOCK(0,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
psllw mm0, PASS1_BITS
movq mm2, mm0 ; mm0=in0=(00 01 02 03)
punpcklwd mm0, mm0 ; mm0=(00 00 01 01)
punpckhwd mm2, mm2 ; mm2=(02 02 03 03)
movq mm1, mm0
punpckldq mm0, mm0 ; mm0=(00 00 00 00)
punpckhdq mm1, mm1 ; mm1=(01 01 01 01)
movq mm3, mm2
punpckldq mm2, mm2 ; mm2=(02 02 02 02)
punpckhdq mm3, mm3 ; mm3=(03 03 03 03)
movq MMWORD [MMBLOCK(0,0,edi,SIZEOF_JCOEF)], mm0
movq MMWORD [MMBLOCK(0,1,edi,SIZEOF_JCOEF)], mm0
movq MMWORD [MMBLOCK(1,0,edi,SIZEOF_JCOEF)], mm1
movq MMWORD [MMBLOCK(1,1,edi,SIZEOF_JCOEF)], mm1
movq MMWORD [MMBLOCK(2,0,edi,SIZEOF_JCOEF)], mm2
movq MMWORD [MMBLOCK(2,1,edi,SIZEOF_JCOEF)], mm2
movq MMWORD [MMBLOCK(3,0,edi,SIZEOF_JCOEF)], mm3
movq MMWORD [MMBLOCK(3,1,edi,SIZEOF_JCOEF)], mm3
jmp near .nextcolumn
alignx 16, 7
%endif
.columnDCT:
; -- Even part
movq mm0, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(2,0,esi,SIZEOF_JCOEF)]
pmullw mm0, MMWORD [MMBLOCK(0,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm1, MMWORD [MMBLOCK(2,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm2, MMWORD [MMBLOCK(4,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(6,0,esi,SIZEOF_JCOEF)]
pmullw mm2, MMWORD [MMBLOCK(4,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm3, MMWORD [MMBLOCK(6,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
; (Original)
; z1 = (z2 + z3) * 0.541196100;
; tmp2 = z1 + z3 * -1.847759065;
; tmp3 = z1 + z2 * 0.765366865;
;
; (This implementation)
; tmp2 = z2 * 0.541196100 + z3 * (0.541196100 - 1.847759065);
; tmp3 = z2 * (0.541196100 + 0.765366865) + z3 * 0.541196100;
movq mm4, mm1 ; mm1=in2=z2
movq mm5, mm1
punpcklwd mm4, mm3 ; mm3=in6=z3
punpckhwd mm5, mm3
movq mm1, mm4
movq mm3, mm5
pmaddwd mm4, [GOTOFF(ebx,PW_F130_F054)] ; mm4=tmp3L
pmaddwd mm5, [GOTOFF(ebx,PW_F130_F054)] ; mm5=tmp3H
pmaddwd mm1, [GOTOFF(ebx,PW_F054_MF130)] ; mm1=tmp2L
pmaddwd mm3, [GOTOFF(ebx,PW_F054_MF130)] ; mm3=tmp2H
movq mm6, mm0
paddw mm0, mm2 ; mm0=in0+in4
psubw mm6, mm2 ; mm6=in0-in4
pxor mm7, mm7
pxor mm2, mm2
punpcklwd mm7, mm0 ; mm7=tmp0L
punpckhwd mm2, mm0 ; mm2=tmp0H
psrad mm7, (16-CONST_BITS) ; psrad mm7,16 & pslld mm7,CONST_BITS
psrad mm2, (16-CONST_BITS) ; psrad mm2,16 & pslld mm2,CONST_BITS
movq mm0, mm7
paddd mm7, mm4 ; mm7=tmp10L
psubd mm0, mm4 ; mm0=tmp13L
movq mm4, mm2
paddd mm2, mm5 ; mm2=tmp10H
psubd mm4, mm5 ; mm4=tmp13H
movq MMWORD [wk(0)], mm7 ; wk(0)=tmp10L
movq MMWORD [wk(1)], mm2 ; wk(1)=tmp10H
movq MMWORD [wk(2)], mm0 ; wk(2)=tmp13L
movq MMWORD [wk(3)], mm4 ; wk(3)=tmp13H
pxor mm5, mm5
pxor mm7, mm7
punpcklwd mm5, mm6 ; mm5=tmp1L
punpckhwd mm7, mm6 ; mm7=tmp1H
psrad mm5, (16-CONST_BITS) ; psrad mm5,16 & pslld mm5,CONST_BITS
psrad mm7, (16-CONST_BITS) ; psrad mm7,16 & pslld mm7,CONST_BITS
movq mm2, mm5
paddd mm5, mm1 ; mm5=tmp11L
psubd mm2, mm1 ; mm2=tmp12L
movq mm0, mm7
paddd mm7, mm3 ; mm7=tmp11H
psubd mm0, mm3 ; mm0=tmp12H
movq MMWORD [wk(4)], mm5 ; wk(4)=tmp11L
movq MMWORD [wk(5)], mm7 ; wk(5)=tmp11H
movq MMWORD [wk(6)], mm2 ; wk(6)=tmp12L
movq MMWORD [wk(7)], mm0 ; wk(7)=tmp12H
; -- Odd part
movq mm4, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm6, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
pmullw mm4, MMWORD [MMBLOCK(1,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm6, MMWORD [MMBLOCK(3,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm1, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
pmullw mm1, MMWORD [MMBLOCK(5,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
pmullw mm3, MMWORD [MMBLOCK(7,0,edx,SIZEOF_ISLOW_MULT_TYPE)]
movq mm5, mm6
movq mm7, mm4
paddw mm5, mm3 ; mm5=z3
paddw mm7, mm1 ; mm7=z4
; (Original)
; z5 = (z3 + z4) * 1.175875602;
; z3 = z3 * -1.961570560; z4 = z4 * -0.390180644;
; z3 += z5; z4 += z5;
;
; (This implementation)
; z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602;
; z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644);
movq mm2, mm5
movq mm0, mm5
punpcklwd mm2, mm7
punpckhwd mm0, mm7
movq mm5, mm2
movq mm7, mm0
pmaddwd mm2, [GOTOFF(ebx,PW_MF078_F117)] ; mm2=z3L
pmaddwd mm0, [GOTOFF(ebx,PW_MF078_F117)] ; mm0=z3H
pmaddwd mm5, [GOTOFF(ebx,PW_F117_F078)] ; mm5=z4L
pmaddwd mm7, [GOTOFF(ebx,PW_F117_F078)] ; mm7=z4H
movq MMWORD [wk(10)], mm2 ; wk(10)=z3L
movq MMWORD [wk(11)], mm0 ; wk(11)=z3H
; (Original)
; z1 = tmp0 + tmp3; z2 = tmp1 + tmp2;
; tmp0 = tmp0 * 0.298631336; tmp1 = tmp1 * 2.053119869;
; tmp2 = tmp2 * 3.072711026; tmp3 = tmp3 * 1.501321110;
; z1 = z1 * -0.899976223; z2 = z2 * -2.562915447;
; tmp0 += z1 + z3; tmp1 += z2 + z4;
; tmp2 += z2 + z3; tmp3 += z1 + z4;
;
; (This implementation)
; tmp0 = tmp0 * (0.298631336 - 0.899976223) + tmp3 * -0.899976223;
; tmp1 = tmp1 * (2.053119869 - 2.562915447) + tmp2 * -2.562915447;
; tmp2 = tmp1 * -2.562915447 + tmp2 * (3.072711026 - 2.562915447);
; tmp3 = tmp0 * -0.899976223 + tmp3 * (1.501321110 - 0.899976223);
; tmp0 += z3; tmp1 += z4;
; tmp2 += z3; tmp3 += z4;
movq mm2, mm3
movq mm0, mm3
punpcklwd mm2, mm4
punpckhwd mm0, mm4
movq mm3, mm2
movq mm4, mm0
pmaddwd mm2, [GOTOFF(ebx,PW_MF060_MF089)] ; mm2=tmp0L
pmaddwd mm0, [GOTOFF(ebx,PW_MF060_MF089)] ; mm0=tmp0H
pmaddwd mm3, [GOTOFF(ebx,PW_MF089_F060)] ; mm3=tmp3L
pmaddwd mm4, [GOTOFF(ebx,PW_MF089_F060)] ; mm4=tmp3H
paddd mm2, MMWORD [wk(10)] ; mm2=tmp0L
paddd mm0, MMWORD [wk(11)] ; mm0=tmp0H
paddd mm3, mm5 ; mm3=tmp3L
paddd mm4, mm7 ; mm4=tmp3H
movq MMWORD [wk(8)], mm2 ; wk(8)=tmp0L
movq MMWORD [wk(9)], mm0 ; wk(9)=tmp0H
movq mm2, mm1
movq mm0, mm1
punpcklwd mm2, mm6
punpckhwd mm0, mm6
movq mm1, mm2
movq mm6, mm0
pmaddwd mm2, [GOTOFF(ebx,PW_MF050_MF256)] ; mm2=tmp1L
pmaddwd mm0, [GOTOFF(ebx,PW_MF050_MF256)] ; mm0=tmp1H
pmaddwd mm1, [GOTOFF(ebx,PW_MF256_F050)] ; mm1=tmp2L
pmaddwd mm6, [GOTOFF(ebx,PW_MF256_F050)] ; mm6=tmp2H
paddd mm2, mm5 ; mm2=tmp1L
paddd mm0, mm7 ; mm0=tmp1H
paddd mm1, MMWORD [wk(10)] ; mm1=tmp2L
paddd mm6, MMWORD [wk(11)] ; mm6=tmp2H
movq MMWORD [wk(10)], mm2 ; wk(10)=tmp1L
movq MMWORD [wk(11)], mm0 ; wk(11)=tmp1H
; -- Final output stage
movq mm5, MMWORD [wk(0)] ; mm5=tmp10L
movq mm7, MMWORD [wk(1)] ; mm7=tmp10H
movq mm2, mm5
movq mm0, mm7
paddd mm5, mm3 ; mm5=data0L
paddd mm7, mm4 ; mm7=data0H
psubd mm2, mm3 ; mm2=data7L
psubd mm0, mm4 ; mm0=data7H
movq mm3, [GOTOFF(ebx,PD_DESCALE_P1)] ; mm3=[PD_DESCALE_P1]
paddd mm5, mm3
paddd mm7, mm3
psrad mm5, DESCALE_P1
psrad mm7, DESCALE_P1
paddd mm2, mm3
paddd mm0, mm3
psrad mm2, DESCALE_P1
psrad mm0, DESCALE_P1
packssdw mm5, mm7 ; mm5=data0=(00 01 02 03)
packssdw mm2, mm0 ; mm2=data7=(70 71 72 73)
movq mm4, MMWORD [wk(4)] ; mm4=tmp11L
movq mm3, MMWORD [wk(5)] ; mm3=tmp11H
movq mm7, mm4
movq mm0, mm3
paddd mm4, mm1 ; mm4=data1L
paddd mm3, mm6 ; mm3=data1H
psubd mm7, mm1 ; mm7=data6L
psubd mm0, mm6 ; mm0=data6H
movq mm1, [GOTOFF(ebx,PD_DESCALE_P1)] ; mm1=[PD_DESCALE_P1]
paddd mm4, mm1
paddd mm3, mm1
psrad mm4, DESCALE_P1
psrad mm3, DESCALE_P1
paddd mm7, mm1
paddd mm0, mm1
psrad mm7, DESCALE_P1
psrad mm0, DESCALE_P1
packssdw mm4, mm3 ; mm4=data1=(10 11 12 13)
packssdw mm7, mm0 ; mm7=data6=(60 61 62 63)
movq mm6, mm5 ; transpose coefficients(phase 1)
punpcklwd mm5, mm4 ; mm5=(00 10 01 11)
punpckhwd mm6, mm4 ; mm6=(02 12 03 13)
movq mm1, mm7 ; transpose coefficients(phase 1)
punpcklwd mm7, mm2 ; mm7=(60 70 61 71)
punpckhwd mm1, mm2 ; mm1=(62 72 63 73)
movq mm3, MMWORD [wk(6)] ; mm3=tmp12L
movq mm0, MMWORD [wk(7)] ; mm0=tmp12H
movq mm4, MMWORD [wk(10)] ; mm4=tmp1L
movq mm2, MMWORD [wk(11)] ; mm2=tmp1H
movq MMWORD [wk(0)], mm5 ; wk(0)=(00 10 01 11)
movq MMWORD [wk(1)], mm6 ; wk(1)=(02 12 03 13)
movq MMWORD [wk(4)], mm7 ; wk(4)=(60 70 61 71)
movq MMWORD [wk(5)], mm1 ; wk(5)=(62 72 63 73)
movq mm5, mm3
movq mm6, mm0
paddd mm3, mm4 ; mm3=data2L
paddd mm0, mm2 ; mm0=data2H
psubd mm5, mm4 ; mm5=data5L
psubd mm6, mm2 ; mm6=data5H
movq mm7, [GOTOFF(ebx,PD_DESCALE_P1)] ; mm7=[PD_DESCALE_P1]
paddd mm3, mm7
paddd mm0, mm7
psrad mm3, DESCALE_P1
psrad mm0, DESCALE_P1
paddd mm5, mm7
paddd mm6, mm7
psrad mm5, DESCALE_P1
psrad mm6, DESCALE_P1
packssdw mm3, mm0 ; mm3=data2=(20 21 22 23)
packssdw mm5, mm6 ; mm5=data5=(50 51 52 53)
movq mm1, MMWORD [wk(2)] ; mm1=tmp13L
movq mm4, MMWORD [wk(3)] ; mm4=tmp13H
movq mm2, MMWORD [wk(8)] ; mm2=tmp0L
movq mm7, MMWORD [wk(9)] ; mm7=tmp0H
movq mm0, mm1
movq mm6, mm4
paddd mm1, mm2 ; mm1=data3L
paddd mm4, mm7 ; mm4=data3H
psubd mm0, mm2 ; mm0=data4L
psubd mm6, mm7 ; mm6=data4H
movq mm2, [GOTOFF(ebx,PD_DESCALE_P1)] ; mm2=[PD_DESCALE_P1]
paddd mm1, mm2
paddd mm4, mm2
psrad mm1, DESCALE_P1
psrad mm4, DESCALE_P1
paddd mm0, mm2
paddd mm6, mm2
psrad mm0, DESCALE_P1
psrad mm6, DESCALE_P1
packssdw mm1, mm4 ; mm1=data3=(30 31 32 33)
packssdw mm0, mm6 ; mm0=data4=(40 41 42 43)
movq mm7, MMWORD [wk(0)] ; mm7=(00 10 01 11)
movq mm2, MMWORD [wk(1)] ; mm2=(02 12 03 13)
movq mm4, mm3 ; transpose coefficients(phase 1)
punpcklwd mm3, mm1 ; mm3=(20 30 21 31)
punpckhwd mm4, mm1 ; mm4=(22 32 23 33)
movq mm6, mm0 ; transpose coefficients(phase 1)
punpcklwd mm0, mm5 ; mm0=(40 50 41 51)
punpckhwd mm6, mm5 ; mm6=(42 52 43 53)
movq mm1, mm7 ; transpose coefficients(phase 2)
punpckldq mm7, mm3 ; mm7=(00 10 20 30)
punpckhdq mm1, mm3 ; mm1=(01 11 21 31)
movq mm5, mm2 ; transpose coefficients(phase 2)
punpckldq mm2, mm4 ; mm2=(02 12 22 32)
punpckhdq mm5, mm4 ; mm5=(03 13 23 33)
movq mm3, MMWORD [wk(4)] ; mm3=(60 70 61 71)
movq mm4, MMWORD [wk(5)] ; mm4=(62 72 63 73)
movq MMWORD [MMBLOCK(0,0,edi,SIZEOF_JCOEF)], mm7
movq MMWORD [MMBLOCK(1,0,edi,SIZEOF_JCOEF)], mm1
movq MMWORD [MMBLOCK(2,0,edi,SIZEOF_JCOEF)], mm2
movq MMWORD [MMBLOCK(3,0,edi,SIZEOF_JCOEF)], mm5
movq mm7, mm0 ; transpose coefficients(phase 2)
punpckldq mm0, mm3 ; mm0=(40 50 60 70)
punpckhdq mm7, mm3 ; mm7=(41 51 61 71)
movq mm1, mm6 ; transpose coefficients(phase 2)
punpckldq mm6, mm4 ; mm6=(42 52 62 72)
punpckhdq mm1, mm4 ; mm1=(43 53 63 73)
movq MMWORD [MMBLOCK(0,1,edi,SIZEOF_JCOEF)], mm0
movq MMWORD [MMBLOCK(1,1,edi,SIZEOF_JCOEF)], mm7
movq MMWORD [MMBLOCK(2,1,edi,SIZEOF_JCOEF)], mm6
movq MMWORD [MMBLOCK(3,1,edi,SIZEOF_JCOEF)], mm1
.nextcolumn:
add esi, byte 4*SIZEOF_JCOEF ; coef_block
add edx, byte 4*SIZEOF_ISLOW_MULT_TYPE ; quantptr
add edi, byte 4*DCTSIZE*SIZEOF_JCOEF ; wsptr
dec ecx ; ctr
jnz near .columnloop
; ---- Pass 2: process rows from work array, store into output array.
mov eax, [original_ebp]
lea esi, [workspace] ; JCOEF *wsptr
mov edi, JSAMPARRAY [output_buf(eax)] ; (JSAMPROW *)
mov eax, JDIMENSION [output_col(eax)]
mov ecx, DCTSIZE/4 ; ctr
alignx 16, 7
.rowloop:
; -- Even part
movq mm0, MMWORD [MMBLOCK(0,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(2,0,esi,SIZEOF_JCOEF)]
movq mm2, MMWORD [MMBLOCK(4,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(6,0,esi,SIZEOF_JCOEF)]
; (Original)
; z1 = (z2 + z3) * 0.541196100;
; tmp2 = z1 + z3 * -1.847759065;
; tmp3 = z1 + z2 * 0.765366865;
;
; (This implementation)
; tmp2 = z2 * 0.541196100 + z3 * (0.541196100 - 1.847759065);
; tmp3 = z2 * (0.541196100 + 0.765366865) + z3 * 0.541196100;
movq mm4, mm1 ; mm1=in2=z2
movq mm5, mm1
punpcklwd mm4, mm3 ; mm3=in6=z3
punpckhwd mm5, mm3
movq mm1, mm4
movq mm3, mm5
pmaddwd mm4, [GOTOFF(ebx,PW_F130_F054)] ; mm4=tmp3L
pmaddwd mm5, [GOTOFF(ebx,PW_F130_F054)] ; mm5=tmp3H
pmaddwd mm1, [GOTOFF(ebx,PW_F054_MF130)] ; mm1=tmp2L
pmaddwd mm3, [GOTOFF(ebx,PW_F054_MF130)] ; mm3=tmp2H
movq mm6, mm0
paddw mm0, mm2 ; mm0=in0+in4
psubw mm6, mm2 ; mm6=in0-in4
pxor mm7, mm7
pxor mm2, mm2
punpcklwd mm7, mm0 ; mm7=tmp0L
punpckhwd mm2, mm0 ; mm2=tmp0H
psrad mm7, (16-CONST_BITS) ; psrad mm7,16 & pslld mm7,CONST_BITS
psrad mm2, (16-CONST_BITS) ; psrad mm2,16 & pslld mm2,CONST_BITS
movq mm0, mm7
paddd mm7, mm4 ; mm7=tmp10L
psubd mm0, mm4 ; mm0=tmp13L
movq mm4, mm2
paddd mm2, mm5 ; mm2=tmp10H
psubd mm4, mm5 ; mm4=tmp13H
movq MMWORD [wk(0)], mm7 ; wk(0)=tmp10L
movq MMWORD [wk(1)], mm2 ; wk(1)=tmp10H
movq MMWORD [wk(2)], mm0 ; wk(2)=tmp13L
movq MMWORD [wk(3)], mm4 ; wk(3)=tmp13H
pxor mm5, mm5
pxor mm7, mm7
punpcklwd mm5, mm6 ; mm5=tmp1L
punpckhwd mm7, mm6 ; mm7=tmp1H
psrad mm5, (16-CONST_BITS) ; psrad mm5,16 & pslld mm5,CONST_BITS
psrad mm7, (16-CONST_BITS) ; psrad mm7,16 & pslld mm7,CONST_BITS
movq mm2, mm5
paddd mm5, mm1 ; mm5=tmp11L
psubd mm2, mm1 ; mm2=tmp12L
movq mm0, mm7
paddd mm7, mm3 ; mm7=tmp11H
psubd mm0, mm3 ; mm0=tmp12H
movq MMWORD [wk(4)], mm5 ; wk(4)=tmp11L
movq MMWORD [wk(5)], mm7 ; wk(5)=tmp11H
movq MMWORD [wk(6)], mm2 ; wk(6)=tmp12L
movq MMWORD [wk(7)], mm0 ; wk(7)=tmp12H
; -- Odd part
movq mm4, MMWORD [MMBLOCK(1,0,esi,SIZEOF_JCOEF)]
movq mm6, MMWORD [MMBLOCK(3,0,esi,SIZEOF_JCOEF)]
movq mm1, MMWORD [MMBLOCK(5,0,esi,SIZEOF_JCOEF)]
movq mm3, MMWORD [MMBLOCK(7,0,esi,SIZEOF_JCOEF)]
movq mm5, mm6
movq mm7, mm4
paddw mm5, mm3 ; mm5=z3
paddw mm7, mm1 ; mm7=z4
; (Original)
; z5 = (z3 + z4) * 1.175875602;
; z3 = z3 * -1.961570560; z4 = z4 * -0.390180644;
; z3 += z5; z4 += z5;
;
; (This implementation)
; z3 = z3 * (1.175875602 - 1.961570560) + z4 * 1.175875602;
; z4 = z3 * 1.175875602 + z4 * (1.175875602 - 0.390180644);
movq mm2, mm5
movq mm0, mm5
punpcklwd mm2, mm7
punpckhwd mm0, mm7
movq mm5, mm2
movq mm7, mm0
pmaddwd mm2, [GOTOFF(ebx,PW_MF078_F117)] ; mm2=z3L
pmaddwd mm0, [GOTOFF(ebx,PW_MF078_F117)] ; mm0=z3H
pmaddwd mm5, [GOTOFF(ebx,PW_F117_F078)] ; mm5=z4L
pmaddwd mm7, [GOTOFF(ebx,PW_F117_F078)] ; mm7=z4H
movq MMWORD [wk(10)], mm2 ; wk(10)=z3L
movq MMWORD [wk(11)], mm0 ; wk(11)=z3H
; (Original)
; z1 = tmp0 + tmp3; z2 = tmp1 + tmp2;
; tmp0 = tmp0 * 0.298631336; tmp1 = tmp1 * 2.053119869;
; tmp2 = tmp2 * 3.072711026; tmp3 = tmp3 * 1.501321110;
; z1 = z1 * -0.899976223; z2 = z2 * -2.562915447;
; tmp0 += z1 + z3; tmp1 += z2 + z4;
; tmp2 += z2 + z3; tmp3 += z1 + z4;
;
; (This implementation)
; tmp0 = tmp0 * (0.298631336 - 0.899976223) + tmp3 * -0.899976223;
; tmp1 = tmp1 * (2.053119869 - 2.562915447) + tmp2 * -2.562915447;
; tmp2 = tmp1 * -2.562915447 + tmp2 * (3.072711026 - 2.562915447);
; tmp3 = tmp0 * -0.899976223 + tmp3 * (1.501321110 - 0.899976223);
; tmp0 += z3; tmp1 += z4;
; tmp2 += z3; tmp3 += z4;
movq mm2, mm3
movq mm0, mm3
punpcklwd mm2, mm4
punpckhwd mm0, mm4
movq mm3, mm2
movq mm4, mm0
pmaddwd mm2, [GOTOFF(ebx,PW_MF060_MF089)] ; mm2=tmp0L
pmaddwd mm0, [GOTOFF(ebx,PW_MF060_MF089)] ; mm0=tmp0H
pmaddwd mm3, [GOTOFF(ebx,PW_MF089_F060)] ; mm3=tmp3L
pmaddwd mm4, [GOTOFF(ebx,PW_MF089_F060)] ; mm4=tmp3H
paddd mm2, MMWORD [wk(10)] ; mm2=tmp0L
paddd mm0, MMWORD [wk(11)] ; mm0=tmp0H
paddd mm3, mm5 ; mm3=tmp3L
paddd mm4, mm7 ; mm4=tmp3H
movq MMWORD [wk(8)], mm2 ; wk(8)=tmp0L
movq MMWORD [wk(9)], mm0 ; wk(9)=tmp0H
movq mm2, mm1
movq mm0, mm1
punpcklwd mm2, mm6
punpckhwd mm0, mm6
movq mm1, mm2
movq mm6, mm0
pmaddwd mm2, [GOTOFF(ebx,PW_MF050_MF256)] ; mm2=tmp1L
pmaddwd mm0, [GOTOFF(ebx,PW_MF050_MF256)] ; mm0=tmp1H
pmaddwd mm1, [GOTOFF(ebx,PW_MF256_F050)] ; mm1=tmp2L
pmaddwd mm6, [GOTOFF(ebx,PW_MF256_F050)] ; mm6=tmp2H
paddd mm2, mm5 ; mm2=tmp1L
paddd mm0, mm7 ; mm0=tmp1H
paddd mm1, MMWORD [wk(10)] ; mm1=tmp2L
paddd mm6, MMWORD [wk(11)] ; mm6=tmp2H
movq MMWORD [wk(10)], mm2 ; wk(10)=tmp1L
movq MMWORD [wk(11)], mm0 ; wk(11)=tmp1H
; -- Final output stage
movq mm5, MMWORD [wk(0)] ; mm5=tmp10L
movq mm7, MMWORD [wk(1)] ; mm7=tmp10H
movq mm2, mm5
movq mm0, mm7
paddd mm5, mm3 ; mm5=data0L
paddd mm7, mm4 ; mm7=data0H
psubd mm2, mm3 ; mm2=data7L
psubd mm0, mm4 ; mm0=data7H
movq mm3, [GOTOFF(ebx,PD_DESCALE_P2)] ; mm3=[PD_DESCALE_P2]
paddd mm5, mm3
paddd mm7, mm3
psrad mm5, DESCALE_P2
psrad mm7, DESCALE_P2
paddd mm2, mm3
paddd mm0, mm3
psrad mm2, DESCALE_P2
psrad mm0, DESCALE_P2
packssdw mm5, mm7 ; mm5=data0=(00 10 20 30)
packssdw mm2, mm0 ; mm2=data7=(07 17 27 37)
movq mm4, MMWORD [wk(4)] ; mm4=tmp11L
movq mm3, MMWORD [wk(5)] ; mm3=tmp11H
movq mm7, mm4
movq mm0, mm3
paddd mm4, mm1 ; mm4=data1L
paddd mm3, mm6 ; mm3=data1H
psubd mm7, mm1 ; mm7=data6L
psubd mm0, mm6 ; mm0=data6H
movq mm1, [GOTOFF(ebx,PD_DESCALE_P2)] ; mm1=[PD_DESCALE_P2]
paddd mm4, mm1
paddd mm3, mm1
psrad mm4, DESCALE_P2
psrad mm3, DESCALE_P2
paddd mm7, mm1
paddd mm0, mm1
psrad mm7, DESCALE_P2
psrad mm0, DESCALE_P2
packssdw mm4, mm3 ; mm4=data1=(01 11 21 31)
packssdw mm7, mm0 ; mm7=data6=(06 16 26 36)
packsswb mm5, mm7 ; mm5=(00 10 20 30 06 16 26 36)
packsswb mm4, mm2 ; mm4=(01 11 21 31 07 17 27 37)
movq mm6, MMWORD [wk(6)] ; mm6=tmp12L
movq mm1, MMWORD [wk(7)] ; mm1=tmp12H
movq mm3, MMWORD [wk(10)] ; mm3=tmp1L
movq mm0, MMWORD [wk(11)] ; mm0=tmp1H
movq MMWORD [wk(0)], mm5 ; wk(0)=(00 10 20 30 06 16 26 36)
movq MMWORD [wk(1)], mm4 ; wk(1)=(01 11 21 31 07 17 27 37)
movq mm7, mm6
movq mm2, mm1
paddd mm6, mm3 ; mm6=data2L
paddd mm1, mm0 ; mm1=data2H
psubd mm7, mm3 ; mm7=data5L
psubd mm2, mm0 ; mm2=data5H
movq mm5, [GOTOFF(ebx,PD_DESCALE_P2)] ; mm5=[PD_DESCALE_P2]
paddd mm6, mm5
paddd mm1, mm5
psrad mm6, DESCALE_P2
psrad mm1, DESCALE_P2
paddd mm7, mm5
paddd mm2, mm5
psrad mm7, DESCALE_P2
psrad mm2, DESCALE_P2
packssdw mm6, mm1 ; mm6=data2=(02 12 22 32)
packssdw mm7, mm2 ; mm7=data5=(05 15 25 35)
movq mm4, MMWORD [wk(2)] ; mm4=tmp13L
movq mm3, MMWORD [wk(3)] ; mm3=tmp13H
movq mm0, MMWORD [wk(8)] ; mm0=tmp0L
movq mm5, MMWORD [wk(9)] ; mm5=tmp0H
movq mm1, mm4
movq mm2, mm3
paddd mm4, mm0 ; mm4=data3L
paddd mm3, mm5 ; mm3=data3H
psubd mm1, mm0 ; mm1=data4L
psubd mm2, mm5 ; mm2=data4H
movq mm0, [GOTOFF(ebx,PD_DESCALE_P2)] ; mm0=[PD_DESCALE_P2]
paddd mm4, mm0
paddd mm3, mm0
psrad mm4, DESCALE_P2
psrad mm3, DESCALE_P2
paddd mm1, mm0
paddd mm2, mm0
psrad mm1, DESCALE_P2
psrad mm2, DESCALE_P2
movq mm5, [GOTOFF(ebx,PB_CENTERJSAMP)] ; mm5=[PB_CENTERJSAMP]
packssdw mm4, mm3 ; mm4=data3=(03 13 23 33)
packssdw mm1, mm2 ; mm1=data4=(04 14 24 34)
movq mm0, MMWORD [wk(0)] ; mm0=(00 10 20 30 06 16 26 36)
movq mm3, MMWORD [wk(1)] ; mm3=(01 11 21 31 07 17 27 37)
packsswb mm6, mm1 ; mm6=(02 12 22 32 04 14 24 34)
packsswb mm4, mm7 ; mm4=(03 13 23 33 05 15 25 35)
paddb mm0, mm5
paddb mm3, mm5
paddb mm6, mm5
paddb mm4, mm5
movq mm2, mm0 ; transpose coefficients(phase 1)
punpcklbw mm0, mm3 ; mm0=(00 01 10 11 20 21 30 31)
punpckhbw mm2, mm3 ; mm2=(06 07 16 17 26 27 36 37)
movq mm1, mm6 ; transpose coefficients(phase 1)
punpcklbw mm6, mm4 ; mm6=(02 03 12 13 22 23 32 33)
punpckhbw mm1, mm4 ; mm1=(04 05 14 15 24 25 34 35)
movq mm7, mm0 ; transpose coefficients(phase 2)
punpcklwd mm0, mm6 ; mm0=(00 01 02 03 10 11 12 13)
punpckhwd mm7, mm6 ; mm7=(20 21 22 23 30 31 32 33)
movq mm5, mm1 ; transpose coefficients(phase 2)
punpcklwd mm1, mm2 ; mm1=(04 05 06 07 14 15 16 17)
punpckhwd mm5, mm2 ; mm5=(24 25 26 27 34 35 36 37)
movq mm3, mm0 ; transpose coefficients(phase 3)
punpckldq mm0, mm1 ; mm0=(00 01 02 03 04 05 06 07)
punpckhdq mm3, mm1 ; mm3=(10 11 12 13 14 15 16 17)
movq mm4, mm7 ; transpose coefficients(phase 3)
punpckldq mm7, mm5 ; mm7=(20 21 22 23 24 25 26 27)
punpckhdq mm4, mm5 ; mm4=(30 31 32 33 34 35 36 37)
pushpic ebx ; save GOT address
mov edx, JSAMPROW [edi+0*SIZEOF_JSAMPROW]
mov ebx, JSAMPROW [edi+1*SIZEOF_JSAMPROW]
movq MMWORD [edx+eax*SIZEOF_JSAMPLE], mm0
movq MMWORD [ebx+eax*SIZEOF_JSAMPLE], mm3
mov edx, JSAMPROW [edi+2*SIZEOF_JSAMPROW]
mov ebx, JSAMPROW [edi+3*SIZEOF_JSAMPROW]
movq MMWORD [edx+eax*SIZEOF_JSAMPLE], mm7
movq MMWORD [ebx+eax*SIZEOF_JSAMPLE], mm4
poppic ebx ; restore GOT address
add esi, byte 4*SIZEOF_JCOEF ; wsptr
add edi, byte 4*SIZEOF_JSAMPROW
dec ecx ; ctr
jnz near .rowloop
emms ; empty MMX state
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 32
|
CODE SEGMENT
ASSUME CS:CODE,DS:CODE
ORG 100H
MAIN: MOV AX,CS
MOV DS,AX
MOV SI,0
MOV DI,0
MOV BX,0
JMP L2
L1: INC SI
L2: MOV AL,A1[SI]
MOV CL,A2[DI]
MUL CL
ADD DL,AL
ADD DI,N
CMP DI,9; number of total elements of input matrix
JL L1
MOV B1[BX],DL
MOV DL,0
INC BX
CMP BX,9; number of total elements of input matrix
JE FIN
CMP BX,M
JGE L3
MOV AX,M
MOV CX,N
SUB AX,CX
MOV SI,AX
JMP L4
L3: MOV SI,M
MOV AX,M
MOV CX,N
ADD AX,CX
MOV M,AX
L4: INC K
MOV AX,K
CMP AX,N
JL L5
MOV K,0
L5: MOV DI,K
JMP L2
FIN: INT 3
ORG 600H
B1 DB ?,?,?, ?,?,?, ?,?,?
A1 DB 1,1,2, 1,2,3, 0,1,1; input Matrix1 (square)
A2 DB 1,2,0, 1,0,2, 4,2,0; input Matrix2 (square)
N DW 3; order of input matrix
M DW 3; order of input matrix
K DW 0
CODE ENDS
END MAIN
|
#include <string>
#include "common/runtime/runtime_impl.h"
#include "common/runtime/uuid_util.h"
#include "test/test_common/test_base.h"
namespace Envoy {
TEST(UUIDUtilsTest, mod) {
uint64_t result;
EXPECT_TRUE(UuidUtils::uuidModBy("00000000-0000-0000-0000-000000000000", result, 100));
EXPECT_EQ(0, result);
EXPECT_TRUE(UuidUtils::uuidModBy("00000001-0000-0000-0000-000000000000", result, 100));
EXPECT_EQ(1, result);
EXPECT_TRUE(UuidUtils::uuidModBy("0000000f-0000-0000-0000-00000000000a", result, 100));
EXPECT_EQ(15, result);
EXPECT_FALSE(UuidUtils::uuidModBy("", result, 100));
EXPECT_TRUE(UuidUtils::uuidModBy("000000ff-0000-0000-0000-000000000000", result, 100));
EXPECT_EQ(55, result);
EXPECT_TRUE(UuidUtils::uuidModBy("000000ff-0000-0000-0000-000000000000", result, 10000));
EXPECT_EQ(255, result);
EXPECT_TRUE(UuidUtils::uuidModBy("a0090100-0012-0110-00ff-0c00400600ff", result, 137));
EXPECT_EQ(8, result);
EXPECT_TRUE(UuidUtils::uuidModBy("ffffffff-0012-0110-00ff-0c00400600ff", result, 100));
EXPECT_EQ(95, result);
EXPECT_TRUE(UuidUtils::uuidModBy("ffffffff-0012-0110-00ff-0c00400600ff", result, 10000));
EXPECT_EQ(7295, result);
}
TEST(UUIDUtilsTest, checkDistribution) {
Runtime::RandomGeneratorImpl random;
const int mod = 100;
const int required_percentage = 11;
int total_samples = 0;
int interesting_samples = 0;
for (int i = 0; i < 500000; ++i) {
std::string uuid = random.uuid();
const char c = uuid[19];
ASSERT_TRUE(uuid[14] == '4'); // UUID version 4 (random)
ASSERT_TRUE(c == '8' || c == '9' || c == 'a' || c == 'b'); // UUID variant 1 (RFC4122)
uint64_t value;
ASSERT_TRUE(UuidUtils::uuidModBy(uuid, value, mod));
if (value < required_percentage) {
interesting_samples++;
}
total_samples++;
}
EXPECT_NEAR(required_percentage / 100.0, interesting_samples * 1.0 / total_samples, 0.002);
}
TEST(UUIDUtilsTest, DISABLED_benchmark) {
Runtime::RandomGeneratorImpl random;
for (int i = 0; i < 100000000; ++i) {
random.uuid();
}
}
TEST(UUIDUtilsTest, setAndCheckTraceable) {
Runtime::RandomGeneratorImpl random;
std::string uuid = random.uuid();
EXPECT_EQ(UuidTraceStatus::NoTrace, UuidUtils::isTraceableUuid(uuid));
EXPECT_TRUE(UuidUtils::setTraceableUuid(uuid, UuidTraceStatus::Sampled));
EXPECT_EQ(UuidTraceStatus::Sampled, UuidUtils::isTraceableUuid(uuid));
EXPECT_TRUE(UuidUtils::setTraceableUuid(uuid, UuidTraceStatus::Client));
EXPECT_EQ(UuidTraceStatus::Client, UuidUtils::isTraceableUuid(uuid));
EXPECT_TRUE(UuidUtils::setTraceableUuid(uuid, UuidTraceStatus::Forced));
EXPECT_EQ(UuidTraceStatus::Forced, UuidUtils::isTraceableUuid(uuid));
EXPECT_TRUE(UuidUtils::setTraceableUuid(uuid, UuidTraceStatus::NoTrace));
EXPECT_EQ(UuidTraceStatus::NoTrace, UuidUtils::isTraceableUuid(uuid));
std::string invalid_uuid = "";
EXPECT_FALSE(UuidUtils::setTraceableUuid(invalid_uuid, UuidTraceStatus::Forced));
}
} // namespace Envoy
|
#include<iostream>
using namespace std;
int main(){
int
data[5] = {1,2,5,8,10},
total = 0;
for (int count : data) {
cout << data[count] << endl;
}
cout << total << endl;
}
|
; A141413: Inverse binomial transform of A140962.
; 0,-1,1,-3,9,-27,81,-243,729,-2187,6561,-19683,59049,-177147,531441,-1594323,4782969,-14348907,43046721,-129140163,387420489,-1162261467,3486784401,-10460353203,31381059609,-94143178827,282429536481,-847288609443,2541865828329,-7625597484987,22876792454961,-68630377364883,205891132094649,-617673396283947,1853020188851841,-5559060566555523
sub $0,2
mov $2,1
mov $3,-3
lpb $2,1
add $0,$2
lpb $3,1
sub $1,1
mul $3,$0
lpe
add $0,$2
mov $2,$3
pow $2,$3
sub $2,1
lpe
pow $3,$0
add $1,$3
|
; A010513: Decimal expansion of square root of 60.
; 7,7,4,5,9,6,6,6,9,2,4,1,4,8,3,3,7,7,0,3,5,8,5,3,0,7,9,9,5,6,4,7,9,9,2,2,1,6,6,5,8,4,3,4,1,0,5,8,3,1,8,1,6,5,3,1,7,5,1,4,7,5,3,2,2,2,6,9,6,6,1,8,3,8,7,3,9,5,8,0,6,7,0,3,8,5,7,4,7,5,3,7,1,7,3,4,7,0,3,5
mov $1,1
mov $2,1
mov $3,$0
add $3,8
mov $4,$0
add $4,3
mul $4,2
mov $7,10
pow $7,$4
mov $9,10
lpb $3
mov $4,$2
pow $4,2
mul $4,60
mov $5,$1
pow $5,2
add $4,$5
mov $6,$1
mov $1,$4
mul $6,$2
mul $6,2
mov $2,$6
mov $8,$4
div $8,$7
max $8,2
div $1,$8
div $2,$8
sub $3,1
lpe
mov $3,$9
pow $3,$0
div $2,$3
div $1,$2
mod $1,$9
mov $0,$1
|
; A052295: a(n) = (n*(n+1)/2)!.
; Submitted by Jon Maiga
; 1,1,6,720,3628800,1307674368000,51090942171709440000,304888344611713860501504000000,371993326789901217467999448150835200000000,119622220865480194561963161495657715064383733760000000000,12696403353658275925965100847566516959580321051449436762275840000000000000
seq $0,105335 ; a(n) = n*(n+1)/2 mod 64.
seq $0,142 ; Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters).
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1993 -- All Rights Reserved
PROJECT:
MODULE:
FILE: prefcompSerialValue.asm
AUTHOR: Adam de Boor, Jan 19, 1993
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Adam 1/19/93 Initial revision
DESCRIPTION:
Implementation of PrefCompSerialValueClass, a subclass of PrefValue
used to adjust the interrupt level of a serial port.
$Id: prefcompSerialValue.asm,v 1.1 97/04/05 01:33:22 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompCode segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PCSVSetSpecialValue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the PCSVS_SPECIAL_VALUE field to that passed
CALLED BY: (INTERNAL)
PASS: al = PrefCompSerialValueSpecialValue to set
*ds:si = PrefCompSerialValue object
RETURN: nothing
DESTROYED: ax
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PCSVSetSpecialValue proc near
class PrefCompSerialValueClass
uses cx, di, dx, es
.enter
mov di, ds:[si]
add di, ds:[di].PrefCompSerialValue_offset
mov cl, offset PCSVS_SPECIAL_VALUE
mov ah, al
shl al, cl
CheckHack <offset PCSVS_SPECIAL_VALUE eq 6 and \
width PCSVS_SPECIAL_VALUE eq 2>
andnf ds:[di].PCSVI_state, not mask PCSVS_SPECIAL_VALUE
ornf ds:[di].PCSVI_state, al
tst ah
jnz notifySpui
done:
.leave
ret
notifySpui:
;
; Force a visual update, in case we're not coming up for the first time.
; This ugly piece o' code simply sends the MSG_GEN_VALUE_SET_VALUE to
; the specific UI, setting the thing to the current value. It's what
; Chris suggested I use...
;
mov di, ds:[si]
add di, ds:[di].Gen_offset
movwwf dxcx, ds:[di].GVLI_value
segmov es, <segment GenValueClass>, di
mov di, offset GenValueClass
mov ax, MSG_GEN_VALUE_SET_VALUE
call ObjCallSuperNoLock
jmp done
PCSVSetSpecialValue endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueLoadOptions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Fetch the interrupt level for the port from the serial
driver and set our state accordingly.
CALLED BY: MSG_META_LOAD_OPTIONS
PASS: *ds:si = PrefCompSerialValue object
RETURN: nothing
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS: original value set
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/18/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueLoadOptions method dynamic PrefCompSerialValueClass,
MSG_META_LOAD_OPTIONS
.enter
;
; Load the value from the .ini file, in case driver has no clue.
;
mov di, offset PrefCompSerialValueClass
CallSuper MSG_META_LOAD_OPTIONS
;
; Set the maximum interrupt level based on whether there's a second
; interrupt controller in the machine. Must do this before getting
; the port's interrupt level so if it's > 7, it doesn't get truncated
; by the max being only 7...
;
call SysGetConfig
test al, mask SCF_2ND_IC
mov dx, 7
jz haveMax
mov dx, 15
haveMax:
clr cx ; no fraction
mov ax, MSG_GEN_VALUE_SET_MAXIMUM
call ObjCallInstanceNoLock
;
; Now see if the driver has an opinion.
;
push ds, si
mov bx, handle serial
call GeodeInfoDriver
segmov es, ds
mov bp, si
pop ds, si
mov di, ds:[si]
add di, ds:[di].PrefCompSerialValue_offset
mov bx, ds:[di].PCSVI_portNum
mov di, DR_SERIAL_STAT_PORT
call es:[bp].DIS_strategy
jc off
cmp al, -1
je indeterminate
;
; Value is known. Make sure we know it's known, then set our value
; according to what the driver thinks, as it may be different from
; what the user thought.
;
cbw
mov_tr cx, ax
mov al, PCSVSV_KNOWN
call PCSVSetSpecialValue
clr bp ; not indeterminate
mov ax, MSG_PREF_VALUE_SET_ORIGINAL_VALUE
call ObjCallInstanceNoLock
done:
mov di, ds:[si]
add di, ds:[di].PrefCompSerialValue_offset
mov al, ds:[di].PCSVI_state
mov ah, al
andnf ax, ((not mask PCSVS_ORIG_SPECIAL_VALUE) and 0xff) or \
(mask PCSVS_SPECIAL_VALUE shl 8)
CheckHack <offset PCSVS_SPECIAL_VALUE - \
offset PCSVS_ORIG_SPECIAL_VALUE eq 2>
shr ah
shr ah
or al, ah
mov ds:[di].PCSVI_state, al
.leave
ret
off:
;
; Make sure we know the thing is off. We leave the value as fetched
; from the .ini file.
;
mov al, PCSVSV_OFF
call PCSVSetSpecialValue
forceUpdate:
jmp done
indeterminate:
;
; Make sure we know we don't know. We leave the value as fetched from
; the .ini file.
;
mov al, PCSVSV_UNKNOWN
call PCSVSetSpecialValue
jmp forceUpdate
PrefCompSerialValueLoadOptions endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueGetValueText
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Fetch the textual representation of a value.
CALLED BY: MSG_GEN_VALUE_GET_VALUE_TEXT
PASS: *ds:si = PrefCompSerialValue object
cx:dx = buffer in which to place the result.
bp = GenValueType
RETURN: cx:dx = filled
DESTROYED: ax, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueGetValueText method dynamic PrefCompSerialValueClass,
MSG_GEN_VALUE_GET_VALUE_TEXT
cmp bp, GVT_LONG
je returnOffString ; we assume the "Off" string is longer
; than anything else we can produce
cmp bp, GVT_VALUE
jne passItUp ; if not current value, just let our
; superclass handle it
test ds:[di].PCSVI_state, mask PCSVS_SPECIAL_VALUE
jz passItUp ; if want current value and port isn't
; in special state, let superclass
; handle it
CheckHack <PCSVSV_UNKNOWN eq 2 and \
offset PCSVS_SPECIAL_VALUE eq 6>
js isUnknown
returnOffString:
mov bx, handle Strings
call MemLock
mov ds, ax
assume ds:Strings
mov si, ds:[SerialValueOffString]
movdw esdi, cxdx
ChunkSizePtr ds, si, cx
rep movsb
done:
mov cx, es
call MemUnlock
assume ds:nothing
ret
passItUp:
mov di, offset PrefCompSerialValueClass
GOTO ObjCallSuperNoLock
isUnknown:
;
; Get the normal text for the thing.
;
mov di, offset PrefCompSerialValueClass
call ObjCallSuperNoLock
;
; Now append the SerialValueUnknownString to that.
;
mov bx, handle Strings
call MemLock
mov ds, ax
assume ds:Strings
mov si, ds:[SerialValueUnknownString]
movdw esdi, cxdx
clr ax
mov cx, -1
LocalFindChar ; find null byte
LocalPrevChar esdi ; point back to null
ChunkSizePtr ds, si, cx
rep movsb
jmp done
assume ds:nothing
PrefCompSerialValueGetValueText endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueGetTextFilter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Return the set of characters we allow the user to type
into us.
CALLED BY: MSG_GEN_VALUE_GET_TEXT_FILTER
PASS: *ds:si = PrefCompSerialValue object
RETURN: al = VisTextFilters
DESTROYED: ah, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueGetTextFilter method dynamic PrefCompSerialValueClass,
MSG_GEN_VALUE_GET_TEXT_FILTER
.enter
mov al, mask VTF_NO_SPACES or \
mask VTF_NO_TABS or \
VTFC_ALPHA_NUMERIC shl offset VTF_FILTER_CLASS
.leave
ret
PrefCompSerialValueGetTextFilter endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueSetValueFromText
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the value for the range from the given text.
CALLED BY: MSG_GEN_VALUE_SET_VALUE_FROM_TEXT
PASS: *ds:si PrefCompSerialValue object
cx:dx = pointer to text
bp = GenValueType
RETURN: carry set if value instance data changed.
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueSetValueFromText method dynamic PrefCompSerialValueClass,
MSG_GEN_VALUE_SET_VALUE_FROM_TEXT
cmp bp, GVT_VALUE
jne passItUp
;
; Compare passed string with the one indicating the port is off.
;
mov bx, handle Strings
push ds, si, es
call MemLock
mov es, ax
assume es:Strings
mov di, es:[SerialValueOffString] ; es:di <- string2
movdw dssi, cxdx ; ds:si <- string1
clr cx ; null terminated
call LocalCmpStringsNoCase
mov cx, ds ; restore cx for possible super-
; class call
pop ds, si, es
call MemUnlock
assume es:nothing
jne clearOffPassItUp
;
; Set the PCSVS_OFF flag, mark ourselves dirty and return carry set to
; indicate we changed the instance data.
;
mov al, PCSVSV_OFF
call PCSVSetSpecialValue
call ObjMarkDirty
doneModified:
stc
done:
ret
clearOffPassItUp:
mov ax, MSG_GEN_VALUE_SET_VALUE_FROM_TEXT
mov di, offset PrefCompSerialValueClass
call ObjCallSuperNoLock
jnc done
mov al, PCSVSV_KNOWN
call PCSVSetSpecialValue
jmp doneModified
passItUp:
mov di, offset PrefCompSerialValueClass
GOTO ObjCallSuperNoLock
PrefCompSerialValueSetValueFromText endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueIncrement
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Interception of increment message to switch the port OFF
if appropriate.
CALLED BY: MSG_GEN_VALUE_INCREMENT
PASS: *ds:si = PrefCompSerialValue object
ds:di = PrefCompSerialValueInstance
RETURN: carry set if value instance data changed
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueIncrement method dynamic PrefCompSerialValueClass,
MSG_GEN_VALUE_INCREMENT
test ds:[di].PCSVI_state, mask PCSVS_SPECIAL_VALUE
js wasUnknown
jz checkForSwitchOff
;
; Port is now off. Change to minimum.
;
mov al, PCSVSV_KNOWN
call PCSVSetSpecialValue
mov di, ds:[si]
add di, ds:[di].GenValue_offset
movwwf dxcx, ds:[di].GVLI_value ; use default port
cmp dx, PCSV_HACK_OFF_VALUE ; value if set
jne doneModified
mov dx, PCSV_ACTUAL_MIN
clr cx
doneModified:
mov ax, MSG_GEN_VALUE_SET_VALUE
clr bp
call ObjCallInstanceNoLock
stc
ret
wasUnknown:
;
; State was unknown, but user is changing it, so switch to known, on
; the assumption user's not an ass (a dangerous assumption, at best)
;
mov al, PCSVSV_KNOWN
call PCSVSetSpecialValue
checkForSwitchOff:
;
; If current value is maximum, this means we should cycle back to off
;
mov di, ds:[si]
add di, ds:[di].GenValue_offset
mov ax, ds:[di].GVLI_maximum.WWF_int
cmp ds:[di].GVLI_value.WWF_int, ax
je switchToOff
mov ax, MSG_GEN_VALUE_INCREMENT
mov di, offset PrefCompSerialValueClass
GOTO ObjCallSuperNoLock
switchToOff:
mov al, PCSVSV_OFF
call PCSVSetSpecialValue
mov dx, PCSV_HACK_OFF_VALUE
clr cx
jmp doneModified
PrefCompSerialValueIncrement endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueDecrement
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Interception of decrement message to switch the port OFF
if appropriate.
CALLED BY: MSG_GEN_VALUE_DECREMENT
PASS: *ds:si = PrefCompSerialValue object
ds:di = PrefCompSerialValueInstance
RETURN: carry set if value instance data changed
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueDecrement method dynamic PrefCompSerialValueClass,
MSG_GEN_VALUE_DECREMENT
test ds:[di].PCSVI_state, mask PCSVS_SPECIAL_VALUE
js wasUnknown
jz checkForSwitchOff
;
; Port is now off. Change to maximum.
;
mov al, PCSVSV_KNOWN
call PCSVSetSpecialValue
mov di, ds:[si]
add di, ds:[di].GenValue_offset
movwwf dxcx, ds:[di].GVLI_value
cmp dx, PCSV_HACK_OFF_VALUE ; use default value for port
jne doneModified ; if set.
movwwf dxcx, ds:[di].GVLI_maximum
doneModified:
mov ax, MSG_GEN_VALUE_SET_VALUE
clr bp
call ObjCallInstanceNoLock
stc
ret
wasUnknown:
;
; State was unknown, but user is changing it, so switch to known, on
; the assumption user's not an ass (a dangerous assumption, at best)
;
mov al, PCSVSV_KNOWN
call PCSVSetSpecialValue
checkForSwitchOff:
;
; If current value is minimum, this means we should cycle back to off
;
mov di, ds:[si]
add di, ds:[di].GenValue_offset
cmp ds:[di].GVLI_value.WWF_int, PCSV_ACTUAL_MIN
je switchToOff
passItUp:
mov ax, MSG_GEN_VALUE_DECREMENT
mov di, offset PrefCompSerialValueClass
GOTO ObjCallSuperNoLock
switchToOff:
mov al, PCSVSV_OFF
call PCSVSetSpecialValue
jmp passItUp
PrefCompSerialValueDecrement endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueReset
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Reset value to original value stored.
CALLED BY: MSG_GEN_RESET
PASS: *ds:si = PrefCompSerialValue object
RETURN: nothing
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueReset method dynamic PrefCompSerialValueClass, MSG_GEN_RESET
;
; Take care of our special state first.
;
mov cl, ds:[di].PCSVI_state
mov ch, cl
andnf cx, (mask PCSVS_ORIG_SPECIAL_VALUE shl 8) or \
((not mask PCSVS_SPECIAL_VALUE) and 0xff)
CheckHack <offset PCSVS_SPECIAL_VALUE - \
offset PCSVS_ORIG_SPECIAL_VALUE eq 2>
shl ch
shl ch
or cl, ch
mov ds:[di].PCSVI_state, cl
;
; Then let our superclass revert its state.
;
mov di, offset PrefCompSerialValueClass
GOTO ObjCallSuperNoLock
PrefCompSerialValueReset endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueSaveOptions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Save our value to the .ini file and communicate it to the
serial driver as well.
CALLED BY: MSG_GEN_SAVE_OPTIONS
PASS: *ds:si = PrefCompSerialValue object
ds:di = PrefCompSerialValueInstance
ss:bp = GenOptionsParams
RETURN: nothing
DESTROYED:
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueSaveOptions method dynamic PrefCompSerialValueClass,
MSG_GEN_SAVE_OPTIONS
.enter
test ds:[di].PCSVI_state, mask PCSVS_SPECIAL_VALUE
jz getValue
mov cx, -1 ; assume shut off
jns haveValue
; if unknown, don't touch it
done:
.leave
ret
getValue:
add bx, ds:[bx].GenValue_offset
mov cx, ds:[bx].GVLI_value.WWF_int
haveValue:
;
; First verify things with the serial driver.
;
push bp, ds, di, cx, si
mov ax, ds:[di].PCSVI_portBase
mov bx, handle serial
call GeodeInfoDriver
mov bx, -1 ; Not PCMCIA, we assume
mov di, DR_SERIAL_DEFINE_PORT
call ds:[si].DIS_strategy
pop bp, ds, di, cx, si
jc error
;
; Seems ok. Write the value to the ini file.
;
mov_tr ax, cx ; save irq #
segmov ds, ss, cx ; ds, cx <- ss
lea si, ss:[bp].GOP_category
lea dx, ss:[bp].GOP_key
mov_tr bp, ax ; bp <- value to write
call InitFileWriteInteger
jmp done
error:
sub sp, size StandardDialogParams
mov bp, sp
mov ss:[bp].SDP_customFlags,CustomDialogBoxFlags <
0, ; CDBF_SYSTEM_MODAL
CDT_ERROR, ; CDBF_TYPE
GIT_NOTIFICATION, ; CDBF_RESPONSE_TYPE
0 ; CDBF_DESTRUCTIVE_ACTION
>
mov di, offset SerialNoSuchDevice
cmp ax, STREAM_NO_DEVICE
je haveErrString
mov di, offset SerialDeviceInUse
EC < cmp ax, STREAM_DEVICE_IN_USE >
EC < WARNING_NE UNHANDLED_STREAM_ERROR_CODE_FROM_DEFINE_PORT>
haveErrString:
mov bx, handle Strings
call MemLock
mov es, ax
mov ss:[bp].SDP_customString.segment, ax
mov di, es:[di]
mov ss:[bp].SDP_customString.offset, di
mov di, ds:[si]
add di, ds:[di].Gen_offset
mov di, ds:[di].GI_visMoniker
EC < tst di >
EC < ERROR_Z NEED_MONIKER_FOR_ERROR_MESSAGE >
mov di, ds:[di]
add di, offset VM_data + offset VMT_text
movdw ss:[bp].SDP_stringArg1, dsdi
clr ax
mov ss:[bp].SDP_helpContext.segment, ax
mov ss:[bp].SDP_customTriggers.segment, ax
mov ss:[bp].SDP_stringArg2.segment, ax
call UserStandardDialog
jmp done
PrefCompSerialValueSaveOptions endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrefCompSerialValueHasStateChanged
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: See if the state of the object has changed, from our
perspective.
CALLED BY: MSG_PREF_HAS_STATE_CHANGED
PASS: *ds:si = PrefCompSerialValue object
ds:di = PrefCompSerialValueInstance
RETURN: carry set if anything changed
DESTROYED: ax, cx, dx, bp
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrefCompSerialValueHasStateChanged method dynamic PrefCompSerialValueClass,
MSG_PREF_HAS_STATE_CHANGED
mov cl, ds:[di].PCSVI_state
mov ch, cl
andnf cx, mask PCSVS_ORIG_SPECIAL_VALUE or \
(mask PCSVS_SPECIAL_VALUE shl 8)
CheckHack <offset PCSVS_SPECIAL_VALUE - \
offset PCSVS_ORIG_SPECIAL_VALUE eq 2>
shl cl
shl cl
cmp cl, ch
je passItUp
stc
ret
passItUp:
mov di, offset PrefCompSerialValueClass
GOTO ObjCallSuperNoLock
PrefCompSerialValueHasStateChanged endm
PrefCompCode ends
|
#include <json.hpp>
#include "Version.h"
#include "VersionEndPoint.h"
using json = nlohmann::json;
API::VersionEndPoint::VersionEndPoint (const std::string& inPath) :
HTTP::EndPoint (inPath)
{
}
API::VersionEndPoint::~VersionEndPoint () = default;
void API::VersionEndPoint::Get (const HTTP::Request& inRequest, HTTP::Response& outResponse) {
json j;
j["application"] = OS::Version::GetApplicationName ();
j["version"] = OS::Version::GetApplicationVersion ();
outResponse.mCode = HTTP::Code::OK;
outResponse.SetBody (j.dump (), "application/json");
}
|
//===- ELFAttributeValue.cpp ----------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "mcld/Target/ELFAttributeValue.h"
#include <llvm/Support/ErrorHandling.h>
#include "mcld/Support/LEB128.h"
namespace mcld {
size_t ELFAttributeValue::getSize() const {
size_t size = 0;
if (isIntValue())
size += leb128::size<uint32_t>(m_IntValue);
if (isStringValue())
size += m_StringValue.length() + 1 /* for NULL-terminator */;
if (size <= 0)
// unknown type of the value
llvm::report_fatal_error("Unknown type of attribtue value!");
return size;
}
bool ELFAttributeValue::isDefaultValue() const {
if (isUninitialized()) {
// Uninitialized attribute means default value
return true;
} else {
if (isIntValue() && (m_IntValue != 0))
return false;
if (isStringValue() && !m_StringValue.empty())
return false;
// The value hold in the storage is the "default value by default" (i.e., 0
// for int type, empty string for string type), but we need to check whether
// the "default value" is defined (that is, hasNoDefault() = false.)
return !hasNoDefault();
}
// unreachable
}
bool ELFAttributeValue::equals(const ELFAttributeValue& pValue) const {
if ((pValue.type() != m_Type) || isUninitialized())
return false;
if (isIntValue() && (m_IntValue != pValue.getIntValue()))
return false;
if (isStringValue() && (m_StringValue != pValue.getStringValue()))
return false;
return true;
}
} // namespace mcld
|
; Accept digit (from 1-9), display serires from num1 to num2
.MODEL SMALL
.STACK 100
.DATA
p1 DB "Enter 1st digit: $"
p2 DB "Enter 2nd digit: $"
NL DB 13, 10, "$"
d1 DB ?
d2 DB ?
CHAR DB ?
.CODE
MAIN PROC
MOV AX,@DATA
MOV DS,AX
MOV AH, 09H
LEA DX, p1
INT 21H
MOV AH, 01H
INT 21H
MOV CHAR, AL
SUB AL, "1"
MOV d1, AL
CALL NEWLINE
MOV AH, 09H
LEA DX, p1
INT 21H
MOV AH, 01H
INT 21H
SUB AL, "0"
MOV d2, AL
CALL NEWLINE
MOV CL, d2
SUB CL, d1
MOV CH, 0
DISP:
MOV AH, 02H
MOV DL, CHAR
INT 21H
INC CHAR
LOOP DISP
MOV AX,4C00H
INT 21H
MAIN ENDP
NEWLINE PROC
MOV AH, 09H
LEA DX, NL
INT 21H
RET
NEWLINE ENDP
END MAIN |
; A292246: Base-2 expansion of a(n) encodes the steps where numbers of the form 3k+2 are encountered when map x -> A253889(x) is iterated down to 1, starting from x=n.
; 0,1,0,2,3,0,4,1,2,14,5,12,6,7,8,2,1,0,0,9,26,22,3,20,6,5,16,10,29,10,4,11,30,2,25,60,56,13,28,54,15,48,24,17,44,8,5,12,38,3,30,26,1,24,20,1,18,6,19,62,14,53,4,14,45,0,42,7,124,118,41,50,58,13,116,106,11,40,104,33,32,98,21,92,6,59,88,18,21,82,76,9,34,36,23,74,64,61,62,58
mul $0,2
seq $0,64989 ; Multiplicative with a(2^e) = 1 and a(p^e) = prevprime(p)^e for odd primes p.
seq $0,261693 ; Irregular triangle read by rows in which row n lists the positive odd numbers in decreasing order starting with 2^n - 1. T(0, 1) = 0 and T(n, k) for n >= 1, 1 <= k <= 2^(n-1).
div $0,2
|
; A235963: n appears (n+1)/(1 + (n mod 2)) times.
; 0,1,2,2,2,3,3,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,8,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13
mov $2,$0
mul $2,2
lpb $2,1
add $1,1
lpb $1,1
add $3,$0
mov $1,$3
lpe
mov $0,2
sub $2,$1
trn $2,1
lpe
|
include \masm32\include\masm32rt.inc
.data
Node STRUCT
value DWORD ? ; value of the node
next DWORD ? ; pointer to the next node
Node ENDS
Queue STRUCT
head DWORD ? ; first out (Node*)
tail DWORD ? ; last in (Node*)
count DWORD ? ; guess (unsigned int)
Queue ENDS
Stack STRUCT
pointer DWORD ? ; Node*
count DWORD ? ; unsigned int
Stack ENDS
List STRUCT
items DWORD ? ; pointer to array
count DWORD ? ; unsigned int
List ENDS
;;;; NODE ;;;;
new_node PROTO value:DWORD,next:DWORD
delete_node PROTO node:DWORD
;;;; QUEUE ;;;;
queue_push PROTO queue:DWORD, value:DWORD
queue_pop PROTO queue:DWORD
delete_queue PROTO queue:DWORD
;;;; STACK ;;;;
stack_push PROTO queue:DWORD, value:DWORD
stack_pop PROTO queue:DWORD
delete_stack PROTO queue:DWORD
;;;; BOTH STACK AND QUEUE
peek PROTO object:DWORD
;;;; BIN TREE ;;;;
;;;; lIST ;;;;
list_insert PROTO list:DWORD,value:DWORD
list_set PROTO list:DWORD, index:DWORD, value:DWORD
list_index_of PROTO list:DWORD, item:DWORD
list_delete_at PROTO list:DWORD, index:DWORD
list_get_item PROTO list:DWORD, index:DWORD
delete_list PROTO list:DWORD
.code
;;;; NODE ;;;;
new_node PROC ,value:DWORD, next:DWORD ; creates a node and returns a pointer
invoke Alloc,SIZEOF Node ; allocate node
push value
pop DWORD PTR [eax] ; initialize value
push next
pop DWORD PTR [eax+4] ; initialize next
ret
new_node ENDP
delete_node PROC, node:DWORD ; deletes the node and all it's children
push ebx
push edx
push ecx
push eax
push node ; push the node to go to ebx at first
delete_child_loop:
pop ebx ; get the current node pointer
push DWORD PTR [ebx+4] ; push the next pointer
invoke Free,ebx ; delete the current node
cmp DWORD PTR [esp],NULL ; stop if the next node is a nullptr
jne delete_child_loop
pop eax
pop ecx
pop edx
pop ebx
ret
delete_node ENDP
;;;; QUEUE ;;;;
queue_push PROC, queue:DWORD, value:DWORD ; add an element to the end of the queue
pusha
invoke new_node,value,NULL ; eax = new Node(value = value,next = NULL)
mov ebx,queue
inc DWORD PTR [ebx+8] ; count++
cmp DWORD PTR [ebx+8],1 ; queue is empty
je HandleNull
mov edx,[ebx+4] ; edx is a pointer to tail
mov [edx+4],eax ; tail.next = new node
jmp final
HandleNull: ; if head == null
mov [ebx],eax ; queue.head is the new node
final:
mov [ebx+4],eax ; queue.tail is the new node
popa
ret
queue_push ENDP
queue_pop PROC,queue:DWORD ; retrives an element from the beginning of the queue
mov eax,queue
cmp DWORD PTR [eax+8],0 ; if count == 0 return null
jne notNull
mov eax,NULL
ret
notNull:
dec DWORD PTR [eax+8] ; count--
mov eax,[eax] ; pointer to head
mov eax,[eax] ; head.value
pusha
mov ebx,queue
mov edx,[ebx] ; edx = queue.head
mov edx,[edx+4] ; head.next
push edx
invoke Free,[ebx] ; delete node
pop edx
mov [ebx],edx ; queue.head = queue.head.next
popa
finish:
ret
queue_pop ENDP
delete_queue PROC, queue:DWORD
pusha
mov ebx,queue
mov ecx,[ebx+8] ; queue.count
push DWORD PTR[ebx]
delete_nodes_loop:
pop ebx
push DWORD PTR [ebx+4] ; ebx = ebx.next
invoke Free,ebx ; delete node
loop delete_nodes_loop
invoke Free,queue
popa
ret
delete_queue ENDP
;;;; STACK ;;;;
stack_push PROC, stack:DWORD, value:DWORD
pusha
mov ebx,stack
invoke new_node,value,[ebx] ; eax = new Node(value = value,next = stack.pointer)
mov ebx,stack
inc DWORD PTR [ebx+4] ; count++
mov [ebx],eax ; pointer = new Node(value,old pointer)
final:
popa
ret
stack_push ENDP
stack_pop PROC,stack:DWORD
mov eax,stack
cmp DWORD PTR [eax+4],0 ; if count is 0
jne notNull
mov eax,NULL
ret
notNull:
dec DWORD PTR [eax+4]
mov eax,[eax] ; pointer to stack pointer
mov eax,[eax] ; pointer.value
pusha
mov ebx,stack
mov edx,[ebx] ; edx = stack.pointer
mov edx,[edx+4] ; stack.next
push edx ; push stack.pointer.next
push ebx
invoke Free,[ebx] ; delete node
pop ebx
pop DWORD PTR [ebx] ; stack.pointer = stack.pointer.next
popa
finish:
ret
stack_pop ENDP
delete_stack PROC, stack:DWORD
pusha
mov ebx,stack
mov ecx,[ebx+4] ; stack.count
push DWORD PTR [ebx]
delete_nodes_loop:
pop ebx
push DWORD PTR [ebx+4] ; ebx = ebx.next
invoke Free,ebx ; delete node
loop delete_nodes_loop
invoke Free,stack
popa
ret
delete_stack ENDP
;;;; BOTH ;;;;
peek PROC,object:DWORD ; works on both Queue and Stack
mov eax,object
mov eax,[eax] ; pointer to head
cmp eax,NULL
je finish
mov eax,[eax] ; head.value
finish:
ret
peek ENDP
;;;; LIST ;;;;
list_insert proc, list:DWORD,value:DWORD ; adds the value to the end of the list
pusha
mov ebx,list
inc DWORD PTR [ebx+4] ; count++
mov ecx,[ebx+4]
shl ecx,2 ; count * sizeof dword
invoke Alloc, ecx ; allocate new memory
mov edi,eax ; destination = new array
mov ebx,list
mov esi,[ebx] ; source = old array
mov ecx,[ebx+4]
dec ecx ; ecx = count-1
push es
push ds ; data to extra for movsd
pop es ; flashbacks from codeguru :)
rep movsd ; copy from old array to new
pop es ; restore old extra segment
push value
pop DWORD PTR [edi] ; last element = value
invoke Free, [ebx] ; delete old array
mov ebx,list
mov ecx,[ebx+4]
dec ecx
shl ecx,2 ; ecx *= 4
sub edi,ecx ; beginning of the new array
mov [ebx],edi
popa
ret
list_insert ENDP
list_get_item PROC,list:DWORD,index:DWORD ; return the item at the index
push ebx
mov ebx,list
mov ebx,[ebx] ; items array pointer
mov eax,index
shl eax,2
mov eax,[ebx+eax] ; linear address of items array[index]
pop ebx
ret
list_get_item ENDP
list_set PROC,list:DWORD,index:DWORD,value:DWORD ; sets the item at the index to the value
push eax
push ebx
mov ebx,list
mov ebx,[ebx] ; pointer to items array
mov eax,index
shl eax,2
push value
pop DWORD PTR [ebx+eax] ; linear address of items[index]
pop ebx
pop eax
ret
list_set ENDP
list_index_of PROC, list:DWORD , item:DWORD ; returns the index of the first appearance of the item,-1 if item isn't found
push ecx
push ebx
mov ebx,list
mov ecx,[ebx+4] ; ecx -> count
mov eax,item
mov edi,[ebx] ; edi -> items
inc ecx
sub edi,4 ; adding later
jmp check_loop ; first check then do
loop_label:
add edi,4
cmp [edi],eax
check_loop:loopnz loop_label ; loop if list[i]!=item, break if item found
jnz notFound
; if loop terminated in the middle, ZF will be marked, if loop was terminated because ecx = 0, ZF will not be marked
sub edi,[ebx] ; edi = &item - &first_item = the distance in bytes between the item and the first item
mov eax,edi
shr eax,2 ; edi /= 4n = distance above in dwords = index
jmp final
notFound:
mov eax,-1 ; case item wasn't found
final:
pop ebx
pop ecx
ret
list_index_of endp
list_delete_at PROC, list:DWORD, index:DWORD ; removes the item at the index from the list and shortens the list by 1 element
pusha
mov ebx,list
push DWORD PTR [ebx+4] ; count
mov ecx,[esp]
dec ecx
shl ecx,2
invoke Alloc,ecx ; new array to size count-1
mov edi,eax ; edi = new array
mov ebx,list
mov esi,[ebx] ; esi = old array
mov ecx,index
push es
push ds ; data to extra (CodeGuru!!!)
pop es
rep movsd ; copy from old array to new array right until the index of the item to delete
mov ecx,index
inc ecx
sub [esp+4],ecx ; count - index - 1
mov ecx,[esp+4] ; ecx = items left to copy
add esi,4 ; skip over the item deleted
rep movsd ; continue to copy from old array to new
pop es
pop ecx ; list.count - index - 1
add ecx,index ; list.count -1
shl ecx,2 ; byte size of new array
sub edi,ecx ; point to the beginning of the array
invoke Free,[ebx] ; delete old array
mov ebx,list
mov [ebx],edi ; set items as new array
dec DWORD PTR [ebx+4] ; count--
popa
ret
list_delete_at ENDP
delete_list PROC,list:DWORD ; deletes the list
push eax
mov eax,list
invoke Free,[eax] ; delete the item array
invoke Free,list
pop eax
ret
delete_list endp
;;;; MACROS ;;;;
new_stack MACRO
invoke Alloc,SIZEOF Stack
ENDM
new_queue MACRO
invoke Alloc,NULL,SIZEOF Queue
ENDM
stack_peek MACRO stack
push stack
call peek
ENDM
queue_peek MACRO queue
push queue
call peek
ENDM
new_list MACRO
invoke Alloc,SIZEOF List
ENDM
.686
.data
;;;;;;;;;; NOTE!! ALL MATH FUNCTIONS RETURN REAL4 VALUES THROUGH EAX ;;;;;;;;;
;;;; SERIES ;;;;
factor PROTO x:REAL4
;;;; LOGARITHMS AND EXPONENTIALS
log2 PROTO x:REAL4
ln PROTO x:REAL4
exp PROTO x:REAL4
pow PROTO x:REAL4,y:REAL4 ; x to the power of y
log PROTO x:REAL4,y:REAL4 ; logarithm base x of y
;;;; TRIGONOMETRY ;;;;
cos PROTO x:REAL4
sin PROTO x:REAL4
tan PROTO x:REAL4
tanh PROTO x:REAL4
cosh PROTO x:REAL4
sinh PROTO x:REAL4
acos PROTO x:REAL4
asin PROTO x:REAL4
atan PROTO x:REAL4
atanh PROTO x:REAL4
acosh PROTO x:REAL4
asinh PROTO x:REAL4
;;;; NOT SURE HOW TO DESCRIBE THIS ;;;;
random PROTO
.code
;;;; MEMORY TO MEMORY MACROS ;;;;
st0_to_eax MACRO ; name is self-explaining
sub esp, 4
fstp dword ptr [esp]
pop eax
ENDM
fld_eax MACRO ; name also self-explaining
push eax
fld DWORD PTR [esp]
pop eax
ENDM
f_add MACRO x,y ;x += y for float
fld REAL4 PTR x
fadd REAL4 PTR y
fstp REAL4 PTR x
endm
f_sub MACRO x,y ; x -= y for float
fld REAL4 PTR x
fsub REAL4 PTR y
fstp REAL4 PTR x
endm
f_mul MACRO x,y ; x *= y for float
fld REAL4 PTR x
fmul REAL4 PTR y
fstp REAL4 PTR x
endm
f_div MACRO x,y ; x /= y for float
fld REAL4 PTR x
fdiv REAL4 PTR y
fstp REAL4 PTR x
endm
f_mod MACRO x,y ; x %= y for float
fld REAL4 PTR x
fld REAL4 PTR y
fprem st(1),st
fstp st(0) ; pop
fstp REAL4 PTR x
endm
f_to_int MACRO x,y ; x = (int)y ; for x is int, y is float
fld REAL4 PTR y
fistp DWORD PTR x
endm
f_to_float MACRO x,y ; x = (float)y ; for x is float, y is int
fild DWORD PTR y
fstp REAL4 PTR x
endm
ln PROC, x:REAL4 ; ln(x) = ln(2)*log2(x)
fldln2
fld REAL4 ptr x
FYL2X
st0_to_eax
ret
ln ENDP
factor PROC, x:REAL4 ; x!
fld x ; counter
fld1 ; result
the_loop:
fldz
fcomip st,st(2) ; if counter == 0 return result
je the_finish
fmul st,st(1) ; result *= counter
fld1
fsubp st(2),st ; counter--
jmp the_loop
the_finish:
st0_to_eax
fstp st(0) ; pop counter
ret
factor endp
exp PROC, x:REAL4 ; returns e^x
; fpu instruction didn't work so this is calculated by the taylor series
; exp(x) = sum from n = 0 to inf [x^n/n!]
push ecx
sub esp,8
fld1 ; first element of the series, x^0/0! == 1
fstp DWORD PTR [esp] ; [esp] = result
mov [esp+4],dword ptr 1 ; [esp+4] counter
the_loop:
fild DWORD PTR [esp+4]
st0_to_eax ; eax -> counter as float
invoke factor,eax
; normalpow x,counter
mov ecx,[esp+4] ; ecx -> counter as int
fld x
fld1 ; result of normalpow, temp y = 1
pow_loop:
fmul st,st(1) ; y*=x
loop pow_loop ; repeat counter times, y = x*x*x*x... counter times = x^n
fstp st(1) ; pop, y to st
fld_eax ; st = n!
fdivp st(1),st ; st(0) = x^n/n!
fld DWORD PTR [esp] ; sum
fadd st,st(1) ; st = sum + (x^n/n!)
fstp dword ptr [esp] ; store new sum in sum local variable
fstp st(0) ; pop
inc DWORD PTR [esp+4] ; counter++
cmp [esp+4],DWORD PTR 35 ; maximum factorial that isn't infinity
jl the_loop
mov eax,[esp] ; result
add esp,8 ; delete locals
pop ecx
ret
exp ENDP
pow PROC, x:REAL4, y:REAL4 ; x^y
invoke ln,x
fld y
fmul x ; y*ln(x)
st0_to_eax
invoke exp,eax ; x^y = exp(ln(x)*y)
ret
pow endp
log PROC, x:REAL4, y:REAL4 ; logx(y) = log2(y)/log2(x)
fld1
fld y
fyl2x ; log2(y)
fld1
fld x
fyl2x ; log2(x)
fdivp st(1),st ; log2(y)/log2(x)
st0_to_eax
ret
log endp
log2 PROC,x:REAL4 ; using fpu instruction
fld1
fld x
fyl2x
st0_to_eax
ret
log2 endp
cos PROC,x:REAL4 ; fpu instruction
fld x
fcos
st0_to_eax
ret
cos endp
sin PROC,x:REAL4 ; fpu instruction
fld x
fsin
st0_to_eax
ret
sin endp
tan PROC,x:REAL4 ; fpu instruction
fld x
fptan
fstp st(0) ; fptan pushes 1 to the stack
st0_to_eax
ret
tan endp
tanh PROC,x:REAL4 ; hyperbolic tangent = (exp(2x)-1)/(exp(2x)+1)
fld x
fadd x ; 2x
st0_to_eax
invoke exp,eax ; exp(2x)
fld_eax
fld_eax
fld1
fsub st(2),st ; exp(2x)-1
fadd st(1),st ; exp(2x)+1
fstp st(0) ; pop
fdivp st(1),st ; st = (exp(2x)-1)/(exp(2x)+1)
st0_to_eax
ret
tanh endp
sinh PROC,x:REAL4 ; hyperbolic sine = (exp(x)-exp(-x))/2
invoke exp,x
fld_eax
fld1
fld_eax
fdivp st(1),st ; exp(-x) = 1/exp(x)
fsubp st(1),st ; st = exp(x)-exp(-x)
fld1
fld1
faddp st(1),st ; 2.0
fdivp st(1),st
st0_to_eax
ret
sinh ENDP
cosh PROC,x:REAL4 ; hyperbolic cosine = (exp(x)+exp(-x))/2
invoke exp,x
fld_eax
fld1
fld_eax
fdivp st(1),st ; exp(-x) = 1/exp(x)
faddp st(1),st ; st = exp(x)+exp(-x)
fld1
fld1
faddp st(1),st ; 2.0
fdivp st(1),st
st0_to_eax
ret
cosh ENDP
atan PROC,x:REAL4 ; fpu instruction
fld x
fld1 ; arctan(x/1) = arctan(x)
fpatan
st0_to_eax
ret
atan ENDP
asin PROC,x:REAL4
fld x
fld1
fld1
fld x
fmul x ; x^2
fsubp st(1),st ; 1-x^2
fsqrt
faddp st(1),st ; 1+sqrt(1-x^2)
fpatan ; arcsin(x) = 2*arctan(x/(1+sqrt(1-x^2)))
fadd st,st(0) ; mul by 2
st0_to_eax
ret
asin ENDP
acos PROC,x:REAL4
fld1
fld x
fmul x ; x^2
fsubp st(1),st ; 1-x^2
fsqrt ; st(0) = sqrt(1-x^2)
fld1
fld x
faddp st(1),st ; st(0) = x+1
fpatan ; arccos(x) = 2*arctan(sqrt(1-x^2)/x+1)
fadd st,st(0) ; mul by 2
st0_to_eax
ret
acos ENDP
atanh PROC,x:REAL4 ; atanh(x) = ln((1+x)/(1-x))/2
fld x
fld x
fld1
fadd st(2),st ; st(2) = 1+x
fsub st(1),st ; st(1) = 1-x
fstp st(0) ; pop
fdivp st(1),st ; (1+x)/(1-x)
st0_to_eax
invoke ln,eax
fld_eax
fld1
fld1
faddp st(1),st ; 2.0
fdivp st(1),st ; divide by 2
st0_to_eax
ret
atanh ENDP
asinh PROC,x:REAL4
fld x
fmul x
fld1
faddp st(1),st
fsqrt ; sqrt(x^2+1)
fadd x
st0_to_eax
invoke ln,eax ; asinh(x) = ln(x+sqrt(x^2+1))
ret
asinh ENDP
acosh PROC,x:REAL4
fld x
fmul x
fld1
fsubp st(1),st
fsqrt ; sqrt(x^2+1)
fadd x
st0_to_eax
invoke ln,eax ; acosh(x) = ln(x+sqrt(x^2-1))
ret
acosh ENDP
random PROC ; returns a random number between 0 and 1
push edx
rdtsc ; edx:eax = systime
ror eax,8 ; most changing number as the highest parts of the integer
and eax,01111111111111111111111111111111b ; remove sign
push eax
fild DWORD PTR [esp] ; load random integer
push DWORD PTR 01111111111111111111111111111111b
fild DWORD PTR [esp] ; load int max value
pop edx ; clear from stack
fdivp st(1),st ; random number / max
fstp dword ptr [esp] ; store result in stack
pop eax ; result to eax
pop edx
ret
random ENDP
.data
Matrix STRUCT
elements DWORD ? ; pointers to the first element in each row
rows DWORD ?
columns DWORD ?
Matrix ends
zero_matrix PROTO rows:DWORD,columns:DWORD
matrix_get_row PROTO mat:dword,row:DWORD
matrix_get_element PROTO mat:DWORD,row:DWORD,col:DWORD
matrix_set_element PROTO mat:DWORD,row:DWORD,col:DWORD,value:DWORD
matrix_set_row PROTO mat:DWORD,row:DWORD,reprow:DWORD
matrix_add PROTO dst:DWORD,scr:DWORD ; +=
.code
matrix_delete PROC,mat:DWORD ; name is self-exlaining
pusha
mov ebx,mat
mov ebx,[ebx]
invoke Free,[ebx] ; the byte data
mov ebx,mat ; the pointers to the first element of every row
invoke Free,[ebx]
invoke Free,mat ; the matrix data (rows,columns,pointer to pointers
popa
RET
matrix_delete ENDP
zero_matrix PROC,rows:DWORD,columns:DWORD ; returns a pointer to a new zero matrix
push ebx
push ecx
push edx
invoke Alloc,SIZEOF Matrix ; create a new matrix
push eax
mov ebx,eax ; ebx is a pointer to the new matrix
mov ecx,rows
mov [ebx+4],ecx
mov edx,columns
mov [ebx+8],edx ; initialize rows and columns counters
invoke Alloc,rows ; allocate room for pointers
mov ebx,[esp]
mov [ebx],eax ; place pointer to pointer in matrix.elements
mov ecx,rows
shl columns,2
mov eax,columns
mul ecx ; eax = rows*columns*4, byte size of the matrix
invoke Alloc,eax
mov edx,eax
mov ebx,[esp]
mov ebx,[ebx] ; ebx = pointers
mov ecx,rows ; repeat rows times
row_loop:
mov [ebx],edx ; initialize the pointer
add edx,columns ; jump up the matrix by columns*4
add ebx,4 ; jump up the pointers by 4
loop row_loop ; repeat rows times
pop eax
pop edx
pop ecx
pop ebx
ret
zero_matrix ENDP
matrix_get_row PROC,mat:DWORD,row:DWORD ; returns a pointer to the first element in the row
push ebx
mov eax,mat
mov eax,[eax] ; eax = pointer to pointers
mov ebx,row
shl ebx,2 ; ebx = rows*4
mov eax,[eax+ebx] ; linear address of the pointer
pop ebx
ret
matrix_get_row endp
matrix_get_element PROC,mat:DWORD,row:DWORD,col:DWORD ; returns mat[row,col]
push ebx
invoke matrix_get_row,mat,row ; retrive the specific row to eax
mov ebx,col
shl ebx,2 ; linear location (row[col*4])
mov eax,[eax+ebx]
pop ebx
ret
matrix_get_element ENDP
matrix_set_element PROC,mat:DWORD,row:DWORD,col:DWORD,value:DWORD ; mat[row,col] = value
push ebx
push eax
invoke matrix_get_row,mat,row ; retrive to specific row to eax
mov ebx,col
shl ebx,2 ; linear location (row[col*4])
push value
pop DWORD PTR [eax+ebx] ; move the value
pop eax
pop ebx
ret
matrix_set_element ENDP
matrix_set_row PROC,mat:DWORD,row:DWORD,reprow:DWORD ; copies the row specified by the row pointer reprow to the row of the matrix
pusha
invoke matrix_get_row,mat,row ; get the pointer to the row to eax
mov ecx,mat
mov ecx,[ecx+8] ; columns
push ds
pop es ; extra to data (thanks to CodeGuru Extreme for the idea)
mov edi,eax ; destination = mat[row]
mov esi,reprow ; source = reprow
rep movsd ; copy dword from reprow to row columns times
popa
ret
matrix_set_row ENDP
matrix_load PROC,dst:DWORD,src:DWORD ; copies the destination matrix to the source matrix
push eax
push ecx
mov ecx,dst
mov ecx,[ecx+4] ; ecx = rows
the_loop:
dec ecx ; matrix is 0 based indexed, loop instruction is 1 based
invoke matrix_get_row,src,ecx ; get the row pointer at src[ecx] to eax
invoke matrix_set_row,dst,ecx,eax ; copy the row to dst[ecx]
inc ecx
loop the_loop ; repeat rows times
pop ecx
pop eax
ret
matrix_load endp
matrix_add PROC,dst:DWORD,src:DWORD ; += instruction for matrices, dst += src
pusha
mov ebx,src
mov ecx,[ebx+4] ; rows
push DWORD PTR [ebx+8] ; columns
mov eax,dst
mov ebx,[ebx] ; pointer to row pointers of source matrix
mov eax,[eax] ; pointer to row pointers of destination matrix
outer_loop: ; loop through every row
push ecx
dec ecx ; matrix is 0 bases, loop instruction is 1 based
shl ecx,2
mov edi,[eax+ecx] ; row from dst
mov esi,[ebx+ecx] ; row from src
mov edx,[esp+4] ; temporary columns variable pushed to the stack earlier
inner_loop: ; loop through every column
push edx ; for every element in the row
dec edx
shl edx,2 ; linear location, row[col*4]
f_add [edi+edx],[esi+edx] ; float addition macro, add element in source to element in destination
pop edx
dec edx ; loops backwords (from columns-1 to 0)
jnz inner_loop
pop ecx
loop outer_loop
pop edx ; delete temporary columns variable from the stack
popa
ret
matrix_add ENDP
matrix_plus PROC,dst:DWORD,src:DWORD ; +, returns a pointer to the new matrix dst+src
mov eax,dst
invoke zero_matrix,[eax+4],[eax+8] ; new zero matrix to size of the matrices
invoke matrix_load,eax,dst ; copy the destination matrix
invoke matrix_add,eax,src ; add the source matrix
ret
matrix_plus ENDP
matrix_sub PROC,dst:DWORD,src:DWORD ; -= instruction for matrices, dst-= src
pusha
mov ebx,src
mov ecx,[ebx+4] ; ecx = rows
push DWORD PTR [ebx+8] ; temporary columns variable
mov eax,dst
mov ebx,[ebx] ; pointer to the row pointers of source matrix
mov eax,[eax] ; pointer to the row pointers of destination matrix
outer_loop:
push ecx
dec ecx ; matrix is 0 based index, loop instruction is 1 based
shl ecx,2 ; linear location
mov edi,[eax+ecx] ; edi = dst[ecx]
mov esi,[ebx+ecx] ; esi = dst[ecx]
mov edx,[esp+4]
inner_loop:
push edx
dec edx
shl edx,2 ; linear location
f_sub [edi+edx],[esi+edx] ; using the float sub macro
pop edx
dec edx
jnz inner_loop
pop ecx
loop outer_loop
pop edx ; delete temporary column variable
popa
ret
matrix_sub ENDP
matrix_minus PROC,dst:DWORD,src:DWORD ; -, returns a pointer to the new matrix dst-src
mov eax,dst
invoke zero_matrix,[eax+4],[eax+8] ; create a new matrix to size of the matrices
invoke matrix_load,eax,dst ; copy the destination matrix to the new matrix
invoke matrix_sub,eax,src ; substruct the source matrix
ret
matrix_minus ENDP
matrix_elementwize_mul PROC,dst:DWORD,src:DWORD ; *=, multiply dst by src elementwize
pusha
mov ebx,src
mov ecx,[ebx+4] ; rows
push DWORD PTR [ebx+8] ; temp columns constant
mov eax,dst
mov ebx,[ebx]
mov eax,[eax]
outer_loop: ; loop for every row
push ecx
dec ecx ; matrix zero bases, loop 1 based
shl ecx,2 ; linear location
mov edi,[eax+ecx] ; row of destination
mov esi,[ebx+ecx] ; row of source
mov edx,[esp+4] ; columns
inner_loop: ; loop for every column
push edx
dec edx
shl edx,2 ; linear location
f_mul [edi+edx],[esi+edx] ; float multiply macro
pop edx
dec edx
jnz inner_loop
pop ecx
loop outer_loop
pop edx ; remove temp columns constant
popa
ret
matrix_elementwize_mul ENDP
matrix_elementwize_times PROC,dst:DWORD,src:DWORD ; *, returns a pointer to the new matrix src*dst
mov eax,dst
invoke zero_matrix,[eax+4],[eax+8] ; new matrix to size of the destination matrix
invoke matrix_load,eax,dst ; copy of the destination matrix
invoke matrix_elementwize_mul,eax,src ; multiply elementwize by the source matrix
ret
matrix_elementwize_times ENDP
matrix_mul PROC,mat1:DWORD,mat2:DWORD ; matrix multiplication, returns pointer to a new matrix
push ebx
push ecx
push edx
push esi
push edi
; mat1 is R(n*m), mat2 is R(m*k)
; the returned matrix is R(n*k)
mov ebx,mat1
mov ecx,mat2
invoke zero_matrix,[ebx+4],[ecx+8] ; new matrix with the amount of rows in mat1 and columns of mat2
push eax ; pointer to the new matrix
push REAL4 ptr 0 ; float sum = 0
push DWORD ptr 0; int i = 0, row counter for mat1
push DWORD ptr 0 ; int j = 0, column counter for mat2
push DWORD ptr 0 ; int k = 0, row/column counter for mat2/mat1, respectively
outer_loop_1: ; row loop for mat1
mov [esp+4],DWORD PTR 0 ; j = 0
outer_loop_2: ; column loop for mat2
mov REAL4 PTR [esp+12],0 ; sum = 0
mov [esp],DWORD PTR 0 ; k = 0
inner_loop: ; sum loop
mov ebx,[esp+8] ; ebx = i
mov ecx,[esp] ; ecx = k
invoke matrix_get_element,mat1,ebx,ecx ; mat1[i,k]
fld_eax ; load to fpu stack
mov ebx,[esp+4] ; ebx = j
invoke matrix_get_element,mat2,ecx,ebx ; mat2[k,j]
fld_eax ; load to fpu stack
fmulp st(1),st ; mat1[i,k]*mat2[k,j]
fld REAL4 PTR [esp+12] ; load sum
faddp st(1),st ; add mat1[i,k]*mat2[k,j] to sum
fstp REAL4 PTR [esp+12] ; store result in sum
inc DWORD PTR [esp] ; k++
mov eax,mat1
mov eax,[eax+8] ; mat1.columns
cmp eax,[esp] ; repeat until k = mat1.columns
jnz inner_loop
mov eax,[esp+16] ; the return matrix
mov ebx,[esp+8] ; i
mov ecx,[esp+4] ; j
mov edx,[esp+12] ; sum
invoke matrix_set_element,eax,ebx,ecx,edx ; return matrix at [i,j] = sum
inc DWORD PTR [esp+4] ; j++
mov eax,[esp+16]
mov eax,[eax+8] ; new matrix columns
cmp eax,[esp+4] ; repeat for j = 0 to columns
jnz outer_loop_2
inc DWORD PTR [esp+8] ; i++
mov eax,[esp+16]
mov eax,[eax+4] ; new matrix rows
cmp eax,[esp+8] ; repeat for i=0 to rows
jnz outer_loop_1
add esp,16 ; delete temporary variables
pop eax ; restore result matrix to eax
pop edi
pop esi
pop edx
pop ecx
pop ebx
ret
matrix_mul endp
matrix_scalar_mul PROC,mat:DWORD,scl:REAL4 ; matrix multiplication by a scalar, mat *= scl
pusha
mov ebx,mat
mov ecx,[ebx+4] ; ecx = rows
push DWORD PTR [ebx+8] ; temp column constant
mov ebx,[ebx] ; ebx = pointer to rows pointers
outer_loop: ; for every row
push ecx
dec ecx
shl ecx,2 ; linear address of the row
mov edi,[ebx+ecx] ; edi = row
mov edx,[esp+4] ; edx = columns
inner_loop: ; for every column
push edx
dec edx
shl edx,2 ; linear address
f_mul [edi+edx],scl ; float multiplication macro
pop edx
dec edx
jnz inner_loop
pop ecx
loop outer_loop
pop edx ; delete temp column constant
popa
ret
matrix_scalar_mul ENDP
matrix_scalar_times PROC,mat:DWORD,scl:REAL4 ; *, returns a new matrix
mov eax,mat
invoke zero_matrix,[eax+4],[eax+8]
invoke matrix_load,eax,mat
invoke matrix_scalar_mul,eax,scl
ret
matrix_scalar_times endp
matrix_elementwize PROC,mat:DWORD,func:DWORD ; function must be stdcall, and take one REAL4 argument; equivalent to element = f(element) for every element
pusha
mov ebx,mat
mov ecx,[ebx+4] ; ecx = rows
push DWORD PTR [ebx+8] ; temp columns
mov ebx,[ebx] ; row pointers
outer_loop: ; rows
push ecx
dec ecx
shl ecx,2 ; linear address
mov edi,[ebx+ecx] ; edi = row pointer
mov edx,[esp+4] ; columns
inner_loop: ; columns
push edx
dec edx
shl edx,2 ; linear location
push edi ; protect values
push edx
push REAL4 PTR [edi+edx] ; call the function with mat[row,col] as an argument
call func
pop edx
pop edi ; restore values
mov [edi+edx],eax ; move the result to the element location, mat[row,col] = f(mat[row,col])
pop edx
dec edx
jnz inner_loop
pop ecx
loop outer_loop
pop edx ; delete temp
popa
ret
matrix_elementwize ENDP
matrix_element_function PROC,mat:DWORD,func:DWORD ; function must be stdcall, and take one REAL4 argument; returns f(element) for each element
mov eax,mat
invoke zero_matrix,[eax+4],[eax+8] ; new matrix by dimensions of the source
invoke matrix_load,eax,mat ; copy matrix
invoke matrix_elementwize,eax,func ; perform the function on every element and get the result
ret
matrix_element_function endp
random_matrix PROC,rows:DWORD,columns:DWORD ; returns a new matrix R(rows,columns) of random values between 0 and 1
push ebx
push ecx
push edx
invoke Alloc,SIZEOF Matrix ; create new matrix
push eax
mov ebx,eax
mov ecx,rows
mov [ebx+4],ecx
mov edx,columns
mov [ebx+8],edx ; initialize rows and column fields of the matrix
invoke Alloc,rows ; allocate rows pointer
mov ebx,[esp]
mov [ebx],eax ; initialize rows pointer
mov ecx,rows
shl columns,2
mov eax,columns
mul ecx ; byte size of the matrix = rows*columns*4
push eax
invoke Alloc,eax ; allocate raw data
pop ecx ; size of matrix
mov edx,eax
push edx ; edx = raw data pointer
rand_loop: ; for every element set to random number between 0 and 1
invoke random ; random number to eax
mov [edx],eax ; store in element
add edx,4
loop rand_loop
pop edx ; restore raw data pointer
mov ebx,[esp] ; return matrix
mov ebx,[ebx] ; row pointers
mov ecx,rows
row_loop: ; initialize row pointers
mov [ebx],edx
add edx,columns ; beginning of next row
add ebx,4 ; next row pointer
loop row_loop
pop eax ; new matrix pointer to eax
pop edx
pop ecx
pop ebx
ret
random_matrix ENDP
ones_matrix PROC,rows:DWORD,columns:DWORD ; returns a matrix R(rows,columns) of ones
push ebx
push ecx
push edx
invoke Alloc,SIZEOF Matrix
push eax ; new matrix
mov ebx,eax
mov ecx,rows
mov [ebx+4],ecx
mov edx,columns
mov [ebx+8],edx ; initialize rows and columns fields
invoke Alloc,rows ; allocate rows pointers
mov ebx,[esp]
mov [ebx],eax ; initialize rows pointers
mov ecx,rows
shl columns,2
mov eax,columns
mul ecx ; byte size = rows*columns*4
push eax
invoke Alloc,eax ; allocate raw data
pop ecx ; matrix size
mov edx,eax
push edx
ones_loop:
fld1
fstp REAL4 PTR [edx] ; store 1 in the element
add edx,4
loop ones_loop ; loop for every element
pop edx ; first element pointer
mov ebx,[esp] ; return matrix
mov ebx,[ebx] ; rows pointers
mov ecx,rows
row_loop: ; set pointer for every row
mov [ebx],edx
add edx,columns ; next row
add ebx,4 ; next pointer
loop row_loop
pop eax ; return matrix
pop edx
pop ecx
pop ebx
ret
ones_matrix ENDP
identity_matrix PROC,rows:DWORD,columns:DWORD ; returns the identity_matrix by the dimensions R(rows,columns)
push ecx
push edx
invoke zero_matrix,rows,columns ; new matrix to dimensions R(rows,columns)
mov ecx,rows
cmp ecx,columns
jl afterFoundMin ; get min(rows,columns) to ecx, number of times to loop
mov ecx,columns
afterFoundMin:
fld1
push DWORD PTR 0
fstp DWORD PTR [esp]
pop edx ; edx = 1.0
ones_loop:
dec ecx
invoke matrix_set_element,eax,ecx,ecx,edx ; set mat[ecx,ecx] to 1
inc ecx
loop ones_loop ; loop min(rows,columns) times
pop edx
pop ecx
ret
identity_matrix ENDP
matrix_transpose PROC, mat:DWORD ; returns the transpose of the matrix through eax
push ebx
push ecx
push edx
mov ebx,mat
invoke zero_matrix,[ebx+8],[ebx+4] ; new matrix by the transpose dimensions of mat
mov ecx,[ebx+4] ; rows
push DWORD PTR [ebx+8] ; columns
mov ebx,eax ; return matrix
outer_loop:
mov edx,[esp] ; columns
inner_loop:
dec edx
dec ecx
invoke matrix_get_element,mat,ecx,edx ; get element at mat[ecx,edx]
invoke matrix_set_element,ebx,edx,ecx,eax ; set return matrix at [edx,ecx] to mat[ecx,edx]
inc edx
inc ecx
dec edx
jnz inner_loop ; for every column
loop outer_loop ; for every row
mov eax,ebx ; return matrix
pop edx ; delete temp columns
pop edx
pop ecx
pop ebx
ret
matrix_transpose ENDP
matrix_concat_rows PROC,mat1:DWORD, mat2:DWORD ; concat mat1 and mat2 by the rows, mat1 is R(n,m), mat2 is R(k,m), return is R(n+k,m)
push ebx
push ecx
push edx
mov ebx,mat1
mov ecx,[ebx+4]
mov ebx,mat2
add ecx,[ebx+4] ; ecx = mat1.rows+mat2.rows, amount of rows in the new matrix
invoke zero_matrix,ecx,[ebx+8] ; new matrix R(n+k,m)
mov edx,eax
mov eax,mat1
mov ecx,[eax+4] ; ecx = mat1.rows
loop_1: ; load from mat1 to return matrix
dec ecx
invoke matrix_get_row,mat1,ecx ; copy row from mat1 to return matrix
invoke matrix_set_row,edx,ecx,eax
inc ecx
loop loop_1 ; loop mat1.rows times
mov ebx,mat1
mov ebx,[ebx+4] ; mat1.rows
mov ecx,mat2
mov ecx,[ecx+4] ; mat2.rows
loop_2: ; load from mat2 to return matrix
dec ecx
invoke matrix_get_row,mat2,ecx ; get row at ecx
add ecx,ebx ; set row at mat1.rows+ecx to mat2[ecx]
; rows at 0 to mat1.rows-1 have been filled by rows at mat1
invoke matrix_set_row,edx,ecx,eax
sub ecx,ebx
inc ecx
loop loop_2 ; loop for each row in mat2
mov eax,edx ; return matrix
pop edx
pop ecx
pop ebx
ret
matrix_concat_rows ENDP
matrix_concat_columns PROC,mat1:DWORD,mat2:DWORD ; concat mat1 and mat2 by the columns, mat1 is R(n,m), mat2 is R(n,k), return is R(n,m+k)
push ebx
; linear identity
; [a;b] = [a.T,b.T].T
invoke matrix_transpose,mat1; mat1.T
mov ebx,eax
invoke matrix_transpose,mat2; mat2.T
push eax ; to delete later
invoke matrix_concat_rows,ebx,eax ; eax = [mat1.T, mat2.T]
invoke matrix_delete,ebx ; delete mat1.T
pop ebx
invoke matrix_delete,ebx ; delete mat2.T
mov ebx,eax
invoke matrix_transpose,eax ; transpose of [mat1.T, mat2.T]
invoke matrix_delete,ebx ; delete [mat1.T, mat2.T]
pop ebx
ret
matrix_concat_columns ENDP
.const
INT_MIN_VALUE equ 10000000000000000000000000000000b
NOT_INT_MIN_VALUE equ -(INT_MIN_VALUE)-1
.data
str_length PROTO string:DWORD
parse_int PROTO string:DWORD
int_to_string PROTO number:DWORD
concat PROTO st1:DWORD,st2:DWORD
compare PROTO st1:DWORD,st2:DWORD
index_of PROTO st1:DWORD,patt:DWORD
.code
str_length PROC,string:DWORD ; returns the length of the string
push ebx
push ecx
mov ebx,string
xor ecx,ecx
get_length_loop:
mov al,[ebx+ecx]
test al,al ; search for the null char
jz finish ; finish if found
inc ecx ; add 1 to counter if not found
jmp get_length_loop
finish:
mov eax,ecx
pop ecx
pop ebx
ret
str_length ENDP
parse_int PROC, string:DWORD ; returns (int)string
push ebx
push ecx
push edx
push edi
push esi
invoke str_length,string
xor esi,esi
mov ecx,eax ; ecx = length
xor eax,eax
mov edx,string
xor edi,edi
; check if negative
cmp byte ptr [edx],"-"
jnz AfterNeg ; if negative
inc esi ; boolean indicating weather the number is negative
inc edx ; skip the "-" sign
dec ecx ; length is lenght-1 without the "-" sign
AfterNeg:
eval_loop:
xor ebx,ebx
mov bl,[edx+edi] ; the char
sub bl,"0" ; from ascii to digit
push edi
push ecx
push eax
push edx
mov eax,1 ; eax = exponent
mov edi,10
jmp check_pow_loop
pow_loop:
mul edi ; get 10^(ecx-1) to eax
dec ecx
check_pow_loop:
cmp ecx,1
jnz pow_loop
after_pow_loop:
mul ebx
mov ebx,eax ; ebx = digit*10^(ecx-1)
pop edx
pop eax
pop ecx
pop edi
add eax,ebx ; add the number to the total sum
inc edi
loop eval_loop
test esi,esi
jz finish ; positive
neg eax
finish:
pop esi
pop edi
pop edx
pop ecx
pop ebx
ret
parse_int ENDP
int_to_string PROC, number:DWORD ; returns (string)number, pointer to the string through eax
push ebx
push ecx
push edx
push edi
; protect values
mov edi,10 ; for division
xor ecx,ecx ; counter
mov eax,number
test eax,10000000000000000000000000000000b ; if negative
jz get_length_loop
neg eax
get_length_loop:
; length is amount of times needed to divide the number by 10 (the base) until it becomes zero
inc ecx
xor edx,edx
div edi
test eax,eax
jnz get_length_loop
afterCount:
inc ecx ; one after must be 0
push ecx
mov eax,number
test eax,10000000000000000000000000000000b ; if negative
jnz negativeAlloc
invoke Alloc,ecx
jmp afterAlloc
negativeAlloc: ; allocate one more byte for the - sign
inc ecx
invoke Alloc,ecx
mov byte ptr [eax],"-"
inc eax ; skip the "-" sign
afterAlloc:
pop ecx
dec ecx
mov ebx,eax ; ebx = string pointer
mov eax,number
test eax,10000000000000000000000000000000b ; if negative
jz afterNegation
neg eax ; get absolute value
afterNegation:
push edx
mov edi,10
write_string_loop:
xor edx,edx
div edi ; remainder is the current units digit
add dl,"0" ; to ascii
mov [ebx+ecx-1],dl
loop write_string_loop
pop edx
test number,10000000000000000000000000000000b ; if negative
jz finish_1
dec ebx ; if the number is negative the pointer should be one below for the "-" sign
finish_1:
mov eax,ebx
pop edi
pop edx
pop ecx
pop ebx
; restore values
ret
int_to_string ENDP
concat PROC,st1:DWORD,st2:DWORD ; st1+st2, pointer to the new string through eax
push ebx
push ecx
push edx
push edi
push esi
push es
invoke str_length,st1
mov ebx,eax
invoke str_length,st2
mov ecx,eax
add ecx,ebx
push ecx
push eax
push ebx
invoke Alloc,ecx ; new string
mov edi,eax ; new string
pop ecx ; st1 len
mov esi,st1 ; first string
push ds
pop es
rep movsb ; copy from first string
mov esi,st2
pop ecx ; st2 len
rep movsb ; copy from second string
mov eax,edi
pop ebx ; total length
sub eax,ebx
pop es
pop esi
pop edi
pop edx
pop ecx
pop ebx
ret
concat endp
compare PROC,st1:DWORD,st2:DWORD ; returns st1 == st2
push ecx
push edi
push esi
push es
invoke str_length,st1
push eax
invoke str_length,st2
cmp eax,[esp] ; if sizes don't match return false
je afterFalse
pop eax ; clear stack
xor eax,eax ; zero eax
; restore values
pop es
pop esi
pop edi
pop ecx
ret
afterFalse:
pop ecx ; length
push ds
pop es ; extra to data
mov esi,st1
mov edi,st2
repe cmpsb ; while edi[i] == esi[i] && ecx != 0
je rettrue ; if loop was terminated because ecx reached 0 then ZF is still signed
; if loop was terminated because edi[i] != esi[i] then ZF is not signed
retfalse:
xor eax,eax
jmp finish
rettrue:
mov eax,1
finish:
pop es
pop esi
pop edi
pop ecx
ret
compare endp
index_of PROC, st1:DWORD,patt:DWORD ; first appearance of the pattern in the string, not a regex pattern btw
push ecx
invoke str_length,st1
push eax
invoke str_length,patt
cmp eax,[esp] ; if length of patt is larger the st1 then the input is iligal
jle ligalInput
pop eax
mov eax, -1 ; return -1 for iligal input
pop ecx
ret
ligalInput:
pop ecx ; st1 length
push ebx
push edx
push esi
push edi
mov edi,st1
mov esi,patt
xor edx,edx
xor ebx,ebx
scan_loop:
xor ebx,ebx ; index in patt
push edi
tempmatch_loop:
cmp ebx,eax ; if reached the end of patt; eax = length of patt
jz found
mov dl,[edi] ; next char
cmp dl,[esi+ebx] ; compare chars
jnz nextloop ; if chars don't match the index wasn't a match
inc edi
inc ebx
jmp tempmatch_loop
nextloop:
pop edi
inc edi ; previous index + 1
loop scan_loop
mov eax,-1 ; if loop reached it's end without finding a match
jmp final
found:
invoke str_length,st1
sub eax,ecx ; ecx is a backwords counter
pop edi ; jumped while something was in the stack
final:
pop edi
pop esi
pop edx
pop ebx
pop ecx
ret
index_of ENDP
.data
bubble_sort PROTO list:DWORD ; sorts the list from smallest item to largest using bubble sort
insert_sorted PROTO list:DWORD,value:DWORD ; inserts the new value to the list while keeping it sorted from smallest to largest
list_map PROTO list:DWORD,func:DWORD ; returns a new list, function must be cdecl and can accept item,index
list_filter PROTO list:DWORD,func:DWORD ; returns a new list, function must be cdecl and can accept item,index
list_concat PROTO l1:DWORD,l2:DWORD ; returns a new list
.code
bubble_sort PROC,list:DWORD
pusha
mov ebx,list
mov ecx,[ebx+4] ; ecx = count
jmp check_loop_first
bubble_loop:
push ecx
mov edx,ecx
dec edx
invoke list_get_item,list,ecx
xchg ebx,eax;ebx = list[edx+1]
invoke list_get_item,list,edx ; list[edx]
cmp eax,ebx ; if list[edx]>list[edx+1]
jle afterSort
sort_loop:
invoke list_set,list,ecx,eax ; list[edx+1] = list[edx] ; BTW there is a temp variable
invoke list_set,list,edx,ebx ; list[edx] = list[edx+1]
; replace order of items
mov edx,ecx
inc ecx
mov ebx,list
cmp ecx,[ebx+4]
je afterSort
invoke list_get_item,list,ecx
xchg ebx,eax;ebx = list[edx+1]
invoke list_get_item,list,edx ; list[edx]
cmp eax,ebx ; if list[edx]>list[edx+1]
jg sort_loop
afterSort:
pop ecx
check_loop_first:
loop bubble_loop
popa
ret
bubble_sort ENDP
insert_sorted PROC,list:DWORD,value:DWORD
pusha
mov ecx,list
mov ecx,[ecx+4]
inc ecx
shl ecx,2
invoke Alloc,ecx
mov ebx,eax
mov edx,list
push [edx+4]
inc DWORD PTR [edx+4]
check_insert_loop_1:
cmp ecx,[esp]
je after_first_insert
invoke list_get_item,list,ecx
cmp eax,value
jg after_first_insert
shl ecx,2
mov [ebx+ecx],eax
shr ecx,2
inc ecx
jmp check_insert_loop_1
after_first_insert:
shl ecx,2
mov eax,value
mov [ebx+ecx],eax
shr ecx,2
insert_loop_2:
cmp ecx,[esp]
je finish
invoke list_get_item,list,ecx
shl ecx,2
mov [ebx+ecx+4],eax
shr ecx,2
inc ecx
jmp insert_loop_2
finish:
mov ss:[esp], ebx
invoke Free,[edx]
mov edx,list
pop DWORD PTR [edx]
popa
ret
insert_sorted ENDP
list_map PROC,list:DWORD,func:DWORD
push ebx
push ecx
push edx
new_list
push eax
mov ecx,list
mov ecx,[ecx+4]
shl ecx,2
invoke Alloc,ecx
mov ebx,[esp]
mov [ebx],eax
mov ecx,list
mov ecx,[ecx+4]
mov [ebx+4],ecx
inc ecx
jmp check_loop
for_each_loop:
invoke list_get_item,list,ecx
push ebx
push ecx
push ecx ; bpth protect and argument
dec DWORD PTR [esp]
push eax ; argument for func
call func
add esp,8 ; clear stack
pop ecx
pop ebx
invoke list_set,ebx,ecx,eax
check_loop:
loop for_each_loop
pop eax
pop edx
pop ecx
pop ebx
ret
list_map ENDP
list_filter PROC,list:DWORD,func:DWORD
push ebx
push ecx
push edx
new_list
mov ebx, eax
mov ecx,list
mov ecx,[ecx+4]
inc ecx
jmp check_loop_1
for_each_loop:
dec ecx
invoke list_get_item,list,ecx
inc ecx
push eax
push ebx
push ecx ; both protect and argument
push eax ; argument for func
call func
pop ecx ; clear stack from arguments
pop ecx
pop ebx
test eax,eax ; if function returned false
jz check_loop
mov eax,[esp]
invoke list_insert,ebx,eax
check_loop:
pop eax
check_loop_1:
loop for_each_loop
mov eax,ebx
pop edx
pop ecx
pop ebx
ret
list_filter ENDP
list_concat PROC l1:DWORD,l2:DWORD
push ebx
push ecx
push esi
push edi
new_list
push eax
mov ebx,l1
mov ecx,[ebx+4]
mov ebx,l2
add ecx,[ebx+4]
shl ecx,2
push ecx
invoke Alloc,ecx
mov edi,eax
mov esi,l1
push es
push ds
pop es
mov ecx,[esi+4]
mov esi,[esi]
rep movsd
mov esi, l2
mov ecx,[esi+4]
mov esi,[esi]
rep movsd
pop es
pop ecx
sub edi,ecx
pop eax
mov [eax],edi
shr ecx,2
mov [eax+4],ecx
pop edi
pop esi
pop ecx
pop ebx
ret
list_concat ENDP
end
|
; A315519: Coordination sequence Gal.6.332.5 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,6,11,17,22,27,33,38,43,49,54,60,66,71,77,82,87,93,98,103,109,114,120,126,131,137,142,147,153,158,163,169,174,180,186,191,197,202,207,213,218,223,229,234,240,246,251,257,262,267
mov $5,$0
mul $0,4
mov $4,$0
sub $0,1
div $0,11
add $0,1
mov $2,$4
mul $2,3
div $2,11
mov $6,$2
add $6,$0
mov $1,$6
mov $3,$5
mul $3,4
add $1,$3
mov $0,$1
|
LKS_Fade_in:
lda LKS_FADE +_fdphase
cmp #0
beq +
rtl
+:
lda LKS_FADE +_fdbrg
sta INIDISP
ldy LKS_FADE +_fdtimer
cpy #2
bne +
ina
stz LKS_FADE +_fdtimer
bra ++
+:
inc LKS_FADE +_fdtimer
++:
cmp #$10
bne +
lda #$0F
sta INIDISP
inc LKS_FADE +_fdphase
stz LKS_FADE +_fdtimer
rtl
+:
sta LKS_FADE +_fdbrg
rtl
LKS_Fade_out:
lda LKS_FADE +_fdphase
cmp #0
bne +
rtl
+:
lda LKS_FADE +_fdbrg
sta INIDISP
ldy LKS_FADE +_fdtimer
cpy #2
bne +
dea
stz LKS_FADE +_fdtimer
bra ++
+:
inc LKS_FADE +_fdtimer
++:
cmp #-$1
bne +
lda #$00
sta INIDISP
inc LKS_FADE +_fdphase
stz LKS_FADE +_fdtimer
rtl
+:
sta LKS_FADE +_fdbrg
rtl
|
; A054488: Expansion of (1+2*x)/(1-6*x+x^2).
; 1,8,47,274,1597,9308,54251,316198,1842937,10741424,62605607,364892218,2126747701,12395593988,72246816227,421085303374,2454265004017,14304504720728,83372763320351,485932075201378,2832219687887917
mov $1,1
mov $2,1
lpb $0,1
sub $0,1
add $2,1
add $2,$1
add $2,$1
add $1,$2
sub $2,1
add $1,$2
lpe
|
;BellossomBaseStats: ; 388ae (e:48ae)
db DEX_BELLOSSOM ; pokedex id
db 75 ; base hp
db 80 ; base attack
db 95 ; base defense
db 50 ; base speed
db 100 ; base special
db GRASS ; species type 1
db GRASS ; species type 2
db 46 ; catch rate
db 184 ; base exp yield
INCBIN "pic/ymon/bellossom.pic",0,1 ; 77, sprite dimensions
dw BellossomPicFront
dw BellossomPicBack
; move tutor compatibility flags
db ABSORB
db 0
db 0
db 0
db 3 ; growth rate
; learnset
tmlearn 6
tmlearn 15
tmlearn 21,22
tmlearn 32
tmlearn 39
tmlearn 44
tmlearn 49,50,51
db BANK(BellossomPicFront)
|
dnl X86-64 mpn_com optimised for AMD Zen.
dnl Copyright 2012 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
ABI_SUPPORT(DOS64)
ABI_SUPPORT(STD64)
MULFUNC_PROLOGUE(mpn_com)
include_mpn(`x86_64/fastsse/com.asm')
|
; A131136: Denominator of (exponential) expansion of log((x/2-1)/(x-1)).
; 1,2,4,4,8,4,8,8,16,4,8,8,16,8,16,16,32,4,8,8,16,8,16,16,32,8,16,16,32,16,32,32,64,4,8,8,16,8,16,16,32,8,16,16,32,16,32,32,64,8,16,16,32,16,32,32,64,16,32,32,64,32,64,64,128,4,8,8,16,8,16,16,32,8,16,16
mov $2,$0
mov $0,0
mov $3,$2
mul $2,2
lpb $2
mov $1,$2
add $3,$0
lpb $3
mul $3,2
mov $2,$3
sub $3,1
mov $0,$3
trn $3,$1
lpe
sub $2,1
lpe
mov $1,$0
add $1,1
|
BankOfMom:
ldh a, [hInMenu]
push af
ld a, $1
ldh [hInMenu], a
xor a
ld [wJumptableIndex], a
.loop
ld a, [wJumptableIndex]
bit 7, a
jr nz, .done
call .RunJumptable
jr .loop
.done
pop af
ldh [hInMenu], a
ret
.RunJumptable:
ld a, [wJumptableIndex]
ld e, a
ld d, 0
ld hl, .dw
add hl, de
add hl, de
ld a, [hli]
ld h, [hl]
ld l, a
jp hl
.dw
dw .CheckIfBankInitialized
dw .InitializeBank
dw .IsThisAboutYourMoney
dw .AccessBankOfMom
dw .StoreMoney
dw .TakeMoney
dw .StopOrStartSavingMoney
dw .AskDST
dw .JustDoWhatYouCan
.CheckIfBankInitialized:
ld a, [wMomSavingMoney]
bit MOM_ACTIVE_F, a
jr nz, .savingmoneyalready
set MOM_ACTIVE_F, a
ld [wMomSavingMoney], a
ld a, $1
jr .done_0
.savingmoneyalready
ld a, $2
.done_0
ld [wJumptableIndex], a
ret
.InitializeBank:
ld hl, UnknownText_0x16649
call PrintText
call YesNoBox
jr c, .DontSaveMoney
ld hl, UnknownText_0x1664e
call PrintText
ld a, (1 << MOM_ACTIVE_F) | (1 << MOM_SAVING_SOME_MONEY_F)
jr .done_1
.DontSaveMoney:
ld a, 1 << MOM_ACTIVE_F
.done_1
ld [wMomSavingMoney], a
ld hl, UnknownText_0x16653
call PrintText
ld a, $8
ld [wJumptableIndex], a
ret
.IsThisAboutYourMoney:
ld hl, UnknownText_0x16658
call PrintText
call YesNoBox
jr c, .nope
ld a, $3
jr .done_2
.nope
call DSTChecks
ld a, $7
.done_2
ld [wJumptableIndex], a
ret
.AccessBankOfMom:
ld hl, UnknownText_0x1665d
call PrintText
call LoadStandardMenuHeader
ld hl, MenuHeader_0x166b5
call CopyMenuHeader
call VerticalMenu
call CloseWindow
jr c, .cancel
ld a, [wMenuCursorY]
cp $1
jr z, .withdraw
cp $2
jr z, .deposit
cp $3
jr z, .stopsaving
.cancel
ld a, $7
jr .done_3
.withdraw
ld a, $5
jr .done_3
.deposit
ld a, $4
jr .done_3
.stopsaving
ld a, $6
.done_3
ld [wJumptableIndex], a
ret
.StoreMoney:
ld hl, UnknownText_0x16662
call PrintText
xor a
ld hl, wStringBuffer2
ld [hli], a
ld [hli], a
ld [hl], a
ld a, 5
ld [wMomBankDigitCursorPosition], a
call LoadStandardMenuHeader
call Mom_SetUpDepositMenu
call Mom_Wait10Frames
call Mom_WithdrawDepositMenuJoypad
call CloseWindow
jr c, .CancelDeposit
ld hl, wStringBuffer2
ld a, [hli]
or [hl]
inc hl
or [hl]
jr z, .CancelDeposit
ld de, wMoney
ld bc, wStringBuffer2
farcall CompareMoney
jr c, .DontHaveThatMuchToDeposit
ld hl, wStringBuffer2
ld de, wStringBuffer2 + 3
ld bc, 3
call CopyBytes
ld bc, wMomsMoney
ld de, wStringBuffer2
farcall GiveMoney
jr c, .CantDepositThatMuch
ld bc, wStringBuffer2 + 3
ld de, wMoney
farcall TakeMoney
ld hl, wStringBuffer2
ld de, wMomsMoney
ld bc, 3
call CopyBytes
ld de, SFX_TRANSACTION
call PlaySFX
call WaitSFX
ld hl, UnknownText_0x1668a
call PrintText
ld a, $8
jr .done_4
.DontHaveThatMuchToDeposit:
ld hl, UnknownText_0x1667b
call PrintText
ret
.CantDepositThatMuch:
ld hl, UnknownText_0x16680
call PrintText
ret
.CancelDeposit:
ld a, $7
.done_4
ld [wJumptableIndex], a
ret
.TakeMoney:
ld hl, UnknownText_0x16667
call PrintText
xor a
ld hl, wStringBuffer2
ld [hli], a
ld [hli], a
ld [hl], a
ld a, 5
ld [wMomBankDigitCursorPosition], a
call LoadStandardMenuHeader
call Mom_SetUpWithdrawMenu
call Mom_Wait10Frames
call Mom_WithdrawDepositMenuJoypad
call CloseWindow
jr c, .CancelWithdraw
ld hl, wStringBuffer2
ld a, [hli]
or [hl]
inc hl
or [hl]
jr z, .CancelWithdraw
ld hl, wStringBuffer2
ld de, wStringBuffer2 + 3
ld bc, 3
call CopyBytes
ld de, wMomsMoney
ld bc, wStringBuffer2
farcall CompareMoney
jr c, .InsufficientFundsInBank
ld bc, wMoney
ld de, wStringBuffer2
farcall GiveMoney
jr c, .NotEnoughRoomInWallet
ld bc, wStringBuffer2 + 3
ld de, wMomsMoney
farcall TakeMoney
ld hl, wStringBuffer2
ld de, wMoney
ld bc, 3
call CopyBytes
ld de, SFX_TRANSACTION
call PlaySFX
call WaitSFX
ld hl, UnknownText_0x1668f
call PrintText
ld a, $8
jr .done_5
.InsufficientFundsInBank:
ld hl, UnknownText_0x16671
call PrintText
ret
.NotEnoughRoomInWallet:
ld hl, UnknownText_0x16676
call PrintText
ret
.CancelWithdraw:
ld a, $7
.done_5
ld [wJumptableIndex], a
ret
.StopOrStartSavingMoney:
ld hl, UnknownText_0x1666c
call PrintText
call YesNoBox
jr c, .StopSavingMoney
ld a, (1 << MOM_ACTIVE_F) | (1 << MOM_SAVING_SOME_MONEY_F)
ld [wMomSavingMoney], a
ld hl, UnknownText_0x16685
call PrintText
ld a, $8
ld [wJumptableIndex], a
ret
.StopSavingMoney:
ld a, 1 << MOM_ACTIVE_F
ld [wMomSavingMoney], a
ld a, $7
ld [wJumptableIndex], a
ret
.AskDST:
ld hl, UnknownText_0x16694
call PrintText
.JustDoWhatYouCan:
ld hl, wJumptableIndex
set 7, [hl]
ret
DSTChecks:
; check the time; avoid changing DST if doing so would change the current day
ld a, [wDST]
bit 7, a
ldh a, [hHours]
jr z, .NotDST
and a ; within one hour of 00:00?
jr z, .LostBooklet
jr .loop
.NotDST:
cp 23 ; within one hour of 23:00?
jr nz, .loop
; fallthrough
.LostBooklet:
call .ClearBox
bccoord 1, 14
ld hl, .Text_AdjustClock
call PlaceHLTextAtBC
call YesNoBox
ret c
call .ClearBox
bccoord 1, 14
ld hl, .Text_LostInstructionBooklet
call PlaceHLTextAtBC
ret
.loop
call .ClearBox
bccoord 1, 14
ld a, [wDST]
bit 7, a
jr z, .SetDST
ld hl, .Text_IsDSTOver
call PlaceHLTextAtBC
call YesNoBox
ret c
ld a, [wDST]
res 7, a
ld [wDST], a
call .SetClockBack
call .ClearBox
bccoord 1, 14
ld hl, .Text_SetClockBack
call PlaceHLTextAtBC
ret
.SetDST:
ld hl, .Text_SwitchToDST
call PlaceHLTextAtBC
call YesNoBox
ret c
ld a, [wDST]
set 7, a
ld [wDST], a
call .SetClockForward
call .ClearBox
bccoord 1, 14
ld hl, .Text_SetClockForward
call PlaceHLTextAtBC
ret
.SetClockForward:
ld a, [wStartHour]
add 1
sub 24
jr nc, .DontLoopHourForward
add 24
.DontLoopHourForward:
ld [wStartHour], a
ccf
ld a, [wStartDay]
adc 0
ld [wStartDay], a
ret
.SetClockBack:
ld a, [wStartHour]
sub 1
jr nc, .DontLoopHourBack
add 24
.DontLoopHourBack:
ld [wStartHour], a
ld a, [wStartDay]
sbc 0
jr nc, .DontLoopDayBack
add 7
.DontLoopDayBack:
ld [wStartDay], a
ret
.ClearBox:
hlcoord 1, 14
lb bc, 3, 18
call ClearBox
ret
.Text_AdjustClock:
; Do you want to adjust your clock for Daylight Saving Time?
text_far UnknownText_0x1c6095
text_end
.Text_LostInstructionBooklet:
; I lost the instruction booklet for the POKéGEAR.
; Come back again in a while.
text_far UnknownText_0x1c60d1
text_end
.Text_SwitchToDST:
; Do you want to switch to Daylight Saving Time?
text_far UnknownText_0x1c6000
text_end
.Text_SetClockForward:
; I set the clock forward by one hour.
text_far UnknownText_0x1c6030
text_end
.Text_IsDSTOver:
; Is Daylight Saving Time over?
text_far UnknownText_0x1c6056
text_end
.Text_SetClockBack:
; I put the clock back one hour.
text_far UnknownText_0x1c6075
text_end
Mom_SetUpWithdrawMenu:
ld de, Mon_WithdrawString
jr Mom_ContinueMenuSetup
Mom_SetUpDepositMenu:
ld de, Mom_DepositString
Mom_ContinueMenuSetup:
push de
xor a
ldh [hBGMapMode], a
hlcoord 0, 0
lb bc, 6, 18
call Textbox
hlcoord 1, 2
ld de, Mom_SavedString
call PlaceString
hlcoord 12, 2
ld de, wMomsMoney
lb bc, PRINTNUM_MONEY | 3, 6
call PrintNum
hlcoord 1, 4
ld de, Mom_HeldString
call PlaceString
hlcoord 12, 4
ld de, wMoney
lb bc, PRINTNUM_MONEY | 3, 6
call PrintNum
hlcoord 1, 6
pop de
call PlaceString
hlcoord 12, 6
ld de, wStringBuffer2
lb bc, PRINTNUM_MONEY | PRINTNUM_LEADINGZEROS | 3, 6
call PrintNum
call UpdateSprites
call CGBOnly_CopyTilemapAtOnce
ret
Mom_Wait10Frames:
ld c, 10
call DelayFrames
ret
Mom_WithdrawDepositMenuJoypad:
.loop
call JoyTextDelay
ld hl, hJoyPressed
ld a, [hl]
and B_BUTTON
jr nz, .pressedB
ld a, [hl]
and A_BUTTON
jr nz, .pressedA
call .dpadaction
xor a
ldh [hBGMapMode], a
hlcoord 12, 6
ld bc, 7
ld a, " "
call ByteFill
hlcoord 12, 6
ld de, wStringBuffer2
lb bc, PRINTNUM_MONEY | PRINTNUM_LEADINGZEROS | 3, 6
call PrintNum
ldh a, [hVBlankCounter]
and $10
jr nz, .skip
hlcoord 13, 6
ld a, [wMomBankDigitCursorPosition]
ld c, a
ld b, 0
add hl, bc
ld [hl], " "
.skip
call WaitBGMap
jr .loop
.pressedB
scf
ret
.pressedA
and a
ret
.dpadaction
ld hl, hJoyLast
ld a, [hl]
and D_UP
jr nz, .incrementdigit
ld a, [hl]
and D_DOWN
jr nz, .decrementdigit
ld a, [hl]
and D_LEFT
jr nz, .movecursorleft
ld a, [hl]
and D_RIGHT
jr nz, .movecursorright
and a
ret
.movecursorleft
ld hl, wMomBankDigitCursorPosition
ld a, [hl]
and a
ret z
dec [hl]
ret
.movecursorright
ld hl, wMomBankDigitCursorPosition
ld a, [hl]
cp 5
ret nc
inc [hl]
ret
.incrementdigit
ld hl, .DigitQuantities
call .getdigitquantity
ld c, l
ld b, h
ld de, wStringBuffer2
farcall GiveMoney
ret
.decrementdigit
ld hl, .DigitQuantities
call .getdigitquantity
ld c, l
ld b, h
ld de, wStringBuffer2
farcall TakeMoney
ret
.getdigitquantity
ld a, [wMomBankDigitCursorPosition]
push de
ld e, a
ld d, 0
add hl, de
add hl, de
add hl, de
pop de
ret
.DigitQuantities:
dt 100000
dt 10000
dt 1000
dt 100
dt 10
dt 1
dt 100000
dt 10000
dt 1000
dt 100
dt 10
dt 1
dt 900000
dt 90000
dt 9000
dt 900
dt 90
dt 9
UnknownText_0x16649:
; Wow, that's a cute #MON. Where did you get it? … So, you're leaving on an adventure… OK! I'll help too. But what can I do for you? I know! I'll save money for you. On a long journey, money's important. Do you want me to save your money?
text_far _MomLeavingText1
text_end
UnknownText_0x1664e:
; OK, I'll take care of your money.
text_far _MomLeavingText2
text_end
UnknownText_0x16653:
; Be careful. #MON are your friends. You need to work as a team. Now, go on!
text_far _MomLeavingText3
text_end
UnknownText_0x16658:
; Hi! Welcome home! You're trying very hard, I see. I've kept your room tidy. Or is this about your money?
text_far _MomVisitingText1
text_end
UnknownText_0x1665d:
; What do you want to do?
text_far _MomVisitingText2
text_end
UnknownText_0x16662:
; How much do you want to save?
text_far _MomVisitingText3
text_end
UnknownText_0x16667:
; How much do you want to take?
text_far _MomVisitingText4
text_end
UnknownText_0x1666c:
; Do you want to save some money?
text_far _MomVisitingText5
text_end
UnknownText_0x16671:
; You haven't saved that much.
text_far _MomVisitingText6
text_end
UnknownText_0x16676:
; You can't take that much.
text_far _MomVisitingText7
text_end
UnknownText_0x1667b:
; You don't have that much.
text_far _MomVisitingText8
text_end
UnknownText_0x16680:
; You can't save that much.
text_far _MomVisitingText9
text_end
UnknownText_0x16685:
; OK, I'll save your money. Trust me! , stick with it!
text_far _MomVisitingText10
text_end
UnknownText_0x1668a:
; Your money's safe here! Get going!
text_far _MomVisitingText11
text_end
UnknownText_0x1668f:
; , don't give up!
text_far _MomVisitingText12
text_end
UnknownText_0x16694:
; Just do what you can.
text_far _MomVisitingText13
text_end
Mom_SavedString:
db "SAVED@"
Mon_WithdrawString:
db "WITHDRAW@"
Mom_DepositString:
db "DEPOSIT@"
Mom_HeldString:
db "HELD@"
MenuHeader_0x166b5:
db MENU_BACKUP_TILES ; flags
menu_coords 0, 0, 10, 10
dw MenuData_0x166bd
db 1 ; default option
MenuData_0x166bd:
db STATICMENU_CURSOR ; flags
db 4 ; items
db "GET@"
db "SAVE@"
db "CHANGE@"
db "CANCEL@"
|
; A080540: Number of neutrons in longest known radioactive decay series ending with Lead 209, reversed.
; 127,126,128,130,132,134,136,137,139,141,142,144,145,147,149,151,153,155,157,159,161,163
mov $1,3
mov $2,2
mov $3,6
mov $6,$0
lpb $0
sub $3,$1
add $2,$3
sub $0,$2
trn $0,1
mov $1,1
mov $2,$5
lpe
add $3,4
mov $1,$3
add $1,117
mov $4,$6
mul $4,2
add $1,$4
|
;Disp 'Help us' until Step-Key pushed:
ORG 1800H
LD IX,Help
Disp CALL Scan
CP 13H ;Key-Step
JR NZ,Disp
HALT
ORG 1820H
Help DEFB 0AEH ;'S'
DEFB 0B5H ;'U'
DEFB 01FH ;'P'
DEFB 085H ;'L'
DEFB 08FH ;'E'
DEFB 037H ;'H'
;
Scan EQU 05FEH
END |
; A067869: Numbers n such that n and 2^n end with the same 5 digits.
; 48736,148736,248736,348736,448736,548736,648736,748736,848736,948736,1048736,1148736,1248736,1348736,1448736,1548736,1648736,1748736,1848736,1948736,2048736,2148736,2248736,2348736,2448736,2548736
mul $0,100000
add $0,48736
|
; size_t getdelim(char **lineptr, size_t *n, int delimiter, FILE *stream)
INCLUDE "config_private.inc"
SECTION code_clib
SECTION code_stdio
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
IF __CLIB_OPT_MULTITHREAD & $02
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC _getdelim
EXTERN asm_getdelim
_getdelim:
pop af
pop hl
pop de
pop bc
pop ix
push hl
push bc
push de
push hl
push af
jp asm_getdelim
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ELSE
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PUBLIC _getdelim
EXTERN _getdelim_unlocked
defc _getdelim = _getdelim_unlocked
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ENDIF
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
; A246780: Strictly increasing terms of the sequence A246778: a(1)= A246778(1) and for n>0 a(n+1) is next term greater than a(n) after that a(n) appears in A246778 for the first time.
; 2,3,4,6,8,9,11,12,13,14,15,16,17,18,19,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70
mov $1,2
add $1,$0
mov $2,$0
mov $3,3
mov $4,$0
mov $5,2
lpb $2
lpb $4
add $1,1
sub $2,4
trn $4,$3
sub $3,1
add $5,$4
lpe
sub $4,1
lpb $5
mov $2,6
add $3,$4
mov $4,3
mov $5,0
lpe
sub $2,$4
trn $2,1
add $4,5
lpe
mov $0,$1
|
;---------------------------------------------------------------;
; ;
; Banchor ;
; Enemy AI Scripts ;
; ;
;---------------------------------------------------------------;
;------------------------------------------------
; All enemy AI scripts follow
; input: IX => Start of enemy entry
; output: IX => Start of enemy entry
;------------------------------------------------
;------------------------------------------------
; aiKnightNoShoot - early version of the Knight that just wanders (no shooting)
; uses: enemyWander
;------------------------------------------------
aiKnightNoShoot:
call despawnOffScreen
ret c
ld a,(frame)
bit 0,a
call z,enemyWander
ret
;------------------------------------------------
; aiKnight - standard Knight that wanders and occasionally pauses to shoot in a cardinal direction
; aiTroll has identical behaviour
; uses: enemyWander
; enemyShoot
; E_PAUSECNT (counter for pausing to shoot)
;------------------------------------------------
aiKnight:
aiTroll:
call despawnOffScreen
ret c
ld hl,getAngleCardinal
ld de,enemyWander
ld a,50
aiKnightCommon:
ld (__enemyShootAngle),hl
ld (__knightWander),de
ld (__knightPauseCeiling),a
ld a,(ix+E_PAUSECNT)
or a
jr nz,aiKnightPaused ; enemy currently paused
call checkEnemyTileAligned
jr nz,aiKnightContinueWander ; if not tile aligned, continue the wandering
__knightPauseCeiling = $+1
ld b,$00
call random
or a
jr nz,aiKnightContinueWander ; 1-in-B chance of starting a pause, otherwise continue wandering
aiKnightStartPause:
ld (ix+E_PAUSECNT),50
aiKnightPaused:
dec (ix+E_PAUSECNT)
ret nz
jp enemyShoot
aiKnightContinueWander:
ld a,(frame)
bit 0,a
__knightWander = $+1
call z,$000000
call enemyDirToFrame
ret
;------------------------------------------------
; aiKnightAim - endgame Knight that wanders and occasionally pauses to shoot
; uses: aiKnight
;------------------------------------------------
aiKnightAim:
call despawnOffScreen
ret c
ld hl,getAngle
ld de,enemyWander
ld a,50
jr aiKnightCommon
;------------------------------------------------
; aiOctopus - jump on the spot and occasionally shoot at player
; uses: enemyJump
; enemyShoot
;------------------------------------------------
aiOctopus:
call enemyJump
ld hl,getAngle
ld (__enemyShootAngle),hl
ld a,(ix+E_JUMPCNT)
or a
ret nz ; don't shoot if mid-jump
ld b,200
call random
or a
ret nz
jp enemyShoot
;------------------------------------------------
; aiPotatoBug - chase the player every 2nd frame
; aiMummy has identical behaviour
; uses: enemyFollow
;------------------------------------------------
aiPotatoBug:
aiMummy:
call despawnOffScreen
ret c
ld a,(frame)
bit 0,a
call z,enemyFollow
call enemyDirToFrame
ret
;------------------------------------------------
; aiJellyfish - chase the player, but pause between each tile
; uses: enemyFollow
; E_PAUSECNT (counter for pausing between tiles)
;------------------------------------------------
aiJellyfish:
call despawnOffScreen
ret c
ld a,20
ld c,OP_CALLZ
aiJellyfishCommon:
ld (__jellyfishPause),a
ld a,c
ld (__jellyfishSpeed),a
ld a,(ix+E_PAUSECNT)
or a
jr nz,aiJellyfishPaused
call checkEnemyTileAligned
jr nz,aiJellyfishFollow
__jellyfishPause = $+1
ld b,20
call random
add a,30
ld (ix+E_PAUSECNT),a
aiJellyfishPaused:
dec (ix+E_PAUSECNT)
ld a,(ix+E_PAUSECNT)
and %11111110
ret nz
aiJellyfishFollow:
ld a,(frame)
bit 0,a
__jellyfishSpeed = $
call z,enemyFollow
call enemyDirToFrame
ret
;------------------------------------------------
; aiBat - chase player using the 16 directions in arc patterns by slowing down when it needs to alter it's trajectory and speeding up when it's on course
; this is a unique behaviour used only by Bats
; uses: E_SPEED (used to keep track of how fast the Bat is moving
;------------------------------------------------
aiBat:
call despawnOffScreen
ret c
; first, check if E_SPEED has been initialised (only happens once per Bat)
ld a,(ix+E_SPEED)
or a
jr nz,aiBatSpeedSet
; it's a brand new Bat, initialise E_SPEED and E_DIR
ld (ix+E_SPEED),32
call getAngle
inc a
ld (ix+E_DIR),a
aiBatSpeedSet:
; first, check if the Bat is heading towards the player already
call getAngle
ld b,(ix+E_DIR)
dec b
call aiBatCalcAngleDiff
cp 2
jr c,aiBatSpeedUp ; if angle is off by 1 or less, speed up and keep current direction
cp 4
jr c,aiBatAlterDir ; if angle is only off by 3 or less, maintain current speed and adjust angle by 1
; otherwise, slow down before adjusting angle
aiBatSlowDown:
ld a,(frame)
and %00000001
jr nz,aiBatAlterDir ; can only slow down every 2nd frame
ld a,(ix+E_SPEED)
cp 32
jr z,aiBatAlterDir ; already at min speed
inc a
ld (ix+E_SPEED),a
aiBatAlterDir:
ld a,(frame)
and %00000011
jr nz,aiBatMove ; can only alter direction every 4th frame
ld e,(ix+E_DIR)
dec e
ld d,16
mlt de ; dir16Turn row offset
ld hl,0
ld l,c
add hl,de
ld de,dir16Turn
add hl,de
ld a,(hl) ; A = new direction
inc a
ld (ix+E_DIR),a
jr aiBatMove
aiBatSpeedUp:
ld a,(ix+E_SPEED)
cp 8
jr z,aiBatMove ; already at max speed
dec a
ld (ix+E_SPEED),a
aiBatMove:
ld a,(ix+E_DIR)
dec a
ld b,(ix+E_SPEED)
srl b
srl b
srl b
dec b
call moveDir16
ret
aiBatCalcAngleDiff:
ld c,a
sub b
ABSA()
cp 8
ret c
sub 16
ABSA()
ret
;------------------------------------------------
; aiSnake - chase the player and occasionally jump
; uses: enemyFollow
; enemyJump
;------------------------------------------------
aiSnake:
call despawnOffScreen
ret c
call enemyJump
ld a,(ix+E_JUMPCNT)
or a
ret nz ; don't follow if mid-jump
ld a,(frame)
bit 0,a
call z,enemyFollow
call enemyDirToFrame
ret
;------------------------------------------------
; aiBee - move around in a circle either clockwise or counter clockwise, and in one of 3 radii
; this is a unique behaviour used only by Bees
; uses: E_SPEED (used to determine the circle radius by how often the Bee changes it's angle)
; E_FLAGS (bit 0 is the circle direction, either CW or CCW)
;------------------------------------------------
aiBee:
call despawnOffScreen
ret c
; first, check if E_SPEED has been set (not zero), this only happens once per Bee
ld a,(ix+E_SPEED)
or a
ld c,a
jr nz,aiBeeSpeedSet ; if so, skip this next bit
; choose a random speed value (will either be %00000001, %00000011 or %00000111)
; this value will cause the Bee to change it's direction every 2nd, 4th or 8th frame, to get the "random" circle radii
ld b,3
call random
inc a
ld b,a
xor a
ld c,1
aiBeeCalcSpeed:
or c
rlc c
djnz aiBeeCalcSpeed
ld c,a
ld (ix+E_SPEED),c
; choose either CW or CCW direction
ld b,2
call random
ld (ix+E_FLAGS),a
aiBeeSpeedSet:
ld c,-1
bit 0,(ix+E_FLAGS)
jr z,aiBeeCheckFrame
ld c,1
aiBeeCheckFrame:
ld a,(frame)
and (ix+E_SPEED)
ld a,(ix+E_DIR)
jr nz,aiBeeMove
dec a
add a,c
and $0F
inc a
ld (ix+E_DIR),a
aiBeeMove:
dec a
ld b,1
call moveDir16
aiBeeShoot:
ld b,200
call random
or a
ret nz
ld hl,getAngle
ld (__enemyShootAngle),hl
jp enemyShoot
;------------------------------------------------
; aiFrog - jump across the screen either left or right
; this is a unique behaviour used only by Frogs
; uses: E_JUMPCNT (counter for the various tables used to calculate the jump)
;------------------------------------------------
aiFrog:
ld a,(frame)
bit 0,a
ret nz
call despawnOffScreen
ret c
ld a,(ix+E_JUMPCNT)
or a
jr nz,aiFrogContinue
inc (ix+E_JUMPCNT)
ld a,(x)
sub (ix+E_X)
jr c,aiFrogLeft
aiFrogRight:
ld (ix+E_DIR),3
jr aiFrogContinue
aiFrogLeft:
ld (ix+E_DIR),1
aiFrogContinue:
ld bc,0
ld c,(ix+E_JUMPCNT)
dec c
push bc
ld hl,frogYTable
add hl,bc
ld a,(hl)
add a,(ix+E_Y)
ld (ix+E_Y),a
ld a,(ix+E_DIR)
cp 3
ld a,$80
ld b,2
jr nc,aiFrogCalcValues
ld a,$90
ld b,0
aiFrogCalcValues:
ld (__aiFrogAddSub),a
ld a,b
ld (__aiFrogDir),a
pop bc
push bc
ld hl,frogXTable
add hl,bc
ld b,(hl)
ld a,(ix+E_X)
__aiFrogAddSub = $
nop
ld (ix+E_X),a
__aiFrogDir = $+1
ld a,$00
pop bc
ld hl,frogDirTable
add hl,bc
add a,(hl)
ld (ix+E_DIR),a
call enemyDirToFrame
inc (ix+E_JUMPCNT)
ld a,(ix+E_JUMPCNT)
cp FROG_CNT_MAX+1
ret c
ld (ix+E_JUMPCNT),1
ret
;------------------------------------------------
; aiSpider - wanders with no clipping and occasionally pauses to shoot
; uses: aiKnight
;------------------------------------------------
aiSpider:
call despawnOffScreen
ret c
ld hl,getAngle
ld de,enemyWanderNoClip
ld a,100
jp aiKnightCommon
;------------------------------------------------
; aiPigmySkeleton - chase the player fast
; uses: enemyFollow
;------------------------------------------------
aiPigmySkeleton:
call despawnOffScreen
ret c
call enemyFollow
call enemyDirToFrame
ret
;------------------------------------------------
; aiPigmySkeletonJump - chase the player fast and occasionally jump
; uses: enemyFollow
; enemyJump
;------------------------------------------------
aiPigmySkeletonJump:
call despawnOffScreen
ret c
call enemyJump
ld a,(ix+E_JUMPCNT)
or a
call z,enemyFollow ; don't follow if mid-jump
call enemyDirToFrame
ret
;------------------------------------------------
; aiMudman - chase the player every 2nd frame with no wall clipping
; aiShadowBeast has identical behaviour
; uses: enemyFollow
;------------------------------------------------
aiMudman:
aiShadowBeast:
ld a,(frame)
bit 0,a
call z,enemyFollowNoClip
call enemyDirToFrame
ret
;------------------------------------------------
; aiTreeMonster - chase the player like Jellyfish but walks faster and has potential for longer pauses between each tile
; uses: aiJellyfish
;------------------------------------------------
aiTreeMonster:
call despawnOffScreen
ret c
ld a,80
ld c,OP_CALL
jp aiJellyfishCommon
;------------------------------------------------
; aiDeathLord - swoop up/down and left/right around the screen
; uses: E_JUMPCNT (to keep track of the horizontal movement)
; E_SPEED (assigned a random number after spawn to use as an offset for frame counter to track vertical movement)
; E_FLAGS (to track up/down and left/right directions)
;------------------------------------------------
aiDeathLord:
call despawnOffScreen
ret c
; first, check if E_SPEED has been set (not zero), this only happens once per Death Lord
ld a,(ix+E_SPEED)
or a
jr nz,aiDeathLordSpeedSet
; choose a random speed value between 1-16
ld b,16
call random
inc a
ld (ix+E_SPEED),a
aiDeathLordSpeedSet:
; horizontal movement, works off E_JUMPCNT
ld a,(ix+E_JUMPCNT)
LDHLA()
ld de,deathLordHoriz
add hl,de
inc a
cp DEATHLORD_HORIZ_MAX
jr nz,aiDeathLordSaveCount
ld a,(ix+E_FLAGS)
xor %00000001
ld (ix+E_FLAGS),a
xor a
aiDeathLordSaveCount:
ld (ix+E_JUMPCNT),a
bit 0,(ix+E_FLAGS)
ld a,(hl)
jr nz,aiDeathLordHoriz
neg
aiDeathLordHoriz:
add a,(ix+E_X)
ld (ix+E_X),a
; vertical movement, works off the frame counter with E_SPEED being a random offset for each Death Lord
ld a,(frame)
add a,(ix+E_SPEED)
and %00011111
jr nz,aiDeathLordAfterToggle
ld c,a
ld a,(ix+E_FLAGS)
xor %00000010
ld (ix+E_FLAGS),a
ld a,c
aiDeathLordAfterToggle:
LDHLA()
ld de,deathLordVert
add hl,de
bit 1,(ix+E_FLAGS)
ld a,(hl)
jr nz,aiDeathLordVert
neg
aiDeathLordVert:
add a,(ix+E_Y)
ld (ix+E_Y),a
ret
;------------------------------------------------
; aiKoranda - chase the player every 2nd frame with no wall clipping, and occasionally shoot
; uses: enemyFollow
; enemyShoot
;------------------------------------------------
aiKoranda:
ld a,(frame)
bit 0,a
call z,enemyFollowNoClip
ld b,200
call random
or a
ret nz
ld hl,getAngle
ld (__enemyShootAngle),hl
jp enemyShoot
; below are common routines used by various AI scripts
;------------------------------------------------
; enemyWander - enemy wanders around in any cardinal direction
;------------------------------------------------
enemyWander:
call enemySetClip
enemyWanderCommon:
xor a
ld (dirFlags),a
call checkEnemyTileAligned
jp nz,moveEnemyDir ; if enemy is not tile aligned, continue moving in the direction they're facing
; pick a new direction and try to move in it (with a chance enemy will decide to stay idle)
ld b,6
call random ; 0 <= A <= 5
or a
jp z,moveEnemyUp
dec a
jp z,moveEnemyDown
dec a
jp z,moveEnemyLeft
dec a
jp z,moveEnemyRight
ret
;------------------------------------------------
; enemyWanderNoClip - enemy wanders around in any cardinal direction without wall clipping
;------------------------------------------------
enemyWanderNoClip:
call enemySetNoClip
jr enemyWanderCommon
;------------------------------------------------
; enemyFollow - enemy follows the player
;------------------------------------------------
enemyFollow:
call enemySetClip
enemyFollowCommon:
xor a
ld (dirFlags),a
call checkEnemyTileAligned
jp nz,moveEnemyDir ; if enemy is not tile aligned, continue moving in the direction they're facing
; pick a new direction based on player position
; get x-axis position difference
ld a,(x)
sub (ix+E_X)
ld d,a
ABSA()
ld b,a
; get y-axis position difference
ld a,(y)
sub (ix+E_Y)
ld e,a
ABSA()
; which is bigger?
push de ; save x & y differences for later
ld hl,enemyFollow1stAttempt ; RET location for first move attempt
cp b
jr nc,enemyFollowVert ; if y difference is bigger, try to move vertical
enemyFollowHoriz:
; going to try to move horizontally, check if left or right
ld b,0 ; B = moving horizontally
push bc ; save it
bit 7,d
ld a,3
jr z,enemyFollowTryMove
ld a,2
jr enemyFollowTryMove
enemyFollowVert:
; going to try to move vertically, check if up or down
ld b,1 ; B = moving vertically
push bc
bit 7,e
ld a,1
jr z,enemyFollowTryMove
xor a
enemyFollowTryMove:
push hl ; where to RET to after trying to move
or a
jp z,moveEnemyUp
dec a
jp z,moveEnemyDown
dec a
jp z,moveEnemyLeft
jp moveEnemyRight
enemyFollow1stAttempt:
pop bc ; B = axis flag
pop de ; D = x diff, E = y diff
ret nc ; if moved successfully, nothing else to do
ld hl,enemyFollow2ndAttempt
push hl ; where to RET to after trying to move a 2nd time
ld a,b
or a
jr z,enemyFollowVert
jr enemyFollowHoriz
enemyFollow2ndAttempt:
pop bc ; clear stack
ret nc ; if moved successfully, nothing else to do
; if execution gets here, the enemy has tried and failed to move closer to the player on both axes
; whichever two directions were attemped will have had their bits set in dirFlags
call moveEnemyUp
call c,moveEnemyDown
call c,moveEnemyLeft
call c,moveEnemyRight
ret
;------------------------------------------------
; enemyFollowNoClip - enemy follows the player without wall clipping
;------------------------------------------------
enemyFollowNoClip:
call enemySetNoClip
jp enemyFollowCommon
;------------------------------------------------
; enemyShoot - try to shoot at the player
; uses: (__enemyShootAngle) should be either getAngle or getAngleCardinal
;------------------------------------------------
enemyShoot:
call getEmptyBulletEntry
ret c
push hl
__enemyShootAngle = $+1
call $000000
pop hl
inc a
ld (hl),a
inc hl
ld a,(ix+E_X)
inc a
ld (hl),a
inc hl
ld a,(ix+E_Y)
inc a
ld (hl),a
ret
;------------------------------------------------
; enemyJump - occasionally jump in place (used by snakes, octopii and endgame pigmy skeletons
; uses: E_JUMPCNT (counter for jumpTable)
;------------------------------------------------
enemyJump:
ld a,(ix+E_JUMPCNT)
or a
jr nz,enemyJumpContinue
ld b,40
call random
or a ; 1-in-B chance of jumping
ret nz
; A = 0 here for the first jump frame
enemyJumpContinue:
LDHLA()
ld de,jumpTable
add hl,de
ld a,(hl)
add a,(ix+E_Y)
ld (ix+E_Y),a
inc (ix+E_JUMPCNT)
ld a,(ix+E_JUMPCNT)
cp JUMP_MAX
ret c
ld (ix+E_JUMPCNT),0
ret
;------------------------------------------------
; checkEnemyTileAligned - check if enemy is tile aligned
; input: IX => enemy entry
; output: IX => enemy entry
; Z if tile aligned, NZ if not
;------------------------------------------------
checkEnemyTileAligned:
ld a,(ix+E_X)
and %00000111
ret nz
ld a,(ix+E_Y)
and %00000111
ret
;------------------------------------------------
; moveEnemyDir - move enemy in a cardinal direction according to direction value
; input: IX => enemy entry
; output: IX => enemy entry
;------------------------------------------------
moveEnemyDir:
ld a,(ix+E_DIR)
dec a
jp z,moveEnemyUp
dec a
jp z,moveEnemyDown
dec a
jp z,moveEnemyLeft
dec a
jp z,moveEnemyRight
ret
;------------------------------------------------
; moveEnemyUp - try to move an enemy up
; input: IX => Start of enemy entry
; output: IX => Start of enemy entry
; CA = 1 if couldn't move
;------------------------------------------------
moveEnemyUp:
ld hl,dirFlags
bit 0,(hl)
scf
set 0,(hl)
ret nz ; leave if this direction has already been attempted, with carry set to signify move failed
ld a,(ix+E_X)
ld l,(ix+E_Y)
dec l
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
ld a,(ix+E_X)
add a,7
ld l,(ix+E_Y)
dec l
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
dec (ix+E_Y)
ld (ix+E_DIR),1
or a
ret
;------------------------------------------------
; moveEnemyDown - try to move an enemy down
; input: IX => Start of enemy entry
; output: IX => Start of enemy entry
; CA = 1 if couldn't move
;------------------------------------------------
moveEnemyDown:
ld hl,dirFlags
bit 1,(hl)
scf
set 1,(hl)
ret nz
ld a,(ix+E_Y)
add a,8
ld l,a
ld a,(ix+E_X)
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
ld a,(ix+E_Y)
add a,8
ld l,a
ld a,(ix+E_X)
add a,7
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
inc (ix+E_Y)
ld (ix+E_DIR),2
or a
ret
;------------------------------------------------
; moveEnemyLeft - try to move an enemy left
; input: IX => Start of enemy entry
; output: IX => Start of enemy entry
; CA = 1 if couldn't move
;------------------------------------------------
moveEnemyLeft:
ld hl,dirFlags
bit 2,(hl)
scf
set 2,(hl)
ret nz
ld a,(ix+E_X)
dec a
ld l,(ix+E_Y)
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
ld a,(ix+E_Y)
add a,7
ld l,a
ld a,(ix+E_X)
dec a
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
dec (ix+E_X)
ld (ix+E_DIR),3
or a
ret
;------------------------------------------------
; moveEnemyRight - try to move an enemy right
; input: IX => Start of enemy entry
; output: IX => Start of enemy entry
; CA = 1 if couldn't move
;------------------------------------------------
moveEnemyRight:
ld hl,dirFlags
bit 3,(hl)
scf
set 3,(hl)
ret nz
ld a,(ix+E_X)
add a,8
ld l,(ix+E_Y)
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
ld a,(ix+E_Y)
add a,7
ld l,a
ld a,(ix+E_X)
add a,8
call enemyGetTile
cp ENEMY_WALL
ccf
ret c
inc (ix+E_X)
ld (ix+E_DIR),4
or a
ret
;------------------------------------------------
; enemySetClip - modify enemyGetTile for wall clipping
; input: none
; output: none
;------------------------------------------------
enemySetClip:
xor a
ld (__enemyGetTile),a ; load "nop"
ret
;------------------------------------------------
; enemySetNoClip - modify enemyGetTile for NO wall clipping
; input: none
; output: none
;------------------------------------------------
enemySetNoClip:
ld a,OP_XOR_A
ld (__enemyGetTile),a ; load "xor a"
ret
;------------------------------------------------
; enemyGetTile - same as getTile, but can be hacked for flying enemies
; input: A = X Coord
; L = Y Coord
; output: HL => Tile
; A = Tile
;------------------------------------------------
enemyGetTile:
call getTile
__enemyGetTile = $
nop ; this instruction can be changed to "xor a" for flying enemies
ret
;------------------------------------------------
; despawnOffScreen - despawn enemy if off screen
; input: IX => enemy entry
; output: IX => enemy entry
; CA = 1 if enemy was despawned
;------------------------------------------------
despawnOffScreen:
call checkEnemyOnScreen
ret nc
ld (ix+E_DIR),0
ret
;------------------------------------------------
; enemyDirToFrame - convert E_DIR value to E_FRAME value
; input: IX => enemy entry
; output: IX => enemy entry
;------------------------------------------------
enemyDirToFrame:
ld a,(ix+E_DIR)
dec a
ld (ix+E_FRAME),a
ret
.end
|
_wc: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
printf(1, "%d %d %d %s\n", l, w, c, name);
}
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 57 push %edi
e: 56 push %esi
f: 53 push %ebx
10: 51 push %ecx
11: be 01 00 00 00 mov $0x1,%esi
16: 83 ec 18 sub $0x18,%esp
19: 8b 01 mov (%ecx),%eax
1b: 8b 59 04 mov 0x4(%ecx),%ebx
1e: 83 c3 04 add $0x4,%ebx
int fd, i;
if(argc <= 1){
21: 83 f8 01 cmp $0x1,%eax
{
24: 89 45 e4 mov %eax,-0x1c(%ebp)
if(argc <= 1){
27: 7e 56 jle 7f <main+0x7f>
29: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
wc(0, "");
exit();
}
for(i = 1; i < argc; i++){
if((fd = open(argv[i], 0)) < 0){
30: 83 ec 08 sub $0x8,%esp
33: 6a 00 push $0x0
35: ff 33 pushl (%ebx)
37: e8 d6 03 00 00 call 412 <open>
3c: 83 c4 10 add $0x10,%esp
3f: 85 c0 test %eax,%eax
41: 89 c7 mov %eax,%edi
43: 78 26 js 6b <main+0x6b>
printf(1, "wc: cannot open %s\n", argv[i]);
exit();
}
wc(fd, argv[i]);
45: 83 ec 08 sub $0x8,%esp
48: ff 33 pushl (%ebx)
for(i = 1; i < argc; i++){
4a: 83 c6 01 add $0x1,%esi
wc(fd, argv[i]);
4d: 50 push %eax
4e: 83 c3 04 add $0x4,%ebx
51: e8 4a 00 00 00 call a0 <wc>
close(fd);
56: 89 3c 24 mov %edi,(%esp)
59: e8 9c 03 00 00 call 3fa <close>
for(i = 1; i < argc; i++){
5e: 83 c4 10 add $0x10,%esp
61: 39 75 e4 cmp %esi,-0x1c(%ebp)
64: 75 ca jne 30 <main+0x30>
}
exit();
66: e8 67 03 00 00 call 3d2 <exit>
printf(1, "wc: cannot open %s\n", argv[i]);
6b: 50 push %eax
6c: ff 33 pushl (%ebx)
6e: 68 bb 08 00 00 push $0x8bb
73: 6a 01 push $0x1
75: e8 c6 04 00 00 call 540 <printf>
exit();
7a: e8 53 03 00 00 call 3d2 <exit>
wc(0, "");
7f: 52 push %edx
80: 52 push %edx
81: 68 ad 08 00 00 push $0x8ad
86: 6a 00 push $0x0
88: e8 13 00 00 00 call a0 <wc>
exit();
8d: e8 40 03 00 00 call 3d2 <exit>
92: 66 90 xchg %ax,%ax
94: 66 90 xchg %ax,%ax
96: 66 90 xchg %ax,%ax
98: 66 90 xchg %ax,%ax
9a: 66 90 xchg %ax,%ax
9c: 66 90 xchg %ax,%ax
9e: 66 90 xchg %ax,%ax
000000a0 <wc>:
{
a0: 55 push %ebp
a1: 89 e5 mov %esp,%ebp
a3: 57 push %edi
a4: 56 push %esi
a5: 53 push %ebx
l = w = c = 0;
a6: 31 db xor %ebx,%ebx
{
a8: 83 ec 1c sub $0x1c,%esp
inword = 0;
ab: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp)
l = w = c = 0;
b2: c7 45 e0 00 00 00 00 movl $0x0,-0x20(%ebp)
b9: c7 45 dc 00 00 00 00 movl $0x0,-0x24(%ebp)
while((n = read(fd, buf, sizeof(buf))) > 0){
c0: 83 ec 04 sub $0x4,%esp
c3: 68 00 02 00 00 push $0x200
c8: 68 e0 0b 00 00 push $0xbe0
cd: ff 75 08 pushl 0x8(%ebp)
d0: e8 15 03 00 00 call 3ea <read>
d5: 83 c4 10 add $0x10,%esp
d8: 83 f8 00 cmp $0x0,%eax
db: 89 c6 mov %eax,%esi
dd: 7e 61 jle 140 <wc+0xa0>
for(i=0; i<n; i++){
df: 31 ff xor %edi,%edi
e1: eb 13 jmp f6 <wc+0x56>
e3: 90 nop
e4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
inword = 0;
e8: c7 45 e4 00 00 00 00 movl $0x0,-0x1c(%ebp)
for(i=0; i<n; i++){
ef: 83 c7 01 add $0x1,%edi
f2: 39 fe cmp %edi,%esi
f4: 74 42 je 138 <wc+0x98>
if(buf[i] == '\n')
f6: 0f be 87 e0 0b 00 00 movsbl 0xbe0(%edi),%eax
l++;
fd: 31 c9 xor %ecx,%ecx
ff: 3c 0a cmp $0xa,%al
101: 0f 94 c1 sete %cl
if(strchr(" \r\t\n\v", buf[i]))
104: 83 ec 08 sub $0x8,%esp
107: 50 push %eax
108: 68 98 08 00 00 push $0x898
l++;
10d: 01 cb add %ecx,%ebx
if(strchr(" \r\t\n\v", buf[i]))
10f: e8 3c 01 00 00 call 250 <strchr>
114: 83 c4 10 add $0x10,%esp
117: 85 c0 test %eax,%eax
119: 75 cd jne e8 <wc+0x48>
else if(!inword){
11b: 8b 55 e4 mov -0x1c(%ebp),%edx
11e: 85 d2 test %edx,%edx
120: 75 cd jne ef <wc+0x4f>
for(i=0; i<n; i++){
122: 83 c7 01 add $0x1,%edi
w++;
125: 83 45 dc 01 addl $0x1,-0x24(%ebp)
inword = 1;
129: c7 45 e4 01 00 00 00 movl $0x1,-0x1c(%ebp)
for(i=0; i<n; i++){
130: 39 fe cmp %edi,%esi
132: 75 c2 jne f6 <wc+0x56>
134: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
138: 01 75 e0 add %esi,-0x20(%ebp)
13b: eb 83 jmp c0 <wc+0x20>
13d: 8d 76 00 lea 0x0(%esi),%esi
if(n < 0){
140: 75 24 jne 166 <wc+0xc6>
printf(1, "%d %d %d %s\n", l, w, c, name);
142: 83 ec 08 sub $0x8,%esp
145: ff 75 0c pushl 0xc(%ebp)
148: ff 75 e0 pushl -0x20(%ebp)
14b: ff 75 dc pushl -0x24(%ebp)
14e: 53 push %ebx
14f: 68 ae 08 00 00 push $0x8ae
154: 6a 01 push $0x1
156: e8 e5 03 00 00 call 540 <printf>
}
15b: 83 c4 20 add $0x20,%esp
15e: 8d 65 f4 lea -0xc(%ebp),%esp
161: 5b pop %ebx
162: 5e pop %esi
163: 5f pop %edi
164: 5d pop %ebp
165: c3 ret
printf(1, "wc: read error\n");
166: 50 push %eax
167: 50 push %eax
168: 68 9e 08 00 00 push $0x89e
16d: 6a 01 push $0x1
16f: e8 cc 03 00 00 call 540 <printf>
exit();
174: e8 59 02 00 00 call 3d2 <exit>
179: 66 90 xchg %ax,%ax
17b: 66 90 xchg %ax,%ax
17d: 66 90 xchg %ax,%ax
17f: 90 nop
00000180 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
180: 55 push %ebp
181: 89 e5 mov %esp,%ebp
183: 53 push %ebx
184: 8b 45 08 mov 0x8(%ebp),%eax
187: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
18a: 89 c2 mov %eax,%edx
18c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
190: 83 c1 01 add $0x1,%ecx
193: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
197: 83 c2 01 add $0x1,%edx
19a: 84 db test %bl,%bl
19c: 88 5a ff mov %bl,-0x1(%edx)
19f: 75 ef jne 190 <strcpy+0x10>
;
return os;
}
1a1: 5b pop %ebx
1a2: 5d pop %ebp
1a3: c3 ret
1a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
1aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000001b0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
1b0: 55 push %ebp
1b1: 89 e5 mov %esp,%ebp
1b3: 53 push %ebx
1b4: 8b 55 08 mov 0x8(%ebp),%edx
1b7: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
1ba: 0f b6 02 movzbl (%edx),%eax
1bd: 0f b6 19 movzbl (%ecx),%ebx
1c0: 84 c0 test %al,%al
1c2: 75 1c jne 1e0 <strcmp+0x30>
1c4: eb 2a jmp 1f0 <strcmp+0x40>
1c6: 8d 76 00 lea 0x0(%esi),%esi
1c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
1d0: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
1d3: 0f b6 02 movzbl (%edx),%eax
p++, q++;
1d6: 83 c1 01 add $0x1,%ecx
1d9: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
1dc: 84 c0 test %al,%al
1de: 74 10 je 1f0 <strcmp+0x40>
1e0: 38 d8 cmp %bl,%al
1e2: 74 ec je 1d0 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
1e4: 29 d8 sub %ebx,%eax
}
1e6: 5b pop %ebx
1e7: 5d pop %ebp
1e8: c3 ret
1e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
1f0: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
1f2: 29 d8 sub %ebx,%eax
}
1f4: 5b pop %ebx
1f5: 5d pop %ebp
1f6: c3 ret
1f7: 89 f6 mov %esi,%esi
1f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000200 <strlen>:
uint
strlen(const char *s)
{
200: 55 push %ebp
201: 89 e5 mov %esp,%ebp
203: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
206: 80 39 00 cmpb $0x0,(%ecx)
209: 74 15 je 220 <strlen+0x20>
20b: 31 d2 xor %edx,%edx
20d: 8d 76 00 lea 0x0(%esi),%esi
210: 83 c2 01 add $0x1,%edx
213: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
217: 89 d0 mov %edx,%eax
219: 75 f5 jne 210 <strlen+0x10>
;
return n;
}
21b: 5d pop %ebp
21c: c3 ret
21d: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
220: 31 c0 xor %eax,%eax
}
222: 5d pop %ebp
223: c3 ret
224: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
22a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000230 <memset>:
void*
memset(void *dst, int c, uint n)
{
230: 55 push %ebp
231: 89 e5 mov %esp,%ebp
233: 57 push %edi
234: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
237: 8b 4d 10 mov 0x10(%ebp),%ecx
23a: 8b 45 0c mov 0xc(%ebp),%eax
23d: 89 d7 mov %edx,%edi
23f: fc cld
240: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
242: 89 d0 mov %edx,%eax
244: 5f pop %edi
245: 5d pop %ebp
246: c3 ret
247: 89 f6 mov %esi,%esi
249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000250 <strchr>:
char*
strchr(const char *s, char c)
{
250: 55 push %ebp
251: 89 e5 mov %esp,%ebp
253: 53 push %ebx
254: 8b 45 08 mov 0x8(%ebp),%eax
257: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
25a: 0f b6 10 movzbl (%eax),%edx
25d: 84 d2 test %dl,%dl
25f: 74 1d je 27e <strchr+0x2e>
if(*s == c)
261: 38 d3 cmp %dl,%bl
263: 89 d9 mov %ebx,%ecx
265: 75 0d jne 274 <strchr+0x24>
267: eb 17 jmp 280 <strchr+0x30>
269: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
270: 38 ca cmp %cl,%dl
272: 74 0c je 280 <strchr+0x30>
for(; *s; s++)
274: 83 c0 01 add $0x1,%eax
277: 0f b6 10 movzbl (%eax),%edx
27a: 84 d2 test %dl,%dl
27c: 75 f2 jne 270 <strchr+0x20>
return (char*)s;
return 0;
27e: 31 c0 xor %eax,%eax
}
280: 5b pop %ebx
281: 5d pop %ebp
282: c3 ret
283: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
289: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000290 <gets>:
char*
gets(char *buf, int max)
{
290: 55 push %ebp
291: 89 e5 mov %esp,%ebp
293: 57 push %edi
294: 56 push %esi
295: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
296: 31 f6 xor %esi,%esi
298: 89 f3 mov %esi,%ebx
{
29a: 83 ec 1c sub $0x1c,%esp
29d: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
2a0: eb 2f jmp 2d1 <gets+0x41>
2a2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
2a8: 8d 45 e7 lea -0x19(%ebp),%eax
2ab: 83 ec 04 sub $0x4,%esp
2ae: 6a 01 push $0x1
2b0: 50 push %eax
2b1: 6a 00 push $0x0
2b3: e8 32 01 00 00 call 3ea <read>
if(cc < 1)
2b8: 83 c4 10 add $0x10,%esp
2bb: 85 c0 test %eax,%eax
2bd: 7e 1c jle 2db <gets+0x4b>
break;
buf[i++] = c;
2bf: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
2c3: 83 c7 01 add $0x1,%edi
2c6: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
2c9: 3c 0a cmp $0xa,%al
2cb: 74 23 je 2f0 <gets+0x60>
2cd: 3c 0d cmp $0xd,%al
2cf: 74 1f je 2f0 <gets+0x60>
for(i=0; i+1 < max; ){
2d1: 83 c3 01 add $0x1,%ebx
2d4: 3b 5d 0c cmp 0xc(%ebp),%ebx
2d7: 89 fe mov %edi,%esi
2d9: 7c cd jl 2a8 <gets+0x18>
2db: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
2dd: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
2e0: c6 03 00 movb $0x0,(%ebx)
}
2e3: 8d 65 f4 lea -0xc(%ebp),%esp
2e6: 5b pop %ebx
2e7: 5e pop %esi
2e8: 5f pop %edi
2e9: 5d pop %ebp
2ea: c3 ret
2eb: 90 nop
2ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
2f0: 8b 75 08 mov 0x8(%ebp),%esi
2f3: 8b 45 08 mov 0x8(%ebp),%eax
2f6: 01 de add %ebx,%esi
2f8: 89 f3 mov %esi,%ebx
buf[i] = '\0';
2fa: c6 03 00 movb $0x0,(%ebx)
}
2fd: 8d 65 f4 lea -0xc(%ebp),%esp
300: 5b pop %ebx
301: 5e pop %esi
302: 5f pop %edi
303: 5d pop %ebp
304: c3 ret
305: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
309: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000310 <stat>:
int
stat(const char *n, struct stat *st)
{
310: 55 push %ebp
311: 89 e5 mov %esp,%ebp
313: 56 push %esi
314: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
315: 83 ec 08 sub $0x8,%esp
318: 6a 00 push $0x0
31a: ff 75 08 pushl 0x8(%ebp)
31d: e8 f0 00 00 00 call 412 <open>
if(fd < 0)
322: 83 c4 10 add $0x10,%esp
325: 85 c0 test %eax,%eax
327: 78 27 js 350 <stat+0x40>
return -1;
r = fstat(fd, st);
329: 83 ec 08 sub $0x8,%esp
32c: ff 75 0c pushl 0xc(%ebp)
32f: 89 c3 mov %eax,%ebx
331: 50 push %eax
332: e8 f3 00 00 00 call 42a <fstat>
close(fd);
337: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
33a: 89 c6 mov %eax,%esi
close(fd);
33c: e8 b9 00 00 00 call 3fa <close>
return r;
341: 83 c4 10 add $0x10,%esp
}
344: 8d 65 f8 lea -0x8(%ebp),%esp
347: 89 f0 mov %esi,%eax
349: 5b pop %ebx
34a: 5e pop %esi
34b: 5d pop %ebp
34c: c3 ret
34d: 8d 76 00 lea 0x0(%esi),%esi
return -1;
350: be ff ff ff ff mov $0xffffffff,%esi
355: eb ed jmp 344 <stat+0x34>
357: 89 f6 mov %esi,%esi
359: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000360 <atoi>:
int
atoi(const char *s)
{
360: 55 push %ebp
361: 89 e5 mov %esp,%ebp
363: 53 push %ebx
364: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
367: 0f be 11 movsbl (%ecx),%edx
36a: 8d 42 d0 lea -0x30(%edx),%eax
36d: 3c 09 cmp $0x9,%al
n = 0;
36f: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
374: 77 1f ja 395 <atoi+0x35>
376: 8d 76 00 lea 0x0(%esi),%esi
379: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
380: 8d 04 80 lea (%eax,%eax,4),%eax
383: 83 c1 01 add $0x1,%ecx
386: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
38a: 0f be 11 movsbl (%ecx),%edx
38d: 8d 5a d0 lea -0x30(%edx),%ebx
390: 80 fb 09 cmp $0x9,%bl
393: 76 eb jbe 380 <atoi+0x20>
return n;
}
395: 5b pop %ebx
396: 5d pop %ebp
397: c3 ret
398: 90 nop
399: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000003a0 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
3a0: 55 push %ebp
3a1: 89 e5 mov %esp,%ebp
3a3: 56 push %esi
3a4: 53 push %ebx
3a5: 8b 5d 10 mov 0x10(%ebp),%ebx
3a8: 8b 45 08 mov 0x8(%ebp),%eax
3ab: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
3ae: 85 db test %ebx,%ebx
3b0: 7e 14 jle 3c6 <memmove+0x26>
3b2: 31 d2 xor %edx,%edx
3b4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
3b8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
3bc: 88 0c 10 mov %cl,(%eax,%edx,1)
3bf: 83 c2 01 add $0x1,%edx
while(n-- > 0)
3c2: 39 d3 cmp %edx,%ebx
3c4: 75 f2 jne 3b8 <memmove+0x18>
return vdst;
}
3c6: 5b pop %ebx
3c7: 5e pop %esi
3c8: 5d pop %ebp
3c9: c3 ret
000003ca <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
3ca: b8 01 00 00 00 mov $0x1,%eax
3cf: cd 40 int $0x40
3d1: c3 ret
000003d2 <exit>:
SYSCALL(exit)
3d2: b8 02 00 00 00 mov $0x2,%eax
3d7: cd 40 int $0x40
3d9: c3 ret
000003da <wait>:
SYSCALL(wait)
3da: b8 03 00 00 00 mov $0x3,%eax
3df: cd 40 int $0x40
3e1: c3 ret
000003e2 <pipe>:
SYSCALL(pipe)
3e2: b8 04 00 00 00 mov $0x4,%eax
3e7: cd 40 int $0x40
3e9: c3 ret
000003ea <read>:
SYSCALL(read)
3ea: b8 05 00 00 00 mov $0x5,%eax
3ef: cd 40 int $0x40
3f1: c3 ret
000003f2 <write>:
SYSCALL(write)
3f2: b8 10 00 00 00 mov $0x10,%eax
3f7: cd 40 int $0x40
3f9: c3 ret
000003fa <close>:
SYSCALL(close)
3fa: b8 15 00 00 00 mov $0x15,%eax
3ff: cd 40 int $0x40
401: c3 ret
00000402 <kill>:
SYSCALL(kill)
402: b8 06 00 00 00 mov $0x6,%eax
407: cd 40 int $0x40
409: c3 ret
0000040a <exec>:
SYSCALL(exec)
40a: b8 07 00 00 00 mov $0x7,%eax
40f: cd 40 int $0x40
411: c3 ret
00000412 <open>:
SYSCALL(open)
412: b8 0f 00 00 00 mov $0xf,%eax
417: cd 40 int $0x40
419: c3 ret
0000041a <mknod>:
SYSCALL(mknod)
41a: b8 11 00 00 00 mov $0x11,%eax
41f: cd 40 int $0x40
421: c3 ret
00000422 <unlink>:
SYSCALL(unlink)
422: b8 12 00 00 00 mov $0x12,%eax
427: cd 40 int $0x40
429: c3 ret
0000042a <fstat>:
SYSCALL(fstat)
42a: b8 08 00 00 00 mov $0x8,%eax
42f: cd 40 int $0x40
431: c3 ret
00000432 <link>:
SYSCALL(link)
432: b8 13 00 00 00 mov $0x13,%eax
437: cd 40 int $0x40
439: c3 ret
0000043a <mkdir>:
SYSCALL(mkdir)
43a: b8 14 00 00 00 mov $0x14,%eax
43f: cd 40 int $0x40
441: c3 ret
00000442 <chdir>:
SYSCALL(chdir)
442: b8 09 00 00 00 mov $0x9,%eax
447: cd 40 int $0x40
449: c3 ret
0000044a <dup>:
SYSCALL(dup)
44a: b8 0a 00 00 00 mov $0xa,%eax
44f: cd 40 int $0x40
451: c3 ret
00000452 <getpid>:
SYSCALL(getpid)
452: b8 0b 00 00 00 mov $0xb,%eax
457: cd 40 int $0x40
459: c3 ret
0000045a <sbrk>:
SYSCALL(sbrk)
45a: b8 0c 00 00 00 mov $0xc,%eax
45f: cd 40 int $0x40
461: c3 ret
00000462 <sleep>:
SYSCALL(sleep)
462: b8 0d 00 00 00 mov $0xd,%eax
467: cd 40 int $0x40
469: c3 ret
0000046a <uptime>:
SYSCALL(uptime)
46a: b8 0e 00 00 00 mov $0xe,%eax
46f: cd 40 int $0x40
471: c3 ret
00000472 <getpriority>:
SYSCALL(getpriority)
472: b8 16 00 00 00 mov $0x16,%eax
477: cd 40 int $0x40
479: c3 ret
0000047a <setpriority>:
SYSCALL(setpriority)
47a: b8 17 00 00 00 mov $0x17,%eax
47f: cd 40 int $0x40
481: c3 ret
00000482 <getusage>:
SYSCALL(getusage)
482: b8 18 00 00 00 mov $0x18,%eax
487: cd 40 int $0x40
489: c3 ret
0000048a <trace>:
SYSCALL(trace)
48a: b8 19 00 00 00 mov $0x19,%eax
48f: cd 40 int $0x40
491: c3 ret
00000492 <getptable>:
SYSCALL(getptable)
492: b8 1a 00 00 00 mov $0x1a,%eax
497: cd 40 int $0x40
499: c3 ret
49a: 66 90 xchg %ax,%ax
49c: 66 90 xchg %ax,%ax
49e: 66 90 xchg %ax,%ax
000004a0 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
4a0: 55 push %ebp
4a1: 89 e5 mov %esp,%ebp
4a3: 57 push %edi
4a4: 56 push %esi
4a5: 53 push %ebx
4a6: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
4a9: 85 d2 test %edx,%edx
{
4ab: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
4ae: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
4b0: 79 76 jns 528 <printint+0x88>
4b2: f6 45 08 01 testb $0x1,0x8(%ebp)
4b6: 74 70 je 528 <printint+0x88>
x = -xx;
4b8: f7 d8 neg %eax
neg = 1;
4ba: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
4c1: 31 f6 xor %esi,%esi
4c3: 8d 5d d7 lea -0x29(%ebp),%ebx
4c6: eb 0a jmp 4d2 <printint+0x32>
4c8: 90 nop
4c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
4d0: 89 fe mov %edi,%esi
4d2: 31 d2 xor %edx,%edx
4d4: 8d 7e 01 lea 0x1(%esi),%edi
4d7: f7 f1 div %ecx
4d9: 0f b6 92 d8 08 00 00 movzbl 0x8d8(%edx),%edx
}while((x /= base) != 0);
4e0: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
4e2: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
4e5: 75 e9 jne 4d0 <printint+0x30>
if(neg)
4e7: 8b 45 c4 mov -0x3c(%ebp),%eax
4ea: 85 c0 test %eax,%eax
4ec: 74 08 je 4f6 <printint+0x56>
buf[i++] = '-';
4ee: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
4f3: 8d 7e 02 lea 0x2(%esi),%edi
4f6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
4fa: 8b 7d c0 mov -0x40(%ebp),%edi
4fd: 8d 76 00 lea 0x0(%esi),%esi
500: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
503: 83 ec 04 sub $0x4,%esp
506: 83 ee 01 sub $0x1,%esi
509: 6a 01 push $0x1
50b: 53 push %ebx
50c: 57 push %edi
50d: 88 45 d7 mov %al,-0x29(%ebp)
510: e8 dd fe ff ff call 3f2 <write>
while(--i >= 0)
515: 83 c4 10 add $0x10,%esp
518: 39 de cmp %ebx,%esi
51a: 75 e4 jne 500 <printint+0x60>
putc(fd, buf[i]);
}
51c: 8d 65 f4 lea -0xc(%ebp),%esp
51f: 5b pop %ebx
520: 5e pop %esi
521: 5f pop %edi
522: 5d pop %ebp
523: c3 ret
524: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
528: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
52f: eb 90 jmp 4c1 <printint+0x21>
531: eb 0d jmp 540 <printf>
533: 90 nop
534: 90 nop
535: 90 nop
536: 90 nop
537: 90 nop
538: 90 nop
539: 90 nop
53a: 90 nop
53b: 90 nop
53c: 90 nop
53d: 90 nop
53e: 90 nop
53f: 90 nop
00000540 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
540: 55 push %ebp
541: 89 e5 mov %esp,%ebp
543: 57 push %edi
544: 56 push %esi
545: 53 push %ebx
546: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
549: 8b 75 0c mov 0xc(%ebp),%esi
54c: 0f b6 1e movzbl (%esi),%ebx
54f: 84 db test %bl,%bl
551: 0f 84 b3 00 00 00 je 60a <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
557: 8d 45 10 lea 0x10(%ebp),%eax
55a: 83 c6 01 add $0x1,%esi
state = 0;
55d: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
55f: 89 45 d4 mov %eax,-0x2c(%ebp)
562: eb 2f jmp 593 <printf+0x53>
564: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
568: 83 f8 25 cmp $0x25,%eax
56b: 0f 84 a7 00 00 00 je 618 <printf+0xd8>
write(fd, &c, 1);
571: 8d 45 e2 lea -0x1e(%ebp),%eax
574: 83 ec 04 sub $0x4,%esp
577: 88 5d e2 mov %bl,-0x1e(%ebp)
57a: 6a 01 push $0x1
57c: 50 push %eax
57d: ff 75 08 pushl 0x8(%ebp)
580: e8 6d fe ff ff call 3f2 <write>
585: 83 c4 10 add $0x10,%esp
588: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
58b: 0f b6 5e ff movzbl -0x1(%esi),%ebx
58f: 84 db test %bl,%bl
591: 74 77 je 60a <printf+0xca>
if(state == 0){
593: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
595: 0f be cb movsbl %bl,%ecx
598: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
59b: 74 cb je 568 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
59d: 83 ff 25 cmp $0x25,%edi
5a0: 75 e6 jne 588 <printf+0x48>
if(c == 'd'){
5a2: 83 f8 64 cmp $0x64,%eax
5a5: 0f 84 05 01 00 00 je 6b0 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
5ab: 81 e1 f7 00 00 00 and $0xf7,%ecx
5b1: 83 f9 70 cmp $0x70,%ecx
5b4: 74 72 je 628 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
5b6: 83 f8 73 cmp $0x73,%eax
5b9: 0f 84 99 00 00 00 je 658 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
5bf: 83 f8 63 cmp $0x63,%eax
5c2: 0f 84 08 01 00 00 je 6d0 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
5c8: 83 f8 25 cmp $0x25,%eax
5cb: 0f 84 ef 00 00 00 je 6c0 <printf+0x180>
write(fd, &c, 1);
5d1: 8d 45 e7 lea -0x19(%ebp),%eax
5d4: 83 ec 04 sub $0x4,%esp
5d7: c6 45 e7 25 movb $0x25,-0x19(%ebp)
5db: 6a 01 push $0x1
5dd: 50 push %eax
5de: ff 75 08 pushl 0x8(%ebp)
5e1: e8 0c fe ff ff call 3f2 <write>
5e6: 83 c4 0c add $0xc,%esp
5e9: 8d 45 e6 lea -0x1a(%ebp),%eax
5ec: 88 5d e6 mov %bl,-0x1a(%ebp)
5ef: 6a 01 push $0x1
5f1: 50 push %eax
5f2: ff 75 08 pushl 0x8(%ebp)
5f5: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
5f8: 31 ff xor %edi,%edi
write(fd, &c, 1);
5fa: e8 f3 fd ff ff call 3f2 <write>
for(i = 0; fmt[i]; i++){
5ff: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
603: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
606: 84 db test %bl,%bl
608: 75 89 jne 593 <printf+0x53>
}
}
}
60a: 8d 65 f4 lea -0xc(%ebp),%esp
60d: 5b pop %ebx
60e: 5e pop %esi
60f: 5f pop %edi
610: 5d pop %ebp
611: c3 ret
612: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
618: bf 25 00 00 00 mov $0x25,%edi
61d: e9 66 ff ff ff jmp 588 <printf+0x48>
622: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
628: 83 ec 0c sub $0xc,%esp
62b: b9 10 00 00 00 mov $0x10,%ecx
630: 6a 00 push $0x0
632: 8b 7d d4 mov -0x2c(%ebp),%edi
635: 8b 45 08 mov 0x8(%ebp),%eax
638: 8b 17 mov (%edi),%edx
63a: e8 61 fe ff ff call 4a0 <printint>
ap++;
63f: 89 f8 mov %edi,%eax
641: 83 c4 10 add $0x10,%esp
state = 0;
644: 31 ff xor %edi,%edi
ap++;
646: 83 c0 04 add $0x4,%eax
649: 89 45 d4 mov %eax,-0x2c(%ebp)
64c: e9 37 ff ff ff jmp 588 <printf+0x48>
651: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
658: 8b 45 d4 mov -0x2c(%ebp),%eax
65b: 8b 08 mov (%eax),%ecx
ap++;
65d: 83 c0 04 add $0x4,%eax
660: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
663: 85 c9 test %ecx,%ecx
665: 0f 84 8e 00 00 00 je 6f9 <printf+0x1b9>
while(*s != 0){
66b: 0f b6 01 movzbl (%ecx),%eax
state = 0;
66e: 31 ff xor %edi,%edi
s = (char*)*ap;
670: 89 cb mov %ecx,%ebx
while(*s != 0){
672: 84 c0 test %al,%al
674: 0f 84 0e ff ff ff je 588 <printf+0x48>
67a: 89 75 d0 mov %esi,-0x30(%ebp)
67d: 89 de mov %ebx,%esi
67f: 8b 5d 08 mov 0x8(%ebp),%ebx
682: 8d 7d e3 lea -0x1d(%ebp),%edi
685: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
688: 83 ec 04 sub $0x4,%esp
s++;
68b: 83 c6 01 add $0x1,%esi
68e: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
691: 6a 01 push $0x1
693: 57 push %edi
694: 53 push %ebx
695: e8 58 fd ff ff call 3f2 <write>
while(*s != 0){
69a: 0f b6 06 movzbl (%esi),%eax
69d: 83 c4 10 add $0x10,%esp
6a0: 84 c0 test %al,%al
6a2: 75 e4 jne 688 <printf+0x148>
6a4: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
6a7: 31 ff xor %edi,%edi
6a9: e9 da fe ff ff jmp 588 <printf+0x48>
6ae: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
6b0: 83 ec 0c sub $0xc,%esp
6b3: b9 0a 00 00 00 mov $0xa,%ecx
6b8: 6a 01 push $0x1
6ba: e9 73 ff ff ff jmp 632 <printf+0xf2>
6bf: 90 nop
write(fd, &c, 1);
6c0: 83 ec 04 sub $0x4,%esp
6c3: 88 5d e5 mov %bl,-0x1b(%ebp)
6c6: 8d 45 e5 lea -0x1b(%ebp),%eax
6c9: 6a 01 push $0x1
6cb: e9 21 ff ff ff jmp 5f1 <printf+0xb1>
putc(fd, *ap);
6d0: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
6d3: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
6d6: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
6d8: 6a 01 push $0x1
ap++;
6da: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
6dd: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
6e0: 8d 45 e4 lea -0x1c(%ebp),%eax
6e3: 50 push %eax
6e4: ff 75 08 pushl 0x8(%ebp)
6e7: e8 06 fd ff ff call 3f2 <write>
ap++;
6ec: 89 7d d4 mov %edi,-0x2c(%ebp)
6ef: 83 c4 10 add $0x10,%esp
state = 0;
6f2: 31 ff xor %edi,%edi
6f4: e9 8f fe ff ff jmp 588 <printf+0x48>
s = "(null)";
6f9: bb cf 08 00 00 mov $0x8cf,%ebx
while(*s != 0){
6fe: b8 28 00 00 00 mov $0x28,%eax
703: e9 72 ff ff ff jmp 67a <printf+0x13a>
708: 66 90 xchg %ax,%ax
70a: 66 90 xchg %ax,%ax
70c: 66 90 xchg %ax,%ax
70e: 66 90 xchg %ax,%ax
00000710 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
710: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
711: a1 c0 0b 00 00 mov 0xbc0,%eax
{
716: 89 e5 mov %esp,%ebp
718: 57 push %edi
719: 56 push %esi
71a: 53 push %ebx
71b: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
71e: 8d 4b f8 lea -0x8(%ebx),%ecx
721: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
728: 39 c8 cmp %ecx,%eax
72a: 8b 10 mov (%eax),%edx
72c: 73 32 jae 760 <free+0x50>
72e: 39 d1 cmp %edx,%ecx
730: 72 04 jb 736 <free+0x26>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
732: 39 d0 cmp %edx,%eax
734: 72 32 jb 768 <free+0x58>
break;
if(bp + bp->s.size == p->s.ptr){
736: 8b 73 fc mov -0x4(%ebx),%esi
739: 8d 3c f1 lea (%ecx,%esi,8),%edi
73c: 39 fa cmp %edi,%edx
73e: 74 30 je 770 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
740: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
743: 8b 50 04 mov 0x4(%eax),%edx
746: 8d 34 d0 lea (%eax,%edx,8),%esi
749: 39 f1 cmp %esi,%ecx
74b: 74 3a je 787 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
74d: 89 08 mov %ecx,(%eax)
freep = p;
74f: a3 c0 0b 00 00 mov %eax,0xbc0
}
754: 5b pop %ebx
755: 5e pop %esi
756: 5f pop %edi
757: 5d pop %ebp
758: c3 ret
759: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
760: 39 d0 cmp %edx,%eax
762: 72 04 jb 768 <free+0x58>
764: 39 d1 cmp %edx,%ecx
766: 72 ce jb 736 <free+0x26>
{
768: 89 d0 mov %edx,%eax
76a: eb bc jmp 728 <free+0x18>
76c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
770: 03 72 04 add 0x4(%edx),%esi
773: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
776: 8b 10 mov (%eax),%edx
778: 8b 12 mov (%edx),%edx
77a: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
77d: 8b 50 04 mov 0x4(%eax),%edx
780: 8d 34 d0 lea (%eax,%edx,8),%esi
783: 39 f1 cmp %esi,%ecx
785: 75 c6 jne 74d <free+0x3d>
p->s.size += bp->s.size;
787: 03 53 fc add -0x4(%ebx),%edx
freep = p;
78a: a3 c0 0b 00 00 mov %eax,0xbc0
p->s.size += bp->s.size;
78f: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
792: 8b 53 f8 mov -0x8(%ebx),%edx
795: 89 10 mov %edx,(%eax)
}
797: 5b pop %ebx
798: 5e pop %esi
799: 5f pop %edi
79a: 5d pop %ebp
79b: c3 ret
79c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000007a0 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
7a0: 55 push %ebp
7a1: 89 e5 mov %esp,%ebp
7a3: 57 push %edi
7a4: 56 push %esi
7a5: 53 push %ebx
7a6: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
7a9: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
7ac: 8b 15 c0 0b 00 00 mov 0xbc0,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
7b2: 8d 78 07 lea 0x7(%eax),%edi
7b5: c1 ef 03 shr $0x3,%edi
7b8: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
7bb: 85 d2 test %edx,%edx
7bd: 0f 84 9d 00 00 00 je 860 <malloc+0xc0>
7c3: 8b 02 mov (%edx),%eax
7c5: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
7c8: 39 cf cmp %ecx,%edi
7ca: 76 6c jbe 838 <malloc+0x98>
7cc: 81 ff 00 10 00 00 cmp $0x1000,%edi
7d2: bb 00 10 00 00 mov $0x1000,%ebx
7d7: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
7da: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
7e1: eb 0e jmp 7f1 <malloc+0x51>
7e3: 90 nop
7e4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
7e8: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
7ea: 8b 48 04 mov 0x4(%eax),%ecx
7ed: 39 f9 cmp %edi,%ecx
7ef: 73 47 jae 838 <malloc+0x98>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
7f1: 39 05 c0 0b 00 00 cmp %eax,0xbc0
7f7: 89 c2 mov %eax,%edx
7f9: 75 ed jne 7e8 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
7fb: 83 ec 0c sub $0xc,%esp
7fe: 56 push %esi
7ff: e8 56 fc ff ff call 45a <sbrk>
if(p == (char*)-1)
804: 83 c4 10 add $0x10,%esp
807: 83 f8 ff cmp $0xffffffff,%eax
80a: 74 1c je 828 <malloc+0x88>
hp->s.size = nu;
80c: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
80f: 83 ec 0c sub $0xc,%esp
812: 83 c0 08 add $0x8,%eax
815: 50 push %eax
816: e8 f5 fe ff ff call 710 <free>
return freep;
81b: 8b 15 c0 0b 00 00 mov 0xbc0,%edx
if((p = morecore(nunits)) == 0)
821: 83 c4 10 add $0x10,%esp
824: 85 d2 test %edx,%edx
826: 75 c0 jne 7e8 <malloc+0x48>
return 0;
}
}
828: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
82b: 31 c0 xor %eax,%eax
}
82d: 5b pop %ebx
82e: 5e pop %esi
82f: 5f pop %edi
830: 5d pop %ebp
831: c3 ret
832: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
838: 39 cf cmp %ecx,%edi
83a: 74 54 je 890 <malloc+0xf0>
p->s.size -= nunits;
83c: 29 f9 sub %edi,%ecx
83e: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
841: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
844: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
847: 89 15 c0 0b 00 00 mov %edx,0xbc0
}
84d: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
850: 83 c0 08 add $0x8,%eax
}
853: 5b pop %ebx
854: 5e pop %esi
855: 5f pop %edi
856: 5d pop %ebp
857: c3 ret
858: 90 nop
859: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
860: c7 05 c0 0b 00 00 c4 movl $0xbc4,0xbc0
867: 0b 00 00
86a: c7 05 c4 0b 00 00 c4 movl $0xbc4,0xbc4
871: 0b 00 00
base.s.size = 0;
874: b8 c4 0b 00 00 mov $0xbc4,%eax
879: c7 05 c8 0b 00 00 00 movl $0x0,0xbc8
880: 00 00 00
883: e9 44 ff ff ff jmp 7cc <malloc+0x2c>
888: 90 nop
889: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
prevp->s.ptr = p->s.ptr;
890: 8b 08 mov (%eax),%ecx
892: 89 0a mov %ecx,(%edx)
894: eb b1 jmp 847 <malloc+0xa7>
|
; A113925: a(1)=0. a(1)=1. a(n+2) = gcd(a(n+1) + a(n), n).
; Submitted by Jon Maiga
; 0,1,1,2,3,1,1,2,1,1,1,2,1,3,1,2,3,1,1,2,1,1,1,2,1,3,1,2,3,1,1,2,1,1,1,2,1,3,1,2,3,5,1,6,1,1,1,2,1,3,1,2,3,1,1,2,1,1,1,2,1,3,1,2,3,1,1,2,1,1,1,2,1,3,1,2,3,1,1,2,1,1,1,2,1,3,1,2,3,1,1,2,1,1,1,2,1,3,1,2
mov $1,$0
mov $2,1
mov $4,1
lpb $1
mov $0,$4
sub $1,1
mov $4,$2
mov $2,1
add $2,$4
add $3,$0
gcd $4,$3
mov $3,$0
lpe
|
.include "defines.asm"
.RAMSECTION "Render Vars" SLOT "RAM"
wPlayerX: dw ; Player X in 8.8 fixed point
wPlayerY: dw ; Player Y in 8.8 fixed point
wPlayerFacingAngle: db ;the scale of this is decided by the FOV
wPlayerFacingQuadrant: db ;where 0 is top-right, 1 is bottom-right, 2 is bottom-left, 3 is top-left
wRayAngle: db ;the angle of the ray being cast
wRayX: db ;the x-coordinate of the ray being cast
wRayY: db ;the y-coordinate of the ray being cast
wXComponent: db ;the x component of the ray
wYComponent: db ;the y component of the ray
wLevelPtr: db ;the low byte of the level pointer
wLevelPtrHigh: db ;the high byte of the level pointer
.ENDS
.def HFOV 70
.def NUM_SCANLINES 192
.def NUM_VECTOR_DOUBLES 4
.def NUM_VECTOR_ANGLES NUM_SCANLINES/2
;half the size of the trig tables by only rendering half the scanlines with different angles
.slot "ROM"
.SECTION "Initial X Vector table Top Right", FREE
YVectorTableBottomRight:
XVectorTableTopRight: .DBSIN 0, 90 / HFOV * NUM_SCANLINES , HFOV / NUM_SCANLINES, 255.999 / (2^NUM_VECTOR_DOUBLES), 0
.ENDS
.SECTION "Initial X Vector table Bottom Right", FREE
YVectorTableBottomLeft:
XVectorTableBottomRight: .DBSIN 90, 90 / HFOV * NUM_SCANLINES , HFOV / NUM_SCANLINES, 255.999 / (2^NUM_VECTOR_DOUBLES), 0
.ENDS
.SECTION "Initial X Vector table Bottom Left", FREE
YVectorTableTopLeft:
XVectorTableBottomLeft: .DBSIN 180, 90 / HFOV * NUM_SCANLINES , HFOV / NUM_SCANLINES, 255.999 / (2^NUM_VECTOR_DOUBLES), 0
.ENDS
.SECTION "Initial X Vector table Top Left", FREE
YVectorTableTopRight:
XVectorTableTopLeft: .DBSIN 270, 90 / HFOV * NUM_SCANLINES , HFOV / NUM_SCANLINES, 255.999 / (2^NUM_VECTOR_DOUBLES), 0
.ENDS
.SECTION "Draw Frame Top Right", FREE
DrawFrame:
DrawFrameTopRight:
lda wPlayerFacingAngle
sta wRayAngle ;copy the permanent angle to a temporary copy used for ray casting
lda wPlayerX + 1
asl a
tay ;get the offset to the level data pointer
lda wPlayerY + 1
sta wLevelPtrHigh ;store the high byte of the level pointer
CastRayTopRight:
;start by getting the X and Y componesnts of the ray
ldx wRayAngle
cpx # 90 / HFOV * NUM_SCANLINES + 1
bcc _continue
_continue
lda.w XVectorTableTopRight,x ;get the initial x component of the ray
lsr a ;the x component get halved for the first half-step
sta wXComponent
; now cast the ray the first half-step
adc wPlayerX ;add the player's x coordinate to the x component of the ray
sta wRayX ;store the new x coordinate of the ray
bcc _first_x_done
;if the ray's fractional x coordinate overflowed, then increment the integer part
;this is in Y
iny
iny
;now check for collision with the level
iny
lda (wLevelPtr),y ;read the level data
beq _first_x_done_dey
;if the ray hit a wall, then a contains the wall's color
sta COLUPF
lda #$ff
sta PF0 ;fill the playfield
sta PF1
sta PF2
jmp CastRayTopRight
_first_x_done_dey
dey
_first_x_done
lda.w YVectorTableTopRight,x ;get the initial y component of the ray
; no halving for the Y
sta wYComponent
.ENDS |
/*
* Copyright 2019 Google 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.
*/
#include "SkFontCollection.h"
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "SkTextStyle.h"
// TODO: Extract the platform dependent part
#define DEFAULT_FONT_FAMILY "sans-serif"
bool SkFontCollection::FamilyKey::operator==(
const SkFontCollection::FamilyKey& other) const {
return fFontFamily == other.fFontFamily &&
fLocale == other.fLocale &&
fFontStyle == other.fFontStyle;
}
size_t SkFontCollection::FamilyKey::Hasher::operator()(
const SkFontCollection::FamilyKey& key) const {
return std::hash<std::string>()(key.fFontFamily) ^
std::hash<std::string>()(key.fLocale) ^
std::hash<uint32_t>()(key.fFontStyle.weight()) ^
std::hash<uint32_t>()(key.fFontStyle.slant());
}
SkFontCollection::SkFontCollection()
: fEnableFontFallback(true)
, fDefaultFontManager(SkFontMgr::RefDefault())
, fDefaultFamilyName(DEFAULT_FONT_FAMILY) {
}
SkFontCollection::~SkFontCollection() = default;
size_t SkFontCollection::getFontManagersCount() const {
return this->getFontManagerOrder().size();
}
void SkFontCollection::setAssetFontManager(sk_sp<SkFontMgr> font_manager) {
fAssetFontManager = font_manager;
}
void SkFontCollection::setDynamicFontManager(sk_sp<SkFontMgr> font_manager) {
fDynamicFontManager = font_manager;
}
void SkFontCollection::setTestFontManager(sk_sp<SkFontMgr> font_manager) {
fTestFontManager = font_manager;
}
void SkFontCollection::setDefaultFontManager(
sk_sp<SkFontMgr> fontManager,
const std::string& defaultFamilyName) {
fDefaultFontManager = fontManager;
fDefaultFamilyName = defaultFamilyName;
}
// Return the available font managers in the order they should be queried.
std::vector<sk_sp<SkFontMgr>> SkFontCollection::getFontManagerOrder() const {
std::vector<sk_sp<SkFontMgr>> order;
if (fDynamicFontManager) {
order.push_back(fDynamicFontManager);
}
if (fAssetFontManager) {
order.push_back(fAssetFontManager);
}
if (fTestFontManager) {
order.push_back(fTestFontManager);
}
if (fDefaultFontManager && fEnableFontFallback) {
order.push_back(fDefaultFontManager);
}
return order;
}
// TODO: locale
sk_sp<SkTypeface> SkFontCollection::findTypeface(const std::string& familyName, SkFontStyle fontStyle) {
// Look inside the font collections cache first
FamilyKey familyKey(familyName, "en", fontStyle);
auto found = fTypefaces.find(familyKey);
if (found) {
return *found;
}
sk_sp<SkTypeface> typeface = nullptr;
for (auto manager : this->getFontManagerOrder()) {
SkFontStyleSet* set = manager->matchFamily(familyName.c_str());
if (nullptr == set || set->count() == 0) {
continue;
}
for (int i = 0; i < set->count(); ++i) {
set->createTypeface(i);
}
sk_sp<SkTypeface> match(set->matchStyle(fontStyle));
if (match) {
typeface = std::move(match);
break;
}
}
if (typeface == nullptr && fEnableFontFallback) {
typeface.reset(fDefaultFontManager->matchFamilyStyle(fDefaultFamilyName.c_str(), fontStyle));
SkDebugf("Using default %s instead of %s (%d %s)\n",
fDefaultFamilyName.c_str(),
familyName.c_str(),
(int)fontStyle.weight(),
fontStyle.slant() == SkFontStyle::kUpright_Slant ? "normal" : "italic");
return typeface;
}
fTypefaces.set(familyKey, typeface);
return typeface;
}
void SkFontCollection::disableFontFallback() {
fEnableFontFallback = false;
}
|
<%
from pwnlib.shellcraft.arm.linux import syscall
%>
<%page args="timer"/>
<%docstring>
Invokes the syscall time. See 'man 2 time' for more information.
Arguments:
timer(time_t): timer
</%docstring>
${syscall('SYS_time', timer)}
|
; A325282: Maximum adjusted frequency depth among integer partitions of n.
; 0,1,2,3,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
mov $2,$0
sub $2,$0
lpb $0
sub $0,$2
div $0,7
add $0,2
mul $0,2
add $2,1
add $0,$2
sub $0,1
lpe
mov $1,$0
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cert.h>
#include <certdb.h>
#include <pk11pub.h>
#include <algorithm>
#include "base/bind.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/lazy_instance.h"
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_loop_proxy.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/scoped_test_nss_db.h"
#include "net/base/crypto_module.h"
#include "net/base/net_errors.h"
#include "net/base/test_data_directory.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/cert_verify_proc_nss.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/nss_cert_database.h"
#include "net/cert/x509_certificate.h"
#include "net/test/cert_test_util.h"
#include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h"
#include "testing/gtest/include/gtest/gtest.h"
// In NSS 3.13, CERTDB_VALID_PEER was renamed CERTDB_TERMINAL_RECORD. So we use
// the new name of the macro.
#if !defined(CERTDB_TERMINAL_RECORD)
#define CERTDB_TERMINAL_RECORD CERTDB_VALID_PEER
#endif
using base::ASCIIToUTF16;
namespace net {
namespace {
void SwapCertList(CertificateList* destination,
scoped_ptr<CertificateList> source) {
ASSERT_TRUE(destination);
destination->swap(*source);
}
} // namespace
class CertDatabaseNSSTest : public testing::Test {
public:
virtual void SetUp() {
ASSERT_TRUE(test_nssdb_.is_open());
cert_db_.reset(new NSSCertDatabase(
crypto::ScopedPK11Slot(
PK11_ReferenceSlot(test_nssdb_.slot())) /* public slot */,
crypto::ScopedPK11Slot(
PK11_ReferenceSlot(test_nssdb_.slot())) /* private slot */));
public_module_ = cert_db_->GetPublicModule();
// Test db should be empty at start of test.
EXPECT_EQ(0U, ListCerts().size());
}
virtual void TearDown() {
// Run the message loop to process any observer callbacks (e.g. for the
// ClientSocketFactory singleton) so that the scoped ref ptrs created in
// NSSCertDatabase::NotifyObservers* get released.
base::MessageLoop::current()->RunUntilIdle();
}
protected:
net::CryptoModule* GetPublicModule() {
return public_module_.get();
}
static std::string ReadTestFile(const std::string& name) {
std::string result;
base::FilePath cert_path = GetTestCertsDirectory().AppendASCII(name);
EXPECT_TRUE(base::ReadFileToString(cert_path, &result));
return result;
}
static bool ReadCertIntoList(const std::string& name,
CertificateList* certs) {
scoped_refptr<X509Certificate> cert(
ImportCertFromFile(GetTestCertsDirectory(), name));
if (!cert.get())
return false;
certs->push_back(cert);
return true;
}
CertificateList ListCerts() {
CertificateList result;
CERTCertList* cert_list = PK11_ListCertsInSlot(test_nssdb_.slot());
for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);
!CERT_LIST_END(node, cert_list);
node = CERT_LIST_NEXT(node)) {
result.push_back(X509Certificate::CreateFromHandle(
node->cert, X509Certificate::OSCertHandles()));
}
CERT_DestroyCertList(cert_list);
// Sort the result so that test comparisons can be deterministic.
std::sort(result.begin(), result.end(), X509Certificate::LessThan());
return result;
}
scoped_ptr<NSSCertDatabase> cert_db_;
const CertificateList empty_cert_list_;
crypto::ScopedTestNSSDB test_nssdb_;
scoped_refptr<net::CryptoModule> public_module_;
};
TEST_F(CertDatabaseNSSTest, ListCertsSync) {
// This test isn't terribly useful, though it will at least let valgrind test
// for leaks.
CertificateList certs;
cert_db_->ListCertsSync(&certs);
// The test DB is empty, but let's assume there will always be something in
// the other slots.
EXPECT_LT(0U, certs.size());
}
TEST_F(CertDatabaseNSSTest, ListCerts) {
// This test isn't terribly useful, though it will at least let valgrind test
// for leaks.
CertificateList certs;
cert_db_->SetSlowTaskRunnerForTest(base::MessageLoopProxy::current());
cert_db_->ListCerts(base::Bind(&SwapCertList, base::Unretained(&certs)));
EXPECT_EQ(0U, certs.size());
base::RunLoop().RunUntilIdle();
// The test DB is empty, but let's assume there will always be something in
// the other slots.
EXPECT_LT(0U, certs.size());
}
TEST_F(CertDatabaseNSSTest, ImportFromPKCS12WrongPassword) {
std::string pkcs12_data = ReadTestFile("client.p12");
EXPECT_EQ(ERR_PKCS12_IMPORT_BAD_PASSWORD,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
base::string16(),
true, // is_extractable
NULL));
// Test db should still be empty.
EXPECT_EQ(0U, ListCerts().size());
}
TEST_F(CertDatabaseNSSTest, ImportFromPKCS12AsExtractableAndExportAgain) {
std::string pkcs12_data = ReadTestFile("client.p12");
EXPECT_EQ(OK,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
ASCIIToUTF16("12345"),
true, // is_extractable
NULL));
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
EXPECT_EQ("testusercert",
cert->subject().common_name);
// TODO(mattm): move export test to separate test case?
std::string exported_data;
EXPECT_EQ(1, cert_db_->ExportToPKCS12(cert_list, ASCIIToUTF16("exportpw"),
&exported_data));
ASSERT_LT(0U, exported_data.size());
// TODO(mattm): further verification of exported data?
}
TEST_F(CertDatabaseNSSTest, ImportFromPKCS12Twice) {
std::string pkcs12_data = ReadTestFile("client.p12");
EXPECT_EQ(OK,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
ASCIIToUTF16("12345"),
true, // is_extractable
NULL));
EXPECT_EQ(1U, ListCerts().size());
// NSS has a SEC_ERROR_PKCS12_DUPLICATE_DATA error, but it doesn't look like
// it's ever used. This test verifies that.
EXPECT_EQ(OK,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
ASCIIToUTF16("12345"),
true, // is_extractable
NULL));
EXPECT_EQ(1U, ListCerts().size());
}
TEST_F(CertDatabaseNSSTest, ImportFromPKCS12AsUnextractableAndExportAgain) {
std::string pkcs12_data = ReadTestFile("client.p12");
EXPECT_EQ(OK,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
ASCIIToUTF16("12345"),
false, // is_extractable
NULL));
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
EXPECT_EQ("testusercert",
cert->subject().common_name);
std::string exported_data;
EXPECT_EQ(0, cert_db_->ExportToPKCS12(cert_list, ASCIIToUTF16("exportpw"),
&exported_data));
}
// Importing a PKCS#12 file with a certificate but no corresponding
// private key should not mark an existing private key as unextractable.
TEST_F(CertDatabaseNSSTest, ImportFromPKCS12OnlyMarkIncludedKey) {
std::string pkcs12_data = ReadTestFile("client.p12");
EXPECT_EQ(OK,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
ASCIIToUTF16("12345"),
true, // is_extractable
NULL));
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
// Now import a PKCS#12 file with just a certificate but no private key.
pkcs12_data = ReadTestFile("client-nokey.p12");
EXPECT_EQ(OK,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
ASCIIToUTF16("12345"),
false, // is_extractable
NULL));
cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
// Make sure the imported private key is still extractable.
std::string exported_data;
EXPECT_EQ(1, cert_db_->ExportToPKCS12(cert_list, ASCIIToUTF16("exportpw"),
&exported_data));
ASSERT_LT(0U, exported_data.size());
}
TEST_F(CertDatabaseNSSTest, ImportFromPKCS12InvalidFile) {
std::string pkcs12_data = "Foobarbaz";
EXPECT_EQ(ERR_PKCS12_IMPORT_INVALID_FILE,
cert_db_->ImportFromPKCS12(GetPublicModule(),
pkcs12_data,
base::string16(),
true, // is_extractable
NULL));
// Test db should still be empty.
EXPECT_EQ(0U, ListCerts().size());
}
TEST_F(CertDatabaseNSSTest, ImportCACert_SSLTrust) {
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
EXPECT_FALSE(certs[0]->os_cert_handle()->isperm);
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(certs, NSSCertDatabase::TRUSTED_SSL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
EXPECT_EQ("Test Root CA", cert->subject().common_name);
EXPECT_EQ(NSSCertDatabase::TRUSTED_SSL,
cert_db_->GetCertTrust(cert.get(), CA_CERT));
EXPECT_EQ(unsigned(CERTDB_VALID_CA | CERTDB_TRUSTED_CA |
CERTDB_TRUSTED_CLIENT_CA),
cert->os_cert_handle()->trust->sslFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
cert->os_cert_handle()->trust->emailFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
cert->os_cert_handle()->trust->objectSigningFlags);
}
TEST_F(CertDatabaseNSSTest, ImportCACert_EmailTrust) {
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
EXPECT_FALSE(certs[0]->os_cert_handle()->isperm);
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(certs, NSSCertDatabase::TRUSTED_EMAIL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
EXPECT_EQ("Test Root CA", cert->subject().common_name);
EXPECT_EQ(NSSCertDatabase::TRUSTED_EMAIL,
cert_db_->GetCertTrust(cert.get(), CA_CERT));
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
cert->os_cert_handle()->trust->sslFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA | CERTDB_TRUSTED_CA |
CERTDB_TRUSTED_CLIENT_CA),
cert->os_cert_handle()->trust->emailFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
cert->os_cert_handle()->trust->objectSigningFlags);
}
TEST_F(CertDatabaseNSSTest, ImportCACert_ObjSignTrust) {
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
EXPECT_FALSE(certs[0]->os_cert_handle()->isperm);
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(certs, NSSCertDatabase::TRUSTED_OBJ_SIGN,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> cert(cert_list[0]);
EXPECT_EQ("Test Root CA", cert->subject().common_name);
EXPECT_EQ(NSSCertDatabase::TRUSTED_OBJ_SIGN,
cert_db_->GetCertTrust(cert.get(), CA_CERT));
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
cert->os_cert_handle()->trust->sslFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
cert->os_cert_handle()->trust->emailFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA | CERTDB_TRUSTED_CA |
CERTDB_TRUSTED_CLIENT_CA),
cert->os_cert_handle()->trust->objectSigningFlags);
}
TEST_F(CertDatabaseNSSTest, ImportCA_NotCACert) {
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "ok_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
EXPECT_FALSE(certs[0]->os_cert_handle()->isperm);
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(certs, NSSCertDatabase::TRUSTED_SSL,
&failed));
ASSERT_EQ(1U, failed.size());
// Note: this compares pointers directly. It's okay in this case because
// ImportCACerts returns the same pointers that were passed in. In the
// general case IsSameOSCert should be used.
EXPECT_EQ(certs[0], failed[0].certificate);
EXPECT_EQ(ERR_IMPORT_CA_CERT_NOT_CA, failed[0].net_error);
EXPECT_EQ(0U, ListCerts().size());
}
TEST_F(CertDatabaseNSSTest, ImportCACertHierarchy) {
CertificateList certs;
ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("www_us_army_mil_cert.der", &certs));
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
// Have to specify email trust for the cert verification of the child cert to
// work (see
// http://mxr.mozilla.org/mozilla/source/security/nss/lib/certhigh/certvfy.c#752
// "XXX This choice of trustType seems arbitrary.")
EXPECT_TRUE(cert_db_->ImportCACerts(
certs, NSSCertDatabase::TRUSTED_SSL | NSSCertDatabase::TRUSTED_EMAIL,
&failed));
ASSERT_EQ(2U, failed.size());
EXPECT_EQ("DOD CA-17", failed[0].certificate->subject().common_name);
EXPECT_EQ(ERR_FAILED, failed[0].net_error); // The certificate expired.
EXPECT_EQ("www.us.army.mil", failed[1].certificate->subject().common_name);
EXPECT_EQ(ERR_IMPORT_CA_CERT_NOT_CA, failed[1].net_error);
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name);
}
TEST_F(CertDatabaseNSSTest, ImportCACertHierarchyDupeRoot) {
CertificateList certs;
ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs));
// First import just the root.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(
certs, NSSCertDatabase::TRUSTED_SSL | NSSCertDatabase::TRUSTED_EMAIL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name);
ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("www_us_army_mil_cert.der", &certs));
// Now import with the other certs in the list too. Even though the root is
// already present, we should still import the rest.
failed.clear();
EXPECT_TRUE(cert_db_->ImportCACerts(
certs, NSSCertDatabase::TRUSTED_SSL | NSSCertDatabase::TRUSTED_EMAIL,
&failed));
ASSERT_EQ(3U, failed.size());
EXPECT_EQ("DoD Root CA 2", failed[0].certificate->subject().common_name);
EXPECT_EQ(ERR_IMPORT_CERT_ALREADY_EXISTS, failed[0].net_error);
EXPECT_EQ("DOD CA-17", failed[1].certificate->subject().common_name);
EXPECT_EQ(ERR_FAILED, failed[1].net_error); // The certificate expired.
EXPECT_EQ("www.us.army.mil", failed[2].certificate->subject().common_name);
EXPECT_EQ(ERR_IMPORT_CA_CERT_NOT_CA, failed[2].net_error);
cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name);
}
TEST_F(CertDatabaseNSSTest, ImportCACertHierarchyUntrusted) {
CertificateList certs;
ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs));
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(certs, NSSCertDatabase::TRUST_DEFAULT,
&failed));
ASSERT_EQ(1U, failed.size());
EXPECT_EQ("DOD CA-17", failed[0].certificate->subject().common_name);
// TODO(mattm): should check for net error equivalent of
// SEC_ERROR_UNTRUSTED_ISSUER
EXPECT_EQ(ERR_FAILED, failed[0].net_error);
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name);
}
TEST_F(CertDatabaseNSSTest, ImportCACertHierarchyTree) {
CertificateList certs;
ASSERT_TRUE(ReadCertIntoList("dod_root_ca_2_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("dod_ca_13_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs));
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(
certs, NSSCertDatabase::TRUSTED_SSL | NSSCertDatabase::TRUSTED_EMAIL,
&failed));
EXPECT_EQ(2U, failed.size());
EXPECT_EQ("DOD CA-13", failed[0].certificate->subject().common_name);
EXPECT_EQ(ERR_FAILED, failed[0].net_error); // The certificate expired.
EXPECT_EQ("DOD CA-17", failed[1].certificate->subject().common_name);
EXPECT_EQ(ERR_FAILED, failed[1].net_error); // The certificate expired.
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
EXPECT_EQ("DoD Root CA 2", cert_list[0]->subject().common_name);
}
TEST_F(CertDatabaseNSSTest, ImportCACertNotHierarchy) {
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
ASSERT_TRUE(ReadCertIntoList("dod_ca_13_cert.der", &certs));
ASSERT_TRUE(ReadCertIntoList("dod_ca_17_cert.der", &certs));
// Import it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(
certs, NSSCertDatabase::TRUSTED_SSL | NSSCertDatabase::TRUSTED_EMAIL |
NSSCertDatabase::TRUSTED_OBJ_SIGN, &failed));
ASSERT_EQ(2U, failed.size());
// TODO(mattm): should check for net error equivalent of
// SEC_ERROR_UNKNOWN_ISSUER
EXPECT_EQ("DOD CA-13", failed[0].certificate->subject().common_name);
EXPECT_EQ(ERR_FAILED, failed[0].net_error);
EXPECT_EQ("DOD CA-17", failed[1].certificate->subject().common_name);
EXPECT_EQ(ERR_FAILED, failed[1].net_error);
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
EXPECT_EQ("Test Root CA", cert_list[0]->subject().common_name);
}
// http://crbug.com/108009 - Disabled, as google.chain.pem is an expired
// certificate.
TEST_F(CertDatabaseNSSTest, DISABLED_ImportServerCert) {
// Need to import intermediate cert for the verify of google cert, otherwise
// it will try to fetch it automatically with cert_pi_useAIACertFetch, which
// will cause OCSPCreateSession on the main thread, which is not allowed.
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "google.chain.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(2U, certs.size());
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportServerCert(certs, NSSCertDatabase::TRUST_DEFAULT,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(2U, cert_list.size());
scoped_refptr<X509Certificate> goog_cert(cert_list[0]);
scoped_refptr<X509Certificate> thawte_cert(cert_list[1]);
EXPECT_EQ("www.google.com", goog_cert->subject().common_name);
EXPECT_EQ("Thawte SGC CA", thawte_cert->subject().common_name);
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(goog_cert.get(), SERVER_CERT));
EXPECT_EQ(0U, goog_cert->os_cert_handle()->trust->sslFlags);
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(goog_cert.get(),
"www.google.com",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result.cert_status);
}
TEST_F(CertDatabaseNSSTest, ImportServerCert_SelfSigned) {
CertificateList certs;
ASSERT_TRUE(ReadCertIntoList("punycodetest.der", &certs));
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportServerCert(certs, NSSCertDatabase::TRUST_DEFAULT,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> puny_cert(cert_list[0]);
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(puny_cert.get(), SERVER_CERT));
EXPECT_EQ(0U, puny_cert->os_cert_handle()->trust->sslFlags);
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(puny_cert.get(),
"xn--wgv71a119e.com",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, error);
EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result.cert_status);
}
TEST_F(CertDatabaseNSSTest, ImportServerCert_SelfSigned_Trusted) {
CertificateList certs;
ASSERT_TRUE(ReadCertIntoList("punycodetest.der", &certs));
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportServerCert(certs, NSSCertDatabase::TRUSTED_SSL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList cert_list = ListCerts();
ASSERT_EQ(1U, cert_list.size());
scoped_refptr<X509Certificate> puny_cert(cert_list[0]);
EXPECT_EQ(NSSCertDatabase::TRUSTED_SSL,
cert_db_->GetCertTrust(puny_cert.get(), SERVER_CERT));
EXPECT_EQ(unsigned(CERTDB_TRUSTED | CERTDB_TERMINAL_RECORD),
puny_cert->os_cert_handle()->trust->sslFlags);
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(puny_cert.get(),
"xn--wgv71a119e.com",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result.cert_status);
}
TEST_F(CertDatabaseNSSTest, ImportCaAndServerCert) {
CertificateList ca_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_certs.size());
// Import CA cert and trust it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(ca_certs, NSSCertDatabase::TRUSTED_SSL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "ok_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
// Import server cert with default trust.
EXPECT_TRUE(cert_db_->ImportServerCert(certs, NSSCertDatabase::TRUST_DEFAULT,
&failed));
EXPECT_EQ(0U, failed.size());
// Server cert should verify.
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result.cert_status);
}
TEST_F(CertDatabaseNSSTest, ImportCaAndServerCert_DistrustServer) {
CertificateList ca_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "root_ca_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_certs.size());
// Import CA cert and trust it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(ca_certs, NSSCertDatabase::TRUSTED_SSL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "ok_cert.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
// Import server cert without inheriting trust from issuer (explicit
// distrust).
EXPECT_TRUE(cert_db_->ImportServerCert(
certs, NSSCertDatabase::DISTRUSTED_SSL, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::DISTRUSTED_SSL,
cert_db_->GetCertTrust(certs[0].get(), SERVER_CERT));
EXPECT_EQ(unsigned(CERTDB_TERMINAL_RECORD),
certs[0]->os_cert_handle()->trust->sslFlags);
// Server cert should fail to verify.
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(ERR_CERT_REVOKED, error);
EXPECT_EQ(CERT_STATUS_REVOKED, verify_result.cert_status);
}
TEST_F(CertDatabaseNSSTest, TrustIntermediateCa) {
CertificateList ca_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-root.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_certs.size());
// Import Root CA cert and distrust it.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportCACerts(ca_certs, NSSCertDatabase::DISTRUSTED_SSL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList intermediate_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, intermediate_certs.size());
// Import Intermediate CA cert and trust it.
EXPECT_TRUE(cert_db_->ImportCACerts(intermediate_certs,
NSSCertDatabase::TRUSTED_SSL, &failed));
EXPECT_EQ(0U, failed.size());
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-ee-by-2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
// Import server cert with default trust.
EXPECT_TRUE(cert_db_->ImportServerCert(
certs, NSSCertDatabase::TRUST_DEFAULT, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(certs[0].get(), SERVER_CERT));
// Server cert should verify.
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result.cert_status);
// Trust the root cert and distrust the intermediate.
EXPECT_TRUE(cert_db_->SetCertTrust(
ca_certs[0].get(), CA_CERT, NSSCertDatabase::TRUSTED_SSL));
EXPECT_TRUE(cert_db_->SetCertTrust(
intermediate_certs[0].get(), CA_CERT, NSSCertDatabase::DISTRUSTED_SSL));
EXPECT_EQ(
unsigned(CERTDB_VALID_CA | CERTDB_TRUSTED_CA | CERTDB_TRUSTED_CLIENT_CA),
ca_certs[0]->os_cert_handle()->trust->sslFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
ca_certs[0]->os_cert_handle()->trust->emailFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
ca_certs[0]->os_cert_handle()->trust->objectSigningFlags);
EXPECT_EQ(unsigned(CERTDB_TERMINAL_RECORD),
intermediate_certs[0]->os_cert_handle()->trust->sslFlags);
EXPECT_EQ(unsigned(CERTDB_VALID_CA),
intermediate_certs[0]->os_cert_handle()->trust->emailFlags);
EXPECT_EQ(
unsigned(CERTDB_VALID_CA),
intermediate_certs[0]->os_cert_handle()->trust->objectSigningFlags);
// Server cert should fail to verify.
CertVerifyResult verify_result2;
error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result2);
EXPECT_EQ(ERR_CERT_REVOKED, error);
EXPECT_EQ(CERT_STATUS_REVOKED, verify_result2.cert_status);
}
TEST_F(CertDatabaseNSSTest, TrustIntermediateCa2) {
if (NSS_VersionCheck("3.14.2") && !NSS_VersionCheck("3.15")) {
// See http://bugzil.la/863947 for details.
LOG(INFO) << "Skipping test for NSS 3.14.2 - NSS 3.15";
return;
}
NSSCertDatabase::ImportCertFailureList failed;
CertificateList intermediate_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, intermediate_certs.size());
// Import Intermediate CA cert and trust it.
EXPECT_TRUE(cert_db_->ImportCACerts(intermediate_certs,
NSSCertDatabase::TRUSTED_SSL, &failed));
EXPECT_EQ(0U, failed.size());
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-ee-by-2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
// Import server cert with default trust.
EXPECT_TRUE(cert_db_->ImportServerCert(
certs, NSSCertDatabase::TRUST_DEFAULT, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(certs[0].get(), SERVER_CERT));
// Server cert should verify.
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result.cert_status);
// Without explicit trust of the intermediate, verification should fail.
EXPECT_TRUE(cert_db_->SetCertTrust(
intermediate_certs[0].get(), CA_CERT, NSSCertDatabase::TRUST_DEFAULT));
// Server cert should fail to verify.
CertVerifyResult verify_result2;
error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result2);
EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, error);
EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result2.cert_status);
}
TEST_F(CertDatabaseNSSTest, TrustIntermediateCa3) {
if (NSS_VersionCheck("3.14.2") && !NSS_VersionCheck("3.15")) {
// See http://bugzil.la/863947 for details.
LOG(INFO) << "Skipping test for NSS 3.14.2 - NSS 3.15";
return;
}
NSSCertDatabase::ImportCertFailureList failed;
CertificateList ca_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-root.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_certs.size());
// Import Root CA cert and default trust it.
EXPECT_TRUE(cert_db_->ImportCACerts(ca_certs, NSSCertDatabase::TRUST_DEFAULT,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList intermediate_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, intermediate_certs.size());
// Import Intermediate CA cert and trust it.
EXPECT_TRUE(cert_db_->ImportCACerts(intermediate_certs,
NSSCertDatabase::TRUSTED_SSL, &failed));
EXPECT_EQ(0U, failed.size());
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-ee-by-2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
// Import server cert with default trust.
EXPECT_TRUE(cert_db_->ImportServerCert(
certs, NSSCertDatabase::TRUST_DEFAULT, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(certs[0].get(), SERVER_CERT));
// Server cert should verify.
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result.cert_status);
// Without explicit trust of the intermediate, verification should fail.
EXPECT_TRUE(cert_db_->SetCertTrust(
intermediate_certs[0].get(), CA_CERT, NSSCertDatabase::TRUST_DEFAULT));
// Server cert should fail to verify.
CertVerifyResult verify_result2;
error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result2);
EXPECT_EQ(ERR_CERT_AUTHORITY_INVALID, error);
EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID, verify_result2.cert_status);
}
TEST_F(CertDatabaseNSSTest, TrustIntermediateCa4) {
NSSCertDatabase::ImportCertFailureList failed;
CertificateList ca_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-root.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, ca_certs.size());
// Import Root CA cert and trust it.
EXPECT_TRUE(cert_db_->ImportCACerts(ca_certs, NSSCertDatabase::TRUSTED_SSL,
&failed));
EXPECT_EQ(0U, failed.size());
CertificateList intermediate_certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, intermediate_certs.size());
// Import Intermediate CA cert and distrust it.
EXPECT_TRUE(cert_db_->ImportCACerts(
intermediate_certs, NSSCertDatabase::DISTRUSTED_SSL, &failed));
EXPECT_EQ(0U, failed.size());
CertificateList certs = CreateCertificateListFromFile(
GetTestCertsDirectory(), "2048-rsa-ee-by-2048-rsa-intermediate.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
// Import server cert with default trust.
EXPECT_TRUE(cert_db_->ImportServerCert(
certs, NSSCertDatabase::TRUST_DEFAULT, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(certs[0].get(), SERVER_CERT));
// Server cert should not verify.
scoped_refptr<CertVerifyProc> verify_proc(new CertVerifyProcNSS());
int flags = 0;
CertVerifyResult verify_result;
int error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result);
EXPECT_EQ(ERR_CERT_REVOKED, error);
EXPECT_EQ(CERT_STATUS_REVOKED, verify_result.cert_status);
// Without explicit distrust of the intermediate, verification should succeed.
EXPECT_TRUE(cert_db_->SetCertTrust(
intermediate_certs[0].get(), CA_CERT, NSSCertDatabase::TRUST_DEFAULT));
// Server cert should verify.
CertVerifyResult verify_result2;
error = verify_proc->Verify(certs[0].get(),
"127.0.0.1",
flags,
NULL,
empty_cert_list_,
&verify_result2);
EXPECT_EQ(OK, error);
EXPECT_EQ(0U, verify_result2.cert_status);
}
// Importing two certificates with the same issuer and subject common name,
// but overall distinct subject names, should succeed and generate a unique
// nickname for the second certificate.
TEST_F(CertDatabaseNSSTest, ImportDuplicateCommonName) {
CertificateList certs =
CreateCertificateListFromFile(GetTestCertsDirectory(),
"duplicate_cn_1.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs.size());
EXPECT_EQ(0U, ListCerts().size());
// Import server cert with default trust.
NSSCertDatabase::ImportCertFailureList failed;
EXPECT_TRUE(cert_db_->ImportServerCert(
certs, NSSCertDatabase::TRUST_DEFAULT, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(certs[0].get(), SERVER_CERT));
CertificateList new_certs = ListCerts();
ASSERT_EQ(1U, new_certs.size());
// Now attempt to import a different certificate with the same common name.
CertificateList certs2 =
CreateCertificateListFromFile(GetTestCertsDirectory(),
"duplicate_cn_2.pem",
X509Certificate::FORMAT_AUTO);
ASSERT_EQ(1U, certs2.size());
// Import server cert with default trust.
EXPECT_TRUE(cert_db_->ImportServerCert(
certs2, NSSCertDatabase::TRUST_DEFAULT, &failed));
EXPECT_EQ(0U, failed.size());
EXPECT_EQ(NSSCertDatabase::TRUST_DEFAULT,
cert_db_->GetCertTrust(certs2[0].get(), SERVER_CERT));
new_certs = ListCerts();
ASSERT_EQ(2U, new_certs.size());
EXPECT_STRNE(new_certs[0]->os_cert_handle()->nickname,
new_certs[1]->os_cert_handle()->nickname);
}
} // namespace net
|
;;
; Copyright (C) 2021 The KripayaOS Project Authors.
; + Contributed by Ashwin Paudel <ashwonixer123@gmail.com>
;
; Use of this source code is governed by a BSD-style license that can be
; found in the LICENSE file.
;;
[org 0x7c00]
[bits 16]
%define ENDL 0x0d, 0x0A
; BIOS Parameter Block
jmp short entry
nop
;
; Fat12 Header
;
bdb_oem: db 'MSWIN4.1' ; The version of DOS that being used
bdb_bytes_per_sector: dw 512 ; The number of bytes per sector
bdb_sectors_per_cluster: db 1 ; The number of sectors per cluster
bdb_reserved_sectors: dw 1 ; Number of reserved sectors (the boot record sectors are included in this value)
bdb_fat_count: db 2 ; The number of file allocation tables on the storage media
bdb_dir_entries_count: dw 0E0h ; The number of directory entries
bdb_total_sectors: dw 2880 ; The total number of sectors (2880 * 512 = 1.44MB)
bdb_media_descriptor: db 0F0h ; The Media Descriptor Type (F0 = 3.5" floppy disk)
bdb_sectors_per_fat: dw 9 ; The number of sectors per file allocation table (fat)
bdb_sectors_per_track: dw 18 ; The number of sectors per track
bdb_heads: dw 2 ; The number of heads or sides in the storage media
bdb_hidden_sectors: dd 0 ; The number of hidden sectors (the lba of the beggining partition)
bdb_large_sector_count: dd 0 ; The large sector count
;
; Extended Boot Record
;
ebr_drive_number: db 0 ; The drive number
db 0 ; Reserved Byte
ebr_signature: db 29h ; Flags in Windows NT
ebr_volume_id: db 13h, 14h, 16h, 18h ; Serial Number (can be anything)
ebr_volume_label: db 'KRIPAYA OS' ; The volume name, padded with spaces
ebr_system_id: db 'FAT12 ' ; The File System type
entry:
jmp main
;
; Print a string to the screen
;
; Parameters:
; - si: The string that will be printed
;
print:
; Save the registers
push si
push ax
.loop:
; Load the next character in al
lodsb
; Check if the character is null
or al, al
; If it's null, then jump to the done instruction
jz .done
; Print the character
mov ah, 0x0e
mov bh, 0
int 0x10
; Loop again
jmp .loop
.done:
; Restore the registers and return
pop ax
pop si
ret
main:
mov si, hello_world_msg
call print
hlt
.halt:
jmp .halt
hello_world_msg: db "Hello World", ENDL, 0
times 510-($-$$) db 0
dw 0aa55h
|
; Origin set to 00200H, EOF = 00250H
ORG 00200H
; CPU Type:
CPU 1805
; Labels:
R0203 EQU 0203H
R0204 EQU 0204H
R0215 EQU 0215H
R021C EQU 021CH
R0229 EQU 0229H
R0238 EQU 0238H
; Unused or indirect labels:
; S0230
; S0245
; Register Definitions:
R0 EQU 0
R1 EQU 1
R2 EQU 2
R3 EQU 3
R4 EQU 4
R5 EQU 5
R6 EQU 6
R7 EQU 7
R8 EQU 8
R9 EQU 9
RA EQU 10
RB EQU 11
RC EQU 12
RD EQU 13
RE EQU 14
RF EQU 15
; Start code segment
DB 12H ;0200: 12
DB 60H ;0201: 60
DB 01H ;0202: 01
R0203
REQ ;0203: 7A
R0204
LDA R2 ;0204: 42
RET ;0205: 70
DEC R2 ;0206: 22
SAV ;0207: 78
DEC R2 ;0208: 22
STR R2 ;0209: 52
NOP ;020A: C4
INC R9 ;020B: 19
LDI 00H ;020C: F8 00
PLO R0 ;020E: A0
GHI RB ;020F: 9B
ANI 0EH ;0210: FA 0E
PHI R0 ;0212: B0
SEX R2 ;0213: E2
SEX R2 ;0214: E2
R0215
GLO R0 ;0215: 80
SEX R2 ;0216: E2
DEC R0 ;0217: 20
PLO R0 ;0218: A0
SEX R2 ;0219: E2
BN1 R0215 ;021A: 3C 15
R021C
GLO R0 ;021C: 80
SEX R2 ;021D: E2
DEC R0 ;021E: 20
PLO R0 ;021F: A0
B1 R021C ;0220: 34 1C
GHI R8 ;0222: 98
BZ R0229 ;0223: 32 29
PLO RB ;0225: AB
DEC RB ;0226: 2B
GLO RB ;0227: 8B
PHI R8 ;0228: B8
R0229
GLO R8 ;0229: 88
BZ R0203 ;022A: 32 03
SEQ ;022C: 7B
DEC R8 ;022D: 28
BR R0204 ;022E: 30 04
S0230
LDI 02H ;0230: F8 02
PLO RE ;0232: AE
GHI RB ;0233: 9B
PHI RF ;0234: BF
LDI 00H ;0235: F8 00
PLO RF ;0237: AF
R0238
LDI 00H ;0238: F8 00
STR RF ;023A: 5F
INC RF ;023B: 1F
GLO RF ;023C: 8F
BNZ R0238 ;023D: 3A 38
DEC RE ;023F: 2E
GLO RE ;0240: 8E
BNZ R0238 ;0241: 3A 38
SEP R4 ;0243: D4
DB 01H ;0244: 01
S0245
GHI RB ;0245: 9B
SMI 01H ;0246: FF 01
PHI RB ;0248: BB
SEP R4 ;0249: D4
DB 00H ;024A: 00
DB 00H ;024B: 00
DB 00H ;024C: 00
DB 00H ;024D: 00
DB 00H ;024E: 00
DB 00H ;024F: 00
DB 92H ;0250: 92
END
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>statfs(file, buf) -> str
Invokes the syscall statfs.
See 'man 2 statfs' for more information.
Arguments:
file(char*): file
buf(statfs*): buf
Returns:
int
</%docstring>
<%page args="file=0, buf=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['file']
can_pushstr_array = []
argument_names = ['file', 'buf']
argument_values = [file, buf]
# 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_statfs']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* statfs(${', '.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)}
|
; A143855: Ulam's spiral (ESE spoke).
; 1,10,51,124,229,366,535,736,969,1234,1531,1860,2221,2614,3039,3496,3985,4506,5059,5644,6261,6910,7591,8304,9049,9826,10635,11476,12349,13254,14191,15160,16161,17194,18259,19356,20485,21646,22839,24064,25321,26610,27931,29284,30669,32086,33535,35016,36529,38074,39651,41260,42901,44574,46279,48016,49785,51586,53419,55284,57181,59110,61071,63064,65089,67146,69235,71356,73509,75694,77911,80160,82441,84754,87099,89476,91885,94326,96799,99304,101841,104410,107011,109644,112309,115006,117735,120496
mov $1,$0
mul $1,16
sub $1,7
mul $0,$1
add $0,1
|
;Program to display given string at given screen position
.model small
.stack 100h
.data
i db 0 ;loop control variable
x1 db 16 ;stored value for row number
y1 db 36 ;stored value for column number
len db 0 ;length of entered string
str db 100 dup(0) ;entered string
msg1 db 'Enter the string of 10 characters : $'
msg2 db 'INVALID INPUT : The string does not have 10 characters.$'
.code
main proc
mov ax,@data
mov ds,ax
;printing msg1
mov dx,offset msg1
mov ah,9
int 21h
;taking input in str
mov si,offset str
mov cx,10
loop1:
mov ah,1
int 21h
cmp al,13
je exitloop1
mov [si],al
inc si
inc len
loop loop1
exitloop1:
mov bl,'$'
mov [si],bl
cmp len,10
jne invalid
;displaying str at (x1,y1)
mov si,offset str
mov dh,x1 ;row number
mov dl,y1 ;column number (initial)
mov bh,0 ;page number
loop2:
mov ah,02h ;setting cursor position at (dh,dl)
int 10h
mov ah,08h ;reading character and attribute at cursor position
int 10h
mov bl,ah ;attributes to be written (from attributes returned)
mov al,[si] ;character to be written
mov cx,1 ;number of times to write character
mov ah,09h ;writing character and attribute at cursor position
int 10h
inc dl ;increasing column number
inc si
inc i
cmp i,10
jl loop2
jmp endprog
invalid:
;printing msg2
mov dx,offset msg2
mov ah,9
int 21h
endprog:
;end of program
mov ah,4ch
int 21h
main endp
end main |
; A082662: Numbers k such that the odd part of k is less than sqrt(2k).
; 1,2,4,6,8,12,16,20,24,28,32,40,48,56,64,72,80,88,96,104,112,120,128,144,160,176,192,208,224,240,256,272,288,304,320,336,352,368,384,400,416,432,448,464,480,496,512,544,576,608,640,672,704,736,768,800,832,864,896,928,960,992,1024,1056,1088,1120,1152,1184,1216,1248,1280,1312,1344,1376,1408,1440,1472,1504,1536,1568,1600,1632,1664,1696,1728,1760,1792,1824,1856,1888,1920,1952,1984,2016,2048,2112,2176,2240,2304,2368,2432,2496,2560,2624,2688,2752,2816,2880,2944,3008,3072,3136,3200,3264,3328,3392,3456,3520,3584,3648,3712,3776,3840,3904,3968,4032,4096,4160,4224,4288,4352,4416,4480,4544,4608,4672,4736,4800,4864,4928,4992,5056,5120,5184,5248,5312,5376,5440,5504,5568,5632,5696,5760,5824,5888,5952,6016,6080,6144,6208,6272,6336,6400,6464,6528,6592,6656,6720,6784,6848,6912,6976,7040,7104,7168,7232,7296,7360,7424,7488,7552,7616,7680,7744,7808,7872,7936,8000,8064,8128,8192,8320,8448,8576,8704,8832,8960,9088,9216,9344,9472,9600,9728,9856,9984,10112,10240,10368,10496,10624,10752,10880,11008,11136,11264,11392,11520,11648,11776,11904,12032,12160,12288,12416,12544,12672,12800,12928,13056,13184,13312,13440,13568,13696,13824,13952,14080,14208,14336,14464,14592,14720,14848,14976,15104,15232,15360,15488,15616,15744
mov $6,$0
mov $7,$0
add $7,1
lpb $7
mov $0,$6
sub $7,1
sub $0,$7
mov $2,$0
cmp $0,0
mul $2,2
cal $4,142
mov $3,$4
mov $5,7
lpb $2
div $2,2
mul $3,2
lpb $5
pow $3,$0
sub $5,$4
lpe
trn $2,1
lpe
add $1,$3
lpe
|
// See the file "COPYING" in the main distribution directory for copyright.
#include "TunnelEncapsulation.h"
#include "util.h"
#include "Conn.h"
EncapsulatingConn::EncapsulatingConn(Connection* c, BifEnum::Tunnel::Type t)
: src_addr(c->OrigAddr()), dst_addr(c->RespAddr()),
src_port(c->OrigPort()), dst_port(c->RespPort()),
proto(c->ConnTransport()), type(t), uid(c->GetUID())
{
if ( ! uid )
{
uid.Set(bits_per_uid);
c->SetUID(uid);
}
}
RecordVal* EncapsulatingConn::GetRecordVal() const
{
RecordVal *rv = new RecordVal(BifType::Record::Tunnel::EncapsulatingConn);
auto id_val = make_intrusive<RecordVal>(conn_id);
id_val->Assign(0, make_intrusive<AddrVal>(src_addr));
id_val->Assign(1, val_mgr->GetPort(ntohs(src_port), proto));
id_val->Assign(2, make_intrusive<AddrVal>(dst_addr));
id_val->Assign(3, val_mgr->GetPort(ntohs(dst_port), proto));
rv->Assign(0, std::move(id_val));
rv->Assign(1, BifType::Enum::Tunnel::Type->GetVal(type));
rv->Assign(2, make_intrusive<StringVal>(uid.Base62("C").c_str()));
return rv;
}
bool operator==(const EncapsulationStack& e1, const EncapsulationStack& e2)
{
if ( ! e1.conns )
return e2.conns;
if ( ! e2.conns )
return false;
if ( e1.conns->size() != e2.conns->size() )
return false;
for ( size_t i = 0; i < e1.conns->size(); ++i )
{
if ( (*e1.conns)[i] != (*e2.conns)[i] )
return false;
}
return true;
}
|
class Solution {
public:
ListNode* XXX(ListNode* l1, ListNode* l2)
{
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(l1->val+l2->val <10)
{
ListNode* t = new ListNode(l1->val+l2->val);
t->next = XXX(l1->next, l2->next);
return t;
}
ListNode* t = new ListNode((l1->val + l2->val)%10);
ListNode* tn = new ListNode((l1->val + l2->val)/10);
ListNode* addres = XXX(l1->next, l2->next);
t->next = XXX(tn, addres);
return t;
}
};
undefined
document.getElementsByTagName("code");
HTMLCollection(13) [code, code, code.language-php, code, code.language-javascript, code, code, code, code, code, code, code.language-pgsql, code]
for (i = 0; i < document.getElementsByTagName("code").length; i++) { console.log(document.getElementsByTagName("code")[i].innerText); }
|
; A022469: Expansion of 1/((1-x)*(1-5*x)*(1-8*x)*(1-9*x)).
; Submitted by Jon Maiga
; 1,23,350,4450,51231,554433,5756260,58034900,572630861,5558653243,53279890170,505596134550,4759287370891,44506489496453,413949260130080,3832708325439400,35351885537967321,325028008388124063,2980145152236043990,27260474825925725450,248857740289031716151,2267827993493334696073,20635321568808645039900,187516866039388061408700,1702043644221180570313381,15433527969453159120092483,139822834959423853209965810,1265774189822803794077545150,11450917156475275798974655011,103529850225668459062855513293
add $0,2
lpb $0
sub $0,1
add $2,2
mul $2,8
sub $2,9
mul $3,9
add $3,$1
mul $1,5
add $1,$2
lpe
mov $0,$3
div $0,7
|
ORG $1000
RELOCATE_START
ASSERT 2 * relocate_count == relocate_size
ASSERT 19 == relocate_count
dw relocate_count
dw relocate_size
STRUCT st1
b BYTE $12
w WORD absolute1
relInit WORD reloc1 ; the default init value should be relocated
noRel WORD reloc2-reloc1
badRel WORD 2*reloc1 ; warning about not simple "+offset"
ENDS
STRUCT st2
b BYTE $34
w WORD absolute1
relInit WORD reloc2 ; the default init value should be relocated
noRel WORD reloc2-reloc1
badRel WORD 2*reloc2 ; warning about not simple "+offset"
st1A st1
st1B st1 { high reloc1, absolute2, reloc2, reloc1-reloc2, 2*reloc2 }
ENDS
reloc1:
; instancing the struct in relocatable block
.t1 st2 {} ; default init (no warnings, those were at definition, but relocation data in table)
; ^ expected relocation data: 07 10 10 10 19 10
.t2 st2 {,,$ABCD,,,{,,$ABCD,,},{$EF,,$ABCD,,}} ; remove any relocatable data
.t3 st2 {,,$ABCD,,,{high reloc2,,$ABCD,,},{$EF,,2*reloc1,,reloc2}} ; some relocatable and 2x warnings
; ^ expected relocation data: 53 10
ld ix,reloc1.t1 ; to be relocated (address of instance)
ld iy,.t2 ; to be relocated (address of instance)
; using the struct offsets - no relocation data needed (offsets are relative values)
ld a,(ix+st2.st1A.b)
ld a,(ix+st2.st1A.w)
ld a,(ix+st2.st1A.relInit)
ld a,(ix+st2.st1A.noRel)
ld a,st2 ; struct length is absolute
ld a,st2.st1B ; offset to nested sub-structure is absolute
; using struct addresses - to be relocated
ld a,(reloc1.t1.st1A.b)
ld hl,(reloc1.t1.st1A.w)
ld de,(reloc1.t1.st1A.relInit)
ld bc,(reloc1.t1.st1A.noRel)
ld a,(.t2.st1B.b)
ld hl,(.t2.st1B.w)
ld de,(.t2.st1B.relInit)
ld bc,(.t2.st1B.noRel)
; using absolute struct instance = to be ignored
ld a,(absolute1.t1.st1A.b)
ld hl,(absolute1.t1.st1A.w)
ld de,(absolute1.t1.st1A.relInit)
ld bc,(absolute1.t1.st1A.noRel)
; using alias instance placed at particular address
akaT1 st2 = .t1 ; transitive relocation - to be relocated
ld de,(akaT1.b)
ld bc,(akaT1.w)
ld a,(akaT1.st1B.b)
ld hl,(akaT1.st1B.w)
ld ix,akaT1.st1B
; same alias test, but with absolute instance = no relocation data
akaA1 st2 = absolute1.t1
ld a,(akaA1.st1A.b)
ld hl,(akaA1.st1A.w)
ld de,(akaA1.st1A.relInit)
ld bc,(akaA1.st1A.noRel)
ld ix,akaA1.st1A
reloc2:
RELOCATE_END
ORG $2000
RELOCATE_TABLE
; no relocation area (no warnings, no relocation data)
ORG $87DC
absolute1:
; instancing the struct in absolute block - NOTHING to be relocated
.t1 st2 {}
; no warning about unstable values or value being different
.t2 st2 {,,$ABCD,,,{high reloc2,,$ABCD,,},{$EF,,2*reloc1,,reloc2}}
ld ix,reloc1.t1 ; not to be relocated even when using relocatable instance
ld iy,absolute1.t2
; using the struct offsets - no relocation data needed (offsets are relative values)
ld a,(ix+st2.st1A.b)
ld a,(ix+st2.st1A.w)
ld a,(ix+st2.st1A.relInit)
ld a,(ix+st2.st1A.noRel)
ld a,st2 ; struct length is absolute
ld a,st2.st1B ; offset to nested sub-structure is absolute
; using struct addresses (relocatable ones and absolute ones - either should be NOT relocated)
ld a,(reloc1.t1.st1A.b)
ld hl,(reloc1.t1.st1A.w)
ld de,(reloc1.t1.st1A.relInit)
ld bc,(reloc1.t1.st1A.noRel)
ld a,(absolute1.t2.st1B.b)
ld hl,(absolute1.t2.st1B.w)
ld de,(absolute1.t2.st1B.relInit)
ld bc,(absolute1.t2.st1B.noRel)
; using relocatable alias (outside of block = no relocation)
ld de,(akaT1.b)
ld bc,(akaT1.w)
ld a,(akaT1.st1B.b)
ld hl,(akaT1.st1B.w)
ld ix,akaT1.st1B
absolute2:
ASSERT 0 == __ERRORS__
ASSERT 6 == __WARNINGS__
|
INCLUDE "graphics/grafix.inc"
SECTION code_graphics
PUBLIC pointxy
EXTERN pixeladdress
;
; $Id: pointxy.asm $
;
; ******************************************************************
;
; Check if pixel at (x,y) coordinate is set or not.
;
; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995
;
; (0,0) origin is defined as the top left corner.
;
; in: hl = (x,y) coordinate of pixel to test
; out: Fz = 0, if pixel is set, otherwise Fz = 1.
;
; registers changed after return:
; ..bcdehl/ixiy same
; af....../.... different
;
.pointxy
push bc
push de
push hl
call pixeladdress
ld b,a
ld a,1
jr z, test_pixel ; pixel is at bit 0...
.pixel_position rlca
djnz pixel_position
.test_pixel ex de,hl
and (hl)
pop hl
pop de
pop bc
ret
|
//////////////////////////////////////////////////////////////////////////
//
// pgScript - PostgreSQL Tools
//
// Copyright (C) 2002 - 2013, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////////////////
#include "pgAdmin3.h"
#include "pgscript/exceptions/pgsException.h"
pgsException::pgsException()
{
}
pgsException::~pgsException()
{
}
|
segment .data
array times 100 dd 0
segment .text
global kmp
extern strlen
kmp:
push ebp
mov ebp, esp
mov ecx, [ebp+12] ;ecx = address of search string
mov edx, [ebp+8] ;edx = address of text
xor esi, esi ;si=0
mov edi, 1 ;di = 1
mov dword [array], 0
prefix:
mov ah, [ecx+esi] ;ah = search_string[esi]
mov al, [ecx+edi] ;al = search_string[edi]
cmp al, 0 ;if al == 0
je search ; continue with search
cmp al, ah ; if al == ah
je equal
jmp nequal
equal: ;array[edi] = ++esi
inc esi
mov [array+4*edi], esi
inc edi
jmp prefix
nequal: ;esi=0; array[edi] = esi
xor esi, esi
mov ah, [ecx+esi]
cmp ah, al
jne next
inc esi
next:
mov [array+4*edi], esi
inc edi
jmp prefix
search:
xor esi, esi ;esi=0
xor edi, edi ;edi=0
search_loop:
mov ah, [ecx+esi]
mov al, [edx+edi]
cmp ah, 0
je found ;if search string ends
cmp al, 0
je notfound ;if text ends
cmp ah, al
je pair
jmp unpair
pair: ;edi++;esi++
inc edi
inc esi
jmp search_loop
unpair: ;edi++;esi = array[esi]s
cmp esi, 0
je next_u
dec esi
push dword[array+4*esi]
pop esi
jmp search_loop
next_u:
inc edi
jmp search_loop
found:
sub edi, esi
jmp end
notfound:
mov edi, 101
end:
push dword [ebp+12] ;get search pattern length to esi
call strlen
add esp, 4
mov esi, eax
mov ecx, 0 ; ecx as counter
tochar:
add dword[array + 4*ecx], 48 ; convert number to character
inc ecx
cmp ecx, esi
jne tochar
mov dword[array + 4*ecx], 10 ; endline char
mov eax, 4 ; write system call
mov ebx, 1 ; stdout
mov ecx, array ; start address
inc esi ; array length + endline char
shl esi,2 ; esi *= 4
mov edx, esi
int $80
mov eax, edi ;return value in eax<-edi
mov esp, ebp
pop ebp
ret |
db WARTORTLE ; 008
db 59, 63, 80, 58, 65, 80
; hp atk def spd sat sdf
db WATER, WATER ; type
db 45 ; catch rate
db 143 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F12_5 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/wartortle/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_SLOW ; growth rate
dn EGG_MONSTER, EGG_WATER_1 ; egg groups
; tm/hm learnset
tmhm DYNAMICPUNCH, HEADBUTT, CURSE, ROLLOUT, TOXIC, ROCK_SMASH, HIDDEN_POWER, SNORE, BLIZZARD, ICY_WIND, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, IRON_TAIL, RETURN, DIG, MUD_SLAP, DOUBLE_TEAM, ICE_PUNCH, SWAGGER, SLEEP_TALK, DEFENSE_CURL, REST, ATTRACT, SURF, STRENGTH, WHIRLPOOL, WATERFALL, ICE_BEAM
; end
|
lda {c1}+1,x
cmp {m1}+1
bne !+
lda {c1},x
cmp {m1}
beq {la1}
!:
bcc {la1}
|
page 78,132
;
; Copyright (c) Microsoft Corporation. All rights reserved.
;
; You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
; If you do not agree to the terms, do not use the code.
;
;
; Module Name:
;
; ke\i386\emxcptn.asm
;
; Abstract:
; Module to support getting/setting context to and from the R3
; emulator.
;
.386p
_TEXT SEGMENT DWORD PUBLIC 'CODE'
ASSUME DS:FLAT, ES:FLAT, SS:NOTHING, FS:NOTHING, GS:NOTHING
;;*******************************************************************************
;;
;; Include some more macros and constants.
;;
;;*******************************************************************************
;
NT386 equ 1
include ks386.inc
include em387.inc ; Emulator TEB data layout
include callconv.inc
include irqli386.inc
EXTRNP _KeBugCheck,1
EXTRNP _RtlRaiseStatus,1
extrn _Ki387RoundModeTable:dword
subttl _KiEm87StateToNpxFrame
page
;*** _KiEm87StateToNpxFrames
;
; Translates the R3 emulators state to the NpxFrame
;
; Returns TRUE if NpxFrame successfully completed.
; else FALSE
;
; Warning: This function can only be called at Irql 0 with interrupts
; enabled. It is intended to be called only to deal with R3 exceptions
; when the emulator is being used.
;
; Revision History:
;
;
;*******************************************************************************
cPublicProc _KiEm87StateToNpxFrame, 1
push ebp
mov ebp, esp
push ebx ; Save C runtime variables
push edi
push esi
push esp ; Pass current Esp to handler
push offset stnpx_30 ; Set Handler address
push PCR[PcExceptionList] ; Set next pointer
mov PCR[PcExceptionList],esp ; Link us on
if DBG
pushfd ; Sanity check
pop ecx ; make sure interrupts are enabled
test ecx, EFLAGS_INTERRUPT_MASK
jz short stnpx_err
CurrentIrql ; Sanity check
cmp al, DISPATCH_LEVEL ; make sure Irql is below DPC level
jnc short stnpx_err
endif
xor eax, eax ; set FALSE
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
jne short stnpx_10 ; Yes, then not supported
mov ebx, PCR[PcTeb] ; R3 Teb
cmp [ebx].Einstall, 0 ; Initialized?
je short stnpx_10 ; No, then don't return NpxFrame
test [ebx].CURErr, Summary ; Completed?
jz short stnpx_10 ; No, then don't return NpxFrame
mov esi, [ebp+8] ; (esi) = NpxFrame
call SaveState
mov eax, 1 ; Return TRUE
stnpx_10:
pop PCR[PcExceptionList] ; Remove our exception handle
add esp, 8 ; clear stack
pop esi
pop edi
pop ebx
pop ebp
stdRET _KiEm87StateToNpxFrame
if DBG
stnpx_err:
stdCall _KeBugCheck <IRQL_NOT_LESS_OR_EQUAL>
endif
_KiEm87StateToNpxFrame ENDP
stnpx_30 proc
;
; WARNING: Here we directly unlink the exception handler from the
; exception registration chain. NO unwind is performed. We can take
; this short cut because we know that our handler is a leaf-node.
;
mov esp, [esp+8] ; (esp)-> ExceptionList
xor eax, eax ; Return FALSE
jmp short stnpx_10
stnpx_30 endp
;*** SaveEnv
;
;
; ARGUMENTS
;
; (esi) = NpxFrame
; (ebx) = PcTeb
;
;
; DESCRIPTION
;
SaveEnv:
xor ax,ax
mov [esi].reserved1,ax
mov [esi].reserved2,ax
mov [esi].reserved3,ax
mov [esi].reserved4,ax
mov [esi].reserved5,ax
mov ax,[ebx].ControlWord
mov [esi].E32_ControlWord,ax
call GetEMSEGStatusWord
mov [esi].E32_StatusWord,ax
call GetTagWord
mov [esi].E32_TagWord,ax
mov ax,cs
mov [esi].E32_CodeSeg,ax ; NOTE: Not R0 code & stack
mov ax,ss
mov [esi].E32_DataSeg,ax
mov eax,[ebx].PrevCodeOff
mov [esi].E32_CodeOff,eax
mov eax,[ebx].PrevDataOff
mov [esi].E32_DataOff,eax
ret
;*** SaveState -
;
; ARGUMENTS
; (esi) = where to store environment
; (ebx) = PcTeb
;
; DESCRIPTION
;
; REGISTERS
; Destroys ALL, but EBX
;
SaveState: ; Enter here for debugger save state
mov dword ptr [esi].FpCr0NpxState, CR0_EM
call SaveEnv
add esi,size Env80x87_32 ;Skip over environment
mov ebp,NumLev ;Save entire stack
mov edi,[ebx].CURstk
ss_loop:
mov eax,[ebx+edi].ExpSgn
call StoreTempReal ;in emstore.asm
add esi,10
mov edi,[ebx].CURstk
;;; NextStackElem edi,SaveState
cmp edi,INITstk
jae short ss_wrap
add edi,Reg87Len
ss_continue:
mov [ebx].CURstk,edi
dec ebp
jnz short ss_loop
ret
ss_wrap:
mov edi, BEGstk
jmp short ss_continue
;*** GetTagWord - figures out what the tag word is from the numeric stack
; and returns the value of the tag word in ax.
;
; ARGUMENTS
; (ebx) = PcTeb
;
GetTagWord:
push esi
xor eax, eax
mov ecx, NumLev ; get tags for regs. 0, 7 - 1
mov esi, INITstk
GetTagLoop:
mov dh, [ebx+esi].bTag ; The top 2 bits of Tag are the X87 tag bits.
shld ax, dx, 2
sub esi, Reg87Len
loop GetTagLoop
rol ax, 2 ; This moves Tag(0) into the low 2 bits
pop esi
ret
;*** GetEMSEGStatusWord
;
; User status word returned in ax.
; Uses status word in per-thread data area, otherwise
; identical to GetStatusWord
;
; ARGUMENTS
; (ebx) = PcTeb
GetEMSEGStatusWord:
mov eax, [ebx].CURstk
sub eax, BEGstk
;
; Make sure the 'div' won't overflowed.
;
cmp eax, Reg87Len * (NumLev + 2)
ja short @f
mov dl,Reg87Len
div dl
inc eax
and eax, 7 ; eax is now the stack number
shl ax, 11
or ax, [ebx].StatusWord ; or in the rest of the status word.
ret
@@:
mov eax, STATUS_INTEGER_OVERFLOW
stdCall _RtlRaiseStatus, <eax>
ret ; Should never come here ...
;*** StoreTempReal
;
;
; ARGUMENTS
; ??
; (ebx) = PcTeb
;
StoreTempReal:
mov edx,[ebx+edi].lManHi
mov edi,[ebx+edi].lManLo
;mantissa in edx:edi, exponent in high eax, sign in ah bit 7, tag in al
;memory destination is esi
mov ecx,eax ;get copy of sign and tag
shr ecx,16 ;Bring exponent down
cmp al,bTAG_ZERO
jz short StoreIEEE80 ;Skip bias if zero
add ecx,IexpBias-TexpBias ;Correct bias
cmp al,bTAG_DEN
jz short Denorm80
StoreIEEE80:
and eax,bSign shl 8
or ecx,eax ;Combine sign with exponent
mov [esi],edi
mov [esi+4],edx
mov [esi+8],cx
ret
Denorm80:
;Must change it to a denormal
dec ecx
neg ecx ;Use as shift count
cmp cl,32 ;Long shift?
jae LongDenorm
shrd edi,edx,cl
shr edx,cl
xor ecx,ecx ;Exponent is zero
jmp short StoreIEEE80
LongDenorm:
;edi must be zero if we have 32 bits to shift
xchg edx,edi ;32-bit right shift
shr edi,cl ;shift count is modulo-32
xor ecx,ecx ;Exponent is zero
jmp short StoreIEEE80
;****************************************************
;****************************************************
;****************************************************
;****************************************************
;*** _KiNpxFrameToEm87State
;
; Translates the NpxFrame to the R3 emulators state
;
; Returns TRUE if NpxFrame state successfully transferred.
; else FALSE
;
; Warning: This function can only be called at Irql 0 with interrupts
; enabled. It is intended to be called only to deal with R3 exceptions
; when the emulator is being used.
;
; Revision History:
;
;
;*******************************************************************************
cPublicProc _KiNpxFrameToEm87State, 1
push ebp
mov ebp, esp
push ebx ; Save C runtime variables
push edi
push esi
push esp ; Pass current Esp to handler
push offset npxts_30 ; Set Handler address
push PCR[PcExceptionList] ; Set next pointer
mov PCR[PcExceptionList],esp ; Link us on
if DBG
pushfd ; Sanity check
pop ecx ; make sure interrupts are enabled
test ecx, EFLAGS_INTERRUPT_MASK
jz short npxts_err
CurrentIrql ; Sanity check
cmp al, DISPATCH_LEVEL ; make sure Irql is below DPC level
jnc short npxts_err
endif
xor eax, eax ; set FALSE
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
jne short npxts_10 ; Yes, then not supported
mov ebx, PCR[PcTeb] ; R3 Teb
cmp [ebx].Einstall, 0 ; Initialized?
je short npxts_10 ; No, then don't set NpxFrame
mov esi, [ebp+8] ; (esi) = NpxFrame
call StorState
or [ebx].CURErr, Summary ; Set completed
mov eax, 1 ; Return TRUE
npxts_10:
pop PCR[PcExceptionList] ; Remove our exception handle
add esp, 8 ; clear stack
pop esi
pop edi
pop ebx
pop ebp
stdRet _KiNpxFrameToEm87State
if DBG
npxts_err:
stdCall _KeBugCheck <IRQL_NOT_LESS_OR_EQUAL>
endif
_KiNpxFrameToEm87State ENDP
npxts_30 proc
;
; WARNING: Here we directly unlink the exception handler from the
; exception registration chain. NO unwind is performed. We can take
; this short cut because we know that our handler is a leaf-node.
;
mov esp, [esp+8] ; (esp)-> ExceptionList
xor eax, eax ; Return FALSE
jmp short npxts_10
ret
npxts_30 endp
;*** StorState - emulate FRSTOR [address]
;
; ARGUMENTS
; (esi) = where to get the environment
; (ebx) = PcTeb
;
;
; DESCRIPTION
; This routine emulates an 80387 FRSTOR (restore state)
StorState:
;First we set up the status word so that [CURstk] is initialized.
;The floating-point registers are stored in logical ST(0) - ST(7) order,
;not physical register order. We don't do a full load of the environment
;because we're not ready to use the tag word yet.
mov ax, [esi].E32_StatusWord
call SetEmStatusWord ;Initialize [CURstk]
add esi,size Env80x87_32 ;Skip over environment
;Load of temp real has one difference from real math chip: it is an invalid
;operation to load an unsupported format. By ensuring the exception is
;masked, we will convert unsupported format to Indefinite. Note that the
;mask and [CURerr] will be completely restored by the FLDENV at the end.
mov [ebx].CWmask,3FH ;Mask off invalid operation exception
mov edi,[ebx].CURstk
mov ebp,NumLev
FrstorLoadLoop:
push esi
call LoadTempReal ;In emload.asm
pop esi
add esi,10 ;Point to next temp real
;;; NextStackElem edi,Frstor
cmp edi,INITstk
jae short fr_wrap
add edi,Reg87Len
fr_continue:
dec ebp
jnz short FrstorLoadLoop
sub esi,NumLev*10+size Env80x87_32 ;Point to start of env.
;
; Stor Environment
; (esi) = where to get environment
; (ebx) = PcTeb
;
mov ax, [esi].E32_StatusWord
call SetEmStatusWord ; set up status word
mov ax, [esi].E32_ControlWord
call SetControlWord
mov ax, [esi].E32_TagWord
call UseTagWord
mov eax, [esi].E32_CodeOff
mov [ebx].PrevCodeOff, eax
mov eax, [esi].E32_DataOff
mov [ebx].PrevDataOff, eax
ret
fr_wrap:
mov edi, BEGstk
jmp short fr_continue
;*** SetEmStatusWord -
;
; Given user status word in ax, set into emulator.
; Destroys ebx only.
SetEmStatusWord:
and ax,7F7FH
mov cx,ax
and cx,3FH ; set up CURerr in case user
mov [ebx].CURerr,cl ; wants to force an exception
mov ecx, eax
and ecx, not (7 shl 11) ; remove stack field.
mov [ebx].StatusWord, cx
sub ah, 8 ; adjust for emulator's stack layout
and ah, 7 shl 3
mov al, ah
shr ah, 1
add al, ah ; stack field * 3 * 4
.erre Reg87Len eq 12
and eax, 255 ; eax is now 12*stack number
add eax, BEGstk
mov [ebx].CURstk, eax
ret
SetControlWord:
and ax,0F3FH ; Limit to valid values
mov [ebx].ControlWord, ax ; Store in the emulated control word
not al ;Flip mask bits for fast compare
and al,3FH ;Limit to valid mask bits
mov [ebx].ErrMask,al
and eax,(RoundControl + PrecisionControl) shl 8
.erre RoundControl eq 1100B
.erre PrecisionControl eq 0011B
shr eax,6 ;Put PC and RC in bits 2-5
mov ecx,_Ki387RoundModeTable
mov ecx,[ecx+eax] ;Get correct RoundMode vector
mov [ebx].RoundMode,ecx
mov [ebx].SavedRoundMode,ecx
and eax,RoundControl shl (8-6) ;Mask off precision control
mov ecx,_Ki387RoundModeTable
mov ecx,[ecx+(eax+PC64 shl (8-6))];Get correct RoundMode vector
mov [ebx].TransRound,ecx ;Round mode w/o precision
ret
;*** UseTagWord - Set up tags using tag word from environment
;
; ARGUMENTS
; ax - should contain the tag word
;
; Destroys ax,bx,cx,dx,di
UseTagWord:
ror ax, 2 ; mov Tag(0) into top bits of ax
mov edi,INITstk
mov ecx, NumLev
UseTagLoop:
mov dl,bTAG_EMPTY
cmp ah, 0c0h ;Is register to be tagged Empty?
jae short SetTag ;Yes, go mark it
mov dl,[ebx+edi].bTag ;Get current tag
cmp dl,bTAG_EMPTY ;Is register currently Empty?
je short SetTagNotEmpty ;If so, go figure out tag for it
SetTag:
mov [ebx+edi].bTag,dl
UseTagLoopCheck:
sub edi, Reg87Len
shl eax, 2
loop UseTagLoop
ret
SetTagEmpty:
mov [ebx+edi].bTag, bTAG_EMPTY
jmp short UseTagLoopCheck
SetTagNotEmpty:
;Register is currently tagged empty, but new tag word says it is not empty.
;Figure out a new tag for it. The rules are:
;
;1. Everything is either normalized or zero--unnormalized formats cannot
;get in. So if the high half mantissa is zero, the number is zero.
;
;2. Although the exponent bias is different, NANs and Infinities are in
;standard IEEE format - exponent is TexpMax, mantissa indicates NAN vs.
;infinity (mantissa for infinity is 800..000H).
;
;3. Denormals have an exponent less than TexpMin.
;
;4. If the low half of the mantissa is zero, it is tagged bTAG_SNGL
;
;5. Everything else is bTAG_VALID
cmp [ebx+edi].lManHi, 0
mov dl,bTAG_ZERO ;Try zero first
jz short SetTag ;Is mantissa zero?
mov edx,[ebx+edi].ExpSgn
mov dl,bTAG_DEN
cmp edx,TexpMin shl 16 ;Is it denormal?
jl short SetTag
cmp [ebx+edi].lManLo,0 ;Is low half zero?
.erre bTAG_VALID eq 1
.erre bTAG_SNGL eq 0
setnz dl ;if low half==0 then dl=0 else dl=1
cmp edx,TexpMax shl 16 ;Is it NAN or Infinity?
jl short SetTag ;If not, it's valid
.erre (bTAG_VALID - bTAG_SNGL) shl TAG_SHIFT eq (bTAG_NAN - bTAG_INF)
shl dl,TAG_SHIFT
add dl,bTAG_INF - bTAG_SNGL
;If the low bits were zero we have just changed bTAG_SNGL to bTAG_INF
;If the low bits weren't zero, we changed bTAG_VALID to bTAG_NAN
;See if infinity is really possible: is high half 80..00H?
cmp [ebx+edi].lManHi,1 shl 31 ;Is it infinity?
jz short SetTag ;Store tag for infinity or NAN
mov dl,bTAG_NAN
jmp short SetTag
;*** LoadTempReal
;
;
;
LoadTempReal:
mov ebx,[esi+4] ;Get high half of mantissa
mov cx,[esi+8] ;Get exponent and sign
mov esi,[esi] ;Get low half of mantissa
mov eax,ecx
and ch,7FH ;Mask off sign bit
shl ecx,16 ;Move exponent to high end
mov ch,ah ;Restore sign
jz short ZeroOrDenorm80
;Check for unsupported format: unnormals (MSB not set)
or ebx,ebx
jns short Unsupported
sub ecx,(IexpBias-TexpBias) shl 16 ;Correct the bias
cmp ecx,TexpMax shl 16
jge short NANorInf80
SetupTag:
or esi,esi ;Any bits in low half?
.erre bTAG_VALID eq 1
.erre bTAG_SNGL eq 0
setnz cl ;if low half==0 then cl=0 else cl=1
jmp short SaveStack
NANorInf80:
mov cl,bTAG_NAN
cmp ebx,1 shl 31 ;Only 1 bit set means infinity
jnz short SaveStack
or esi,esi
jnz short SaveStack
mov cl,bTAG_INF
jmp short SaveStack
ZeroOrDenorm80:
;Exponent is zero. Number is either zero or denormalized
or ebx,ebx
jnz short ShortNorm80 ;Are top 32 bits zero?
or esi,esi ;Are low 32 bits zero too?
jnz LongNorm80
mov cl,bTAG_ZERO
jmp short SaveStack
;This code accepts and works correctly with pseudo-denormals (MSB already set)
LongNorm80:
xchg ebx,esi ;Shift up 32 bits
sub ecx,32 shl 16 ;Correct exponent
ShortNorm80:
add ecx,(TexpBias-IexpBias+1-31) shl 16 ;Fix up bias
bsr edx,ebx ;Scan for MSB
;Bit number in edx ranges from 0 to 31
mov cl,dl
not cl ;Convert bit number to shift count
shld ebx,esi,cl
shl esi,cl
shl edx,16 ;Move exp. adjustment to high end
add ecx,edx ;Adjust exponent
jmp short SetUpTag
SaveStack:
mov eax, PCR[PcTeb]
mov [eax].CURstk,edi
mov [eax+edi].lManLo,esi
mov [eax+edi].lManHi,ebx
mov [eax+edi].ExpSgn,ecx
mov ebx, eax ; (ebx) = PcTeb
ret
Unsupported:
mov ebx, PCR[PcTeb]
or [ebx].CURerr,Invalid ; (assume it's masked?)
mov [ebx+edi].lManLo,0
mov [ebx+edi].lManHi,0C0000000H
mov [ebx+edi].ExpSgn,TexpMax shl 16 + bSign shl 8 + bTAG_NAN
mov [ebx].CURstk,edi ;Update top of stack
ret
_TEXT ENDS
END
|
; A017042: a(n) = (7*n + 5)^2.
; 25,144,361,676,1089,1600,2209,2916,3721,4624,5625,6724,7921,9216,10609,12100,13689,15376,17161,19044,21025,23104,25281,27556,29929,32400,34969,37636,40401,43264,46225,49284,52441,55696,59049,62500,66049,69696,73441,77284,81225,85264,89401,93636,97969,102400,106929,111556,116281,121104,126025,131044,136161,141376,146689,152100,157609,163216,168921,174724,180625,186624,192721,198916,205209,211600,218089,224676,231361,238144,245025,252004,259081,266256,273529,280900,288369,295936,303601,311364,319225,327184,335241,343396,351649,360000,368449,376996,385641,394384,403225,412164,421201,430336,439569,448900,458329,467856,477481,487204
mul $0,7
add $0,5
pow $0,2
|
PROGRAM 6
LDGADDR 4
LDCCH 'Z'
STORE2B
LDCSTR "Enter 2 characters: "
PUTSTR
LDGADDR 0
GETCH
STORE2B
LDGADDR 2
GETCH
STORE2B
PUTEOL
LDCSTR "c1 = "
PUTSTR
LDGADDR 0
LOAD2B
PUTCH
PUTEOL
LDCSTR "c2 = "
PUTSTR
LDGADDR 2
LOAD2B
PUTCH
PUTEOL
LDCSTR "c3 = "
PUTSTR
LDGADDR 4
LOAD2B
PUTCH
PUTEOL
HALT
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# 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.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 5, 0x90
.globl cpMontMul4n_avx2
.type cpMontMul4n_avx2, @function
cpMontMul4n_avx2:
push %rbx
push %rbp
push %r12
push %r13
push %r14
sub $(48), %rsp
mov %rdx, %rbp
movslq %r8d, %r8
movq %rdi, (%rsp)
movq %rsi, (16)(%rsp)
movq %rcx, (24)(%rsp)
movq %r8, (32)(%rsp)
movq (96)(%rsp), %rdi
mov %rdi, (8)(%rsp)
vpxor %ymm0, %ymm0, %ymm0
xor %rax, %rax
vmovdqu %ymm0, (%rsi,%r8,8)
vmovdqu %ymm0, (%rcx,%r8,8)
mov %r8, %r14
.p2align 5, 0x90
.LclearLoopgas_1:
vmovdqu %ymm0, (%rdi)
add $(32), %rdi
sub $(4), %r14
jg .LclearLoopgas_1
vmovdqu %ymm0, (%rdi)
lea (3)(%r8), %r14
and $(-4), %r14
.p2align 5, 0x90
.Lloop4_Bgas_1:
sub $(4), %r8
jl .Lexit_loop4_Bgas_1
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq (8)(%rbp), %rbx
vpbroadcastq (8)(%rbp), %ymm5
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r11
mov %r11, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm9
vpbroadcastq %xmm9, %ymm9
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r11
shr $(27), %r11
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r12
add %r11, %r12
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r13
movq (16)(%rbp), %rbx
vpbroadcastq (16)(%rbp), %ymm6
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r12
mov %r12, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm10
vpbroadcastq %xmm10, %ymm10
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r12
shr $(27), %r12
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r13
add %r12, %r13
movq (24)(%rbp), %rbx
vpbroadcastq (24)(%rbp), %ymm7
imulq (%rsi), %rbx
add %rbx, %r13
mov %r13, %rdx
imul %r9d, %edx
and $(134217727), %edx
vmovd %edx, %xmm11
vpbroadcastq %xmm11, %ymm11
imulq (%rcx), %rdx
add %rdx, %r13
shr $(27), %r13
vmovq %r13, %xmm0
vpaddq (32)(%rdi), %ymm0, %ymm0
vmovdqu %ymm0, (32)(%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lloop16_Agas_1:
sub $(16), %r11
jl .Lexit_loop16_Agas_1
vmovdqu (%rdi), %ymm0
vmovdqu (32)(%rdi), %ymm1
vmovdqu (64)(%rdi), %ymm2
vmovdqu (96)(%rdi), %ymm3
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (32)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (32)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (64)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (64)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (96)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (96)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-8)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (24)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (24)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (56)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (56)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (88)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (88)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (48)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (48)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (80)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (80)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-24)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (8)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (8)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (40)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (40)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (72)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (72)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vmovdqu %ymm0, (-32)(%rdi)
vmovdqu %ymm1, (%rdi)
vmovdqu %ymm2, (32)(%rdi)
vmovdqu %ymm3, (64)(%rdi)
add $(128), %rdi
add $(128), %rsi
add $(128), %rcx
jmp .Lloop16_Agas_1
.Lexit_loop16_Agas_1:
add $(16), %r11
jz .LexitAgas_1
.Lloop4_Agas_1:
sub $(4), %r11
jl .LexitAgas_1
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-8)(%rsi), %ymm5, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-24)(%rsi), %ymm7, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vmovdqu %ymm0, (-32)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lloop4_Agas_1
.LexitAgas_1:
vpmuludq (-8)(%rsi), %ymm5, %ymm1
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (-16)(%rsi), %ymm6, %ymm2
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (-24)(%rsi), %ymm7, %ymm3
vpmuludq (-24)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpaddq %ymm2, %ymm1, %ymm1
vpaddq %ymm3, %ymm1, %ymm1
vmovdqu %ymm1, (-32)(%rdi)
jmp .Lloop4_Bgas_1
.Lexit_loop4_Bgas_1:
movq (%rsp), %rdi
movq (8)(%rsp), %rsi
movq (32)(%rsp), %r8
xor %rax, %rax
.Lnorm_loopgas_1:
addq (%rsi), %rax
add $(8), %rsi
mov $(134217727), %rdx
and %rax, %rdx
shr $(27), %rax
movq %rdx, (%rdi)
add $(8), %rdi
sub $(1), %r8
jg .Lnorm_loopgas_1
movq %rax, (%rdi)
add $(48), %rsp
vzeroupper
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
ret
.Lfe1:
.size cpMontMul4n_avx2, .Lfe1-(cpMontMul4n_avx2)
.p2align 5, 0x90
.globl cpMontMul4n1_avx2
.type cpMontMul4n1_avx2, @function
cpMontMul4n1_avx2:
push %rbx
push %rbp
push %r12
push %r13
push %r14
sub $(48), %rsp
mov %rdx, %rbp
movslq %r8d, %r8
movq %rdi, (%rsp)
movq %rsi, (16)(%rsp)
movq %rcx, (24)(%rsp)
movq %r8, (32)(%rsp)
movq (96)(%rsp), %rdi
mov %rdi, (8)(%rsp)
vpxor %ymm0, %ymm0, %ymm0
xor %rax, %rax
vmovdqu %ymm0, (%rsi,%r8,8)
vmovdqu %ymm0, (%rcx,%r8,8)
mov %r8, %r14
.p2align 5, 0x90
.LclearLoopgas_2:
vmovdqu %ymm0, (%rdi)
add $(32), %rdi
sub $(4), %r14
jg .LclearLoopgas_2
movq %rax, (%rdi)
lea (3)(%r8), %r14
and $(-4), %r14
.p2align 5, 0x90
.Lloop4_Bgas_2:
sub $(4), %r8
jl .Lexit_loop4_Bgas_2
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq (8)(%rbp), %rbx
vpbroadcastq (8)(%rbp), %ymm5
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r11
mov %r11, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm9
vpbroadcastq %xmm9, %ymm9
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r11
shr $(27), %r11
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r12
add %r11, %r12
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r13
movq (16)(%rbp), %rbx
vpbroadcastq (16)(%rbp), %ymm6
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r12
mov %r12, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm10
vpbroadcastq %xmm10, %ymm10
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r12
shr $(27), %r12
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r13
add %r12, %r13
movq (24)(%rbp), %rbx
vpbroadcastq (24)(%rbp), %ymm7
imulq (%rsi), %rbx
add %rbx, %r13
mov %r13, %rdx
imul %r9d, %edx
and $(134217727), %edx
vmovd %edx, %xmm11
vpbroadcastq %xmm11, %ymm11
imulq (%rcx), %rdx
add %rdx, %r13
shr $(27), %r13
vmovq %r13, %xmm0
vpaddq (32)(%rdi), %ymm0, %ymm0
vmovdqu %ymm0, (32)(%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lloop16_Agas_2:
sub $(16), %r11
jl .Lexit_loop16_Agas_2
vmovdqu (%rdi), %ymm0
vmovdqu (32)(%rdi), %ymm1
vmovdqu (64)(%rdi), %ymm2
vmovdqu (96)(%rdi), %ymm3
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (32)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (32)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (64)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (64)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (96)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (96)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-8)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (24)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (24)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (56)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (56)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (88)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (88)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (48)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (48)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (80)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (80)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-24)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (8)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (8)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (40)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (40)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (72)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (72)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vmovdqu %ymm0, (-32)(%rdi)
vmovdqu %ymm1, (%rdi)
vmovdqu %ymm2, (32)(%rdi)
vmovdqu %ymm3, (64)(%rdi)
add $(128), %rdi
add $(128), %rsi
add $(128), %rcx
jmp .Lloop16_Agas_2
.Lexit_loop16_Agas_2:
add $(16), %r11
jz .LexitAgas_2
.Lloop4_Agas_2:
sub $(4), %r11
jl .LexitAgas_2
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-8)(%rsi), %ymm5, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-24)(%rsi), %ymm7, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vmovdqu %ymm0, (-32)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lloop4_Agas_2
.LexitAgas_2:
jmp .Lloop4_Bgas_2
.Lexit_loop4_Bgas_2:
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r13, (16)(%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lrem_loop4_Agas_2:
sub $(4), %r11
jl .Lexit_rem_loop4_Agas_2
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vmovdqu %ymm0, (-8)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lrem_loop4_Agas_2
.Lexit_rem_loop4_Agas_2:
movq (%rsp), %rdi
movq (8)(%rsp), %rsi
movq (32)(%rsp), %r8
xor %rax, %rax
.Lnorm_loopgas_2:
addq (%rsi), %rax
add $(8), %rsi
mov $(134217727), %rdx
and %rax, %rdx
shr $(27), %rax
movq %rdx, (%rdi)
add $(8), %rdi
sub $(1), %r8
jg .Lnorm_loopgas_2
movq %rax, (%rdi)
add $(48), %rsp
vzeroupper
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
ret
.Lfe2:
.size cpMontMul4n1_avx2, .Lfe2-(cpMontMul4n1_avx2)
.p2align 5, 0x90
.globl cpMontMul4n2_avx2
.type cpMontMul4n2_avx2, @function
cpMontMul4n2_avx2:
push %rbx
push %rbp
push %r12
push %r13
push %r14
sub $(48), %rsp
mov %rdx, %rbp
movslq %r8d, %r8
movq %rdi, (%rsp)
movq %rsi, (16)(%rsp)
movq %rcx, (24)(%rsp)
movq %r8, (32)(%rsp)
movq (96)(%rsp), %rdi
mov %rdi, (8)(%rsp)
vpxor %ymm0, %ymm0, %ymm0
xor %rax, %rax
vmovdqu %ymm0, (%rsi,%r8,8)
vmovdqu %ymm0, (%rcx,%r8,8)
mov %r8, %r14
.p2align 5, 0x90
.LclearLoopgas_3:
vmovdqu %ymm0, (%rdi)
add $(32), %rdi
sub $(4), %r14
jg .LclearLoopgas_3
vmovdqu %xmm0, (%rdi)
lea (3)(%r8), %r14
and $(-4), %r14
.p2align 5, 0x90
.Lloop4_Bgas_3:
sub $(4), %r8
jl .Lexit_loop4_Bgas_3
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq (8)(%rbp), %rbx
vpbroadcastq (8)(%rbp), %ymm5
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r11
mov %r11, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm9
vpbroadcastq %xmm9, %ymm9
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r11
shr $(27), %r11
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r12
add %r11, %r12
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r13
movq (16)(%rbp), %rbx
vpbroadcastq (16)(%rbp), %ymm6
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r12
mov %r12, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm10
vpbroadcastq %xmm10, %ymm10
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r12
shr $(27), %r12
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r13
add %r12, %r13
movq (24)(%rbp), %rbx
vpbroadcastq (24)(%rbp), %ymm7
imulq (%rsi), %rbx
add %rbx, %r13
mov %r13, %rdx
imul %r9d, %edx
and $(134217727), %edx
vmovd %edx, %xmm11
vpbroadcastq %xmm11, %ymm11
imulq (%rcx), %rdx
add %rdx, %r13
shr $(27), %r13
vmovq %r13, %xmm0
vpaddq (32)(%rdi), %ymm0, %ymm0
vmovdqu %ymm0, (32)(%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lloop16_Agas_3:
sub $(16), %r11
jl .Lexit_loop16_Agas_3
vmovdqu (%rdi), %ymm0
vmovdqu (32)(%rdi), %ymm1
vmovdqu (64)(%rdi), %ymm2
vmovdqu (96)(%rdi), %ymm3
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (32)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (32)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (64)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (64)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (96)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (96)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-8)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (24)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (24)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (56)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (56)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (88)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (88)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (48)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (48)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (80)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (80)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-24)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (8)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (8)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (40)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (40)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (72)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (72)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vmovdqu %ymm0, (-32)(%rdi)
vmovdqu %ymm1, (%rdi)
vmovdqu %ymm2, (32)(%rdi)
vmovdqu %ymm3, (64)(%rdi)
add $(128), %rdi
add $(128), %rsi
add $(128), %rcx
jmp .Lloop16_Agas_3
.Lexit_loop16_Agas_3:
add $(16), %r11
jz .LexitAgas_3
.Lloop4_Agas_3:
sub $(4), %r11
jl .LexitAgas_3
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-8)(%rsi), %ymm5, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-24)(%rsi), %ymm7, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vmovdqu %ymm0, (-32)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lloop4_Agas_3
.LexitAgas_3:
vpmuludq (-24)(%rsi), %ymm7, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vmovdqu %ymm0, (-32)(%rdi)
jmp .Lloop4_Bgas_3
.Lexit_loop4_Bgas_3:
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq (8)(%rbp), %rbx
vpbroadcastq (8)(%rbp), %ymm5
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r11
mov %r11, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm9
vpbroadcastq %xmm9, %ymm9
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r11
shr $(27), %r11
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r12
add %r11, %r12
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r13
movq %r12, (%rdi)
movq %r13, (8)(%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lrem_loop4_Agas_3:
sub $(4), %r11
jl .Lexit_rem_loop4_Agas_3
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-8)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vmovdqu %ymm0, (-16)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lrem_loop4_Agas_3
.Lexit_rem_loop4_Agas_3:
movq (%rsp), %rdi
movq (8)(%rsp), %rsi
movq (32)(%rsp), %r8
xor %rax, %rax
.Lnorm_loopgas_3:
addq (%rsi), %rax
add $(8), %rsi
mov $(134217727), %rdx
and %rax, %rdx
shr $(27), %rax
movq %rdx, (%rdi)
add $(8), %rdi
sub $(1), %r8
jg .Lnorm_loopgas_3
movq %rax, (%rdi)
add $(48), %rsp
vzeroupper
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
ret
.Lfe3:
.size cpMontMul4n2_avx2, .Lfe3-(cpMontMul4n2_avx2)
.p2align 5, 0x90
.globl cpMontMul4n3_avx2
.type cpMontMul4n3_avx2, @function
cpMontMul4n3_avx2:
push %rbx
push %rbp
push %r12
push %r13
push %r14
sub $(48), %rsp
mov %rdx, %rbp
movslq %r8d, %r8
movq %rdi, (%rsp)
movq %rsi, (16)(%rsp)
movq %rcx, (24)(%rsp)
movq %r8, (32)(%rsp)
movq (96)(%rsp), %rdi
mov %rdi, (8)(%rsp)
vpxor %ymm0, %ymm0, %ymm0
xor %rax, %rax
vmovdqu %ymm0, (%rsi,%r8,8)
vmovdqu %ymm0, (%rcx,%r8,8)
mov %r8, %r14
.p2align 5, 0x90
.LclearLoopgas_4:
vmovdqu %ymm0, (%rdi)
add $(32), %rdi
sub $(4), %r14
jg .LclearLoopgas_4
vmovdqu %xmm0, (%rdi)
movq %rax, (16)(%rdi)
lea (3)(%r8), %r14
and $(-4), %r14
.p2align 5, 0x90
.Lloop4_Bgas_4:
sub $(4), %r8
jl .Lexit_loop4_Bgas_4
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq (8)(%rbp), %rbx
vpbroadcastq (8)(%rbp), %ymm5
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r11
mov %r11, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm9
vpbroadcastq %xmm9, %ymm9
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r11
shr $(27), %r11
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r12
add %r11, %r12
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r13
movq (16)(%rbp), %rbx
vpbroadcastq (16)(%rbp), %ymm6
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r12
mov %r12, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm10
vpbroadcastq %xmm10, %ymm10
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r12
shr $(27), %r12
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r13
add %r12, %r13
movq (24)(%rbp), %rbx
vpbroadcastq (24)(%rbp), %ymm7
imulq (%rsi), %rbx
add %rbx, %r13
mov %r13, %rdx
imul %r9d, %edx
and $(134217727), %edx
vmovd %edx, %xmm11
vpbroadcastq %xmm11, %ymm11
imulq (%rcx), %rdx
add %rdx, %r13
shr $(27), %r13
vmovq %r13, %xmm0
vpaddq (32)(%rdi), %ymm0, %ymm0
vmovdqu %ymm0, (32)(%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lloop16_Agas_4:
sub $(16), %r11
jl .Lexit_loop16_Agas_4
vmovdqu (%rdi), %ymm0
vmovdqu (32)(%rdi), %ymm1
vmovdqu (64)(%rdi), %ymm2
vmovdqu (96)(%rdi), %ymm3
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (32)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (32)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (64)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (64)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (96)(%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (96)(%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-8)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (24)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (24)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (56)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (56)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (88)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (88)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (48)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (48)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (80)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (80)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpmuludq (-24)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (8)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm1, %ymm1
vpmuludq (8)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm1, %ymm1
vpmuludq (40)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (40)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm2, %ymm2
vpmuludq (72)(%rsi), %ymm7, %ymm12
vpaddq %ymm12, %ymm3, %ymm3
vpmuludq (72)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vmovdqu %ymm0, (-32)(%rdi)
vmovdqu %ymm1, (%rdi)
vmovdqu %ymm2, (32)(%rdi)
vmovdqu %ymm3, (64)(%rdi)
add $(128), %rdi
add $(128), %rsi
add $(128), %rcx
jmp .Lloop16_Agas_4
.Lexit_loop16_Agas_4:
add $(16), %r11
jz .LexitAgas_4
.Lloop4_Agas_4:
sub $(4), %r11
jl .LexitAgas_4
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-8)(%rsi), %ymm5, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-24)(%rsi), %ymm7, %ymm1
vpaddq %ymm1, %ymm0, %ymm0
vpmuludq (-24)(%rcx), %ymm11, %ymm2
vpaddq %ymm2, %ymm0, %ymm0
vmovdqu %ymm0, (-32)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lloop4_Agas_4
.LexitAgas_4:
vpmuludq (-16)(%rsi), %ymm6, %ymm2
vpmuludq (-16)(%rcx), %ymm10, %ymm12
vpaddq %ymm12, %ymm2, %ymm2
vpmuludq (-24)(%rsi), %ymm7, %ymm3
vpmuludq (-24)(%rcx), %ymm11, %ymm13
vpaddq %ymm13, %ymm3, %ymm3
vpaddq %ymm3, %ymm2, %ymm2
vmovdqu %ymm2, (-32)(%rdi)
jmp .Lloop4_Bgas_4
.Lexit_loop4_Bgas_4:
movq (%rbp), %rbx
vpbroadcastq (%rbp), %ymm4
movq (8)(%rsp), %rdi
movq (16)(%rsp), %rsi
movq (24)(%rsp), %rcx
movq (%rdi), %r10
movq (8)(%rdi), %r11
movq (16)(%rdi), %r12
movq (24)(%rdi), %r13
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r10
mov %r10, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r11
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (24)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm8
vpbroadcastq %xmm8, %ymm8
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r10
shr $(27), %r10
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r11
add %r10, %r11
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r12
mov %rdx, %rax
imulq (24)(%rcx), %rax
add %rax, %r13
movq (8)(%rbp), %rbx
vpbroadcastq (8)(%rbp), %ymm5
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r11
mov %r11, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r12
mov %rbx, %rax
imulq (16)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm9
vpbroadcastq %xmm9, %ymm9
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r11
shr $(27), %r11
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r12
add %r11, %r12
mov %rdx, %rax
imulq (16)(%rcx), %rax
add %rax, %r13
movq (16)(%rbp), %rbx
vpbroadcastq (16)(%rbp), %ymm6
mov %rbx, %rax
imulq (%rsi), %rax
add %rax, %r12
mov %r12, %rdx
imul %r9d, %edx
and $(134217727), %edx
mov %rbx, %rax
imulq (8)(%rsi), %rax
add %rax, %r13
vmovd %edx, %xmm10
vpbroadcastq %xmm10, %ymm10
mov %rdx, %rax
imulq (%rcx), %rax
add %rax, %r12
shr $(27), %r12
mov %rdx, %rax
imulq (8)(%rcx), %rax
add %rax, %r13
add %r12, %r13
movq %r13, (%rdi)
add $(32), %rbp
add $(32), %rsi
add $(32), %rcx
add $(32), %rdi
mov %r14, %r11
sub $(4), %r11
.p2align 5, 0x90
.Lrem_loop4_Agas_4:
sub $(4), %r11
jl .Lexit_rem_loop4_Agas_4
vmovdqu (%rdi), %ymm0
vpmuludq (%rsi), %ymm4, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (%rcx), %ymm8, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-8)(%rsi), %ymm5, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-8)(%rcx), %ymm9, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vmovdqu %ymm0, (-24)(%rdi)
add $(32), %rdi
add $(32), %rsi
add $(32), %rcx
jmp .Lrem_loop4_Agas_4
.Lexit_rem_loop4_Agas_4:
vmovdqu (%rdi), %ymm0
vpmuludq (-16)(%rsi), %ymm6, %ymm12
vpaddq %ymm12, %ymm0, %ymm0
vpmuludq (-16)(%rcx), %ymm10, %ymm13
vpaddq %ymm13, %ymm0, %ymm0
vmovdqu %ymm0, (-24)(%rdi)
movq (%rsp), %rdi
movq (8)(%rsp), %rsi
movq (32)(%rsp), %r8
xor %rax, %rax
.Lnorm_loopgas_4:
addq (%rsi), %rax
add $(8), %rsi
mov $(134217727), %rdx
and %rax, %rdx
shr $(27), %rax
movq %rdx, (%rdi)
add $(8), %rdi
sub $(1), %r8
jg .Lnorm_loopgas_4
movq %rax, (%rdi)
add $(48), %rsp
vzeroupper
pop %r14
pop %r13
pop %r12
pop %rbp
pop %rbx
ret
.Lfe4:
.size cpMontMul4n3_avx2, .Lfe4-(cpMontMul4n3_avx2)
|
; char *_strrstrip_(const char *s)
SECTION code_string
PUBLIC __strrstrip_
EXTERN asm__strrstrip
__strrstrip_:
pop af
pop hl
push hl
push af
jp asm__strrstrip
|
; A162615: Triangle read by rows in which row n lists n terms, starting with n, such that the difference between successive terms is equal to n^3 - 1 = A068601(n).
; Submitted by Christian Krause
; 1,2,9,3,29,55,4,67,130,193,5,129,253,377,501,6,221,436,651,866,1081,7,349,691,1033,1375,1717,2059,8,519,1030,1541,2052,2563,3074,3585,9,737,1465,2193,2921,3649,4377,5105,5833,10,1009,2008,3007,4006,5005,6004,7003,8002,9001,11,1341,2671,4001,5331,6661,7991,9321,10651,11981,13311,12,1739,3466,5193,6920,8647,10374,12101,13828,15555,17282,19009,13,2209,4405,6601,8797,10993,13189,15385,17581,19777,21973,24169,26365,14,2757,5500,8243,10986,13729,16472,19215,21958
mov $2,$0
lpb $0
add $3,1
sub $2,$3
mov $0,$2
add $1,$3
trn $1,$2
lpe
add $3,1
pow $3,3
mul $3,$0
add $1,$3
mov $0,$1
add $0,1
|
ALASKA_X = 2
ALASKA_Y = 2
ALASKA_VRAM = VRAM_START + (ALASKA_X + ALASKA_Y*32) * 16
ALASKA_NEXT_LINE = 32*16
alaska:
; map text bank
lda #bank(alaska.dat)
tam #page(alaska.dat)
; copy data to vram
lda #MEMCPY_SRC_INC_DEST_ALT
sta _hrdw_memcpy_mode
stw #alaska.dat, _hrdw_memcpy_src
stw #video_data_l, _hrdw_memcpy_dst
stw #544, _hrdw_memcpy_len
stw #ALASKA_VRAM, <_di
ldx #11
@l0:
st0 #$00
stw <_di, video_data
st0 #$02
jsr hrdw_memcpy
addw #ALASKA_NEXT_LINE, <_di
addw #544, _hrdw_memcpy_src
dex
bne @l0
stwz color_reg
tia datastorm2017.pal, color_data, 32
rts
alaska.brutal_clean:
stw #ALASKA_VRAM, <_di
ldx #11
@loop:
st0 #$00
lda <_di
sta video_data_l
clc
adc #low(ALASKA_NEXT_LINE)
sta <_di
lda <_di+1
sta video_data_h
adc #high(ALASKA_NEXT_LINE)
sta <_di+1
st0 #$02
tia $2400, video_data, 544
dex
bne @loop
rts
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright(c) 2017-2021, Intel Corporation All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
; * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; * 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.
; * Neither the name of Intel Corporation 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.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%define GCM128_MODE 1
%include "avx2/gcm_avx_gen4.asm"
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xa94c, %rsi
lea addresses_WC_ht+0x1994c, %rdi
clflush (%rsi)
nop
nop
nop
nop
nop
cmp $39850, %r12
mov $36, %rcx
rep movsl
nop
nop
nop
nop
dec %r11
pop %rsi
pop %rdi
pop %rcx
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r15
push %r8
push %r9
push %rdi
push %rdx
// Store
lea addresses_US+0xca0c, %rdi
nop
sub %r15, %r15
movl $0x51525354, (%rdi)
nop
nop
nop
nop
nop
and $52888, %r13
// Store
lea addresses_UC+0x960c, %r15
nop
nop
nop
and %r13, %r13
movw $0x5152, (%r15)
nop
nop
nop
nop
and $5477, %r15
// Store
lea addresses_UC+0x8e98, %r11
xor $14151, %r8
movw $0x5152, (%r11)
nop
cmp $20511, %r8
// Faulty Load
lea addresses_UC+0x960c, %r13
nop
nop
nop
add $24963, %r11
mov (%r13), %r15d
lea oracles, %rdx
and $0xff, %r15
shlq $12, %r15
mov (%rdx,%r15,1), %r15
pop %rdx
pop %rdi
pop %r9
pop %r8
pop %r15
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': True, 'congruent': 10, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'AVXalign': True, 'congruent': 0, 'size': 4, 'same': True, 'NT': True}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}}
{'52': 21829}
52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52
*/
|
;
; jcphuff-sse2.asm - prepare data for progressive Huffman encoding
; (64-bit SSE2)
;
; Copyright (C) 2016, 2018, Matthieu Darbois
;
; Based on the 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
;
; This file contains an SSE2 implementation of data preparation for progressive
; Huffman encoding. See jcphuff.c for more details.
;
; [TAB8]
%include "jsimdext.inc"
; --------------------------------------------------------------------------
SECTION SEG_TEXT
BITS 64
; --------------------------------------------------------------------------
; Macros to load data for jsimd_encode_mcu_AC_first_prepare_sse2() and
; jsimd_encode_mcu_AC_refine_prepare_sse2()
%macro LOAD16 0
pxor N0, N0
pxor N1, N1
mov T0d, INT [LUT + 0*SIZEOF_INT]
mov T1d, INT [LUT + 8*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 0
pinsrw X1, word [BLOCK + T1 * 2], 0
mov T0d, INT [LUT + 1*SIZEOF_INT]
mov T1d, INT [LUT + 9*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 1
pinsrw X1, word [BLOCK + T1 * 2], 1
mov T0d, INT [LUT + 2*SIZEOF_INT]
mov T1d, INT [LUT + 10*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 2
pinsrw X1, word [BLOCK + T1 * 2], 2
mov T0d, INT [LUT + 3*SIZEOF_INT]
mov T1d, INT [LUT + 11*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 3
pinsrw X1, word [BLOCK + T1 * 2], 3
mov T0d, INT [LUT + 4*SIZEOF_INT]
mov T1d, INT [LUT + 12*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 4
pinsrw X1, word [BLOCK + T1 * 2], 4
mov T0d, INT [LUT + 5*SIZEOF_INT]
mov T1d, INT [LUT + 13*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 5
pinsrw X1, word [BLOCK + T1 * 2], 5
mov T0d, INT [LUT + 6*SIZEOF_INT]
mov T1d, INT [LUT + 14*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 6
pinsrw X1, word [BLOCK + T1 * 2], 6
mov T0d, INT [LUT + 7*SIZEOF_INT]
mov T1d, INT [LUT + 15*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 7
pinsrw X1, word [BLOCK + T1 * 2], 7
%endmacro
%macro LOAD15 0
pxor N0, N0
pxor N1, N1
pxor X1, X1
mov T0d, INT [LUT + 0*SIZEOF_INT]
mov T1d, INT [LUT + 8*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 0
pinsrw X1, word [BLOCK + T1 * 2], 0
mov T0d, INT [LUT + 1*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 1
mov T0d, INT [LUT + 2*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 2
mov T0d, INT [LUT + 3*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 3
mov T0d, INT [LUT + 4*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 4
mov T0d, INT [LUT + 5*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 5
mov T0d, INT [LUT + 6*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 6
mov T0d, INT [LUT + 7*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 7
cmp LENEND, 2
jl %%.ELOAD15
mov T1d, INT [LUT + 9*SIZEOF_INT]
pinsrw X1, word [BLOCK + T1 * 2], 1
cmp LENEND, 3
jl %%.ELOAD15
mov T1d, INT [LUT + 10*SIZEOF_INT]
pinsrw X1, word [BLOCK + T1 * 2], 2
cmp LENEND, 4
jl %%.ELOAD15
mov T1d, INT [LUT + 11*SIZEOF_INT]
pinsrw X1, word [BLOCK + T1 * 2], 3
cmp LENEND, 5
jl %%.ELOAD15
mov T1d, INT [LUT + 12*SIZEOF_INT]
pinsrw X1, word [BLOCK + T1 * 2], 4
cmp LENEND, 6
jl %%.ELOAD15
mov T1d, INT [LUT + 13*SIZEOF_INT]
pinsrw X1, word [BLOCK + T1 * 2], 5
cmp LENEND, 7
jl %%.ELOAD15
mov T1d, INT [LUT + 14*SIZEOF_INT]
pinsrw X1, word [BLOCK + T1 * 2], 6
%%.ELOAD15:
%endmacro
%macro LOAD8 0
pxor N0, N0
mov T0d, INT [LUT + 0*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 0
mov T0d, INT [LUT + 1*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 1
mov T0d, INT [LUT + 2*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 2
mov T0d, INT [LUT + 3*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 3
mov T0d, INT [LUT + 4*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 4
mov T0d, INT [LUT + 5*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 5
mov T0d, INT [LUT + 6*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 6
mov T0d, INT [LUT + 7*SIZEOF_INT]
pinsrw X0, word [BLOCK + T0 * 2], 7
%endmacro
%macro LOAD7 0
pxor N0, N0
pxor X0, X0
mov T1d, INT [LUT + 0*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 0
cmp LENEND, 2
jl %%.ELOAD7
mov T1d, INT [LUT + 1*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 1
cmp LENEND, 3
jl %%.ELOAD7
mov T1d, INT [LUT + 2*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 2
cmp LENEND, 4
jl %%.ELOAD7
mov T1d, INT [LUT + 3*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 3
cmp LENEND, 5
jl %%.ELOAD7
mov T1d, INT [LUT + 4*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 4
cmp LENEND, 6
jl %%.ELOAD7
mov T1d, INT [LUT + 5*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 5
cmp LENEND, 7
jl %%.ELOAD7
mov T1d, INT [LUT + 6*SIZEOF_INT]
pinsrw X0, word [BLOCK + T1 * 2], 6
%%.ELOAD7:
%endmacro
%macro REDUCE0 0
movdqa xmm0, XMMWORD [VALUES + ( 0*2)]
movdqa xmm1, XMMWORD [VALUES + ( 8*2)]
movdqa xmm2, XMMWORD [VALUES + (16*2)]
movdqa xmm3, XMMWORD [VALUES + (24*2)]
movdqa xmm4, XMMWORD [VALUES + (32*2)]
movdqa xmm5, XMMWORD [VALUES + (40*2)]
movdqa xmm6, XMMWORD [VALUES + (48*2)]
movdqa xmm7, XMMWORD [VALUES + (56*2)]
pcmpeqw xmm0, ZERO
pcmpeqw xmm1, ZERO
pcmpeqw xmm2, ZERO
pcmpeqw xmm3, ZERO
pcmpeqw xmm4, ZERO
pcmpeqw xmm5, ZERO
pcmpeqw xmm6, ZERO
pcmpeqw xmm7, ZERO
packsswb xmm0, xmm1
packsswb xmm2, xmm3
packsswb xmm4, xmm5
packsswb xmm6, xmm7
pmovmskb eax, xmm0
pmovmskb ecx, xmm2
pmovmskb edx, xmm4
pmovmskb esi, xmm6
shl rcx, 16
shl rdx, 32
shl rsi, 48
or rax, rcx
or rdx, rsi
or rax, rdx
not rax
mov MMWORD [r15], rax
%endmacro
;
; Prepare data for jsimd_encode_mcu_AC_first().
;
; GLOBAL(void)
; jsimd_encode_mcu_AC_first_prepare_sse2(const JCOEF *block,
; const int *jpeg_natural_order_start,
; int Sl, int Al, JCOEF *values,
; size_t *zerobits)
;
; r10 = const JCOEF *block
; r11 = const int *jpeg_natural_order_start
; r12 = int Sl
; r13 = int Al
; r14 = JCOEF *values
; r15 = size_t *zerobits
%define ZERO xmm9
%define X0 xmm0
%define X1 xmm1
%define N0 xmm2
%define N1 xmm3
%define AL xmm4
%define K eax
%define LUT r11
%define T0 rcx
%define T0d ecx
%define T1 rdx
%define T1d edx
%define BLOCK r10
%define VALUES r14
%define LEN r12d
%define LENEND r13d
align 32
GLOBAL_FUNCTION(jsimd_encode_mcu_AC_first_prepare_sse2)
EXTN(jsimd_encode_mcu_AC_first_prepare_sse2):
push rbp
mov rax, rsp ; rax = original rbp
sub rsp, byte 4
and rsp, byte (-SIZEOF_XMMWORD) ; align to 128 bits
mov [rsp], rax
mov rbp, rsp ; rbp = aligned rbp
lea rsp, [rbp - 16]
collect_args 6
movdqa XMMWORD [rbp - 16], ZERO
movd AL, r13d
pxor ZERO, ZERO
mov K, LEN
mov LENEND, LEN
and K, -16
and LENEND, 7
shr K, 4
jz .ELOOP16
.BLOOP16:
LOAD16
pcmpgtw N0, X0
pcmpgtw N1, X1
paddw X0, N0
paddw X1, N1
pxor X0, N0
pxor X1, N1
psrlw X0, AL
psrlw X1, AL
pxor N0, X0
pxor N1, X1
movdqa XMMWORD [VALUES + (0) * 2], X0
movdqa XMMWORD [VALUES + (8) * 2], X1
movdqa XMMWORD [VALUES + (0 + DCTSIZE2) * 2], N0
movdqa XMMWORD [VALUES + (8 + DCTSIZE2) * 2], N1
add VALUES, 16*2
add LUT, 16*SIZEOF_INT
dec K
jnz .BLOOP16
test LEN, 15
je .PADDING
.ELOOP16:
test LEN, 8
jz .TRY7
test LEN, 7
jz .TRY8
LOAD15
pcmpgtw N0, X0
pcmpgtw N1, X1
paddw X0, N0
paddw X1, N1
pxor X0, N0
pxor X1, N1
psrlw X0, AL
psrlw X1, AL
pxor N0, X0
pxor N1, X1
movdqa XMMWORD [VALUES + (0) * 2], X0
movdqa XMMWORD [VALUES + (8) * 2], X1
movdqa XMMWORD [VALUES + (0 + DCTSIZE2) * 2], N0
movdqa XMMWORD [VALUES + (8 + DCTSIZE2) * 2], N1
add VALUES, 16*2
jmp .PADDING
.TRY8:
LOAD8
pcmpgtw N0, X0
paddw X0, N0
pxor X0, N0
psrlw X0, AL
pxor N0, X0
movdqa XMMWORD [VALUES + (0) * 2], X0
movdqa XMMWORD [VALUES + (0 + DCTSIZE2) * 2], N0
add VALUES, 8*2
jmp .PADDING
.TRY7:
LOAD7
pcmpgtw N0, X0
paddw X0, N0
pxor X0, N0
psrlw X0, AL
pxor N0, X0
movdqa XMMWORD [VALUES + (0) * 2], X0
movdqa XMMWORD [VALUES + (0 + DCTSIZE2) * 2], N0
add VALUES, 8*2
.PADDING:
mov K, LEN
add K, 7
and K, -8
shr K, 3
sub K, DCTSIZE2/8
jz .EPADDING
align 16
.ZEROLOOP:
movdqa XMMWORD [VALUES + 0], ZERO
add VALUES, 8*2
inc K
jnz .ZEROLOOP
.EPADDING:
sub VALUES, DCTSIZE2*2
REDUCE0
movdqa ZERO, XMMWORD [rbp - 16]
uncollect_args 6
mov rsp, rbp ; rsp <- aligned rbp
pop rsp ; rsp <- original rbp
pop rbp
ret
%undef ZERO
%undef X0
%undef X1
%undef N0
%undef N1
%undef AL
%undef K
%undef LUT
%undef T0
%undef T0d
%undef T1
%undef T1d
%undef BLOCK
%undef VALUES
%undef LEN
%undef LENEND
;
; Prepare data for jsimd_encode_mcu_AC_refine().
;
; GLOBAL(int)
; jsimd_encode_mcu_AC_refine_prepare_sse2(const JCOEF *block,
; const int *jpeg_natural_order_start,
; int Sl, int Al, JCOEF *absvalues,
; size_t *bits)
;
; r10 = const JCOEF *block
; r11 = const int *jpeg_natural_order_start
; r12 = int Sl
; r13 = int Al
; r14 = JCOEF *values
; r15 = size_t *bits
%define ZERO xmm9
%define ONE xmm5
%define X0 xmm0
%define X1 xmm1
%define N0 xmm2
%define N1 xmm3
%define AL xmm4
%define K eax
%define KK r9d
%define EOB r8d
%define SIGN rdi
%define LUT r11
%define T0 rcx
%define T0d ecx
%define T1 rdx
%define T1d edx
%define BLOCK r10
%define VALUES r14
%define LEN r12d
%define LENEND r13d
align 32
GLOBAL_FUNCTION(jsimd_encode_mcu_AC_refine_prepare_sse2)
EXTN(jsimd_encode_mcu_AC_refine_prepare_sse2):
push rbp
mov rax, rsp ; rax = original rbp
sub rsp, byte 4
and rsp, byte (-SIZEOF_XMMWORD) ; align to 128 bits
mov [rsp], rax
mov rbp, rsp ; rbp = aligned rbp
lea rsp, [rbp - 16]
collect_args 6
movdqa XMMWORD [rbp - 16], ZERO
xor SIGN, SIGN
xor EOB, EOB
xor KK, KK
movd AL, r13d
pxor ZERO, ZERO
pcmpeqw ONE, ONE
psrlw ONE, 15
mov K, LEN
mov LENEND, LEN
and K, -16
and LENEND, 7
shr K, 4
jz .ELOOPR16
.BLOOPR16:
LOAD16
pcmpgtw N0, X0
pcmpgtw N1, X1
paddw X0, N0
paddw X1, N1
pxor X0, N0
pxor X1, N1
psrlw X0, AL
psrlw X1, AL
movdqa XMMWORD [VALUES + (0) * 2], X0
movdqa XMMWORD [VALUES + (8) * 2], X1
pcmpeqw X0, ONE
pcmpeqw X1, ONE
packsswb N0, N1
packsswb X0, X1
pmovmskb T0d, N0 ; lsignbits.val16u[k>>4] = _mm_movemask_epi8(neg);
pmovmskb T1d, X0 ; idx = _mm_movemask_epi8(x1);
shr SIGN, 16 ; make room for sizebits
shl T0, 48
or SIGN, T0
bsr T1d, T1d ; idx = 16 - (__builtin_clz(idx)>>1);
jz .CONTINUER16 ; if (idx) {
mov EOB, KK
add EOB, T1d ; EOB = k + idx;
.CONTINUER16:
add VALUES, 16*2
add LUT, 16*SIZEOF_INT
add KK, 16
dec K
jnz .BLOOPR16
.ELOOPR16:
test LEN, 8
jz .TRYR7
test LEN, 7
jz .TRYR8
LOAD15
pcmpgtw N0, X0
pcmpgtw N1, X1
paddw X0, N0
paddw X1, N1
pxor X0, N0
pxor X1, N1
psrlw X0, AL
psrlw X1, AL
movdqa XMMWORD [VALUES + (0) * 2], X0
movdqa XMMWORD [VALUES + (8) * 2], X1
pcmpeqw X0, ONE
pcmpeqw X1, ONE
packsswb N0, N1
packsswb X0, X1
pmovmskb T0d, N0 ; lsignbits.val16u[k>>4] = _mm_movemask_epi8(neg);
pmovmskb T1d, X0 ; idx = _mm_movemask_epi8(x1);
shr SIGN, 16 ; make room for sizebits
shl T0, 48
or SIGN, T0
bsr T1d, T1d ; idx = 16 - (__builtin_clz(idx)>>1);
jz .CONTINUER15 ; if (idx) {
mov EOB, KK
add EOB, T1d ; EOB = k + idx;
.CONTINUER15:
add VALUES, 16*2
jmp .PADDINGR
.TRYR8:
LOAD8
pcmpgtw N0, X0
paddw X0, N0
pxor X0, N0
psrlw X0, AL
movdqa XMMWORD [VALUES + (0) * 2], X0
pcmpeqw X0, ONE
packsswb N0, ZERO
packsswb X0, ZERO
pmovmskb T0d, N0 ; lsignbits.val16u[k>>4] = _mm_movemask_epi8(neg);
pmovmskb T1d, X0 ; idx = _mm_movemask_epi8(x1);
shr SIGN, 8 ; make room for sizebits
shl T0, 56
or SIGN, T0
bsr T1d, T1d ; idx = 16 - (__builtin_clz(idx)>>1);
jz .CONTINUER8 ; if (idx) {
mov EOB, KK
add EOB, T1d ; EOB = k + idx;
.CONTINUER8:
add VALUES, 8*2
jmp .PADDINGR
.TRYR7:
LOAD7
pcmpgtw N0, X0
paddw X0, N0
pxor X0, N0
psrlw X0, AL
movdqa XMMWORD [VALUES + (0) * 2], X0
pcmpeqw X0, ONE
packsswb N0, ZERO
packsswb X0, ZERO
pmovmskb T0d, N0 ; lsignbits.val16u[k>>4] = _mm_movemask_epi8(neg);
pmovmskb T1d, X0 ; idx = _mm_movemask_epi8(x1);
shr SIGN, 8 ; make room for sizebits
shl T0, 56
or SIGN, T0
bsr T1d, T1d ; idx = 16 - (__builtin_clz(idx)>>1);
jz .CONTINUER7 ; if (idx) {
mov EOB, KK
add EOB, T1d ; EOB = k + idx;
.CONTINUER7:
add VALUES, 8*2
.PADDINGR:
mov K, LEN
add K, 7
and K, -8
shr K, 3
sub K, DCTSIZE2/8
jz .EPADDINGR
align 16
.ZEROLOOPR:
movdqa XMMWORD [VALUES + 0], ZERO
shr SIGN, 8
add VALUES, 8*2
inc K
jnz .ZEROLOOPR
.EPADDINGR:
not SIGN
sub VALUES, DCTSIZE2*2
mov MMWORD [r15+SIZEOF_MMWORD], SIGN
REDUCE0
mov eax, EOB
movdqa ZERO, XMMWORD [rbp - 16]
uncollect_args 6
mov rsp, rbp ; rsp <- aligned rbp
pop rsp ; rsp <- original rbp
pop rbp
ret
%undef ZERO
%undef ONE
%undef X0
%undef X1
%undef N0
%undef N1
%undef AL
%undef K
%undef KK
%undef EOB
%undef SIGN
%undef LUT
%undef T0
%undef T0d
%undef T1
%undef T1d
%undef BLOCK
%undef VALUES
%undef LEN
%undef LENEND
; For some reason, the OS X linker does not honor the request to align the
; segment unless we do this.
align 32
|
/**
* @file /src/examples/console_streams.cpp
*
* @brief Demo for the console streams.
*
* @date October 2009
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <iostream>
#include <string>
#include <ecl/devices/console.hpp>
#include <ecl/streams/text_stream.hpp>
#include <ecl/streams/console_streams.hpp>
#include <ecl/streams/manipulators/end_of_line.hpp>
/*****************************************************************************
** Using
*****************************************************************************/
using std::string;
using ecl::OConsole;
using ecl::IConsole;
using ecl::endl;
using ecl::TextStream;
using ecl::IConsoleStream;
using ecl::OConsoleStream;
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char** argv) {
bool test_istreams = false;
std::cout << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << " OConsole Stream" << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << std::endl;
std::cout << "These can't really be tested very easily by google tests, so" << std::endl;
std::cout << "it's just provided here as a demo, but functionally is a" << std::endl;
std::cout << "unit test (requiring human approval)." << std::endl;
std::cout << std::endl;
OConsoleStream ostream;
std::cout << "Streaming char." << std::endl;
ostream << 'c' << '\n';
std::cout << "Streaming char string." << std::endl;
ostream << "Dude\n";
std::cout << "Streaming string." << std::endl;
string dude("dude_string\n");
ostream << dude;
std::cout << "Streaming integers." << std::endl;
short si = 1;
ostream << si << '\n';
int i = 2;
ostream << i << '\n';
long l = 3;
ostream << l << '\n';
long long ll = 4;
ostream << ll << '\n';
unsigned short us = 5;
ostream << us << '\n';
unsigned int ui = 6;
ostream << ui << '\n';
unsigned long ul = 77;
ostream << ul << '\n';
unsigned long long ull = 8888;
ostream << ull << '\n';
std::cout << "Streaming temporary integers." << std::endl;
ostream << 77 << '\n';
std::cout << "Streaming a boolean." << std::endl;
bool test = true;
ostream << test << '\n';
ostream << false << '\n';
std::cout << "Streaming floating point values." << std::endl;
float f = 32.1;
double d = -33.3;
ostream << f << '\n';
ostream << d << '\n';
std::cout << "Flushing" << std::endl;
ostream.flush();
std::cout << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << " OConsole Manipulators" << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << std::endl;
ostream << "dude with an ecl::endl" << endl;
if ( test_istreams ) {
std::cout << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << " IConsole Stream" << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << std::endl;
char c;
string response;
IConsoleStream istream;
// TextStream<IConsole> istream;
std::cout << "Enter a char." << std::endl;
istream >> c;
std::cout << "Char read: " << c << std::endl;
std::cout << "Enter a word." << std::endl;
istream >> response;
std::cout << "Word read: " << response << std::endl;
std::cout << "Enter a short: " << std::endl;
istream >> si;
if ( istream.fail() ) {
std::cout << "Short read failed: " << istream.errorStatus().what() << std::endl;
} else {
std::cout << "Short read: " << si << std::endl;
}
std::cout << "Enter a bool: " << std::endl;
istream >> test;
if ( istream.fail() ) {
std::cout << "Bool read failed: " << istream.errorStatus().what() << std::endl;
} else {
std::cout << "Bool read: ";
if ( test ) {
std::cout << "true" << std::endl;
} else {
std::cout << "false" << std::endl;
}
}
std::cout << "Enter a double:" << std::endl;
istream >> d;
if ( istream.fail() ) {
std::cout << "Double read failed: " << istream.errorStatus().what() << std::endl;
} else {
std::cout << "Double read: " << d << std::endl;
}
}
std::cout << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << " Passed" << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << std::endl;
return 0;
}
|
; A166593: Partial sums of A166592.
; Submitted by Simon Strandgaard
; 0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0,1,4,6,9,10,10,9,6,4,1,0,0
mov $2,$0
mov $3,$0
lpb $3
mov $0,$2
sub $3,1
sub $0,$3
seq $0,166592 ; Hankel transform of A166588(n-1).
add $1,$0
lpe
mov $0,$1
|
pop_register
stack
|
; A052881: E.g.f.: log(1/(1-x))*x/(1-x).
; Submitted by Jamie Morken(s2)
; 0,0,2,9,44,250,1644,12348,104544,986256,10265760,116915040,1446526080,19323757440,277238626560,4251984710400,69426608025600,1202482800691200,22021300630425600,425162773111910400,8631302936352768000,183811908771993600000,4097385837163745280000,95414965924715458560000,2316935199659833589760000,58569680409967964160000000,1538943349104231293583360000,41970273096984181548318720000,1186459807627102041149276160000,34723111635248091405991280640000,1050839999395794157994783539200000
sub $3,$0
sub $0,1
lpb $0
mul $2,$0
sub $2,$3
mul $3,$0
sub $0,1
lpe
mov $0,$2
|
#include <list>
#include <memory>
#include <algorithm>
#include <vector>
#include <iterator>
#include <cassert>
#include <tuple>
#include <array>
#include <thread>
#include <future>
#include <atomic>
#include <cmath>
#include <cstring>
#include "basedefs.h"
#include "face.h"
#include "hgt_optimizer.h"
#include "binary_streams.h"
constexpr static double ADDITIVE_ERROR = 1E-6;
constexpr static short MIN_VALID_HGT_VALUE = -500;
constexpr static bool vertex_has_zero_height(const point_t& pt) noexcept
{
return pt.z >= 0?pt.z <= ADDITIVE_ERROR:pt.z >= -ADDITIVE_ERROR;
}
inline static bool vertex_has_zero_height(unsigned pt) noexcept;
constexpr static short bswap(short w) noexcept
{
return (short) ((unsigned short) w << 8) | ((unsigned short) w >> 8);
}
template <class FaceType>
inline static ConstantDomainDataId GetFaceDomainDataId(const FaceType& face) noexcept
{
for (const auto& pt:face)
{
if (!vertex_has_zero_height(pt))
return ConstantDomainDataId::SurfaceLand;
}
return ConstantDomainDataId::SurfaceWater;
}
template <class FaceType>
inline static bool SameDomainData(const FaceType& left, const FaceType& right) noexcept
{
return GetFaceDomainDataId(left) == GetFaceDomainDataId(right);
}
class Matrix
{
short* m_points = nullptr;
std::unique_ptr<std::int8_t[]> m_pVertexStatus;
unsigned short m_cColumns = 0, m_cRows = 0;
double m_eColumnResolution = 0, m_eRowResolution = 0;
short m_min_height = std::numeric_limits<short>::max();
short m_max_height = std::numeric_limits<short>::min();
public:
Matrix() = default;
Matrix(short* pPoints, unsigned short cColumns, unsigned short cRows, double eColumnResolution, double eRowResolution)
:m_points(pPoints), m_pVertexStatus(std::make_unique<std::int8_t[]>(std::size_t(cColumns) * cRows)),
m_cColumns(cColumns), m_cRows(cRows), m_eColumnResolution(eColumnResolution), m_eRowResolution(eRowResolution)
{
auto cBlocks = std::thread::hardware_concurrency();
auto cItemsTotal = unsigned(cColumns) * cRows;
auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks;
std::list<std::thread> threads;
std::atomic<unsigned> fence_1(unsigned(0)), fence_2(unsigned(0));
auto pMinMax = std::make_unique<std::pair<std::atomic<short>, std::atomic<short>>[]>(std::size_t(cBlocks));
for (unsigned iThread = 0; iThread < cBlocks; ++iThread)
{
threads.emplace_back([this, iThread, cBlock, cBlocks, cItemsTotal, &fence_1, &fence_2](std::pair<std::atomic<short>, std::atomic<short>>& prMinMax) -> void
{
auto iBegin = iThread * cBlock;
auto iEnd = std::min((iThread + 1) * cBlock, cItemsTotal);
for (auto iElement = iBegin; iElement < iEnd; ++iElement)
m_points[iElement] = height_data_bswap(iElement);
if (fence_1.fetch_add(1, std::memory_order_acq_rel) + 1 < cBlocks)
do {std::this_thread::yield();} while (fence_1.load(std::memory_order_acquire) < cBlocks);
std::unique_ptr<short[]> pBuf;
unsigned buf_begin;
{
for (auto iElement = iBegin; iElement < iEnd; ++iElement)
{
if (m_points[iElement] < MIN_VALID_HGT_VALUE)
{
pBuf = std::make_unique<short[]>(std::size_t(iEnd - iElement));
std::memcpy(pBuf.get(), &m_points[iElement], std::size_t(iEnd - iElement) * sizeof(short));
buf_begin = iElement;
do
{
pBuf[iElement - buf_begin] = average_invalid_height(iElement);
}while (++iElement < iEnd);
}
}
}
if (fence_2.fetch_add(1, std::memory_order_acq_rel) + 1 < cBlocks)
do {std::this_thread::yield();} while (fence_2.load(std::memory_order_acquire) < cBlocks);
if (bool(pBuf))
std::memcpy(&m_points[buf_begin], pBuf.get(), std::size_t(iEnd - buf_begin) * sizeof(short));
if (fence_1.fetch_sub(1, std::memory_order_acq_rel) - 1 > 0)
do {std::this_thread::yield();} while (fence_1.load(std::memory_order_acquire) > 0);
short min_height = std::numeric_limits<short>::max();
short max_height = std::numeric_limits<short>::min();
for (auto iElement = iThread * cBlock; iElement < iEnd; ++iElement)
{
m_pVertexStatus[iElement] = this->is_empty_point_no_cache(iElement);
if (m_points[iElement] < min_height)
min_height = m_points[iElement];
if (m_points[iElement] > max_height)
max_height = m_points[iElement];
}
prMinMax.first.store(min_height, std::memory_order_relaxed);
prMinMax.second.store(max_height, std::memory_order_relaxed);
}, std::ref(pMinMax[iThread]));
}
unsigned iThread = 0;
for (auto& thr:threads)
{
thr.join();
auto l_min_height = pMinMax[iThread].first.load(std::memory_order_relaxed);
auto l_max_height = pMinMax[iThread].second.load(std::memory_order_relaxed);
if (l_min_height < m_min_height)
m_min_height = l_min_height;
if (l_max_height > m_max_height)
m_max_height = l_max_height;
++iThread;
}
}
inline unsigned short columns() const noexcept
{
return m_cColumns;
}
inline unsigned short rows() const noexcept
{
return m_cRows;
}
bool is_empty_point(unsigned short col, unsigned short row) const noexcept
{
return is_empty_point(this->locate(col, row));
}
inline bool is_empty_point(unsigned index) const noexcept
{
return bool(m_pVertexStatus[index]);
}
inline unsigned short point_x(unsigned index) const noexcept
{
return index % this->columns();
}
inline unsigned short point_y(unsigned index) const noexcept
{
return index / this->columns();
}
inline short point_z(unsigned index) const noexcept
{
return m_points[index];
}
inline short point_z(unsigned short col, unsigned short row) const noexcept
{
return this->point_z(this->locate(col, row));
}
inline unsigned locate(unsigned short col, unsigned short row) const noexcept
{
return row * this->columns() + col;
}
inline point_t get_external_point(unsigned short col, unsigned short row) const noexcept
{
return {double(col) * m_eColumnResolution, double(row) * m_eRowResolution, double(point_z(col, row))};
}
inline point_t get_external_point(unsigned index) const noexcept
{
return {double(this->point_x(index)) * m_eColumnResolution, double(this->point_y(index)) * m_eRowResolution, double(point_z(index))};
}
inline short min_height() const
{
return m_min_height;
}
inline short max_height() const
{
return m_max_height;
}
private:
bool is_empty_point_no_cache(unsigned point_index) const
{
auto col = this->point_x(point_index);
auto row = this->point_y(point_index);
if (col > 0 && col < this->columns() - 1
&& row > 0 && row < this->rows() - 1
&& this->point_z(col, row) - this->point_z(col - 1, row) == this->point_z(col + 1, row) - this->point_z(col, row)
&& this->point_z(col, row) - this->point_z(col, row - 1) == this->point_z(col, row + 1) - this->point_z(col, row)
&& this->point_z(col, row - 1) - this->point_z(col - 1, row - 1) == this->point_z(col, row) - this->point_z(col - 1, row)
&& this->point_z(col, row + 1) - this->point_z(col - 1, row + 1) == this->point_z(col, row) - this->point_z(col - 1, row)
&& this->point_z(col + 1, row - 1) - this->point_z(col, row - 1) == this->point_z(col + 1, row) - this->point_z(col, row)
&& this->point_z(col + 1, row + 1) - this->point_z(col, row + 1) == this->point_z(col + 1, row) - this->point_z(col, row))
{
point_t v_tl = this->get_external_point(col - 1, row - 1);
point_t v_tp = this->get_external_point(col, row - 1);
point_t v_tr = this->get_external_point(col + 1, row - 1);
point_t v_lf = this->get_external_point(col - 1, row);
point_t v_md = this->get_external_point(col, row);
point_t v_rt = this->get_external_point(col + 1, row);
point_t v_bl = this->get_external_point(col - 1, row + 1);
point_t v_bt = this->get_external_point(col, row + 1);
point_t v_br = this->get_external_point(col + 1, row + 1);
point_t f_tl_lb[] = {v_tl, v_md, v_lf};
point_t f_tl_rt[] = {v_tl, v_tp, v_md};
point_t f_tr_lb[] = {v_tp, v_rt, v_md};
point_t f_tr_rt[] = {v_tp, v_tr, v_rt};
point_t f_bl_lb[] = {v_lf, v_bt, v_bl};
point_t f_bl_rt[] = {v_lf, v_md, v_bt};
point_t f_br_lb[] = {v_md, v_br, v_bt};
point_t f_br_rt[] = {v_md, v_rt, v_br};
return std::int8_t(SameDomainData(face_t(std::begin(f_tl_lb), std::end(f_tl_lb)), face_t(std::begin(f_tl_rt), std::end(f_tl_rt)))
&& SameDomainData(face_t(std::begin(f_tl_rt), std::end(f_tl_rt)), face_t(std::begin(f_tr_lb), std::end(f_tr_lb)))
&& SameDomainData(face_t(std::begin(f_tr_lb), std::end(f_tr_lb)), face_t(std::begin(f_tr_rt), std::end(f_tr_rt)))
&& SameDomainData(face_t(std::begin(f_tr_rt), std::end(f_tr_rt)), face_t(std::begin(f_bl_lb), std::end(f_bl_lb)))
&& SameDomainData(face_t(std::begin(f_bl_lb), std::end(f_bl_lb)), face_t(std::begin(f_bl_rt), std::end(f_bl_rt)))
&& SameDomainData(face_t(std::begin(f_bl_rt), std::end(f_bl_rt)), face_t(std::begin(f_br_lb), std::end(f_br_lb)))
&& SameDomainData(face_t(std::begin(f_br_lb), std::end(f_br_lb)), face_t(std::begin(f_br_rt), std::end(f_br_rt))));
}
return false;
}
inline short height_data_bswap(unsigned point_index) const noexcept
{
return bswap(m_points[point_index]);
}
short average_invalid_height(unsigned point_index) const noexcept
{
unsigned short cl, cr;
short vl = short(), vr = short();
unsigned short rt, rb;
short vt = short(), vb = short();
auto col = this->point_x(point_index);
auto row = this->point_y(point_index);
for (cr = col + 1; cr < this->columns(); ++cr)
{
if (m_points[point_index + cr - col] >= MIN_VALID_HGT_VALUE)
{
vr = m_points[point_index + cr - col];
break;
}
}
for (cl = 1; cl <= col; ++cl)
{
if (m_points[point_index - cl] >= MIN_VALID_HGT_VALUE)
{
cl = point_index - cl;
vl = m_points[cl];
break;
}
}
for (rb = row + 1; rb < this->rows(); ++rb)
{
if (this->point_z(col, rb) >= MIN_VALID_HGT_VALUE)
{
vb = this->point_z(col, rb);
break;
}
}
for (rt = 1; rt <= row; ++rt)
{
if (this->point_z(col, row - rt) >= MIN_VALID_HGT_VALUE)
{
rt = row - rt;
vt = this->point_z(col, rt);
break;
}
}
double eAve;
if (cr > cl)
{
eAve = double(vr - vl) / double(cr - cl) * (col - cl) + vl;
if (rb > rt)
return short((eAve + double(vb - vt) / double(rb - rt) * (row - rt) + vt) / 2);
return short(eAve);
}
return short(double(vb - vt) / double(rb - rt) * (row - rt) + vt);
}
};
Matrix g_matrix;
class Face
{
public:
typedef unsigned value_type; //index pointing to the matrix element
typedef unsigned* pointer;
typedef const unsigned* const_pointer;
typedef unsigned& reference;
typedef const unsigned& const_reference;
typedef unsigned* iterator;
typedef const unsigned* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef unsigned size_type;
typedef signed difference_type;
private:
static constexpr size_type SMALL_NUMBER = 4;
union
{
pointer m_vertices_big;
value_type m_vertices_small[SMALL_NUMBER];
};
pointer m_pVertices;
size_type m_vertices_count = 0;
public:
explicit operator face_t() const;
inline value_type point(size_type in_face_index) const noexcept
{
return m_pVertices[in_face_index];
}
inline size_type size() const noexcept
{
return m_vertices_count;
}
inline iterator begin() noexcept {return &m_pVertices[0];}
inline const_iterator cbegin() const noexcept {return const_cast<const unsigned*>(&m_pVertices[0]);}
inline const_iterator begin() const noexcept {return this->cbegin();}
inline iterator end() noexcept {return &m_pVertices[m_vertices_count];}
inline const_iterator cend() const noexcept {return const_cast<const unsigned*>(&m_pVertices[m_vertices_count]);}
inline const_iterator end() const noexcept {return this->cend();}
inline reverse_iterator rbegin() noexcept {return std::make_reverse_iterator(this->end());}
inline const_reverse_iterator crbegin() const noexcept {return std::make_reverse_iterator(this->end());}
inline const_reverse_iterator rbegin() const noexcept {return std::make_reverse_iterator(this->end());}
inline reverse_iterator rend() noexcept {return std::make_reverse_iterator(this->begin());}
inline const_reverse_iterator crend() const noexcept {return std::make_reverse_iterator(this->begin());}
inline const_reverse_iterator rend() const noexcept {return std::make_reverse_iterator(this->begin());}
bool is_complanar_to(const Face& right) const
{
auto n1 = cross_product(g_matrix.get_external_point(m_pVertices[1]) - g_matrix.get_external_point(m_pVertices[0]),
g_matrix.get_external_point(m_pVertices[2]) - g_matrix.get_external_point(m_pVertices[1]));
assert(fabs(n1.x) > ADDITIVE_ERROR || fabs(n1.y) > ADDITIVE_ERROR || fabs(n1.z) > ADDITIVE_ERROR);
auto n2 = cross_product(g_matrix.get_external_point(right.m_pVertices[1]) - g_matrix.get_external_point(right.m_pVertices[0]),
g_matrix.get_external_point(right.m_pVertices[2]) - g_matrix.get_external_point(right.m_pVertices[1]));
assert(fabs(n2.x) > ADDITIVE_ERROR || fabs(n2.y) > ADDITIVE_ERROR || fabs(n2.z) > ADDITIVE_ERROR);
auto res = cross_product(n1, n2);
return fabs(res.x) <= ADDITIVE_ERROR && fabs(res.y) <= ADDITIVE_ERROR && fabs(res.z) <= ADDITIVE_ERROR;
}
bool can_unite_with_quadruplet_left_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with_quadruplet_top_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with_quadruplet_right_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with_quadruplet_bottom_edge(unsigned short quad_left_col, unsigned short quad_top_row) const;
bool can_unite_with(const Face& right) const
{
return this->is_complanar_to(right) && SameDomainData(*this, right);
}
private:
class ReversedConstructor;
public:
Face() = default;
class Constructor
{
std::list<unsigned> m_lstEdgeVertices;
public:
Constructor() = default;
void add_point(unsigned short col, unsigned short row) noexcept
{
assert(!g_matrix.is_empty_point(col, row));
if (this->size() >= 2)
{
auto it_pp = m_lstEdgeVertices.rbegin();
auto it_p = it_pp++;
if ((g_matrix.point_y(*it_p) - g_matrix.point_y(*it_pp)) * (col - g_matrix.point_x(*it_p))
== (row - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_p) - g_matrix.point_x(*it_pp)))
*it_p = g_matrix.locate(col, row);
else
m_lstEdgeVertices.emplace_back(g_matrix.locate(col, row));
}else
m_lstEdgeVertices.emplace_back(g_matrix.locate(col, row));
}
void add_list(const Face& face)
{
auto it = face.begin();
auto pt = *it++;
this->add_point(g_matrix.point_x(pt), g_matrix.point_y(pt));
while (it != face.end())
m_lstEdgeVertices.emplace_back(*it);
}
void add_list(Face::Constructor&& right)
{
if (!right.empty())
{
if (m_lstEdgeVertices.empty())
m_lstEdgeVertices = std::move(right.m_lstEdgeVertices);
else
{
auto it_p = std::prev(m_lstEdgeVertices.end());
m_lstEdgeVertices.splice(m_lstEdgeVertices.end(), std::move(right.m_lstEdgeVertices));
auto it_n = it_p--;
auto it = it_n++;
if (it_n != m_lstEdgeVertices.end()
&& (g_matrix.point_y(*it) - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_n) - g_matrix.point_x(*it))
== (g_matrix.point_y(*it_n) - g_matrix.point_y(*it)) * (g_matrix.point_x(*it) - g_matrix.point_x(*it_p)))
m_lstEdgeVertices.erase(it);
}
}
}
typedef Face::ReversedConstructor Reversed;
void add_reversed_list(Reversed&& right);
//returns an index of the next quadruplet to analyze
unsigned add_face_to_the_right(unsigned short col, unsigned short row);
void add_face_to_the_bottom(unsigned short col, unsigned short row);
auto begin() {return m_lstEdgeVertices.begin();}
auto begin() const {return m_lstEdgeVertices.begin();}
auto cbegin() const {return m_lstEdgeVertices.cbegin();}
auto end() {return m_lstEdgeVertices.end();}
auto end() const {return m_lstEdgeVertices.end();}
auto cend() const {return m_lstEdgeVertices.cend();}
auto rbegin() {return m_lstEdgeVertices.rbegin();}
auto rbegin() const {return m_lstEdgeVertices.rbegin();}
auto crbegin() const {return m_lstEdgeVertices.crbegin();}
auto rend() {return m_lstEdgeVertices.rend();}
auto rend() const {return m_lstEdgeVertices.rend();}
auto crend() const {return m_lstEdgeVertices.crend();}
unsigned size() const {return unsigned(m_lstEdgeVertices.size());}
bool empty() const {return m_lstEdgeVertices.empty();}
};
Face(Constructor&& constr):Face(std::move(constr), int()) {}
//MSVC bug with fold expressions: https://developercommunity.visualstudio.com/content/problem/301623/fold-expressions-in-template-instantiations-fail-t.html
template <class ... Points, class = std::enable_if_t<
(sizeof ... (Points) > 1) && (sizeof ... (Points) <= SMALL_NUMBER) && std::conjunction_v<std::is_integral<Points> ...>>>
explicit Face(Points ... vertices):m_vertices_small{vertices...}, m_pVertices(m_vertices_small), m_vertices_count(unsigned(sizeof...(Points)))
{
static_assert(sizeof...(Points) >= 3, "Invalid number of vertices specified for a face");
/*assert((g_matrix.point_y(m_pVertices[sizeof...(Points) - 2]) - g_matrix.point_y(m_pVertices[sizeof...(Points) - 3]))
* (g_matrix.point_x(m_pVertices[sizeof...(Points) - 1]) - g_matrix.point_x(m_pVertices[sizeof...(Points) - 2]))
== (g_matrix.point_y(m_pVertices[sizeof...(Points) - 1]) - g_matrix.point_y(m_pVertices[sizeof...(Points) - 2]))
* (g_matrix.point_x(m_pVertices[sizeof...(Points) - 2]) - g_matrix.point_x(m_pVertices[sizeof...(Points) - 3])));*/
}
template <class ... Points, class = void, class = std::enable_if_t<(sizeof ... (Points) > SMALL_NUMBER) && std::conjunction_v<std::is_integral<Points> ...>>>
explicit Face(Points ... vertices):Face(std::array<typename std::tuple_element<0, std::tuple<Points...>>::type, sizeof ... (Points)>{vertices...}, int()) {}
Face(const Face&) = delete;
Face(Face&& right)
{
*this = std::move(right);
}
Face& operator=(const Face&) = delete;
Face& operator=(Face&& right)
{
if (this == &right)
return *this;
if (m_vertices_count > SMALL_NUMBER)
delete [] m_vertices_big;
if (right.m_vertices_count <= SMALL_NUMBER)
{
std::copy(&right.m_vertices_small[0], &right.m_vertices_small[right.m_vertices_count], &m_vertices_small[0]);
m_pVertices = m_vertices_small;
}else
{
m_vertices_big = right.m_vertices_big;
m_pVertices = m_vertices_big;
}
m_vertices_count = right.m_vertices_count;
right.m_vertices_count = 0;
return *this;
}
~Face() noexcept
{
if (m_vertices_count > SMALL_NUMBER)
delete [] m_vertices_big;
}
private:
class ReversedConstructor
{
Face::Constructor m_list;
public:
void add_point(unsigned short col, unsigned short row)
{
m_list.add_point(col, row);
}
auto begin() {return m_list.begin();}
auto begin() const {return m_list.begin();}
auto cbegin() const {return m_list.cbegin();}
auto end() {return m_list.end();}
auto end() const {return m_list.end();}
auto cend() const {return m_list.cend();}
auto rbegin() {return m_list.rbegin();}
auto rbegin() const {return m_list.rbegin();}
auto crbegin() const {return m_list.crbegin();}
auto rend() {return m_list.rend();}
auto rend() const {return m_list.rend();}
auto crend() const {return m_list.crend();}
unsigned size() const {return unsigned(m_list.size());}
bool empty() const {return m_list.empty();}
};
template <class Container>
Face(Container&& constr, int) noexcept
{
assert(constr.size() >= 3);
auto it_end = std::end(constr);
{
auto it_pp = std::rbegin(constr);
auto it_p = it_pp++;
auto col = g_matrix.point_x(*std::begin(constr));
auto row = g_matrix.point_y(*std::begin(constr));
if ((g_matrix.point_y(*it_p) - g_matrix.point_y(*it_pp)) * (col - g_matrix.point_x(*it_p))
== (row - g_matrix.point_y(*it_p)) * (g_matrix.point_x(*it_p) - g_matrix.point_x(*it_pp)))
{
assert(constr.size() - 1 >= 3);
--it_end;
m_vertices_count = unsigned(constr.size() - 1);
}else
m_vertices_count = unsigned(constr.size());
}
if (m_vertices_count <= SMALL_NUMBER)
m_pVertices = m_vertices_small;
else
{
m_vertices_big = new unsigned [m_vertices_count];
m_pVertices = m_vertices_big;
}
std::move(std::begin(constr), it_end, &m_pVertices[0]);
}
};
void Face::Constructor::add_reversed_list(Face::Constructor::Reversed&& right)
{
for (auto it = std::rbegin(right); it != std::rend(right); ++it)
this->add_point(g_matrix.point_x(*it), g_matrix.point_y(*it));
}
struct vertex_converting_iterator
{
typedef std::input_iterator_tag iterator_category;
typedef point_t value_type;
typedef const point_t *pointer, &reference;
typedef unsigned size_type;
typedef signed difference_type;
reference operator*() const
{
if (!m_fLastVal)
{
m_ptLastVal = g_matrix.get_external_point(*m_it);
m_fLastVal = true;
}
return m_ptLastVal;
}
pointer operator->() const
{
if (!m_fLastVal)
{
m_ptLastVal = g_matrix.get_external_point(*m_it);
m_fLastVal = true;
}
return &m_ptLastVal;
}
vertex_converting_iterator& operator++()
{
++m_it;
this->invalidate_value();
return *this;
}
vertex_converting_iterator operator++(int)
{
auto old = *this;
++*this;
return old;
}
bool operator==(const vertex_converting_iterator& right) const
{
return m_it == right.m_it;
}
bool operator!=(const vertex_converting_iterator& right) const
{
return m_it != right.m_it;
}
vertex_converting_iterator() = default;
explicit vertex_converting_iterator(Face::const_iterator it):m_it(it) {}
vertex_converting_iterator(const vertex_converting_iterator& right):m_fLastVal(right.m_fLastVal), m_it(right.m_it)
{
if (m_fLastVal)
m_ptLastVal = right.m_ptLastVal;
}
vertex_converting_iterator(vertex_converting_iterator&& right):vertex_converting_iterator(right) {}
vertex_converting_iterator& operator=(const vertex_converting_iterator& right)
{
m_fLastVal = right.m_fLastVal;
m_it = right.m_it;
if (m_fLastVal)
m_ptLastVal = right.m_ptLastVal;
return *this;
}
vertex_converting_iterator& operator=(vertex_converting_iterator&& right)
{
return *this = right;
}
private:
mutable bool m_fLastVal = false;
mutable point_t m_ptLastVal;
Face::const_iterator m_it;
inline void invalidate_value() noexcept
{
m_fLastVal = false;
}
};
Face::operator face_t() const
{
return face_t(vertex_converting_iterator(this->begin()), vertex_converting_iterator(this->end()), this->size());
}
inline static bool vertex_has_zero_height(unsigned pt) noexcept
{
return g_matrix.point_z(pt) == 0;
}
struct FaceCompareLess
{
inline bool operator()(const Face& left, const Face& right) const noexcept
{
return std::lexicographical_compare(std::begin(left), std::end(left), std::begin(right), std::end(right));
}
};
struct FaceCompareEqual
{
inline bool operator()(const Face& left, const Face& right) const noexcept
{
return std::equal(std::begin(left), std::end(left), std::begin(right), std::end(right));
}
};
class FaceSet
{
std::vector<Face> m_vFaces;
public:
struct Constructor
{
Constructor()
{
m_vFaces.reserve((g_matrix.columns() - 1) * (g_matrix.rows() - 1) * 2);
}
Face& add_face(Face&& face)
{
m_vFaces.emplace_back(std::move(face));
return *m_vFaces.rbegin();
}
private:
friend class FaceSet;
std::vector<Face> m_vFaces;
};
FaceSet() = default;
FaceSet(Constructor&& constr):m_vFaces(std::move(constr.m_vFaces))
{
m_vFaces.shrink_to_fit();
#ifndef NDEBUG
if (m_vFaces.empty())
return;
std::sort(m_vFaces.begin(), m_vFaces.end(), FaceCompareLess());
FaceCompareEqual eq;
for (auto it = m_vFaces.begin(), it_n = std::next(m_vFaces.begin()); it_n != m_vFaces.end(); it = it_n++)
{
if (eq(*it, *it_n))
throw std::invalid_argument("Non-unique face is found in the input set"); //replace to it_n = m_vFaces.erase(++it, ++it_n);
}
#endif
}
auto begin() noexcept {return m_vFaces.begin();}
auto begin() const noexcept {return m_vFaces.begin();}
auto cbegin() const noexcept {return m_vFaces.cbegin();}
auto end() noexcept {return m_vFaces.end();}
auto end() const noexcept {return m_vFaces.end();}
auto cend() const noexcept {return m_vFaces.cend();}
auto size() const noexcept {return m_vFaces.size();}
bool empty() const noexcept {return m_vFaces.empty();}
};
/*
3 2
x x
x x
0 1
0) o o 1) o o 2) o o 3) o o
o o . o o . . .
4) o . 5) o . 6) o . 7) o .
o o . o o . . .
8) . o 9) . o 10) . o 11) . o
o o . o o . . .
12) . . 13) . . 14) . . 15) . .
o o . o o . . .
*/
unsigned char GetPointQuadrupletType(unsigned short quad_left_col, unsigned short quad_top_row)
{
assert(quad_left_col < g_matrix.columns() && quad_top_row < g_matrix.rows());
return
((unsigned char) (!g_matrix.is_empty_point(quad_left_col, quad_top_row)) << 3) | ((unsigned char)(!g_matrix.is_empty_point(quad_left_col + 1, quad_top_row)) << 2) |
((unsigned char) (!g_matrix.is_empty_point(quad_left_col, quad_top_row + 1)) << 0) | ((unsigned char) (!g_matrix.is_empty_point(quad_left_col + 1, quad_top_row + 1)) << 1);
}
bool Face::can_unite_with_quadruplet_left_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 11:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 13:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col, quad_top_row + 1)};
if (!this->can_unite_with(cur_face))
return false;
if (quad_top_row > 0)
return !cur_face.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1);
return true;
}
case 15:
{
Face face_lb = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
if (!this->can_unite_with(face_lb))
return false;
if (quad_top_row < g_matrix.rows() - 2 && face_lb.can_unite_with_quadruplet_top_edge(quad_left_col, quad_top_row + 1))
return false;
Face face_rt = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)};
return !face_lb.can_unite_with(face_rt) || quad_top_row == 0 || !face_rt.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1);
}
default:
return false;
};
}
bool Face::can_unite_with_quadruplet_top_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 13:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 14:
case 15:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
default:
return false;
};
}
bool Face::can_unite_with_quadruplet_right_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 7:
{
Face cur_face = Face{g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 14:
case 15:
{
Face face_rt = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1)};
if (!this->can_unite_with(face_rt))
return false;
if (quad_top_row > 0 && face_rt.can_unite_with_quadruplet_bottom_edge(quad_left_col, quad_top_row - 1))
return false;
Face face_lb = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return !face_lb.can_unite_with(face_rt) || quad_top_row >= g_matrix.rows() - 2 || !face_lb.can_unite_with_quadruplet_top_edge(quad_left_col, quad_top_row + 1);
}
default:
return false;
};
}
bool Face::can_unite_with_quadruplet_bottom_edge(unsigned short quad_left_col, unsigned short quad_top_row) const
{
assert(quad_left_col < g_matrix.columns() - 1 && quad_top_row < g_matrix.rows() - 1);
switch (GetPointQuadrupletType(quad_left_col, quad_top_row))
{
case 7:
{
Face cur_face = Face{g_matrix.locate(quad_left_col + 1, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
case 11:
case 15:
{
Face cur_face = Face{g_matrix.locate(quad_left_col, quad_top_row), g_matrix.locate(quad_left_col + 1, quad_top_row + 1), g_matrix.locate(quad_left_col, quad_top_row + 1)};
return this->can_unite_with(cur_face);
}
default:
return false;
};
}
//returns an index of the next quadruplet to analyze
unsigned Face::Constructor::add_face_to_the_right(unsigned short col, unsigned short row)
{
Face::Constructor::Reversed constrEnd;
unsigned short cur_col = col;
unsigned ret_index;
do
{
switch (GetPointQuadrupletType(cur_col, row))
{
case 11:
this->add_point(cur_col + 1, row + 1);
ret_index = g_matrix.locate(cur_col, row) + 1;
break;
case 13:
this->add_point(cur_col + 1, row);
ret_index = g_matrix.locate(cur_col, row) + 1;
break;
case 15:
{
Face lb_face = Face{g_matrix.locate(cur_col, row), g_matrix.locate(cur_col + 1, row + 1), g_matrix.locate(cur_col, row + 1)};
Face rt_face = Face{g_matrix.locate(cur_col, row), g_matrix.locate(cur_col + 1, row), g_matrix.locate(cur_col + 1, row + 1)};
if (lb_face.can_unite_with(rt_face) && (row == 0 || !rt_face.can_unite_with_quadruplet_bottom_edge(cur_col, row - 1)))
{
this->add_point(cur_col + 1, row);
constrEnd.add_point(cur_col + 1, row + 1);
if (cur_col < g_matrix.columns() - 2 && rt_face.can_unite_with_quadruplet_left_edge(cur_col + 1, row))
{
++cur_col;
continue;
}
ret_index = g_matrix.locate(cur_col, row) + 1;
}else
{
this->add_point(cur_col + 1, row + 1);
ret_index = g_matrix.locate(cur_col, row);
}
break;
}
default:
#ifndef NDEBUG
assert(false);
#endif
ret_index = g_matrix.locate(g_matrix.columns() - 1, g_matrix.rows() - 1) + 1;
}
break;
}while (true);
this->add_reversed_list(std::move(constrEnd));
return ret_index;
}
void Face::Constructor::add_face_to_the_bottom(unsigned short col, unsigned short row)
{
Face::Constructor::Reversed constrEnd;
unsigned short cur_row = row;
unsigned char cur_type = GetPointQuadrupletType(col, cur_row);
do
{
switch (cur_type)
{
case 13:
this->add_point(col, cur_row + 1);
break;
case 14:
this->add_point(col + 1, cur_row + 1);
break;
case 15:
{
Face rt_face = Face{g_matrix.locate(col, cur_row), g_matrix.locate(col + 1, cur_row), g_matrix.locate(col + 1, cur_row + 1)};
Face lb_face = Face{g_matrix.locate(col, cur_row), g_matrix.locate(col + 1, cur_row + 1), g_matrix.locate(col, cur_row + 1)};
if (lb_face.can_unite_with(rt_face))
{
this->add_point(col + 1, cur_row + 1);
constrEnd.add_point(col, cur_row + 1);
if (cur_row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, cur_row + 1))
{
cur_type = GetPointQuadrupletType(col, ++cur_row);
continue;
}
break;
}else
this->add_point(col + 1, cur_row + 1);
break;
}
#ifndef NDEBUG
default:
assert(false);
#endif
}
break;
}while (true);
this->add_reversed_list(std::move(constrEnd));
}
//returned object will be empty, if a vertex V is encountered for which V < g_matrix.locate(v1_col, v1_row)) is true
Face::Constructor obtain_big_face(unsigned short v1_col, unsigned short v1_row, unsigned short v2_col, unsigned short v2_row)
{
unsigned start = g_matrix.locate(v1_col, v1_row);
Face::Constructor constr;
unsigned short cur_col = v1_col;
unsigned short cur_row = v1_row;
unsigned short next_col = v2_col;
unsigned short next_row = v2_row;
unsigned next_index = g_matrix.locate(next_col, next_row);
constr.add_point(v1_col, v1_row);
do
{
if (next_index < start)
return Face::Constructor();
if (next_row == cur_row + 1)
{
if (next_col == cur_col + 1)
{
if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else //if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
assert(!g_matrix.is_empty_point(next_col, next_row - 1));
cur_col = next_col;
cur_row = next_row--;
}
}else if (next_col == cur_col)
{
if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else //if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
assert(!g_matrix.is_empty_point(next_col + 1, next_row - 1));
cur_col = next_col++;
cur_row = next_row--;
}
}else
{
assert(next_col == cur_col - 1);
if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else //if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
assert(!g_matrix.is_empty_point(next_col + 1, next_row));
cur_col = next_col++;
cur_row = next_row;
}
}
}else if (next_row == cur_row)
{
if (next_col == cur_col + 1)
{
if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else //if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
assert(!g_matrix.is_empty_point(next_col - 1, next_row - 1));
cur_col = next_col--;
cur_row = next_row--;
}
}else
{
assert(next_col == cur_col - 1);
if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
cur_col = next_col;
cur_row = next_row++;
}else //if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
assert((!g_matrix.is_empty_point(next_col + 1, next_row + 1)));
cur_col = next_col++;
cur_row = next_row++;
}
}
}else
{
assert(next_row == cur_row - 1);
if (next_col == cur_col + 1)
{
if (!g_matrix.is_empty_point(next_col + 1, next_row + 1))
{
cur_col = next_col++;
cur_row = next_row++;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else // if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
assert(!g_matrix.is_empty_point(next_col - 1, next_row));
cur_col = next_col--;
cur_row = next_row;
}
}else if (next_col == cur_col)
{
if (!g_matrix.is_empty_point(next_col + 1, next_row))
{
cur_col = next_col++;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else //if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
assert(!g_matrix.is_empty_point(next_col - 1, next_row + 1));
cur_col = next_col--;
cur_row = next_row++;
}
}else
{
assert(next_col == cur_col - 1);
if (!g_matrix.is_empty_point(next_col + 1, next_row - 1))
{
cur_col = next_col++;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col, next_row - 1))
{
cur_col = next_col;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row - 1))
{
cur_col = next_col--;
cur_row = next_row--;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row))
{
cur_col = next_col--;
cur_row = next_row;
}else if (!g_matrix.is_empty_point(next_col - 1, next_row + 1))
{
cur_col = next_col--;
cur_row = next_row++;
}else //if (!g_matrix.is_empty_point(next_col, next_row + 1))
{
assert(!g_matrix.is_empty_point(next_col, next_row + 1));
cur_col = next_col;
cur_row = next_row++;
}
}
}
constr.add_point(cur_col, cur_row);
}while ((next_index = g_matrix.locate(next_col, next_row)) != start);
return constr;
}
//returns an index of the last quadruplet included in the face
unsigned parse_vertex(FaceSet::Constructor& faces, unsigned short col, unsigned short row)
{
assert(col < g_matrix.columns() && row < g_matrix.rows());
if (col == g_matrix.columns() - 1)
return g_matrix.locate(col, row) + 1;
if (row == g_matrix.rows() - 1)
return g_matrix.columns() * g_matrix.rows();
switch (GetPointQuadrupletType(col, row))
{
case 7:
{
Face cur_face = Face{g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)};
if (row < g_matrix.rows() - 2 && cur_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return g_matrix.locate(col, row) + 1;
}else if (col < g_matrix.columns() - 2 && cur_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
Face::Constructor constr;
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}else
{
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
}
case 10:
{
if (g_matrix.is_empty_point(col - 1, row + 1))
return g_matrix.locate(col, row) + 1;
auto constr = obtain_big_face(col, row, col + 1, row + 1);
if (!constr.empty())
faces.add_face(std::move(constr));
return g_matrix.locate(col, row) + 1;
}
case 11:
{
Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)};
if (row < g_matrix.rows() - 2 && cur_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
}else if (col == 0 || !cur_face.can_unite_with_quadruplet_right_edge(col - 1, row))
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
case 12:
{
if (g_matrix.is_empty_point(col - 1, row + 1))
return g_matrix.locate(col, row) + 1;
auto constr = obtain_big_face(col, row, col + 1, row);
if (!constr.empty())
faces.add_face(std::move(constr));
return g_matrix.locate(col, row) + 1;
}
case 13:
{
Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col, row + 1)};
if ((col == 0 || !cur_face.can_unite_with_quadruplet_right_edge(col - 1, row))
&& (row == 0 || !cur_face.can_unite_with_quadruplet_bottom_edge(col, row - 1)))
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
case 14:
{
if (!g_matrix.is_empty_point(col - 1, row + 1))
{
auto constr = obtain_big_face(col, row, col + 1, row + 1);
if (!constr.empty())
faces.add_face(std::move(constr));
}
Face cur_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1)};
if (row > 0 && cur_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))
return g_matrix.locate(col, row) + 1;
if (col < g_matrix.columns() - 2 && cur_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}else
{
faces.add_face(std::move(cur_face));
return g_matrix.locate(col, row) + 1;
}
}
case 15:
{
Face lb_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)};
Face rt_face = Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1)};
if (lb_face.can_unite_with(rt_face))
{
if (row > 0 && rt_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))
return g_matrix.locate(col, row) + 1;
if (row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return g_matrix.locate(col, row) + 1;
}
if (col > 0 && lb_face.can_unite_with_quadruplet_right_edge(col - 1, row))
return g_matrix.locate(col, row) + 1;
if (col == g_matrix.columns() - 2 || !rt_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
faces.add_face(Face{g_matrix.locate(col, row), g_matrix.locate(col + 1, row), g_matrix.locate(col + 1, row + 1), g_matrix.locate(col, row + 1)});
return g_matrix.locate(col, row) + 1;
}else
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}
}else
{
if (row < g_matrix.rows() - 2 && lb_face.can_unite_with_quadruplet_top_edge(col, row + 1))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row + 1);
constr.add_face_to_the_bottom(col, row + 1);
constr.add_point(col, row + 1);
faces.add_face(Face(std::move(constr)));
}else if (col == 0 || !lb_face.can_unite_with_quadruplet_right_edge(col - 1, row))
faces.add_face(std::move(lb_face));
if (row == 0 || !rt_face.can_unite_with_quadruplet_bottom_edge(col, row - 1))
{
if (col < g_matrix.columns() - 2 && rt_face.can_unite_with_quadruplet_left_edge(col + 1, row))
{
Face::Constructor constr;
constr.add_point(col, row);
constr.add_point(col + 1, row);
auto ret = constr.add_face_to_the_right(col + 1, row);
constr.add_point(col + 1, row + 1);
faces.add_face(Face(std::move(constr)));
return ret;
}else
{
faces.add_face(std::move(rt_face));
return g_matrix.locate(col, row) + 1;
}
}else
return g_matrix.locate(col, row) + 1;
}
}
default:
return g_matrix.locate(col, row) + 1;
}
}
FaceSet parse_matrix(unsigned start_element /*= 0*/, unsigned end_element /*= g_matrix.columns() * g_matrix.rows()*/)
{
FaceSet::Constructor set;
for (unsigned index = start_element; index < end_element; )
{
index = parse_vertex(set, g_matrix.point_x(index), g_matrix.point_y(index));
}
return set;
}
#include <ostream>
static std::atomic_flag g_matrix_busy = ATOMIC_FLAG_INIT;
static unsigned convert_hgt_to_index_based_face(binary_ostream& os, short* pInput, unsigned short cColumns, unsigned short cRows, double eColumnResolution, double eRowResolution)
{
std::list<std::future<FaceSet>> futures;
while (g_matrix_busy.test_and_set(std::memory_order_acquire))
continue;
g_matrix = Matrix(pInput, cColumns, cRows, eColumnResolution, eRowResolution);
//auto cBlocks = unsigned(1);
auto cBlocks = unsigned(std::thread::hardware_concurrency());
auto cItemsTotal = unsigned(cColumns) * cRows;
auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks;
for (unsigned i = 0; i < cBlocks; ++i)
futures.emplace_back(std::async(std::launch::async, [i, cBlock, cItemsTotal]() -> auto
{
return parse_matrix(i * cBlock, std::min((i + 1) * cBlock, cItemsTotal));
}));
unsigned face_count = 0;
auto face_count_pos = os.tellp();
os.seekp(sizeof(unsigned), std::ios_base::cur);
for (auto& fut:futures)
{
auto set = fut.get();
face_count += unsigned(set.size());
for (const auto& face:set)
{
os << face.size();
for (auto pt:face)
os << g_matrix.point_x(pt) << g_matrix.point_y(pt) << g_matrix.point_z(pt);
}
}
g_matrix_busy.clear(std::memory_order_release);
auto endp = os.tellp();
os.seekp(face_count_pos);
os << face_count;
os.seekp(endp);
return face_count;
}
#if FILESYSTEM_CPP17
unsigned convert_hgt_to_index_based_face(std::filesystem::path input, std::filesystem::path output)
{
auto os = binary_ofstream(output);
std::ifstream is(input, std::ios_base::in | std::ios_base::binary);
is.seekg(0, std::ios_base::end);
auto cb = is.tellg();
if (cb % sizeof(short) != 0)
throw std::invalid_argument("Unexpected HGT file size");
is.seekg(0, std::ios_base::beg);
switch (cb)
{
case HGT_1.cColumns * HGT_1.cRows * sizeof(short):
{
auto pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is.read(reinterpret_cast<char*>(pInput.get()), cb);
return convert_hgt_to_index_based_face(os, pInput.get(), (unsigned short) (HGT_1.cColumns), (unsigned short) (HGT_1.cRows), HGT_1.dx, HGT_1.dy);
}
case HGT_3.cColumns * HGT_3.cRows * sizeof(short):
{
auto pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is.read(reinterpret_cast<char*>(pInput.get()), cb);
return convert_hgt_to_index_based_face(os, pInput.get(), (unsigned short) (HGT_3.cColumns), (unsigned short) (HGT_3.cRows), HGT_3.dx, HGT_3.dy);
}
default:
throw std::invalid_argument("Unexpected HGT file size");
};
}
#endif //FILESYSTEM_CPP17
struct conversion_result
{
conversion_result() = default;
conversion_result(std::vector<face_t>&& lstWater, std::vector<face_t>&& lstLand)
:m_WaterFaces(std::move(lstWater)), m_LandFaces(std::move(lstLand)) {}
inline std::vector<face_t>& water_faces() noexcept
{
return m_WaterFaces;
}
inline std::vector<face_t>& land_faces() noexcept
{
return m_LandFaces;
}
inline const std::vector<face_t>& water_faces() const noexcept
{
return m_WaterFaces;
}
inline const std::vector<face_t>& land_faces() const noexcept
{
return m_LandFaces;
}
private:
std::vector<face_t> m_WaterFaces;
std::vector<face_t> m_LandFaces;
};
template <class FaceType, class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void internal_face_to_external_face(std::true_type /*do_shift*/, FaceType&& face,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
auto domain_id = GetFaceDomainDataId(face);
auto ext = face_t(std::forward<FaceType>(face));
for (auto& pt:ext)
pt.z += -double(g_matrix.min_height());
switch (domain_id)
{
case ConstantDomainDataId::SurfaceLand:
std::forward<LandFacePlacementCallable>(land_callable)(std::move(ext));
break;
case ConstantDomainDataId::SurfaceWater:
std::forward<WaterFacePlacementCallable>(water_callable)(std::move(ext));
break;
default:
throw std::invalid_argument("Invalid face domain data in HGT");
}
}
template <class FaceType, class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void internal_face_to_external_face(std::false_type /*do_shift*/, FaceType&& face,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
switch (GetFaceDomainDataId(face))
{
case ConstantDomainDataId::SurfaceLand:
std::forward<LandFacePlacementCallable>(land_callable)(face_t(std::forward<FaceType>(face)));
break;
case ConstantDomainDataId::SurfaceWater:
std::forward<WaterFacePlacementCallable>(water_callable)(face_t(std::forward<FaceType>(face)));
break;
default:
throw std::invalid_argument("Invalid face domain data in HGT");
}
}
template <class fDoShift, class InternalFaceSetBeginIteratorType, class InternalFaceSetEndIteratorType,
class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void translate_internal_face_set(fDoShift do_shift, InternalFaceSetBeginIteratorType internal_set_begin, InternalFaceSetEndIteratorType internal_set_end,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
static_assert(std::is_same_v<fDoShift, std::true_type> || std::is_same_v<fDoShift, std::false_type>);
for (auto itFace = internal_set_begin; itFace != internal_set_end; ++itFace)
internal_face_to_external_face(do_shift, *itFace, std::forward<LandFacePlacementCallable>(land_callable),
std::forward<WaterFacePlacementCallable>(water_callable));
}
template <class FaceSetType, class LandFacePlacementCallable, class WaterFacePlacementCallable>
static void translate_internal_face_set(FaceSetType&& face_set,
LandFacePlacementCallable&& land_callable, WaterFacePlacementCallable&& water_callable)
{
if (g_matrix.min_height() < 0)
translate_internal_face_set(std::true_type(), std::begin(face_set), std::end(face_set), std::forward<LandFacePlacementCallable>(land_callable),
std::forward<WaterFacePlacementCallable>(water_callable));
else
translate_internal_face_set(std::false_type(), std::begin(face_set), std::end(face_set), std::forward<LandFacePlacementCallable>(land_callable),
std::forward<WaterFacePlacementCallable>(water_callable));
}
struct hgt_state
{
void start(binary_ostream& os, IDomainConverter& converter, unsigned points_to_process_at_start)
{
assert(m_pOs == nullptr && m_faces.empty() && process_land_face_ptr == nullptr && process_water_face_ptr == nullptr);
m_pOs = &os;
m_face_water_domain_data = converter.constant_face_domain_data(ConstantDomainDataId::SurfaceWater);
m_poly_water_domain_data = converter.constant_poly_domain_data(ConstantDomainDataId::SurfaceWater);
m_face_land_domain_data = converter.constant_face_domain_data(ConstantDomainDataId::SurfaceLand);
m_poly_land_domain_data = converter.constant_poly_domain_data(ConstantDomainDataId::SurfaceLand);
auto internal_set = parse_matrix(0, points_to_process_at_start);
process_land_face_ptr = &hgt_state::write_land_face_and_poly_header_to_stream;
process_water_face_ptr = &hgt_state::write_water_face_and_poly_header_to_stream;
std::vector<face_t> stored_faces;
stored_faces.reserve(internal_set.size());
translate_internal_face_set(internal_set,
[this](face_t&& face) {this->process_land_face(std::move(face));},
[&stored_faces](face_t&& face) {stored_faces.emplace_back(std::move(face));});
stored_faces.shrink_to_fit();
m_face_count_water = unsigned(stored_faces.size());
m_face_count_land = unsigned(internal_set.size()) - m_face_count_water;
m_faces.emplace_back(std::move(stored_faces));
}
void add_results(conversion_result&& res)
{
m_face_count_land += CAMaaS::size_type(res.land_faces().size());
m_face_count_water += CAMaaS::size_type(res.water_faces().size());
for (auto& face:res.land_faces())
process_land_face(std::move(face));
res.land_faces().clear();
m_faces.emplace_back(std::move(res.water_faces()));
}
hgt_t::conversion_statistics_t finalize()
{
if (m_face_count_land != 0)
{
m_pOs->seekp(m_face_count_pos);
*m_pOs << CAMaaS::size_type(m_face_count_land);
m_pOs->seekp(0, std::ios_base::end);
}
if (m_face_count_water != 0)
{
for (auto& vWater:m_faces)
{
for (auto& face:vWater)
this->process_water_face(std::move(face));
}
}
short min_height = g_matrix.min_height(), max_height = g_matrix.max_height();
if (min_height < 0)
{
max_height -= min_height;
min_height = 0;
}
hgt_t::conversion_statistics_t res{m_objects};
*this = hgt_state();
return res;
}
private:
CAMaaS::size_type m_objects = 0;
binary_ostream* m_pOs = nullptr;
binary_ostream::pos_type m_face_count_pos = 0;
CAMaaS::size_type m_face_count_land = 0;
CAMaaS::size_type m_face_count_water = 0;
std::list<std::vector<face_t>> m_faces;
void (hgt_state::*process_land_face_ptr)(face_t&& face) = nullptr;
void (hgt_state::*process_water_face_ptr)(face_t&& face) = nullptr;
domain_data_map m_face_water_domain_data, m_poly_water_domain_data, m_face_land_domain_data, m_poly_land_domain_data;
void write_poly_header(std::string_view poly_name, const domain_data_map& domain_data)
{
*m_pOs << std::uint32_t(poly_name.size());
m_pOs->write(poly_name.data(), poly_name.size());
*m_pOs << std::uint32_t(domain_data.size());
for (auto& prDomain:domain_data)
{
*m_pOs << std::uint32_t(prDomain.first.size());
m_pOs->write(prDomain.first.data(), prDomain.first.size());
*m_pOs << std::uint32_t(prDomain.second.size());
m_pOs->write(prDomain.second.data(), prDomain.second.size());
}
*m_pOs << CAMaaS::ObjectPoly;
m_face_count_pos = m_pOs->tellp();
}
inline void write_land_poly_header()
{
this->write_poly_header("HGT land", m_poly_land_domain_data);
*m_pOs << m_face_count_land;
}
void write_water_poly_header()
{
this->write_poly_header("HGT water", m_poly_water_domain_data);
*m_pOs << m_face_count_water;
}
void write_face_to_stream(face_t&& face, const domain_data_map& domain_data)
{
*m_pOs << std::uint32_t(face.size());
for (auto& pt:face)
*m_pOs << std::uint32_t(3) << pt.x << pt.y << pt.z;
*m_pOs << std::uint32_t(domain_data.size());
for (auto& prDomain:domain_data)
{
*m_pOs << std::uint32_t(prDomain.first.size());
m_pOs->write(prDomain.first.data(), prDomain.first.size());
*m_pOs << std::uint32_t(prDomain.second.size());
m_pOs->write(prDomain.second.data(), prDomain.second.size());
}
}
void write_water_face_to_stream(face_t&& face)
{
this->write_face_to_stream(std::move(face), m_face_water_domain_data);
}
void write_land_face_to_stream(face_t&& face)
{
this->write_face_to_stream(std::move(face), m_face_land_domain_data);
}
void write_water_face_and_poly_header_to_stream(face_t&& face)
{
++m_objects;
this->write_water_poly_header();
this->write_water_face_to_stream(std::move(face));
process_water_face_ptr = &hgt_state::write_water_face_to_stream;
}
void write_land_face_and_poly_header_to_stream(face_t&& face)
{
++m_objects;
this->write_land_poly_header();
this->write_land_face_to_stream(std::move(face));
process_land_face_ptr = &hgt_state::write_land_face_to_stream;
}
inline void process_land_face(face_t&& face)
{
return (this->*process_land_face_ptr)(std::move(face));
}
inline void process_water_face(face_t&& face)
{
return (this->*process_water_face_ptr)(std::move(face));
}
};
class hgt_impl_t:public hgt_t
{
std::unique_ptr<short[]> m_pInput;
IDomainConverter* m_pConverter;
hgt_t::attributes_t m_attr;
public:
hgt_impl_t() = default;
hgt_impl_t(std::istream& is_data, IDomainConverter& converter):m_pConverter(std::addressof(converter))
{
is_data.seekg(0, std::ios_base::end);
auto cb = is_data.tellg();
if (cb % sizeof(short) != 0)
throw std::invalid_argument("Unexpected HGT file size");
is_data.seekg(0, std::ios_base::beg);
switch (cb)
{
case HGT_1.cColumns * HGT_1.cRows * sizeof(short):
{
m_attr.resolution = HGT_1;
m_pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is_data.read(reinterpret_cast<char*>(m_pInput.get()), cb);
break;
}
case HGT_3.cColumns * HGT_3.cRows * sizeof(short):
{
m_attr.resolution = HGT_3;
m_pInput = std::make_unique<short[]>(std::size_t(cb) / sizeof(short));
is_data.read(reinterpret_cast<char*>(m_pInput.get()), cb);
break;
}
default:
throw std::invalid_argument("Unexpected HGT file size");
};
while (g_matrix_busy.test_and_set(std::memory_order_acquire))
continue;
g_matrix = Matrix(m_pInput.get(),
(unsigned short) m_attr.resolution.cColumns, (unsigned short) m_attr.resolution.cRows,
m_attr.resolution.dx, m_attr.resolution.dy);
m_attr.min_height = g_matrix.min_height();
m_attr.max_height = g_matrix.max_height();
m_attr.height_offset = m_attr.min_height < 0?-m_attr.min_height:0;
}
hgt_impl_t(const hgt_impl_t&) = default;
hgt_impl_t(hgt_impl_t&&) = default;
hgt_impl_t& operator=(const hgt_impl_t&) = default;
hgt_impl_t& operator=(hgt_impl_t&&) = default;
virtual ~hgt_impl_t()
{
g_matrix_busy.clear(std::memory_order_relaxed);
}
virtual const attributes_t& attributes() const
{
return m_attr;
}
virtual conversion_statistics_t write(binary_ostream& os) const
{
auto cBlocks = unsigned(std::thread::hardware_concurrency());
auto cItemsTotal = unsigned(m_attr.resolution.cColumns * m_attr.resolution.cRows);
auto cBlock = (cItemsTotal + cBlocks - 1) / cBlocks;
std::list<std::future<conversion_result>> futures;
for (unsigned i = 1; i < cBlocks; ++i)
futures.emplace_back(std::async(std::launch::async, [i, cBlock, cItemsTotal]() -> auto
{
std::vector<face_t> land_faces, water_faces;
unsigned start_element = i * cBlock;
unsigned end_element = std::min(start_element + cBlock, cItemsTotal);
auto internal_set = parse_matrix(start_element, end_element);
land_faces.reserve(internal_set.size());
water_faces.reserve(internal_set.size());
translate_internal_face_set(internal_set,
[&land_faces](face_t&& face) {land_faces.emplace_back(std::move(face));},
[&water_faces](face_t&& face) {water_faces.emplace_back(std::move(face));});
water_faces.shrink_to_fit();
land_faces.shrink_to_fit();
return conversion_result(std::move(water_faces), std::move(land_faces));
}));
hgt_state face_converter;
face_converter.start(os, *m_pConverter, std::min(cBlock, cItemsTotal));
for (auto& fut:futures)
face_converter.add_results(fut.get());
return face_converter.finalize();
}
};
std::unique_ptr<hgt_t> hgt_t::read(std::istream& is_data, IDomainConverter& converter)
{
return std::make_unique<hgt_impl_t>(is_data, converter);
}
|
dnl AMD64 mpn_sublsh1_n -- rp[] = up[] - (vp[] << 1)
dnl Copyright 2003, 2005, 2006, 2007 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU Lesser General Public License as published
dnl by the Free Software Foundation; either version 3 of the License, or (at
dnl your option) any later version.
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
dnl License for more details.
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C K8,K9: 2.2
C K10: 2.2
C P4: 12.75
C P6-15: 3.45
C Sometimes speed degenerates, supposedly related to that some operand
C alignments cause cache conflicts.
C The speed is limited by decoding/issue bandwidth. There are 26 instructions
C in the loop, which corresponds to 26/3/4 = 2.167 c/l.
C INPUT PARAMETERS
define(`rp',`%rdi')
define(`up',`%rsi')
define(`vp',`%rdx')
define(`n', `%rcx')
ASM_START()
TEXT
ALIGN(16)
PROLOGUE(mpn_sublsh1_n)
push %rbx
push %rbp
mov (vp), %r8
mov R32(n), R32(%rax)
lea (rp,n,8), rp
lea (up,n,8), up
lea (vp,n,8), vp
neg n
xor R32(%rbp), R32(%rbp)
and $3, R32(%rax)
je L(b00)
cmp $2, R32(%rax)
jc L(b01)
je L(b10)
L(b11): add %r8, %r8
mov 8(vp,n,8), %r9
adc %r9, %r9
mov 16(vp,n,8), %r10
adc %r10, %r10
sbb R32(%rax), R32(%rax) C save scy
mov (up,n,8), %rbp
mov 8(up,n,8), %rbx
sub %r8, %rbp
sbb %r9, %rbx
mov %rbp, (rp,n,8)
mov %rbx, 8(rp,n,8)
mov 16(up,n,8), %rbp
sbb %r10, %rbp
mov %rbp, 16(rp,n,8)
sbb R32(%rbp), R32(%rbp) C save acy
add $3, n
jmp L(ent)
L(b10): add %r8, %r8
mov 8(vp,n,8), %r9
adc %r9, %r9
sbb R32(%rax), R32(%rax) C save scy
mov (up,n,8), %rbp
mov 8(up,n,8), %rbx
sub %r8, %rbp
sbb %r9, %rbx
mov %rbp, (rp,n,8)
mov %rbx, 8(rp,n,8)
sbb R32(%rbp), R32(%rbp) C save acy
add $2, n
jmp L(ent)
L(b01): add %r8, %r8
sbb R32(%rax), R32(%rax) C save scy
mov (up,n,8), %rbp
sub %r8, %rbp
mov %rbp, (rp,n,8)
sbb R32(%rbp), R32(%rbp) C save acy
inc n
L(ent): jns L(end)
ALIGN(16)
L(oop): add R32(%rax), R32(%rax) C restore scy
mov (vp,n,8), %r8
L(b00): adc %r8, %r8
mov 8(vp,n,8), %r9
adc %r9, %r9
mov 16(vp,n,8), %r10
adc %r10, %r10
mov 24(vp,n,8), %r11
adc %r11, %r11
sbb R32(%rax), R32(%rax) C save scy
add R32(%rbp), R32(%rbp) C restore acy
mov (up,n,8), %rbp
mov 8(up,n,8), %rbx
sbb %r8, %rbp
sbb %r9, %rbx
mov %rbp, (rp,n,8)
mov %rbx, 8(rp,n,8)
mov 16(up,n,8), %rbp
mov 24(up,n,8), %rbx
sbb %r10, %rbp
sbb %r11, %rbx
mov %rbp, 16(rp,n,8)
mov %rbx, 24(rp,n,8)
sbb R32(%rbp), R32(%rbp) C save acy
add $4, n
js L(oop)
L(end): add R32(%rbp), R32(%rax)
neg R32(%rax)
pop %rbp
pop %rbx
ret
EPILOGUE()
|
#pragma once
#include <functional>
/**
* Represent a 24-bit rgb color.
*/
struct Color {
unsigned char r, g, b;
bool operator==(const Color& c) const noexcept { return r == c.r && g == c.g && b == c.b; }
bool operator!=(const Color& c) const noexcept { return !(c == *this); }
};
/**
* Hash function for color.
*/
namespace std {
template <> class hash<Color> {
public:
size_t operator()(const Color& c) const
{
return (size_t)c.r + (size_t)256 * (size_t)c.g + (size_t)256 * (size_t)256 * (size_t)c.b;
}
};
} // namespace std
|
; float __fsmul_callee(float a1, float a2)
SECTION code_fp_math48
PUBLIC cm48_sdccixp_dsmul_callee
EXTERN cm48_sdccixp_dcallee2, am48_dmul, cm48_sdccixp_m482d
cm48_sdccixp_dsmul_callee:
; multiply two sdcc floats
;
; enter : stack = sdcc_float a2, sdcc_float a1, ret
;
; exit : dehl = sdcc_float(a1*a2)
;
; uses : af, bc, de, hl, af', bc', de', hl'
call cm48_sdccixp_dcallee2
; AC'= a2
; AC = a1
call am48_dmul
jp cm48_sdccixp_m482d
|
global malloc, free, realloc, calloc
; these are global but you should never modify them.
; should only by touched once by start.asm for initialization.
global __malloc_beg, __malloc_end, __malloc_align
segment text
; void *_align(void *ptr, u64 align)
; align value must be a power of 2
_align:
mov rax, rdi
neg rdi
dec rsi
and rdi, rsi
add rax, rdi
ret
; the amount of memory for malloc to request at a time (must be a power of 2)
__malloc_step: equ 1 * 1024 * 1024 ; 1 MB
; alignment requirement of a malloc allocation (must be a power of 2)
__malloc_align: equ 16
; malloc linked list structure:
; v initial sys brk (base of stack space)
; <--- stack | ([void *next][void *prev][... data ...])...
; ^ doubly-linked list of zero or more malloc data blocks
;
; we shall assume no one else will be manipulating memory beyond the initial breakpoint.
; the start of each block will be aligned to __malloc_align.
; bit 0 of the 'next' field will hold 1 if the block is occupied.
;
; void *malloc(u64 size)
; allocates contiguous memory in dynamically-allocated space via sys_brk.
; you should not directly call sys_brk at any time (except in the case where it just returns the current break).
; the memory returned is aligned on 16-byte boundaries, making it suitable for all primitive types (including aligned xmm values).
; the pointer returned by this function must later be dealocated by calling free().
; allocating 0 bytes returns null.
; upon failure (e.g. sys_brk refused), returns null.
; upon success, returns a (non-null) pointer to the allocated memory, valid over the address space [0, size).
; dereferencing this pointer out of bounds is undefined behavior - importantly, this can corrupt the malloc data structure.
malloc:
; allocating 0 returns null
cmp rdi, 0
jnz .beg
xor rax, rax
ret
.beg:
; align the request size
mov esi, __malloc_align
call _align
mov rdi, rax
; get the beg/end positions
mov rsi, [__malloc_beg]
mov r8, [__malloc_end]
; look through the list for an available block of sufficient size
; for(void *prev = 0, *pos = beg; pos < end; prev = pos, pos = pos->next)
; -- prev = r11
; -- pos = rsi
; -- end = r8
xor r11, r11
jmp .aft
.top:
; get the next pointer
mov rdx, [rsi]
btr rdx, 0
jc .cont ; if it's occupied, skip
; compute size - if it's not big enough, it won't work
mov rcx, rdx
sub rcx, rsi
sub rcx, 16
cmp rcx, rdi
jb .cont ; if it's too small, skip it
je .nosplit
lea rax, [rsi + 16 + rdi] ; start of split
mov [rax], rdx ; update split's next (vacant)
mov [rax + 8], rsi ; update split's prev
cmp rdx, r8
cmovb [rdx + 8], rax ; if next is in bounds, update next->prev
mov rdx, rax ; update register that holds our next
.nosplit:
or dl, 1 ; mark this block as occupied
mov [rsi], rdx
lea rax, [rsi + 16] ; return pointer to data array
ret
.cont:
mov r11, rsi
mov rsi, rdx
.aft:
cmp rsi, r8
jb .top
; -- if we got here, we went out of range of the malloc field -- ;
.begin_add:
; get program break
mov r9, rdi
mov rbx, r11
mov eax, sys_brk
xor edi, edi
syscall
mov r11, rbx
mov rdi, r9
; if we have room, create a new block on the end and take that
lea r10, [r8 + 16 + rdi]
cmp r10, rax
ja .nospace
.enough_space:
; we have enough space - create the new block on the end (occupied)
mov [__malloc_end], r10
bts r10, 0
mov [r8], r10
mov [r8 + 8], r11
lea rax, [r8 + 16]
ret
.nospace:
; otherwise we have no space - allocate more to make new break (r10) valid
mov rbx, r11
mov rdi, r10
mov rsi, __malloc_step
call _align
mov rdi, rax
mov eax, sys_brk
syscall
mov r11, rbx
; if we got a zero return, we're good
cmp rax, 0
jz .enough_space
; otherwise it failed - return null
xor rax, rax
ret
; void *realloc(void *ptr, qword size)
; creates a new aray with the specified size and copies over the contents.
; the resulting array is identical up to the lesser of the two sizes.
; if posible, the resize is performed in-place.
; returns a pointer to the new array.
; reallocating a null pointer is equivalent to calling malloc()
; reallocating to a size of zero is equivalent to calling free() (and returns null).
realloc:
; if pointer is null, call malloc()
cmp rdi, 0
cmovz rdi, rsi
jz malloc
; if size is zero, call free()
cmp rsi, 0
jnz .resize
call free
xor rax, rax ; we need to return null
ret
.resize:
; align the size (for later)
mov r8, rdi
mov rdi, rsi
mov esi, __malloc_align
call _align
mov rsi, rax ; aligned size back in rsi
mov rdi, r8 ; pointer back in rdi
; compute the size of this block
mov rcx, [rdi - 16]
btr rcx, 0
mov rbx, rcx ; save a copy of next in rbx
sub rcx, rdi
; if we already have enough space, we're good
cmp rcx, rsi
jae .enough_space
; compute the smaller size into rcx
cmova rcx, rsi
; we now know we're resizing to be larger - decide what we can do
cmp rbx, [__malloc_end]
je .inplace_tail ; if next is __malloc_end we can do it in-place as a tail extension
mov r11, [rbx] ; next->next in r11
btr r11, 0
jc .new_array ; if next is occupied, we need a new array
sub r11, rdi ; compute size of merging with (vacant) bucket to the right
cmp r11, rsi
jae .inplace_merge ; if merged has enough space, we can still do it inplace
jmp .new_array ; otherwise we need a new array
.inplace_tail:
mov r8, r11
mov rdx, rdi
mov eax, sys_brk
xor rdi, rdi
syscall ; current break point in rax
mov rdi, rdx
mov r11, r8
lea r8, [rdi + rsi] ; break point needed in r8 (this is why we aligned size earlier)
; if we have enough room, just move __malloc_end
cmp r8, rax
ja .more_mem
.good_mem:
mov [__malloc_end], r8
or r8b, 1
mov [rdi - 16], r8
mov rax, rdi
ret
.more_mem:
; otherwise we need to allocate more space to make new break (r8) valid
mov r10, rdi
mov rdi, r8
mov rsi, __malloc_step
call _align
mov rdi, rax
mov eax, sys_brk
mov rdx, r11
syscall
mov r11, rdx
mov rdi, r10
; if it succeeded, we're done
cmp rax, 0
jz .good_mem
; otherwise it failed - return null
xor rax, rax
ret
.inplace_merge:
lea rax, [rdi - 16] ; my meta block
mov rcx, [rbx] ; next->next in rcx (at this point next is guaranteed to be vacant)
mov [rax], rcx
bts qword ptr [rax], 0
mov [rcx + 8], rax
sub rcx, rdi
jmp .enough_space ; we've now merged with the vacant block, so we can just truncate this expanded block
.new_array: ; sad days, everybody, we need a new array
push rcx
push rdi
mov rdi, rsi
call malloc
mov rdi, rax ; new array in rdi
pop rsi ; old array in rsi
pop rcx ; smaller size in rcx
; copy the contents up to the smaller size (this is why we aligned the size earlier)
shr rcx, 3
cld
push rdi
push rsi
rep movsq
pop rsi
pop rdi
; free the old array
push rdi
mov rdi, rsi
call free
pop rax
ret
.enough_space: ; rcx has (full) size of this block, rsi has aligned requested size (less than or equal to block size), rdi has allocated pointer
cmp rcx, rsi
je .no_split
lea r8, [rdi - 16] ; my meta block
lea r9, [rdi + rsi] ; split point meta block
mov rax, [r8] ; rax is my meta next (has the occupied flag)
mov [r8], r9 ; my next is the split block
bts qword ptr [r8], 0 ; mark myself as allocated (in-place realloc)
mov [r9], rax ; split next is my meta next (occupied because we are occupied - then we'll free it to perform the merge operation)
mov [r9 + 8], r8 ; split prev is my meta block
cmp rax, [__malloc_end] ; make sure next line is in bounds
cmovb [rax - 1 + 8], r9 ; split->next->prev = split PROBLEM HERE
push rdi
lea rdi, [r9 + 16]
call free ; free the split block (marked as allocated) to perform any required merging and pruning operations
pop rax
ret
.no_split:
mov rax, rdi
ret
; void free(void *ptr)
; deallocated resources that were allocated by malloc/calloc/realloc.
; the specified pointer must be exactly what was returned by the allocation function.
; freeing the same allocation twice is undefined behavior.
; freeing null is no-op.
free:
cmp rdi, 0
jz .ret
; get the meta block
sub rdi, 16
; get next in rdx
mov rdx, [rdi]
btr rdx, 0
; if next is in range and not in use, get next->next in rdx (we'll merge right)
cmp rdx, [__malloc_end]
jae .nomerge_right
mov rcx, [rdx]
bt rcx, 0
cmovnc rdx, rcx
.nomerge_right:
; get prev in rcx
mov rcx, [rdi + 8]
; if prev is in range and not in use, merge with it
cmp rcx, 0
jz .nomerge_left
bt qword ptr [rcx], 0
jc .nomerge_left
mov rdi, rcx
.nomerge_left:
; perform all the merging we need
mov [rdi], rdx ; update our next pointer
cmp rdx, [__malloc_end] ; check for the end pointer condition
cmovne [rdx + 8], rdi ; rdx could be the end pointer, in which case don't dereference it (could be out of bounds)
jne .ret ; if our updated next pointer is not the end pointer, we're done
mov [__malloc_end], rdi ; otherwise eliminate this block from the list
.ret: ret
; void *calloc(qword size)
; as malloc except that it also zeroes the contents.
calloc:
call malloc
cmp rax, 0
jz .ret ; if allocation failed, early return
mov r8, rax
mov rdi, rax
xor rax, rax
mov rcx, [rdi - 16] ; remember there's a state flag in bit 0 of this value
sub rcx, rdi
shr rcx, 3 ; division by 8 discards the state flag, so we're ok
cld
rep stosq
mov rax, r8
.ret: ret
segment bss
align 8 ; begin/end address for malloc data structure - these must be initialized before use
__malloc_beg: resq 1
__malloc_end: resq 1
|
; A170289: Number of reduced words of length n in Coxeter group on 40 generators S_i with relations (S_i)^2 = (S_i S_j)^41 = I.
; 1,40,1560,60840,2372760,92537640,3608967960,140749750440,5489240267160,214080370419240,8349134446350360,325616243407664040,12699033492898897560,495262306223057004840,19315229942699223188760
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,39
lpe
mov $0,$2
div $0,39
|
;
; Word: negate
; Dictionary: (a - a)
; Date: 1st February 2018
; Macro: Yes
; Notes:
;
pop ix
xor a
ld l,a
ld h,a
sbc hl,de
ex de,hl
jp (ix) |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
#include <arrow/compute/api.h>
#include <arrow/status.h>
#include <arrow/type.h>
#include <arrow/type_fwd.h>
#include <arrow/type_traits.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <gandiva/configuration.h>
#include <gandiva/node.h>
#include <gandiva/tree_expr_builder.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include "codegen/arrow_compute/ext/array_item_index.h"
#include "codegen/arrow_compute/ext/code_generator_base.h"
#include "codegen/arrow_compute/ext/codegen_common.h"
#include "codegen/arrow_compute/ext/codegen_node_visitor.h"
#include "codegen/arrow_compute/ext/codegen_register.h"
#include "codegen/arrow_compute/ext/kernels_ext.h"
#include "utils/macros.h"
namespace sparkcolumnarplugin {
namespace codegen {
namespace arrowcompute {
namespace extra {
using ArrayList = std::vector<std::shared_ptr<arrow::Array>>;
/////////////// ConditionedJoinArrays ////////////////
class ConditionedJoinArraysKernel::Impl {
public:
Impl(arrow::compute::ExecContext* ctx,
const std::vector<std::shared_ptr<arrow::Field>>& left_key_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_key_list,
const std::shared_ptr<gandiva::Node>& func_node, int join_type,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
const std::shared_ptr<arrow::Schema>& result_schema)
: ctx_(ctx) {
std::vector<int> left_key_index_list;
THROW_NOT_OK(GetIndexList(left_key_list, left_field_list, &left_key_index_list));
std::vector<int> right_key_index_list;
THROW_NOT_OK(GetIndexList(right_key_list, right_field_list, &right_key_index_list));
std::vector<int> left_shuffle_index_list;
std::vector<int> right_shuffle_index_list;
THROW_NOT_OK(
GetIndexListFromSchema(result_schema, left_field_list, &left_shuffle_index_list));
THROW_NOT_OK(GetIndexListFromSchema(result_schema, right_field_list,
&right_shuffle_index_list));
std::vector<std::pair<int, int>> result_schema_index_list;
int exist_index = -1;
THROW_NOT_OK(GetResultIndexList(result_schema, left_field_list, right_field_list,
join_type, exist_index, &result_schema_index_list));
THROW_NOT_OK(LoadJITFunction(
func_node, join_type, left_key_index_list, right_key_index_list,
left_shuffle_index_list, right_shuffle_index_list, left_field_list,
right_field_list, result_schema_index_list, exist_index, &prober_));
}
arrow::Status Evaluate(const ArrayList& in) {
RETURN_NOT_OK(prober_->Evaluate(in));
return arrow::Status::OK();
}
arrow::Status MakeResultIterator(
std::shared_ptr<arrow::Schema> schema,
std::shared_ptr<ResultIterator<arrow::RecordBatch>>* out) {
RETURN_NOT_OK(prober_->MakeResultIterator(schema, out));
return arrow::Status::OK();
}
std::string GetSignature() { return signature_; }
private:
using ArrayType = typename arrow::TypeTraits<arrow::Int64Type>::ArrayType;
arrow::compute::ExecContext* ctx_;
std::shared_ptr<CodeGenBase> prober_;
std::string signature_;
arrow::Status GetResultIndexList(
const std::shared_ptr<arrow::Schema>& result_schema,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
const int join_type, int& exist_index,
std::vector<std::pair<int, int>>* result_schema_index_list) {
int i = 0;
bool found = false;
int target_index = -1;
int right_found = 0;
for (auto target_field : result_schema->fields()) {
target_index++;
i = 0;
found = false;
for (auto field : left_field_list) {
if (StrCmpCaseInsensitive(target_field->name(), field->name())) {
(*result_schema_index_list).push_back(std::make_pair(0, i));
found = true;
break;
}
i++;
}
if (found == true) continue;
i = 0;
for (auto field : right_field_list) {
if (StrCmpCaseInsensitive(target_field->name(), field->name())) {
(*result_schema_index_list).push_back(std::make_pair(1, i));
found = true;
right_found++;
break;
}
i++;
}
if (found == true) continue;
if (join_type == 4) exist_index = target_index;
}
// Add one more col if join_type is ExistenceJoin
if (join_type == 4) {
(*result_schema_index_list).push_back(std::make_pair(1, right_found));
}
return arrow::Status::OK();
}
arrow::Status LoadJITFunction(
const std::shared_ptr<gandiva::Node>& func_node, int join_type,
const std::vector<int>& left_key_index_list,
const std::vector<int>& right_key_index_list,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
const std::vector<std::pair<int, int>>& result_schema_index_list, int exist_index,
std::shared_ptr<CodeGenBase>* out) {
// generate ddl signature
std::stringstream func_args_ss;
func_args_ss << "<MergeJoin>"
<< "[JoinType]" << join_type;
if (func_node) {
std::shared_ptr<CodeGenRegister> node_tmp;
RETURN_NOT_OK(MakeCodeGenRegister(func_node, &node_tmp));
func_args_ss << "[cond]" << node_tmp->GetFingerprint();
}
func_args_ss << "[BuildSchema]";
for (auto field : left_field_list) {
func_args_ss << field->type()->ToString();
}
func_args_ss << "[ProbeSchema]";
for (auto field : right_field_list) {
func_args_ss << field->type()->ToString();
}
func_args_ss << "[LeftKeyIndex]";
for (auto i : left_key_index_list) {
func_args_ss << i << ",";
}
func_args_ss << "[RightKeyIndex]";
for (auto i : right_key_index_list) {
func_args_ss << i << ",";
}
func_args_ss << "[LeftShuffleIndex]";
for (auto i : left_shuffle_index_list) {
func_args_ss << i << ",";
}
func_args_ss << "[RightShuffleIndex]";
for (auto i : right_shuffle_index_list) {
func_args_ss << i << ",";
}
#ifdef DEBUG
std::cout << "signature original line is " << func_args_ss.str() << std::endl;
#endif
std::stringstream signature_ss;
signature_ss << std::hex << std::hash<std::string>{}(func_args_ss.str());
signature_ = signature_ss.str();
auto file_lock = FileSpinLock();
auto status = LoadLibrary(signature_, ctx_, out);
if (!status.ok()) {
// process
try {
auto codes = ProduceCodes(
func_node, join_type, left_key_index_list, right_key_index_list,
left_shuffle_index_list, right_shuffle_index_list, left_field_list,
right_field_list, result_schema_index_list, exist_index);
// compile codes
RETURN_NOT_OK(CompileCodes(codes, signature_));
RETURN_NOT_OK(LoadLibrary(signature_, ctx_, out));
} catch (const std::runtime_error& error) {
FileSpinUnLock(file_lock);
throw error;
}
}
FileSpinUnLock(file_lock);
return arrow::Status::OK();
}
class TypedProberCodeGenImpl {
public:
TypedProberCodeGenImpl(std::string indice, std::shared_ptr<arrow::DataType> data_type,
bool left = true)
: indice_(indice), data_type_(data_type), left_(left) {}
std::string GetImplCachedDefine() {
std::stringstream ss;
ss << "using ArrayType_" << indice_ << " = " << GetTypeString(data_type_, "Array")
<< ";" << std::endl;
ss << "std::vector<std::shared_ptr<ArrayType_" << indice_ << ">> cached_" << indice_
<< "_;" << std::endl;
return ss.str();
}
std::string GetResultIteratorPrepare() {
std::stringstream ss;
if (data_type_->id() == arrow::Type::DECIMAL ||
data_type_->id() == arrow::Type::TIMESTAMP) {
ss << "builder_" << indice_ << "_ = std::make_shared<"
<< GetTypeString(data_type_, "Builder")
<< ">(arrow::" << GetArrowTypeDefString(data_type_)
<< ", ctx_->memory_pool());" << std::endl;
} else {
ss << "builder_" << indice_ << "_ = std::make_shared<"
<< GetTypeString(data_type_, "Builder") << ">(ctx_->memory_pool());"
<< std::endl;
}
return ss.str();
}
std::string GetProcessFinish() {
std::stringstream ss;
ss << "std::shared_ptr<arrow::Array> out_" << indice_ << ";" << std::endl;
ss << "RETURN_NOT_OK(builder_" << indice_ << "_->Finish(&out_" << indice_ << "));"
<< std::endl;
ss << "builder_" << indice_ << "_->Reset();" << std::endl;
return ss.str();
}
std::string GetProcessOutList() {
std::stringstream ss;
ss << "out_" << indice_;
return ss.str();
}
std::string GetResultIterCachedDefine() {
std::stringstream ss;
if (left_) {
ss << "std::vector<std::shared_ptr<" << GetTypeString(data_type_, "Array")
<< ">> cached_" << indice_ << "_;" << std::endl;
} else {
ss << "std::shared_ptr<" << GetTypeString(data_type_, "Array") << "> cached_"
<< indice_ << "_;" << std::endl;
}
ss << "using ArrayType_" << indice_ << " = " << GetTypeString(data_type_, "Array")
<< ";" << std::endl;
ss << "std::shared_ptr<" << GetTypeString(data_type_, "Builder") << "> builder_"
<< indice_ << "_;" << std::endl;
return ss.str();
}
private:
std::string indice_;
std::shared_ptr<arrow::DataType> data_type_;
bool left_;
};
std::string GetJoinKeyFieldListDefine(
const std::vector<int>& left_key_index_list,
const std::vector<std::shared_ptr<arrow::Field>>& field_list) {
std::stringstream ss;
for (int i = 0; i < left_key_index_list.size(); i++) {
auto field = field_list[left_key_index_list[i]];
if (i != (left_key_index_list.size() - 1)) {
ss << "arrow::field(\"" << field->name()
<< "\", arrow::" << GetArrowTypeDefString(field->type()) << "), ";
} else {
ss << "arrow::field(\"" << field->name()
<< "\", arrow::" << GetArrowTypeDefString(field->type()) << ")";
}
}
return ss.str();
}
std::string GetEvaluateCacheInsert(const std::vector<int>& index_list) {
std::stringstream ss;
for (auto i : index_list) {
ss << "cached_0_" << i << "_.push_back(std::make_shared<ArrayType_0_" << i
<< ">(in[" << i << "]));" << std::endl;
}
return ss.str();
}
std::string GetEncodeJoinKey(std::vector<int> key_indices) {
std::stringstream ss;
for (int i = 0; i < key_indices.size(); i++) {
if (i != (key_indices.size() - 1)) {
ss << "in[" << key_indices[i] << "], ";
} else {
ss << "in[" << key_indices[i] << "]";
}
}
return ss.str();
}
std::string GetFinishCachedParameter(const std::vector<int>& key_indices) {
std::stringstream ss;
for (int i = 0; i < key_indices.size(); i++) {
if (i != (key_indices.size() - 1)) {
ss << "cached_0_" << key_indices[i] << "_, ";
} else {
ss << "cached_0_" << key_indices[i] << "_";
}
}
auto ret = ss.str();
if (ret.empty()) {
return ret;
} else {
return ", " + ret;
}
}
std::string GetImplCachedDefine(
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> codegen_list) {
std::stringstream ss;
for (auto codegen : codegen_list) {
ss << codegen->GetImplCachedDefine() << std::endl;
}
return ss.str();
}
std::string GetResultIteratorParams(std::vector<int> key_indices) {
std::stringstream ss;
for (int i = 0; i < key_indices.size(); i++) {
if (i != (key_indices.size() - 1)) {
ss << "const std::vector<std::shared_ptr<ArrayType_0_" << key_indices[i]
<< ">> &cached_0_" << key_indices[i] << ", " << std::endl;
} else {
ss << "const std::vector<std::shared_ptr<ArrayType_0_" << key_indices[i]
<< ">> &cached_0_" << key_indices[i];
}
}
auto ret = ss.str();
if (ret.empty()) {
return ret;
} else {
return ", " + ret;
}
}
std::string GetResultIteratorSet(std::vector<int> key_indices) {
std::stringstream ss;
for (auto i : key_indices) {
ss << "cached_0_" << i << "_ = cached_0_" << i << ";" << std::endl;
}
return ss.str();
}
std::string GetResultIteratorPrepare(
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> left_codegen_list,
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> right_codegen_list) {
std::stringstream ss;
for (auto codegen : left_codegen_list) {
ss << codegen->GetResultIteratorPrepare() << std::endl;
}
for (auto codegen : right_codegen_list) {
ss << codegen->GetResultIteratorPrepare() << std::endl;
}
return ss.str();
}
std::string GetProcessRightSet(std::vector<int> indices) {
std::stringstream ss;
for (auto i : indices) {
ss << "cached_1_" << i << "_ = std::make_shared<ArrayType_1_" << i << ">(in[" << i
<< "]);" << std::endl;
}
return ss.str();
}
std::string GetProcessFinish(
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> left_codegen_list,
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> right_codegen_list) {
std::stringstream ss;
for (auto codegen : left_codegen_list) {
ss << codegen->GetProcessFinish() << std::endl;
}
for (auto codegen : right_codegen_list) {
ss << codegen->GetProcessFinish() << std::endl;
}
return ss.str();
}
std::string GetProcessOutList(
const std::vector<std::pair<int, int>>& result_schema_index_list,
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> left_codegen_list,
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> right_codegen_list) {
std::stringstream ss;
auto item_count = result_schema_index_list.size();
int i = 0;
for (auto index : result_schema_index_list) {
std::shared_ptr<TypedProberCodeGenImpl> codegen;
if (index.first == 0) {
codegen = left_codegen_list[index.second];
} else {
codegen = right_codegen_list[index.second];
}
if (i++ != (item_count - 1)) {
ss << codegen->GetProcessOutList() << ", ";
} else {
ss << codegen->GetProcessOutList();
}
}
return ss.str();
}
std::string GetResultIterCachedDefine(
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> left_codegen_list,
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> right_codegen_list) {
std::stringstream ss;
for (auto codegen : left_codegen_list) {
ss << codegen->GetResultIterCachedDefine() << std::endl;
}
for (auto codegen : right_codegen_list) {
ss << codegen->GetResultIterCachedDefine() << std::endl;
}
return ss.str();
}
std::string GetInnerJoin(bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<int>& right_key_index_list) {
std::stringstream ss;
for (auto i : left_shuffle_index_list) {
ss << "if (cached_0_" << i << "_[tmp.array_id]->null_count()) {" << std::endl;
ss << "if (cached_0_" << i << "_[tmp.array_id]->IsNull(tmp.id)) {" << std::endl;
ss << " RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());" << std::endl;
ss << "} else {" << std::endl;
ss << " RETURN_NOT_OK(builder_0_" << i << "_->Append(cached_0_" << i
<< "_[tmp.array_id]->GetView(tmp.id)));" << std::endl;
ss << "}" << std::endl;
ss << "} else {" << std::endl;
ss << " RETURN_NOT_OK(builder_0_" << i << "_->Append(cached_0_" << i
<< "_[tmp.array_id]->GetView(tmp.id)));" << std::endl;
ss << "}" << std::endl;
}
for (auto i : right_shuffle_index_list) {
ss << "if (cached_1_" << i << "_->null_count()) {" << std::endl;
ss << "if (cached_1_" << i << "_->IsNull(i)) {" << std::endl;
ss << " RETURN_NOT_OK(builder_1_" << i << "_->AppendNull());" << std::endl;
ss << "} else {" << std::endl;
ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
ss << "}" << std::endl;
ss << "} else {" << std::endl;
ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
ss << "}" << std::endl;
}
std::string shuffle_str;
if (cond_check) {
shuffle_str = R"(
if (ConditionCheck(tmp, i)) {
)" + ss.str() +
R"(
out_length += 1;
}
left_it->next();
}
left_it->setpos(cur_idx, seg_len, pl);
)";
} else {
shuffle_str = R"(
)" + ss.str() +
R"(
left_it->next();
out_length += 1;}
left_it->setpos(cur_idx, seg_len, pl);
)";
}
std::string right_value;
if (right_key_index_list.size() > 1) {
right_value += "item_content{";
for (auto i = 0; i < right_key_index_list.size(); i++) {
right_value += "typed_array_" + std::to_string(i) + "->GetView(i)";
if (i != right_key_index_list.size() - 1) {
right_value += ",";
}
}
right_value += "}";
} else {
right_value = "typed_array_0->GetView(i)";
}
return R"(
auto right_content =)" +
right_value + R"(;
if (!typed_array_0->IsNull(i)) {
while (left_it->hasnext() && left_it->value() < right_content) {
left_it->next();
}
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
while(left_it->hasnext() && left_it->value() == right_content) {
auto tmp = GetArrayItemIdex(left_it);)" +
shuffle_str + R"(
//if (left_it->value() > right_content && left_it->hasnext()){
//continue;
//}
}
)";
}
std::string GetOuterJoin(bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<int>& right_key_index_list) {
std::stringstream left_null_ss;
std::stringstream left_valid_ss;
std::stringstream right_valid_ss;
for (auto i : left_shuffle_index_list) {
left_valid_ss << "if (cached_0_" << i << "_[tmp.array_id]->null_count()) {"
<< std::endl;
left_valid_ss << "if (cached_0_" << i << "_[tmp.array_id]->IsNull(tmp.id)) {"
<< std::endl;
left_valid_ss << " RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());"
<< std::endl;
left_valid_ss << "} else {" << std::endl;
left_valid_ss << " RETURN_NOT_OK(builder_0_" << i << "_->Append(cached_0_" << i
<< "_[tmp.array_id]->GetView(tmp.id)));" << std::endl;
left_valid_ss << "}" << std::endl;
left_valid_ss << "} else {" << std::endl;
left_valid_ss << " RETURN_NOT_OK(builder_0_" << i << "_->Append(cached_0_" << i
<< "_[tmp.array_id]->GetView(tmp.id)));" << std::endl;
left_valid_ss << "}" << std::endl;
left_null_ss << "RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());" << std::endl;
}
for (auto i : right_shuffle_index_list) {
right_valid_ss << "if (cached_1_" << i << "_->null_count()) {" << std::endl;
right_valid_ss << "if (cached_1_" << i << "_->IsNull(i)) {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->AppendNull());"
<< std::endl;
right_valid_ss << "} else {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
right_valid_ss << "}" << std::endl;
right_valid_ss << "} else {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
right_valid_ss << "}" << std::endl;
}
std::string shuffle_str;
if (cond_check) {
shuffle_str = R"(
if (ConditionCheck(tmp, i)) {
)" + left_valid_ss.str() +
right_valid_ss.str() + R"(
out_length += 1;
}
)";
} else {
shuffle_str = R"(
)" + left_valid_ss.str() +
right_valid_ss.str() + R"(
out_length += 1;
)";
}
std::string right_value;
if (right_key_index_list.size() > 1) {
right_value += "item_content{";
for (auto i = 0; i < right_key_index_list.size(); i++) {
right_value += "typed_array_" + std::to_string(i) + "->GetView(i)";
if (i != right_key_index_list.size() - 1) {
right_value += ",";
}
}
right_value += "}";
} else {
right_value = "typed_array_0->GetView(i)";
}
return R"(
auto right_content =)" +
right_value + R"(;
if (!typed_array_0->IsNull(i)) {
while (left_it->hasnext() && left_it->value() < right_content ) {
left_it->next();
}
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
while(left_it->hasnext() && left_it->value() == right_content) {
auto tmp = GetArrayItemIdex(left_it);
)" + // TODO: cond check
left_valid_ss.str() +
right_valid_ss.str() + R"(
left_it->next();
last_match_idx = i;
out_length += 1;
}
left_it->setpos(cur_idx, seg_len, pl);
if(left_it->value() > right_content && left_it->hasnext() ) {
if (last_match_idx == i) {
continue;
}
auto tmp = GetArrayItemIdex(left_it);
)" +
left_null_ss.str() + right_valid_ss.str() + R"(
out_length += 1;
}
if (!left_it->hasnext()) {
)" +
left_null_ss.str() + right_valid_ss.str() + R"(
out_length += 1;
}
} else {
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
while(left_it->hasnext() && left_it->value() == right_content) {
auto tmp = GetArrayItemIdex(left_it);
)" +
left_valid_ss.str() + right_valid_ss.str() + R"(
left_it->next();
out_length += 1;
}
left_it->setpos(cur_idx, seg_len, pl);
}
)";
}
std::string GetFullOuterJoin(bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<int>& right_key_index_list) {
std::stringstream left_null_ss;
std::stringstream right_null_ss;
std::stringstream left_valid_ss;
std::stringstream right_valid_ss;
for (auto i : left_shuffle_index_list) {
left_valid_ss << "if (cached_0_" << i << "_[tmp.array_id]->null_count()) {"
<< std::endl;
left_valid_ss << "if (cached_0_" << i << "_[tmp.array_id]->IsNull(tmp.id)) {"
<< std::endl;
left_valid_ss << " RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());"
<< std::endl;
left_valid_ss << "} else {" << std::endl;
left_valid_ss << " RETURN_NOT_OK(builder_0_" << i << "_->Append(cached_0_" << i
<< "_[tmp.array_id]->GetView(tmp.id)));" << std::endl;
left_valid_ss << "}" << std::endl;
left_valid_ss << "} else {" << std::endl;
left_valid_ss << " RETURN_NOT_OK(builder_0_" << i << "_->Append(cached_0_" << i
<< "_[tmp.array_id]->GetView(tmp.id)));" << std::endl;
left_valid_ss << "}" << std::endl;
left_null_ss << "RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());" << std::endl;
}
for (auto i : right_shuffle_index_list) {
right_valid_ss << "if (cached_1_" << i << "_->null_count()) {" << std::endl;
right_valid_ss << "if (cached_1_" << i << "_->IsNull(i)) {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->AppendNull());"
<< std::endl;
right_valid_ss << "} else {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
right_valid_ss << "}" << std::endl;
right_valid_ss << "} else {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
right_valid_ss << "}" << std::endl;
right_null_ss << "RETURN_NOT_OK(builder_1_" << i << "_->AppendNull());"
<< std::endl;
}
std::string shuffle_str;
if (cond_check) {
shuffle_str = R"(
if (ConditionCheck(tmp, i)) {
)" + left_valid_ss.str() +
right_valid_ss.str() + R"(
out_length += 1;
}
)";
} else {
shuffle_str = R"(
)" + left_valid_ss.str() +
right_valid_ss.str() + R"(
out_length += 1;
)";
}
std::string right_value;
if (right_key_index_list.size() > 1) {
right_value += "item_content{";
for (auto i = 0; i < right_key_index_list.size(); i++) {
right_value += "typed_array_" + std::to_string(i) + "->GetView(i)";
if (i != right_key_index_list.size() - 1) {
right_value += ",";
}
}
right_value += "}";
} else {
right_value = "typed_array_0->GetView(i)";
}
return R"(
//full outer join
auto right_content =)" +
right_value + R"(;
while (left_it->hasnext() && left_it->value() < right_content ) {
auto tmp = GetArrayItemIdex(left_it);
)" + // TODO: cond check
left_valid_ss.str() +
right_null_ss.str() + R"(
left_it->next();
}
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
while(left_it->hasnext() && left_it->value() == right_content) {
auto tmp = GetArrayItemIdex(left_it);
)" + // TODO: cond check
left_valid_ss.str() +
right_valid_ss.str() + R"(
left_it->next();
last_match_idx = i;
out_length += 1;
}
left_it->setpos(cur_idx, seg_len, pl);
if(left_it->value() > right_content && left_it->hasnext() ) {
if (last_match_idx == i) {
continue;
}
auto tmp = GetArrayItemIdex(left_it);
)" +
left_null_ss.str() + right_valid_ss.str() + R"(
out_length += 1;
}
if (!left_it->hasnext()) {
)" +
left_null_ss.str() + right_valid_ss.str() + R"(
out_length += 1;
}
)";
}
std::string GetAntiJoin(bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list) {
std::stringstream left_null_ss;
std::stringstream right_valid_ss;
for (auto i : left_shuffle_index_list) {
left_null_ss << "RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());" << std::endl;
}
for (auto i : right_shuffle_index_list) {
right_valid_ss << "if (cached_1_" << i << "_->null_count()) {" << std::endl;
right_valid_ss << "if (cached_1_" << i << "_->IsNull(i)) {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->AppendNull());"
<< std::endl;
right_valid_ss << "} else {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
right_valid_ss << "}" << std::endl;
right_valid_ss << "} else {" << std::endl;
right_valid_ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
right_valid_ss << "}" << std::endl;
}
std::string shuffle_str;
if (cond_check) {
shuffle_str = R"(
hasequaled = true;
auto tmp = GetArrayItemIdex(left_it);
if (ConditionCheck(tmp, i)) {
found = true;
break;
}
left_it->next();
last_match_idx = i;
}
if (!found && hasequaled) {
)" + left_null_ss.str() +
right_valid_ss.str() + R"(
out_length += 1;
}
)";
} else {
shuffle_str = R"(
left_it->next();
last_match_idx = i;
}
)";
}
return R"(
while (left_it->hasnext() && left_it->value() < typed_array_0->GetView(i)) {
left_it->next();
}
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
bool found = false;
bool hasequaled = false;
while (left_it->hasnext() && left_it->value() == typed_array_0->GetView(i)) {
)" + shuffle_str +
R"(
left_it->setpos(cur_idx, seg_len, pl);
if (left_it->value() > typed_array_0->GetView(i) && left_it->hasnext() ) {
if (last_match_idx == i) {
continue;
}
)" +
left_null_ss.str() + right_valid_ss.str() + R"(
out_length += 1; }
if (!left_it->hasnext()) {
)" +
left_null_ss.str() + right_valid_ss.str() + R"(
out_length += 1;
}
)";
}
std::string GetSemiJoin(bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<int>& right_key_index_list) {
std::stringstream ss;
for (auto i : left_shuffle_index_list) {
ss << "RETURN_NOT_OK(builder_0_" << i << "_->AppendNull());" << std::endl;
}
for (auto i : right_shuffle_index_list) {
ss << "if (cached_1_" << i << "_->null_count()) {" << std::endl;
ss << "if (cached_1_" << i << "_->IsNull(i)) {" << std::endl;
ss << " RETURN_NOT_OK(builder_1_" << i << "_->AppendNull());" << std::endl;
ss << "} else {" << std::endl;
ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
ss << "}" << std::endl;
ss << "} else {" << std::endl;
ss << " RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
ss << "}" << std::endl;
}
std::string shuffle_str;
if (cond_check) {
shuffle_str = R"(
while (left_it->hasnext() && left_it->value() == right_content) {
auto tmp = GetArrayItemIdex(left_it);
if (ConditionCheck(tmp, i)) {
)" + ss.str() +
R"(
out_length += 1;
break;
}
)";
} else {
shuffle_str = R"(
if (left_it->value() == right_content && left_it->hasnext()) {
)" + ss.str() +
R"(
out_length += 1;
)";
}
std::string right_value;
if (right_key_index_list.size() > 1) {
right_value += "item_content{";
for (auto i = 0; i < right_key_index_list.size(); i++) {
right_value += "typed_array_" + std::to_string(i) + "->GetView(i)";
if (i != right_key_index_list.size() - 1) {
right_value += ",";
}
}
right_value += "}";
} else {
right_value = "typed_array_0->GetView(i)";
}
return R"(
auto right_content = )" +
right_value + R"(;
if (!typed_array_0->IsNull(i)) {
while (left_it->hasnext() && left_it->value() < right_content) {
left_it->next();
}
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
)" + shuffle_str +
R"(
left_it->next();
}
left_it->setpos(cur_idx, seg_len, pl);
//if (left_it->value() > right_content && left_it->hasnext() ) {
// continue;
//
// }
}
)";
}
std::string GetExistenceJoin(bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<int>& right_key_index_list) {
std::stringstream right_exist_ss;
std::stringstream right_not_exist_ss;
std::stringstream left_valid_ss;
std::stringstream right_valid_ss;
right_exist_ss << "const bool exist = true; "
"RETURN_NOT_OK(builder_1_exists_->Append(exist));"
<< std::endl;
right_not_exist_ss << "const bool not_exist = false; "
"RETURN_NOT_OK(builder_1_exists_->Append(not_exist));"
<< std::endl;
for (auto i : right_shuffle_index_list) {
right_valid_ss << "RETURN_NOT_OK(builder_1_" << i << "_->Append(cached_1_" << i
<< "_->GetView(i)));" << std::endl;
}
std::string shuffle_str;
if (cond_check) {
shuffle_str = R"(
if (ConditionCheck(tmp, i)) {
)" + right_valid_ss.str() +
right_exist_ss.str() + R"(
out_length += 1;
}
)";
} else {
shuffle_str = R"(
)" + right_valid_ss.str() +
right_exist_ss.str() + R"(
out_length += 1;
)";
}
std::string right_value;
if (right_key_index_list.size() > 1) {
right_value += "item_content{";
for (auto i = 0; i < right_key_index_list.size(); i++) {
right_value += "typed_array_" + std::to_string(i) + "->GetView(i)";
if (i != right_key_index_list.size() - 1) {
right_value += ",";
}
}
right_value += "}";
} else {
right_value = "typed_array_0->GetView(i)";
}
return R"(
// existence join
auto right_content = )" +
right_value + R"(;
if (!typed_array_0->IsNull(i)) {
while (left_it->hasnext() && left_it->value() < right_content) {
left_it->next();
}
int64_t cur_idx, seg_len, pl; left_it->getpos(&cur_idx, &seg_len, &pl);
if(left_it->hasnext() && left_it->value() == right_content) {
)" +
shuffle_str + R"(
last_match_idx = i;
while (left_it->hasnext() && left_it->value() == right_content) {
left_it->next();
}
}
left_it->setpos(cur_idx, seg_len, pl);
if(left_it->hasnext() && left_it->value() > right_content) {
if (last_match_idx == i) {
continue;
}
)" +
right_valid_ss.str() + right_not_exist_ss.str() + R"(
out_length += 1;
}
if (!left_it->hasnext()) {
)" +
right_valid_ss.str() + right_not_exist_ss.str() + R"(
out_length += 1;
}
}
)";
}
std::string GetProcessProbe(int join_type, bool cond_check,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<int>& right_key_index_list) {
switch (join_type) {
case 0: { /*Inner Join*/
return GetInnerJoin(cond_check, left_shuffle_index_list, right_shuffle_index_list,
right_key_index_list);
} break;
case 1: { /*Outer Join*/
return GetOuterJoin(cond_check, left_shuffle_index_list, right_shuffle_index_list,
right_key_index_list);
} break;
case 2: { /*Anti Join*/
return GetAntiJoin(cond_check, left_shuffle_index_list, right_shuffle_index_list);
} break;
case 3: { /*Semi Join*/
return GetSemiJoin(cond_check, left_shuffle_index_list, right_shuffle_index_list,
right_key_index_list);
} break;
case 4: { /*Existence Join*/
return GetExistenceJoin(cond_check, left_shuffle_index_list,
right_shuffle_index_list, right_key_index_list);
} break;
case 5: { /*Full outer Join*/
return GetFullOuterJoin(cond_check, left_shuffle_index_list,
right_shuffle_index_list, right_key_index_list);
} break;
default:
std::cout << "ConditionedProbeArraysTypedImpl only support join type: "
"InnerJoin, "
"RightJoin"
<< std::endl;
throw;
}
return "";
}
std::string GetConditionCheckFunc(
const std::shared_ptr<gandiva::Node>& func_node,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
std::vector<int>* left_out_index_list, std::vector<int>* right_out_index_list) {
std::shared_ptr<CodeGenNodeVisitor> func_node_visitor;
int func_count = 0;
std::vector<std::string> input_list;
std::vector<gandiva::ExpressionPtr> project_node_list;
THROW_NOT_OK(MakeCodeGenNodeVisitor(func_node, {left_field_list, right_field_list},
&func_count, &input_list, left_out_index_list,
right_out_index_list, &project_node_list,
&func_node_visitor));
return R"(
inline bool ConditionCheck(ArrayItemIndex x, int y) {
)" + func_node_visitor->GetPrepare() +
R"(
return )" +
func_node_visitor->GetResult() +
R"(;
}
)";
}
arrow::Status GetTypedProberCodeGen(
std::string prefix, bool left, const std::vector<int>& index_list,
const std::vector<std::shared_ptr<arrow::Field>>& field_list, int exist_index,
std::vector<std::shared_ptr<TypedProberCodeGenImpl>>* out_list,
int join_type = -1) {
for (auto i : index_list) {
auto field = field_list[i];
auto codegen = std::make_shared<TypedProberCodeGenImpl>(prefix + std::to_string(i),
field->type(), left);
(*out_list).push_back(codegen);
}
if (join_type == 4 && exist_index != -1) {
auto codegen = std::make_shared<TypedProberCodeGenImpl>(prefix + "exists",
arrow::boolean(), left);
(*out_list).insert((*out_list).begin() + exist_index, codegen);
}
return arrow::Status::OK();
}
std::vector<int> MergeKeyIndexList(const std::vector<int>& left_index_list,
const std::vector<int>& right_index_list) {
std::vector<int> ret = left_index_list;
for (auto i : right_index_list) {
if (std::find(left_index_list.begin(), left_index_list.end(), i) ==
left_index_list.end()) {
ret.push_back(i);
}
}
std::sort(ret.begin(), ret.end());
return ret;
}
std::string GetKeyCType(const std::vector<int>& key_index_list,
const std::vector<std::shared_ptr<arrow::Field>>& field_list) {
auto field = field_list[key_index_list[0]];
return GetCTypeString(field->type());
}
std::string GetIdArrayStr(bool cond_check, int join_type) {
std::stringstream ss;
std::string tuple_str;
if (cond_check) {
tuple_str = "idx_to_arrarid_.emplace_back(cur_array_id_);";
} else {
tuple_str = "idx_to_arrarid_.emplace_back(cur_array_id_);";
if (join_type == 2 || join_type == 3) {
tuple_str = "";
}
}
ss << tuple_str << std::endl;
return ss.str();
}
std::string GetTupleStr(bool multiple_cols, int size) {
std::stringstream ss;
std::string tuple_str;
if (multiple_cols) {
tuple_str = "std::forward_as_tuple";
}
if (multiple_cols) {
for (int i = 0; i < size; i++) {
std::string local_tuple =
"(typed_array_" + std::to_string(i) + "->GetView(cur_id_),";
tuple_str += local_tuple;
}
} else {
tuple_str += "typed_array_0->GetView(cur_id_),";
}
tuple_str.erase(tuple_str.end() - 1, tuple_str.end());
if (multiple_cols) {
tuple_str += "))";
}
ss << std::endl << "left_list_->emplace_back(" << tuple_str << ");" << std::endl;
return ss.str();
}
std::string GetListStr(bool multiple_cols, int size) {
std::stringstream ss;
std::string tuple_str;
if (multiple_cols) {
for (int i = 0; i < size; i++) {
std::string local_tuple = "typed_array_" + std::to_string(i) + ",";
tuple_str += local_tuple;
}
} else {
tuple_str += "typed_array_0,";
}
tuple_str.erase(tuple_str.end() - 1, tuple_str.end());
ss << std::endl << "left_list_.emplace_back(" << tuple_str << ");" << std::endl;
return ss.str();
}
std::string GetListContentStr(bool multiple_cols, int size) {
std::stringstream ss;
std::string tuple_str;
if (multiple_cols) {
for (int i = 0; i < size; i++) {
std::string local_tuple =
"std::get<" + std::to_string(i) + ">(it)->GetView(segment_len),";
tuple_str += local_tuple;
}
tuple_str.erase(tuple_str.end() - 1, tuple_str.end());
ss << std::endl << "return std::forward_as_tuple(" + tuple_str + ");" << std::endl;
} else {
ss << std::endl << "return it->GetView(segment_len);" << std::endl;
}
return ss.str();
}
std::string GetTypedArray(bool multiple_cols, int idx, std::vector<int> key_list,
std::vector<std::shared_ptr<arrow::Field>> field_list) {
std::stringstream ss;
if (multiple_cols) {
for (int i = 0; i < key_list.size(); i++) {
ss << "auto typed_array"
<< "_" << i << " = std::make_shared<"
<< GetTypeString(field_list[key_list[i]]->type(), "Array") << ">(in["
<< key_list[i] << "]);" << std::endl;
}
} else {
ss << "auto typed_array_0 = std::make_shared<"
<< GetTypeString(field_list[key_list[0]]->type(), "Array") << ">(in[" << idx
<< "]);" << std::endl;
}
return ss.str();
}
std::string GetTypedArray(bool multiple_cols, std::string index, int i,
std::string data_type,
std::string evaluate_encode_join_key_str) {
std::stringstream ss;
if (multiple_cols) {
ss << "auto concat_kernel_arr_list = {" << evaluate_encode_join_key_str << "};"
<< std::endl;
ss << "std::shared_ptr<arrow::Array> hash_in;" << std::endl;
ss << "RETURN_NOT_OK(hash_kernel_->Evaluate(concat_kernel_arr_list, "
"&hash_in));"
<< std::endl;
ss << "auto typed_array = std::make_shared<Int32Array>(hash_in);" << std::endl;
} else {
ss << "auto typed_array = std::make_shared<" << data_type << ">(in[" << i << "]);"
<< std::endl;
}
return ss.str();
}
std::string ProduceCodes(
const std::shared_ptr<gandiva::Node>& func_node, int join_type,
const std::vector<int>& left_key_index_list,
const std::vector<int>& right_key_index_list,
const std::vector<int>& left_shuffle_index_list,
const std::vector<int>& right_shuffle_index_list,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
const std::vector<std::pair<int, int>>& result_schema_index_list, int exist_index) {
std::vector<int> left_cond_index_list;
std::vector<int> right_cond_index_list;
bool cond_check = false;
bool multiple_cols = (left_key_index_list.size() > 1);
std::string list_tiem_str;
std::string hash_map_include_str = "";
std::string hash_map_type_str =
GetTypeString(left_field_list[left_key_index_list[0]]->type(), "Array");
std::string item_content_str =
GetCTypeString(left_field_list[left_key_index_list[0]]->type());
if (item_content_str == "std::string") {
item_content_str = "nonstd::sv_lite::string_view";
}
list_tiem_str = R"(
typedef std::shared_ptr<)" +
hash_map_type_str +
R"(> list_item;
typedef )" + item_content_str +
" item_content;";
std::vector<std::string> tuple_types;
std::vector<std::string> content_tuple_types;
if (multiple_cols) {
list_tiem_str = R"(
#include <tuple>)";
for (auto& key : left_key_index_list) {
tuple_types.push_back("std::shared_ptr<" +
GetTypeString(left_field_list[key]->type(), "Array") + ">");
content_tuple_types.push_back(GetCTypeString(left_field_list[key]->type()));
}
std::string tuple_define_str = "std::tuple<";
for (auto type : tuple_types) {
tuple_define_str += type;
tuple_define_str += ",";
}
// remove the ending ','
tuple_define_str.erase(tuple_define_str.end() - 1, tuple_define_str.end());
std::string content_define_str = "std::tuple<";
for (auto type : content_tuple_types) {
if (type == "std::string") {
type = "nonstd::sv_lite::string_view";
}
content_define_str += type;
content_define_str += ",";
}
// remove the ending ','
content_define_str.erase(content_define_str.end() - 1, content_define_str.end());
list_tiem_str += R"(
typedef )" + tuple_define_str +
R"(> list_item;
typedef )" + content_define_str +
"> item_content;";
} else {
tuple_types.push_back(hash_map_type_str);
}
hash_map_include_str += list_tiem_str;
std::string hash_map_define_str = "std::make_shared<std::vector<list_item>>();";
// TODO: fix multi columns case
std::string condition_check_str;
if (func_node) {
// TODO: move to use new API
condition_check_str =
GetConditionCheckFunc(func_node, left_field_list, right_field_list,
&left_cond_index_list, &right_cond_index_list);
cond_check = true;
}
auto process_probe_str =
GetProcessProbe(join_type, cond_check, left_shuffle_index_list,
right_shuffle_index_list, right_key_index_list);
auto left_cache_index_list =
MergeKeyIndexList(left_cond_index_list, left_shuffle_index_list);
auto right_cache_index_list =
MergeKeyIndexList(right_cond_index_list, right_shuffle_index_list);
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> left_cache_codegen_list;
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> left_shuffle_codegen_list;
std::vector<std::shared_ptr<TypedProberCodeGenImpl>> right_shuffle_codegen_list;
GetTypedProberCodeGen("0_", true, left_cache_index_list, left_field_list, exist_index,
&left_cache_codegen_list);
GetTypedProberCodeGen("0_", true, left_shuffle_index_list, left_field_list,
exist_index, &left_shuffle_codegen_list);
GetTypedProberCodeGen("1_", false, right_shuffle_index_list, right_field_list,
exist_index, &right_shuffle_codegen_list, join_type);
auto join_key_type_list_define_str =
GetJoinKeyFieldListDefine(left_key_index_list, left_field_list);
auto evaluate_cache_insert_str = GetEvaluateCacheInsert(left_cache_index_list);
auto evaluate_encode_join_key_str = GetEncodeJoinKey(left_key_index_list);
auto finish_cached_parameter_str = GetFinishCachedParameter(left_cache_index_list);
auto impl_cached_define_str = GetImplCachedDefine(left_cache_codegen_list);
auto result_iter_params_str = GetResultIteratorParams(left_cache_index_list);
auto result_iter_set_str = GetResultIteratorSet(left_cache_index_list);
auto result_iter_prepare_str =
GetResultIteratorPrepare(left_shuffle_codegen_list, right_shuffle_codegen_list);
auto process_right_set_str = GetProcessRightSet(right_cache_index_list);
auto process_encode_join_key_str = GetEncodeJoinKey(right_key_index_list);
auto process_finish_str =
GetProcessFinish(left_shuffle_codegen_list, right_shuffle_codegen_list);
auto process_out_list_str = GetProcessOutList(
result_schema_index_list, left_shuffle_codegen_list, right_shuffle_codegen_list);
auto result_iter_cached_define_str =
GetResultIterCachedDefine(left_cache_codegen_list, right_shuffle_codegen_list);
auto evaluate_get_typed_array_str = GetTypedArray(
multiple_cols, left_key_index_list[0], left_key_index_list, left_field_list);
auto process_get_typed_array_str = GetTypedArray(
multiple_cols, right_key_index_list[0], right_key_index_list, right_field_list);
auto evaluate_get_typed_array_str1 = GetTypedArray(
multiple_cols, "0_" + std::to_string(left_key_index_list[0]),
left_key_index_list[0],
GetTypeString(left_field_list[left_key_index_list[0]]->type(), "Array"),
evaluate_encode_join_key_str);
auto process_get_typed_array_str1 = GetTypedArray(
multiple_cols, "1_" + std::to_string(right_key_index_list[0]),
right_key_index_list[0],
GetTypeString(left_field_list[left_key_index_list[0]]->type(), "Array"),
process_encode_join_key_str);
auto make_tuple_str = GetTupleStr(multiple_cols, left_key_index_list.size());
auto make_idarray_str = GetIdArrayStr(cond_check, join_type);
auto make_list_str = GetListStr(multiple_cols, left_key_index_list.size());
auto make_list_content_str =
GetListContentStr(multiple_cols, left_key_index_list.size());
return BaseCodes() + R"(
#include <numeric>
#include "codegen/arrow_compute/ext/array_item_index.h"
#include "precompile/builder.h"
#include "precompile/gandiva.h"
using namespace sparkcolumnarplugin::precompile;
)" + hash_map_include_str +
R"(
class FVector {
public:
FVector(std::vector<list_item>* left_list, std::vector<int64_t> segment_info) {
left_list_ = left_list;
total_len_ = std::accumulate(segment_info.begin(), segment_info.end(), 0);
segment_info_ = segment_info;
it = (*left_list_)[0];
segment_len = 0;
}
void getpos(int64_t* cur_idx, int64_t* cur_segmeng_len, int64_t *passlen) {
*cur_idx = idx;
*cur_segmeng_len = segment_len;
*passlen = passed_len;
}
void setpos(int64_t cur_idx, int64_t cur_segment_len, int64_t cur_passed_len) {
idx = cur_idx;
it = (*left_list_)[idx];
segment_len = cur_segment_len;
passed_len = cur_passed_len;
}
item_content value() {
)" + make_list_content_str +
R"(}
bool hasnext() {
return (passed_len <= total_len_-1);
}
void next() {
segment_len++;
if (segment_len == segment_info_[idx] && passed_len != total_len_ -1) {
idx++;
segment_len = 0;
it = (*left_list_)[idx];
}
passed_len++;
}
public:
std::vector<list_item>* left_list_;
int64_t total_len_;
std::vector<int64_t> segment_info_;
int64_t idx = 0;
int64_t passed_len = 0;
int64_t segment_len = 0;
list_item it;
};
class TypedProberImpl : public CodeGenBase {
public:
TypedProberImpl(arrow::compute::ExecContext *ctx) : ctx_(ctx) {
}
~TypedProberImpl() {}
arrow::Status Evaluate(const ArrayList& in) override {
)" + evaluate_cache_insert_str +
evaluate_get_typed_array_str + make_list_str +
R"(
idx_to_arrarid_.push_back(typed_array_0->length());
return arrow::Status::OK();
}
arrow::Status MakeResultIterator(
std::shared_ptr<arrow::Schema> schema,
std::shared_ptr<ResultIterator<arrow::RecordBatch>> *out) override {
*out = std::make_shared<ProberResultIterator>(
ctx_, schema, &left_list_, &idx_to_arrarid_)" +
finish_cached_parameter_str + R"(
);
return arrow::Status::OK();
}
private:
uint64_t cur_array_id_ = 0;
uint64_t cur_id_ = 0;
uint64_t idx = 0;
uint64_t num_items_ = 0;
arrow::compute::ExecContext *ctx_;
std::vector<list_item> left_list_;
std::vector<int64_t> idx_to_arrarid_;
)" + impl_cached_define_str +
R"(
class ProberResultIterator : public ResultIterator<arrow::RecordBatch> {
public:
ProberResultIterator(
arrow::compute::ExecContext *ctx,
std::shared_ptr<arrow::Schema> schema,
std::vector<list_item>* left_list,
std::vector<int64_t> *idx_to_arrarid)" +
result_iter_params_str + R"(
)
: ctx_(ctx), result_schema_(schema), left_list_(left_list), last_pos(0), idx_to_arrarid_(idx_to_arrarid) {
)" +
result_iter_set_str + result_iter_prepare_str + R"(
left_it = std::make_shared<FVector>(left_list_, *idx_to_arrarid_);
}
std::string ToString() override { return "ProberResultIterator"; }
ArrayItemIndex GetArrayItemIdex(std::shared_ptr<FVector> left_it) {
int64_t local_arrayid, local_seglen, local_pl;
left_it->getpos(&local_arrayid, &local_seglen, &local_pl);
return ArrayItemIndex(local_arrayid, local_seglen);
}
arrow::Status
Process(const ArrayList &in, std::shared_ptr<arrow::RecordBatch> *out,
const std::shared_ptr<arrow::Array> &selection) override {
uint64_t out_length = 0;
)" + process_right_set_str +
process_get_typed_array_str +
R"(
auto length = cached_1_0_->length();
left_it->setpos(last_idx, last_seg, last_pl);
int last_match_idx = -1;
for (int i = 0; i < length; i++) {)" +
process_probe_str + R"(
}
)" + process_finish_str +
R"(
left_it->getpos(&last_idx, &last_seg, &last_pl);
*out = arrow::RecordBatch::Make(
result_schema_, out_length,
{)" +
process_out_list_str + R"(});
//arrow::PrettyPrint(*(*out).get(), 2, &std::cout);
return arrow::Status::OK();
}
private:
arrow::compute::ExecContext *ctx_;
std::shared_ptr<arrow::Schema> result_schema_;
std::vector<list_item>* left_list_;
std::shared_ptr<FVector> left_it;
int64_t last_pos;
int64_t last_idx = 0;
int64_t last_seg = 0;
int64_t last_pl = 0;
std::vector<int64_t> *idx_to_arrarid_;
)" + result_iter_cached_define_str +
R"(
)" + condition_check_str +
R"(
};
};
extern "C" void MakeCodeGen(arrow::compute::ExecContext *ctx,
std::shared_ptr<CodeGenBase> *out) {
*out = std::make_shared<TypedProberImpl>(ctx);
}
)";
}
};
arrow::Status ConditionedJoinArraysKernel::Make(
arrow::compute::ExecContext* ctx,
const std::vector<std::shared_ptr<arrow::Field>>& left_key_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_key_list,
const std::shared_ptr<gandiva::Node>& func_node, int join_type,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
const std::shared_ptr<arrow::Schema>& result_schema,
std::shared_ptr<KernalBase>* out) {
*out = std::make_shared<ConditionedJoinArraysKernel>(
ctx, left_key_list, right_key_list, func_node, join_type, left_field_list,
right_field_list, result_schema);
return arrow::Status::OK();
}
ConditionedJoinArraysKernel::ConditionedJoinArraysKernel(
arrow::compute::ExecContext* ctx,
const std::vector<std::shared_ptr<arrow::Field>>& left_key_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_key_list,
const std::shared_ptr<gandiva::Node>& func_node, int join_type,
const std::vector<std::shared_ptr<arrow::Field>>& left_field_list,
const std::vector<std::shared_ptr<arrow::Field>>& right_field_list,
const std::shared_ptr<arrow::Schema>& result_schema) {
impl_.reset(new Impl(ctx, left_key_list, right_key_list, func_node, join_type,
left_field_list, right_field_list, result_schema));
ctx_ = ctx;
kernel_name_ = "ConditionedJoinArraysKernel";
}
arrow::Status ConditionedJoinArraysKernel::Evaluate(const ArrayList& in) {
return impl_->Evaluate(in);
}
arrow::Status ConditionedJoinArraysKernel::MakeResultIterator(
std::shared_ptr<arrow::Schema> schema,
std::shared_ptr<ResultIterator<arrow::RecordBatch>>* out) {
return impl_->MakeResultIterator(schema, out);
}
std::string ConditionedJoinArraysKernel::GetSignature() { return impl_->GetSignature(); }
} // namespace extra
} // namespace arrowcompute
} // namespace codegen
} // namespace sparkcolumnarplugin
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x7ff5, %rsi
lea addresses_WT_ht+0x18ff5, %rdi
nop
nop
nop
nop
nop
inc %rbp
mov $34, %rcx
rep movsl
nop
xor $17457, %r12
lea addresses_A_ht+0xe675, %r12
clflush (%r12)
nop
nop
nop
nop
nop
inc %rdx
movl $0x61626364, (%r12)
nop
nop
nop
nop
nop
sub $47187, %rbp
lea addresses_WC_ht+0xf585, %rsi
lea addresses_UC_ht+0x31f5, %rdi
nop
nop
sub %r9, %r9
mov $59, %rcx
rep movsq
nop
and $39241, %rcx
lea addresses_UC_ht+0x89f5, %rsi
lea addresses_UC_ht+0x13245, %rdi
nop
nop
and $56193, %rbx
mov $94, %rcx
rep movsl
nop
xor %rsi, %rsi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r9
push %rax
push %rbp
push %rbx
push %rdx
push %rsi
// Store
lea addresses_UC+0xaa75, %rsi
clflush (%rsi)
nop
nop
nop
nop
add $30964, %r10
mov $0x5152535455565758, %rax
movq %rax, %xmm2
vmovups %ymm2, (%rsi)
nop
nop
nop
nop
nop
and %rbp, %rbp
// Faulty Load
lea addresses_WT+0x1f9f5, %rsi
cmp %rbx, %rbx
mov (%rsi), %r9w
lea oracles, %rbp
and $0xff, %r9
shlq $12, %r9
mov (%rbp,%r9,1), %r9
pop %rsi
pop %rdx
pop %rbx
pop %rbp
pop %rax
pop %r9
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_UC', 'AVXalign': False, 'size': 32}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WT', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}}
{'src': {'same': False, 'congruent': 3, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}}
{'src': {'same': True, 'congruent': 10, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}}
{'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
*/
|
#include "core.h"
#include "vertexBuffer.h"
#include <GL/glew.h>
namespace P3D::Graphics {
VertexBuffer::VertexBuffer() : Bindable(0) {
Log::debug("Created empty vertex buffer");
};
VertexBuffer::VertexBuffer(const BufferLayout& layout, const void* data, size_t sizeInBytes, GLFLAG mode) : Bindable(), currentCapacity(sizeInBytes), currentSize(sizeInBytes), layout(layout) {
glGenBuffers(1, &id);
bind();
if (sizeInBytes != 0)
fill(data, sizeInBytes, mode);
}
VertexBuffer::VertexBuffer(const BufferLayout& layout, const void* data, size_t sizeInBytes) : VertexBuffer(layout, data, sizeInBytes, GL_STATIC_DRAW) {}
VertexBuffer::~VertexBuffer() {
close();
Log::warn("Deleted vertex buffer with id (%d)", id);
}
VertexBuffer::VertexBuffer(VertexBuffer&& other) :
Bindable(other.id),
currentCapacity(other.currentCapacity),
currentSize(other.currentSize),
layout(std::move(other.layout)) {
// Reset to prevent destruction by rvalue
other.id = 0;
}
VertexBuffer& VertexBuffer::operator=(VertexBuffer&& other) {
if (this != &other) {
close();
std::swap(id, other.id);
std::swap(layout, other.layout);
std::swap(currentSize, other.currentSize);
std::swap(currentCapacity, other.currentCapacity);
}
return *this;
}
void VertexBuffer::fill(const void* data, std::size_t sizeInBytes, GLFLAG mode) {
currentSize = sizeInBytes;
currentCapacity = sizeInBytes;
bind();
glBufferData(GL_ARRAY_BUFFER, sizeInBytes, data, mode);
}
void VertexBuffer::update(const void* data, std::size_t sizeInBytes, std::size_t offset) {
size_t newCapacity = offset + sizeInBytes;
bind();
if (newCapacity > currentCapacity) {
Log::error("Buffer update exceeds buffer capacity: buffer=%d, size=%d, capacity=%d", id, sizeInBytes + offset, currentCapacity);
return;
}
glBufferSubData(GL_ARRAY_BUFFER, offset, sizeInBytes, data);
}
size_t VertexBuffer::size() const {
return currentSize;
}
size_t VertexBuffer::capacity() const {
return currentCapacity;
}
void VertexBuffer::bind() {
glBindBuffer(GL_ARRAY_BUFFER, id);
}
void VertexBuffer::unbind() {
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void VertexBuffer::close() {
unbind();
glDeleteBuffers(1, &id);
id = 0;
layout = BufferLayout();
currentCapacity = 0;
currentCapacity = 0;
}
}; |
; A339308: Partial sums of products of proper divisors of n (A007956).
; 1,2,3,5,6,12,13,21,24,34,35,179,180,194,209,273,274,598,599,999,1020,1042,1043,14867,14872,14898,14925,15709,15710,42710,42711,43735,43768,43802,43837,323773,323774,323812,323851,387851,387852,461940,461941,463877
lpb $0
mov $2,$0
sub $0,1
seq $2,7956 ; Product of proper divisors of n.
add $1,$2
lpe
add $1,1
mov $0,$1
|
#include <occa/lang/expr/binaryOpNode.hpp>
#include <occa/lang/expr/emptyNode.hpp>
#include <occa/lang/expr/identifierNode.hpp>
#include <occa/lang/loaders/attributeLoader.hpp>
#include <occa/lang/loaders/variableLoader.hpp>
#include <occa/lang/parser.hpp>
#include <occa/lang/statementContext.hpp>
#include <occa/lang/token.hpp>
namespace occa {
namespace lang {
attributeLoader_t::attributeLoader_t(tokenContext_t &tokenContext_,
statementContext_t &smntContext_,
parser_t &parser_,
nameToAttributeMap &attributeMap_) :
tokenContext(tokenContext_),
smntContext(smntContext_),
parser(parser_),
attributeMap(attributeMap_),
success(true) {}
bool attributeLoader_t::loadAttributes(attributeTokenMap &attrs) {
while (success &&
(token_t::safeOperatorType(tokenContext[0]) & operatorType::attribute)) {
loadAttribute(attrs);
if (!success) {
break;
}
}
return success;
}
void attributeLoader_t::loadAttribute(attributeTokenMap &attrs) {
// Skip [@] token
++tokenContext;
if (!(tokenContext[0]->type() & tokenType::identifier)) {
tokenContext.printError("Expected an attribute name");
success = false;
return;
}
identifierToken &nameToken = *((identifierToken*) tokenContext[0]);
++tokenContext;
attribute_t *attribute = getAttribute(attributeMap,
nameToken.value);
if (!attribute) {
nameToken.printError("Unknown attribute");
success = false;
return;
}
tokenRangeVector argRanges;
const bool hasArgs = (
token_t::safeOperatorType(tokenContext[0]) & operatorType::parenthesesStart
);
if (hasArgs) {
tokenContext.pushPairRange();
getArgumentRanges(tokenContext, argRanges);
}
if (!success) {
if (hasArgs) {
tokenContext.popAndSkip();
}
return;
}
attributeToken_t attr(*attribute, nameToken);
setAttributeArgs(attr, argRanges);
if (hasArgs) {
tokenContext.popAndSkip();
}
if (success) {
attrs[nameToken.value] = attr;
success = attribute->isValid(attr);
}
}
void attributeLoader_t::setAttributeArgs(attributeToken_t &attr,
tokenRangeVector &argRanges) {
const int args = (int) argRanges.size();
bool foundNamedArg = false;
for (int i = 0; i < args; ++i) {
attributeArg_t arg;
tokenContext.push(argRanges[i].start,
argRanges[i].end);
if (!tokenContext.size()) {
arg.expr = new emptyNode();
attr.args.push_back(arg);
tokenContext.popAndSkip();
continue;
}
// Load args
loadAttributes(arg.attributes);
if (!tokenContext.size()) {
arg.expr = new emptyNode();
attr.args.push_back(arg);
tokenContext.popAndSkip();
continue;
}
// Get argument
arg.expr = tokenContext.parseExpression(smntContext,
parser);
if (!success) {
tokenContext.pop();
arg.clear();
return;
}
std::string argName;
// Check for
// |---[=] (binary)
// | |
// | |---[argName] (identifier)
// | |
// | |---[arg] (?)
if (arg.expr->type() & exprNodeType::binary) {
binaryOpNode &equalsNode = arg.expr->to<binaryOpNode>();
if ((equalsNode.opType() & operatorType::assign) &&
(equalsNode.leftValue->type() & exprNodeType::identifier)) {
argName = equalsNode.leftValue->to<identifierNode>().value;
arg.expr = equalsNode.rightValue->clone();
delete &equalsNode;
}
}
if (!argName.size() &&
foundNamedArg) {
tokenContext.printError("All arguments after a named argument"
" must also be named");
success = false;
tokenContext.pop();
arg.clear();
return;
}
if (!argName.size()) {
attr.args.push_back(arg);
} else {
attr.kwargs[argName] = arg;
}
tokenContext.popAndSkip();
}
}
bool loadAttributes(tokenContext_t &tokenContext,
statementContext_t &smntContext,
parser_t &parser,
nameToAttributeMap &attributeMap,
attributeTokenMap &attrs) {
attributeLoader_t loader(tokenContext, smntContext, parser, attributeMap);
return loader.loadAttributes(attrs);
}
attribute_t* getAttribute(nameToAttributeMap &attributeMap,
const std::string &name) {
nameToAttributeMap::iterator it = attributeMap.find(name);
if (it == attributeMap.end()) {
return NULL;
}
return it->second;
}
}
}
|
section reset_vector
dw 0 ; 0
dw 0 ; 1
dw 0 ; 2
dw 0 ; 3
dw 0 ; 4
dw 0 ; 5
dw 0 ; 6
dw 0 ; 7
dw 0 ; 8
dw 0 ; 9
dw 0 ; 10
dw 0 ; 11
dw 0 ; 12
dw 0 ; 13
dw 0 ; 14
dw reset_handler ; 15 = reset
section code
reset_handler:
mov.w #0x980, sp ; setup stack pointer
call #main_main ; Enter main
call #bsp_exit ; Call exit cleaning
end_inf_loop:
jmp end_inf_loop
bsp_putc:
mov.b r12, 0x67(r2) ; write to uart0 tx buf
ret
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 96
call lwaitly_b
ld a, 80
ldff(68), a
ld a, ff
ld c, 69
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
xor a, a
ldff(c), a
ldff(c), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, b
inc a
inc a
ldff(45), a
ld c, 0f
.text@1000
lstatint:
xor a, a
ldff(45), a
.text@10c0
xor a, a
ldff(c), a
.text@10d8
ld a, ff
ldff(45), a
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ldff a, (c)
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
srl a
srl a
srl a
srl a
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
; SPIR-V
; Version: 1.0
; Generator: Khronos Glslang Reference Front End; 10
; Bound: 306
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %287
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 320
OpName %4 "main"
OpName %8 "_GLF_global_loop_count"
OpName %12 "f"
OpName %16 "buf0"
OpMemberName %16 0 "_GLF_uniform_float_values"
OpName %18 ""
OpName %24 "i"
OpName %27 "buf1"
OpMemberName %27 0 "_GLF_uniform_int_values"
OpName %29 ""
OpName %43 "i"
OpName %55 "i"
OpName %67 "i"
OpName %79 "i"
OpName %91 "i"
OpName %103 "i"
OpName %115 "i"
OpName %127 "i"
OpName %139 "i"
OpName %151 "i"
OpName %163 "i"
OpName %176 "i"
OpName %188 "i"
OpName %200 "i"
OpName %259 "sum"
OpName %262 "r"
OpName %287 "_GLF_color"
OpDecorate %15 ArrayStride 16
OpMemberDecorate %16 0 Offset 0
OpDecorate %16 Block
OpDecorate %18 DescriptorSet 0
OpDecorate %18 Binding 0
OpDecorate %26 ArrayStride 16
OpMemberDecorate %27 0 Offset 0
OpDecorate %27 Block
OpDecorate %29 DescriptorSet 0
OpDecorate %29 Binding 1
OpDecorate %287 Location 0
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeInt 32 1
%7 = OpTypePointer Private %6
%8 = OpVariable %7 Private
%9 = OpConstant %6 0
%10 = OpTypeFloat 32
%11 = OpTypePointer Function %10
%13 = OpTypeInt 32 0
%14 = OpConstant %13 3
%15 = OpTypeArray %10 %14
%16 = OpTypeStruct %15
%17 = OpTypePointer Uniform %16
%18 = OpVariable %17 Uniform
%19 = OpConstant %6 1
%20 = OpTypePointer Uniform %10
%23 = OpTypePointer Function %6
%25 = OpConstant %13 4
%26 = OpTypeArray %6 %25
%27 = OpTypeStruct %26
%28 = OpTypePointer Uniform %27
%29 = OpVariable %28 Uniform
%30 = OpTypePointer Uniform %6
%41 = OpTypeBool
%172 = OpConstant %6 2
%219 = OpConstant %6 100
%220 = OpConstant %6 3
%285 = OpTypeVector %10 4
%286 = OpTypePointer Output %285
%287 = OpVariable %286 Output
%4 = OpFunction %2 None %3
%5 = OpLabel
%12 = OpVariable %11 Function
%24 = OpVariable %23 Function
%43 = OpVariable %23 Function
%55 = OpVariable %23 Function
%67 = OpVariable %23 Function
%79 = OpVariable %23 Function
%91 = OpVariable %23 Function
%103 = OpVariable %23 Function
%115 = OpVariable %23 Function
%127 = OpVariable %23 Function
%139 = OpVariable %23 Function
%151 = OpVariable %23 Function
%163 = OpVariable %23 Function
%176 = OpVariable %23 Function
%188 = OpVariable %23 Function
%200 = OpVariable %23 Function
%259 = OpVariable %11 Function
%262 = OpVariable %23 Function
OpStore %8 %9
%21 = OpAccessChain %20 %18 %9 %19
%22 = OpLoad %10 %21
OpStore %12 %22
%31 = OpAccessChain %30 %29 %9 %19
%32 = OpLoad %6 %31
OpStore %24 %32
OpBranch %33
%33 = OpLabel
OpLoopMerge %35 %36 None
OpBranch %37
%37 = OpLabel
%38 = OpLoad %6 %24
%39 = OpAccessChain %30 %29 %9 %9
%40 = OpLoad %6 %39
%42 = OpSLessThan %41 %38 %40
OpBranchConditional %42 %34 %35
%34 = OpLabel
%44 = OpAccessChain %30 %29 %9 %19
%45 = OpLoad %6 %44
OpStore %43 %45
OpBranch %46
%46 = OpLabel
OpLoopMerge %48 %49 None
OpBranch %50
%50 = OpLabel
%51 = OpLoad %6 %43
%52 = OpAccessChain %30 %29 %9 %9
%53 = OpLoad %6 %52
%54 = OpSLessThan %41 %51 %53
OpBranchConditional %54 %47 %48
%47 = OpLabel
%56 = OpAccessChain %30 %29 %9 %19
%57 = OpLoad %6 %56
OpStore %55 %57
OpBranch %58
%58 = OpLabel
OpLoopMerge %60 %61 None
OpBranch %62
%62 = OpLabel
%63 = OpLoad %6 %55
%64 = OpAccessChain %30 %29 %9 %9
%65 = OpLoad %6 %64
%66 = OpSLessThan %41 %63 %65
OpBranchConditional %66 %59 %60
%59 = OpLabel
%68 = OpAccessChain %30 %29 %9 %19
%69 = OpLoad %6 %68
OpStore %67 %69
OpBranch %70
%70 = OpLabel
OpLoopMerge %72 %73 None
OpBranch %74
%74 = OpLabel
%75 = OpLoad %6 %67
%76 = OpAccessChain %30 %29 %9 %9
%77 = OpLoad %6 %76
%78 = OpSLessThan %41 %75 %77
OpBranchConditional %78 %71 %72
%71 = OpLabel
%80 = OpAccessChain %30 %29 %9 %19
%81 = OpLoad %6 %80
OpStore %79 %81
OpBranch %82
%82 = OpLabel
OpLoopMerge %84 %85 None
OpBranch %86
%86 = OpLabel
%87 = OpLoad %6 %79
%88 = OpAccessChain %30 %29 %9 %9
%89 = OpLoad %6 %88
%90 = OpSLessThan %41 %87 %89
OpBranchConditional %90 %83 %84
%83 = OpLabel
%92 = OpAccessChain %30 %29 %9 %19
%93 = OpLoad %6 %92
OpStore %91 %93
OpBranch %94
%94 = OpLabel
OpLoopMerge %96 %97 None
OpBranch %98
%98 = OpLabel
%99 = OpLoad %6 %91
%100 = OpAccessChain %30 %29 %9 %9
%101 = OpLoad %6 %100
%102 = OpSLessThan %41 %99 %101
OpBranchConditional %102 %95 %96
%95 = OpLabel
%104 = OpAccessChain %30 %29 %9 %19
%105 = OpLoad %6 %104
OpStore %103 %105
OpBranch %106
%106 = OpLabel
OpLoopMerge %108 %109 None
OpBranch %110
%110 = OpLabel
%111 = OpLoad %6 %103
%112 = OpAccessChain %30 %29 %9 %9
%113 = OpLoad %6 %112
%114 = OpSLessThan %41 %111 %113
OpBranchConditional %114 %107 %108
%107 = OpLabel
%116 = OpAccessChain %30 %29 %9 %19
%117 = OpLoad %6 %116
OpStore %115 %117
OpBranch %118
%118 = OpLabel
OpLoopMerge %120 %121 None
OpBranch %122
%122 = OpLabel
%123 = OpLoad %6 %115
%124 = OpAccessChain %30 %29 %9 %9
%125 = OpLoad %6 %124
%126 = OpSLessThan %41 %123 %125
OpBranchConditional %126 %119 %120
%119 = OpLabel
%128 = OpAccessChain %30 %29 %9 %19
%129 = OpLoad %6 %128
OpStore %127 %129
OpBranch %130
%130 = OpLabel
OpLoopMerge %132 %133 None
OpBranch %134
%134 = OpLabel
%135 = OpLoad %6 %127
%136 = OpAccessChain %30 %29 %9 %9
%137 = OpLoad %6 %136
%138 = OpSLessThan %41 %135 %137
OpBranchConditional %138 %131 %132
%131 = OpLabel
%140 = OpAccessChain %30 %29 %9 %19
%141 = OpLoad %6 %140
OpStore %139 %141
OpBranch %142
%142 = OpLabel
OpLoopMerge %144 %145 None
OpBranch %146
%146 = OpLabel
%147 = OpLoad %6 %139
%148 = OpAccessChain %30 %29 %9 %9
%149 = OpLoad %6 %148
%150 = OpSLessThan %41 %147 %149
OpBranchConditional %150 %143 %144
%143 = OpLabel
%152 = OpAccessChain %30 %29 %9 %19
%153 = OpLoad %6 %152
OpStore %151 %153
OpBranch %154
%154 = OpLabel
OpLoopMerge %156 %157 None
OpBranch %158
%158 = OpLabel
%159 = OpLoad %6 %151
%160 = OpAccessChain %30 %29 %9 %9
%161 = OpLoad %6 %160
%162 = OpSLessThan %41 %159 %161
OpBranchConditional %162 %155 %156
%155 = OpLabel
%164 = OpAccessChain %30 %29 %9 %19
%165 = OpLoad %6 %164
OpStore %163 %165
OpBranch %166
%166 = OpLabel
OpLoopMerge %168 %169 None
OpBranch %170
%170 = OpLabel
%171 = OpLoad %6 %163
%173 = OpAccessChain %30 %29 %9 %172
%174 = OpLoad %6 %173
%175 = OpSLessThan %41 %171 %174
OpBranchConditional %175 %167 %168
%167 = OpLabel
%177 = OpAccessChain %30 %29 %9 %19
%178 = OpLoad %6 %177
OpStore %176 %178
OpBranch %179
%179 = OpLabel
OpLoopMerge %181 %182 None
OpBranch %183
%183 = OpLabel
%184 = OpLoad %6 %176
%185 = OpAccessChain %30 %29 %9 %9
%186 = OpLoad %6 %185
%187 = OpSLessThan %41 %184 %186
OpBranchConditional %187 %180 %181
%180 = OpLabel
%189 = OpAccessChain %30 %29 %9 %19
%190 = OpLoad %6 %189
OpStore %188 %190
OpBranch %191
%191 = OpLabel
OpLoopMerge %193 %194 None
OpBranch %195
%195 = OpLabel
%196 = OpLoad %6 %188
%197 = OpAccessChain %30 %29 %9 %9
%198 = OpLoad %6 %197
%199 = OpSLessThan %41 %196 %198
OpBranchConditional %199 %192 %193
%192 = OpLabel
%201 = OpAccessChain %30 %29 %9 %19
%202 = OpLoad %6 %201
OpStore %200 %202
OpBranch %203
%203 = OpLabel
OpLoopMerge %205 %206 None
OpBranch %207
%207 = OpLabel
%208 = OpLoad %6 %200
%209 = OpAccessChain %30 %29 %9 %172
%210 = OpLoad %6 %209
%211 = OpSLessThan %41 %208 %210
OpBranchConditional %211 %204 %205
%204 = OpLabel
OpBranch %212
%212 = OpLabel
OpLoopMerge %214 %215 None
OpBranch %213
%213 = OpLabel
%216 = OpLoad %6 %8
%217 = OpIAdd %6 %216 %19
OpStore %8 %217
OpBranch %215
%215 = OpLabel
%218 = OpLoad %6 %8
%221 = OpAccessChain %30 %29 %9 %220
%222 = OpLoad %6 %221
%223 = OpISub %6 %219 %222
%224 = OpSLessThan %41 %218 %223
OpBranchConditional %224 %212 %214
%214 = OpLabel
%225 = OpAccessChain %20 %18 %9 %9
%226 = OpLoad %10 %225
%227 = OpLoad %10 %12
%228 = OpFAdd %10 %227 %226
OpStore %12 %228
OpBranch %206
%206 = OpLabel
%229 = OpLoad %6 %200
%230 = OpIAdd %6 %229 %19
OpStore %200 %230
OpBranch %203
%205 = OpLabel
OpBranch %194
%194 = OpLabel
%231 = OpLoad %6 %188
%232 = OpIAdd %6 %231 %19
OpStore %188 %232
OpBranch %191
%193 = OpLabel
OpBranch %182
%182 = OpLabel
%233 = OpLoad %6 %176
%234 = OpIAdd %6 %233 %19
OpStore %176 %234
OpBranch %179
%181 = OpLabel
OpBranch %169
%169 = OpLabel
%235 = OpLoad %6 %163
%236 = OpIAdd %6 %235 %19
OpStore %163 %236
OpBranch %166
%168 = OpLabel
OpBranch %157
%157 = OpLabel
%237 = OpLoad %6 %151
%238 = OpIAdd %6 %237 %19
OpStore %151 %238
OpBranch %154
%156 = OpLabel
OpBranch %145
%145 = OpLabel
%239 = OpLoad %6 %139
%240 = OpIAdd %6 %239 %19
OpStore %139 %240
OpBranch %142
%144 = OpLabel
OpBranch %133
%133 = OpLabel
%241 = OpLoad %6 %127
%242 = OpIAdd %6 %241 %19
OpStore %127 %242
OpBranch %130
%132 = OpLabel
OpBranch %121
%121 = OpLabel
%243 = OpLoad %6 %115
%244 = OpIAdd %6 %243 %19
OpStore %115 %244
OpBranch %118
%120 = OpLabel
OpBranch %109
%109 = OpLabel
%245 = OpLoad %6 %103
%246 = OpIAdd %6 %245 %19
OpStore %103 %246
OpBranch %106
%108 = OpLabel
OpBranch %97
%97 = OpLabel
%247 = OpLoad %6 %91
%248 = OpIAdd %6 %247 %19
OpStore %91 %248
OpBranch %94
%96 = OpLabel
OpBranch %85
%85 = OpLabel
%249 = OpLoad %6 %79
%250 = OpIAdd %6 %249 %19
OpStore %79 %250
OpBranch %82
%84 = OpLabel
OpBranch %73
%73 = OpLabel
%251 = OpLoad %6 %67
%252 = OpIAdd %6 %251 %19
OpStore %67 %252
OpBranch %70
%72 = OpLabel
OpBranch %61
%61 = OpLabel
%253 = OpLoad %6 %55
%254 = OpIAdd %6 %253 %19
OpStore %55 %254
OpBranch %58
%60 = OpLabel
OpBranch %49
%49 = OpLabel
%255 = OpLoad %6 %43
%256 = OpIAdd %6 %255 %19
OpStore %43 %256
OpBranch %46
%48 = OpLabel
OpBranch %36
%36 = OpLabel
%257 = OpLoad %6 %24
%258 = OpIAdd %6 %257 %19
OpStore %24 %258
OpBranch %33
%35 = OpLabel
%260 = OpAccessChain %20 %18 %9 %19
%261 = OpLoad %10 %260
OpStore %259 %261
%263 = OpAccessChain %30 %29 %9 %19
%264 = OpLoad %6 %263
OpStore %262 %264
OpBranch %265
%265 = OpLabel
OpLoopMerge %267 %268 None
OpBranch %269
%269 = OpLabel
%270 = OpLoad %6 %8
%271 = OpSLessThan %41 %270 %219
OpBranchConditional %271 %266 %267
%266 = OpLabel
%272 = OpLoad %6 %8
%273 = OpIAdd %6 %272 %19
OpStore %8 %273
%274 = OpLoad %10 %12
%275 = OpLoad %10 %259
%276 = OpFAdd %10 %275 %274
OpStore %259 %276
OpBranch %268
%268 = OpLabel
%277 = OpLoad %6 %262
%278 = OpIAdd %6 %277 %19
OpStore %262 %278
OpBranch %265
%267 = OpLabel
%279 = OpLoad %10 %259
%280 = OpAccessChain %20 %18 %9 %172
%281 = OpLoad %10 %280
%282 = OpFOrdEqual %41 %279 %281
OpSelectionMerge %284 None
OpBranchConditional %282 %283 %301
%283 = OpLabel
%288 = OpAccessChain %30 %29 %9 %9
%289 = OpLoad %6 %288
%290 = OpConvertSToF %10 %289
%291 = OpAccessChain %30 %29 %9 %19
%292 = OpLoad %6 %291
%293 = OpConvertSToF %10 %292
%294 = OpAccessChain %30 %29 %9 %19
%295 = OpLoad %6 %294
%296 = OpConvertSToF %10 %295
%297 = OpAccessChain %30 %29 %9 %9
%298 = OpLoad %6 %297
%299 = OpConvertSToF %10 %298
%300 = OpCompositeConstruct %285 %290 %293 %296 %299
OpStore %287 %300
OpBranch %284
%301 = OpLabel
%302 = OpAccessChain %30 %29 %9 %19
%303 = OpLoad %6 %302
%304 = OpConvertSToF %10 %303
%305 = OpCompositeConstruct %285 %304 %304 %304 %304
OpStore %287 %305
OpBranch %284
%284 = OpLabel
OpReturn
OpFunctionEnd
|
; =============================================================================
; Ultima Underworld Hacks -- main
; -----------------------------------------------------------------------------
; by John Glassmyer
; github.com/JohnGlassmyer/UltimaHacks
; assuming that overlay 117 was expanded and moved to the end of the executable:
; java -jar UltimaPatcher.jar --exe=UW.EXE --expand-overlay=117:0x2200 (...)
; =============================================================================
; length of executable to be patched, and of expanded overlay
; -----------------------------------------------------------------------------
; assuming that the expanded overlay has been moved to the end of the file
%assign ORIGINAL_EXE_LENGTH 0x859B0
%assign EXPANDED_OVERLAY_LENGTH 0x2200
%assign ORIGINAL_EOP_LENGTH 0x108F
%assign EXE_LENGTH (ORIGINAL_EXE_LENGTH + EXPANDED_OVERLAY_LENGTH)
; =============================================================================
; data-segment offsets
; -----------------------------------------------------------------------------
; steal bytes from Borland's Turbo C++ copyright string
; (initialized in initializeRepurposedDsegBytes.asm)
dseg_isMouseLookEnabled EQU 0x0008
dseg_wasMouseLookEnabledIn3dView EQU 0x0009
dseg_cursorXDuringMouseLook EQU 0x000A
dseg_cursorYDuringMouseLook EQU 0x000C
dseg_isDrawingBehindPlayer EQU 0x000E
dseg_wasLastBindingKey EQU 0x000F
dseg_pn_lastKeyOrMouseBinding EQU 0x0010
dseg_lastKeyBindingTime EQU 0x0012
dseg_newlineString EQU 0x0016
dseg_trigScale EQU 0x0018
dseg_radianAngle EQU 0x001C
dseg_autoAttackType EQU 0x0020
dseg_haveWarnedAboutDrawQueueLimit EQU 0x0021
dseg_mouseLookOrientation EQU 0x0022
dseg_avatarMovementFlags EQU 0x00D2
dseg_pn_inputState EQU 0x00E2
dseg_cursorX EQU 0x010E
dseg_cursorY EQU 0x0110
dseg_isCursorVisible EQU 0x0114
dseg_currentCursorAreaMinX EQU 0x0120
dseg_lastKeyTime EQU 0x012E
dseg_currentAttackScancode EQU 0x0244
dseg_isGettingFromLook EQU 0x0288
dseg_movementType EQU 0x075A
dseg_rotationSpeedBase EQU 0x075C
dseg_forwardThrottle EQU 0x0763
dseg_rotationThrottle EQU 0x0765
dseg_movementScancodesArray EQU 0x076B
dseg_activePanelNumber EQU 0x0784
dseg_ps_shiftStates EQU 0x2334
dseg_ps_keyStates EQU 0x2344
dseg_ps_time EQU 0x2364
dseg_ps_perspective EQU 0x2378
dseg_cursorMinX EQU 0x2524
dseg_cursorMinY EQU 0x2526
dseg_cursorMaxX EQU 0x257E
dseg_cursorMaxY EQU 0x2580
dseg_currentCursorAreaMinY EQU 0x258C
dseg_currentCursorAreaMaxX EQU 0x25BC
dseg_currentCursorAreaMaxY EQU 0x25BE
dseg_findItemThing EQU 0x2682
dseg_ps_itemAtCursor EQU 0x269E
dseg_cursorMode EQU 0x26AC
dseg_gridViewFlags EQU 0x2890
dseg_leftViewLimit EQU 0x2D00
dseg_rightViewLimit EQU 0x2D11
dseg_drawQueuing_currentColumn EQU 0x2E0C
dseg_drawQueuing_currentRow EQU 0x2E0E
dseg_pitch EQU 0x3588
dseg_mapDungeonLevel EQU 0x381E
dseg_mappedTerrain EQU 0x3820
dseg_interfaceMode EQU 0x565E
dseg_interfaceRoutinesSelector EQU 0x5664
dseg_ps_cursorItem EQU 0x5B06
dseg_pn_avatarData EQU 0x7270
dseg_ps_avatarItem EQU 0x7274
dseg_avatarDungeonLevel EQU 0x7278
dseg_heading EQU 0x727A
dseg_3dViewHeight EQU 0x7280
dseg_3dViewLeftX EQU 0x7282
dseg_3dViewBottomY EQU 0x735E
dseg_3dViewWidth EQU 0x7364
dseg_ps_drawQueueEnd EQU 0x7452
; =============================================================================
; procedure far-call addresses
; -----------------------------------------------------------------------------
defineSegment 4, 0x0020, 0x06E7
defineSegment 5, 0x0028, 0x0EC5
defineAddress 5, 0x1DFF, signedWordToString
defineAddress 5, 0x1E26, unsignedDwordToString
defineAddress 5, 0x290A, strcat
defineSegment 9, 0x0048, 0x193D
defineSegment 11, 0x0058, 0x1A6F
defineAddress 11, 0x0083, bindMouse
defineAddress 11, 0x0105, bindKey
defineAddress 11, 0x02B1, tryKeyAndMouseBindings
defineSegment 12, 0x0060, 0x1AB6
defineAddress 12, 0x00AF, setInterfaceRoutineBit
defineSegment 14, 0x0070, 0x1ADC
defineAddress 14, 0x0075, eraseCursorIfVisible
defineAddress 14, 0x0802, setCursorImage
defineAddress 14, 0x0868, updateCursorRegion
defineAddress 14, 0x0BE8, savePixelsAroundCursor
defineAddress 14, 0x0CF2, drawCursor
defineAddress 14, 0x0E29, moveCursor
defineSegment 15, 0x0078, 0x1BD8
defineAddress 15, 0x0B1B, playSoundEffect
defineSegment 19, 0x0098, 0x1DF0
defineAddress 19, 0x0001, enqueueGridCoords
defineAddress 19, 0x00C5, enqueueDrawWithinLimits
defineAddress 19, 0x0DBC, enqueueDrawBlock
defineSegment 21, 0x00A8, 0x1F3A
defineAddress 21, 0x0EAE, sinAndCosInterpolated
defineSegment 25, 0x00C8, 0x2121
defineAddress 25, 0x11BA, attack
defineSegment 27, 0x00D8, 0x22EF
defineAddress 27, 0x000F, flipCharPanel
defineAddress 27, 0x0032, clickCompass
defineAddress 27, 0x010F, clickFlasks
defineAddress 27, 0x08CA, findItemAtCursor
defineAddress 27, 0x09D0, describeClickedTerrain
defineAddress 27, 0x0CEC, talkModeProc
defineAddress 27, 0x0D20, lookModeProc
defineAddress 27, 0x0E3F, useModeProc
defineAddress 27, 0x13D5, activateMode
defineSegment 30, 0x00F0, 0x2674
defineAddress 30, 0x0A52, isItemCharacter
defineSegment 34, 0x0110, 0x2ABA
defineAddress 34, 0x0246, clearDrawQueue
defineAddress 34, 0x0396, setupPerspective
defineAddress 34, 0x05B4, setupViewLimits
defineAddress 34, 0x115E, applyViewLimits
defineSegment 36, 0x0120, 0x2D02
defineAddress 36, 0x043B, enqueueDrawItems
defineSegment 37, 0x0128, 0x2D9C
defineAddress 37, 0x004E, move
defineAddress 37, 0x0334, easyMove
defineSegment 39, 0x0138, 0x2E9A
defineAddress 39, 0x03DF, setPanelState
defineAddress 39, 0x11B3, animateSlidingPanel
defineAddress 39, 0x1AD5, slidePanel
defineSegment 42, 0x0150, 0x32A8
defineAddress 42, 0x008D, getExternalizedString
defineAddress 42, 0x090E, strcat_far
defineSegment 46, 0x0170, 0x3603
defineAddress 46, 0x02EA, printStringToScroll
defineSegment 72, 0x0240, 0x5624
defineSegment 92, 0x02E0, 0x595C
defineAddress 92, 0x007A, changeMapLevel
defineSegment 95, 0x02F8, 0x597E
defineAddress 95, 0x0070, clickOtherTrade
defineAddress 95, 0x0084, clickAvatarTrade
defineSegment 100, 0x0320, 0x599C
defineAddress 100, 0x003E, ark_say
defineAddress 100, 0x0075, selectConversationOption
defineSegment 109, 0x0368, 0x59D3
defineAddress 109, 0x0048, transitionToInterfaceMode
defineSegment 117, 0x03A8, 0x59FE, eop
defineAddress 117, 0x0020, scrollInventoryDown
defineAddress 117, 0x002F, closeInventoryContainer
defineAddress 117, 0x0043, scrollInventoryUp
defineAddress 117, 0x005C+1*5, varArgsEopDispatcher
defineAddress 117, 0x005C+2*5, byteArgEopDispatcher
defineAddress 117, 0x005C+3*5, byCallSiteEopDispatcher
defineSegment 119, 0x03B8, 0x5A0B
defineAddress 119, 0x0020, tryToCast
defineAddress 119, 0x0034, clickRunePanel
defineSegment 130, 0x0410, 0x5A3D
defineAddress 130, 0x007F, handleControlKey
defineSegment 134, 0x0430, 0x5A53
defineAddress 134, 0x0052, adjustPitch
defineAddress 134, 0x0061, printVersion
defineAddress 134, 0x0066, printDebug
defineSegment 138, 0x0450, 0x5A61
defineSegment 143, 0x0478, 0x5A76
defineAddress 143, 0x008E, sleep
defineAddress 143, 0x0093, track
defineAddress 143, 0x0070, trainSkill
defineSegment 155, 0x04D8, 0x5AAC, dseg
; =============================================================================
; structure offsets
; -----------------------------------------------------------------------------
InputState_relativeX EQU 0x00
InputState_relativeY EQU 0x02
InputState_mouseButton EQU 0x06
InputState_mode EQU 0x08
Perspective_x EQU 0x0A
Perspective_y EQU 0x12
Perspective_heading EQU 0x2C
ViewLimit_headingSin EQU 0x01
ViewLimit_headingCos EQU 0x03
ViewLimit_currentBlockX EQU 0x05
ViewLimit_intraBlockX EQU 0x06
ViewLimit_currentBlockY EQU 0x07
ViewLimit_intraBlockY EQU 0x08
ViewLimit_terrainGrid_ps EQU 0x09
ShiftStates_shift EQU 0
ShiftStates_alt EQU 1
ShiftStates_ctrl EQU 2
; =============================================================================
; enumerations
; -----------------------------------------------------------------------------
%assign MapControl_LEVEL_UP 0
%assign MapControl_LEVEL_DOWN 1
%assign MapControl_AVATAR_LEVEL 4
%assign ReducedHeading_NORTH 0
%assign ReducedHeading_EAST 1
%assign ReducedHeading_SOUTH 2
%assign ReducedHeading_WEST 3
%assign SoundNumber_ERROR 45
%assign StringColor_DEFAULT 0 ; brown
%assign StringColor_AVATAR_SPEECH 1 ; gold
%assign StringColor_NARRATION 2 ; black
%assign StringColor_WHITE 3
%assign StringColor_ERROR 4 ; red
%assign StringColor_BLUE 5
%assign StringColor_MENU 6 ; dark green
%assign InterfaceMode_NORMAL 1
%assign InterfaceMode_MAP 2
%assign InterfaceMode_CONVERSATION 4
; =============================================================================
; other values
; -----------------------------------------------------------------------------
; how far up or down the player is allowed to look
; (original value is 4 * 1024; too-large values allow the view to wrap around)
%assign pitchBound 12 * 1024
; key modifier bits
%assign S 0x080 ; Shift modifier bit
%assign C 0x100 ; Ctrl modifier bit
%assign A 0x200 ; Alt modifier bit
%assign H 0x400 ; High-bit scancode modifier bit
%assign MOUSE_LOOK_INVERT_Y 1
%assign MOUSE_LOOK_INVERT_X 2
|
; A010381: Squares mod 19.
; Submitted by Christian Krause
; 0,1,4,5,6,7,9,11,16,17
lpb $0
mov $2,$0
sub $0,1
seq $2,56113 ; Most significant digit of n-th primorial A002110.
add $1,$2
lpe
div $1,2
mov $0,$1
|
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2009 Soeren Sonnenburg
* Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "ShogunException.h"
#include "Signal.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace shogun;
ShogunException::ShogunException(const char* str)
{
#ifndef WIN32
CSignal::unset_handler();
#endif
val = (char*) malloc(sizeof(char)*4096);
if (val)
strncpy(val,str,4096);
else
{
fprintf(stderr, "Could not even allocate memory for exception - dying.\n");
exit(1);
}
}
ShogunException::~ShogunException()
{
}
|
; sort list of pointers
include win1_mac_oli
section utility
xdef ut_sortlst
;+++
; sort list of string pointers
;
; Entry Exit
; d1.l 0 or nr. of elements
; a1 ptr to list
;
; errors: imem
; cc set
;+++
ut_sortlst subr a0-a3/d1-d3
tst.l d1
bne.s nr_known
xjsr ut_cntlst ; count nr of elements
nr_known
move.l a1,a0 ; a0 final index
xjsr ut_allst ; allocate space for temp index
bne.s exit
xjsr ut_cpylst ; copy to temp list
move.l a0,a2 ; a2 final running pointer
move.l a1,a3 ; a3 unsorted list adr
bra.s start
again bsr.s rival ; get valid rival ptr
beq.s eol ; no more rivals.. smallest found
bsr.s compare ; compare rival to smallest
bpl.s nochg ; rival is bigger.. no change
move.l a0,a1 ; rival becomes smallest
nochg addq.w #4,a0 ; next rival in list
bra.s again ; ..try again
eol move.l (a1),d0 ; ptr to smallest string
move.l d0,(a2)+ ; put smallest in final list
move.l #1,(a1) ; blank it out of unsorted list
start move.l a3,a0 ; first is new rival
bsr.s rival ; get a real rival ptr
beq.s nomore ; no more rivals found?
move.l a0,a1 ; first is new smallest
bra.s again ; for all elements
nomore clr.l (a2) ; end of final list
move.l a3,a0
xjsr ut_rechp
exit subend
; mi = eol
; eq = smaller
; ne = no change
compare subr a0/a1/d1
move.l (a0),a0 ; rival string
move.l (a1),a1 ; smallest string
moveq #1,d0 ; basic comparison
xjsr st_cmpst ; compare strings
subend
deleted addq.l #4,a0 ; try next entry
rival move.l (a0),d0 ; rival entry
beq.s str_eol ; end of list reached
cmp.l #1,d0 ; rival deleted?
beq.s deleted
str_eol rts
end
|
/*
* FreeRTOS Kernel V10.3.1
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
#include "FreeRTOSConfig.h"
#include "portasm.h"
/* These wrappers are only used when interrupt method 2 is being used. See
FreeRTOSConfig.h for an explanation. */
#if configINTERRUPT_EXAMPLE_METHOD == 2
.CODE
/* Wrapper for the Rx UART interrupt. */
_vUARTRx_Wrapper
portSAVE_CONTEXT
call #_vRxISR
portRESTORE_CONTEXT
/*-----------------------------------------------------------*/
/* Wrapper for the Tx UART interrupt. */
_vUARTTx_Wrapper
portSAVE_CONTEXT
call #_vTxISR
portRESTORE_CONTEXT
/*-----------------------------------------------------------*/
/* Place the UART ISRs in the correct vectors. */
.VECTORS
.KEEP
ORG UART1RX_VECTOR
DW _vUARTRx_Wrapper
ORG UART1TX_VECTOR
DW _vUARTTx_Wrapper
#endif /* configINTERRUPT_EXAMPLE_METHOD */
END
|
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_VIEWS_IDENTITY_VIEW_HPP
#define BOOST_GEOMETRY_VIEWS_IDENTITY_VIEW_HPP
#include <boost/range.hpp>
namespace boost { namespace geometry
{
// Silence warning C4512: assignment operator could not be generated
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4512)
#endif
/*!
\brief View on a range, not modifying anything
\tparam Range original range
\ingroup views
*/
template <typename Range>
struct identity_view
{
typedef typename boost::range_iterator<Range const>::type const_iterator;
typedef typename boost::range_iterator<Range>::type iterator;
explicit inline identity_view(Range& r)
: m_range(r)
{}
inline const_iterator begin() const { return boost::begin(m_range); }
inline const_iterator end() const { return boost::end(m_range); }
inline iterator begin() { return boost::begin(m_range); }
inline iterator end() { return boost::end(m_range); }
private :
Range& m_range;
};
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_VIEWS_IDENTITY_VIEW_HPP
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r8
push %rax
push %rcx
push %rdx
push %rsi
lea addresses_normal_ht+0xef6, %rdx
nop
nop
nop
nop
sub %r8, %r8
mov (%rdx), %rsi
nop
sub %rax, %rax
lea addresses_D_ht+0x1c5fc, %r10
nop
cmp $53059, %rcx
mov $0x6162636465666768, %r11
movq %r11, %xmm6
vmovups %ymm6, (%r10)
nop
nop
nop
nop
and %rcx, %rcx
lea addresses_normal_ht+0xc977, %r11
nop
nop
nop
nop
cmp $28547, %rcx
mov $0x6162636465666768, %rax
movq %rax, %xmm1
and $0xffffffffffffffc0, %r11
vmovaps %ymm1, (%r11)
and $57685, %rax
pop %rsi
pop %rdx
pop %rcx
pop %rax
pop %r8
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r8
push %rax
push %rbp
push %rbx
// Faulty Load
lea addresses_A+0xd226, %rbx
dec %r8
mov (%rbx), %rax
lea oracles, %rbx
and $0xff, %rax
shlq $12, %rax
mov (%rbx,%rax,1), %rax
pop %rbx
pop %rbp
pop %rax
pop %r8
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_A', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_normal_ht', 'same': True, 'AVXalign': True, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': True, 'congruent': 0}}
{'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
*/
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/sigtools.h"
#include "kernel/log.h"
#include "libs/subcircuit/subcircuit.h"
#include <algorithm>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
using RTLIL::id2cstr;
class SubCircuitSolver : public SubCircuit::Solver
{
public:
bool ignore_parameters;
std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> ignored_parameters;
std::set<RTLIL::IdString> cell_attr, wire_attr;
SubCircuitSolver() : ignore_parameters(false)
{
}
bool compareAttributes(const std::set<RTLIL::IdString> &attr, const dict<RTLIL::IdString, RTLIL::Const> &needleAttr, const dict<RTLIL::IdString, RTLIL::Const> &haystackAttr)
{
for (auto &it : attr) {
size_t nc = needleAttr.count(it), hc = haystackAttr.count(it);
if (nc != hc || (nc > 0 && needleAttr.at(it) != haystackAttr.at(it)))
return false;
}
return true;
}
RTLIL::Const unified_param(RTLIL::IdString cell_type, RTLIL::IdString param, RTLIL::Const value)
{
if (cell_type.substr(0, 1) != "$" || cell_type.substr(0, 2) == "$_")
return value;
#define param_bool(_n) if (param == _n) return value.as_bool();
param_bool("\\ARST_POLARITY");
param_bool("\\A_SIGNED");
param_bool("\\B_SIGNED");
param_bool("\\CLK_ENABLE");
param_bool("\\CLK_POLARITY");
param_bool("\\CLR_POLARITY");
param_bool("\\EN_POLARITY");
param_bool("\\SET_POLARITY");
param_bool("\\TRANSPARENT");
#undef param_bool
#define param_int(_n) if (param == _n) return value.as_int();
param_int("\\ABITS")
param_int("\\A_WIDTH")
param_int("\\B_WIDTH")
param_int("\\CTRL_IN_WIDTH")
param_int("\\CTRL_OUT_WIDTH")
param_int("\\OFFSET")
param_int("\\PRIORITY")
param_int("\\RD_PORTS")
param_int("\\SIZE")
param_int("\\STATE_BITS")
param_int("\\STATE_NUM")
param_int("\\STATE_NUM_LOG2")
param_int("\\STATE_RST")
param_int("\\S_WIDTH")
param_int("\\TRANS_NUM")
param_int("\\WIDTH")
param_int("\\WR_PORTS")
param_int("\\Y_WIDTH")
#undef param_int
return value;
}
virtual bool userCompareNodes(const std::string &, const std::string &, void *needleUserData,
const std::string &, const std::string &, void *haystackUserData, const std::map<std::string, std::string> &portMapping)
{
RTLIL::Cell *needleCell = (RTLIL::Cell*) needleUserData;
RTLIL::Cell *haystackCell = (RTLIL::Cell*) haystackUserData;
if (!needleCell || !haystackCell) {
log_assert(!needleCell && !haystackCell);
return true;
}
if (!ignore_parameters) {
std::map<RTLIL::IdString, RTLIL::Const> needle_param, haystack_param;
for (auto &it : needleCell->parameters)
if (!ignored_parameters.count(std::pair<RTLIL::IdString, RTLIL::IdString>(needleCell->type, it.first)))
needle_param[it.first] = unified_param(needleCell->type, it.first, it.second);
for (auto &it : haystackCell->parameters)
if (!ignored_parameters.count(std::pair<RTLIL::IdString, RTLIL::IdString>(haystackCell->type, it.first)))
haystack_param[it.first] = unified_param(haystackCell->type, it.first, it.second);
if (needle_param != haystack_param)
return false;
}
if (cell_attr.size() > 0 && !compareAttributes(cell_attr, needleCell->attributes, haystackCell->attributes))
return false;
if (wire_attr.size() > 0)
{
RTLIL::Wire *lastNeedleWire = NULL;
RTLIL::Wire *lastHaystackWire = NULL;
dict<RTLIL::IdString, RTLIL::Const> emptyAttr;
for (auto &conn : needleCell->connections())
{
RTLIL::SigSpec needleSig = conn.second;
RTLIL::SigSpec haystackSig = haystackCell->getPort(portMapping.at(conn.first.str()));
for (int i = 0; i < min(needleSig.size(), haystackSig.size()); i++) {
RTLIL::Wire *needleWire = needleSig[i].wire, *haystackWire = haystackSig[i].wire;
if (needleWire != lastNeedleWire || haystackWire != lastHaystackWire)
if (!compareAttributes(wire_attr, needleWire ? needleWire->attributes : emptyAttr, haystackWire ? haystackWire->attributes : emptyAttr))
return false;
lastNeedleWire = needleWire, lastHaystackWire = haystackWire;
}
}
}
return true;
}
};
struct bit_ref_t {
std::string cell, port;
int bit;
};
bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, RTLIL::Design *sel = NULL,
int max_fanout = -1, std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> *split = NULL)
{
SigMap sigmap(mod);
std::map<RTLIL::SigBit, bit_ref_t> sig_bit_ref;
if (sel && !sel->selected(mod)) {
log(" Skipping module %s as it is not selected.\n", id2cstr(mod->name));
return false;
}
if (mod->processes.size() > 0) {
log(" Skipping module %s as it contains unprocessed processes.\n", id2cstr(mod->name));
return false;
}
if (constports) {
graph.createNode("$const$0", "$const$0", NULL, true);
graph.createNode("$const$1", "$const$1", NULL, true);
graph.createNode("$const$x", "$const$x", NULL, true);
graph.createNode("$const$z", "$const$z", NULL, true);
graph.createPort("$const$0", "\\Y", 1);
graph.createPort("$const$1", "\\Y", 1);
graph.createPort("$const$x", "\\Y", 1);
graph.createPort("$const$z", "\\Y", 1);
graph.markExtern("$const$0", "\\Y", 0);
graph.markExtern("$const$1", "\\Y", 0);
graph.markExtern("$const$x", "\\Y", 0);
graph.markExtern("$const$z", "\\Y", 0);
}
std::map<std::pair<RTLIL::Wire*, int>, int> sig_use_count;
if (max_fanout > 0)
for (auto &cell_it : mod->cells_)
{
RTLIL::Cell *cell = cell_it.second;
if (!sel || sel->selected(mod, cell))
for (auto &conn : cell->connections()) {
RTLIL::SigSpec conn_sig = conn.second;
sigmap.apply(conn_sig);
for (auto &bit : conn_sig)
if (bit.wire != NULL)
sig_use_count[std::pair<RTLIL::Wire*, int>(bit.wire, bit.offset)]++;
}
}
// create graph nodes from cells
for (auto &cell_it : mod->cells_)
{
RTLIL::Cell *cell = cell_it.second;
if (sel && !sel->selected(mod, cell))
continue;
std::string type = cell->type.str();
if (sel == NULL && type.substr(0, 2) == "\\$")
type = type.substr(1);
graph.createNode(cell->name.str(), type, (void*)cell);
for (auto &conn : cell->connections())
{
graph.createPort(cell->name.str(), conn.first.str(), conn.second.size());
if (split && split->count(std::pair<RTLIL::IdString, RTLIL::IdString>(cell->type, conn.first)) > 0)
continue;
RTLIL::SigSpec conn_sig = conn.second;
sigmap.apply(conn_sig);
for (int i = 0; i < conn_sig.size(); i++)
{
auto &bit = conn_sig[i];
if (bit.wire == NULL) {
if (constports) {
std::string node = "$const$x";
if (bit == RTLIL::State::S0) node = "$const$0";
if (bit == RTLIL::State::S1) node = "$const$1";
if (bit == RTLIL::State::Sz) node = "$const$z";
graph.createConnection(cell->name.str(), conn.first.str(), i, node, "\\Y", 0);
} else
graph.createConstant(cell->name.str(), conn.first.str(), i, int(bit.data));
continue;
}
if (max_fanout > 0 && sig_use_count[std::pair<RTLIL::Wire*, int>(bit.wire, bit.offset)] > max_fanout)
continue;
if (sel && !sel->selected(mod, bit.wire))
continue;
if (sig_bit_ref.count(bit) == 0) {
bit_ref_t &bit_ref = sig_bit_ref[bit];
bit_ref.cell = cell->name.str();
bit_ref.port = conn.first.str();
bit_ref.bit = i;
}
bit_ref_t &bit_ref = sig_bit_ref[bit];
graph.createConnection(bit_ref.cell, bit_ref.port, bit_ref.bit, cell->name.str(), conn.first.str(), i);
}
}
}
// mark external signals (used in non-selected cells)
for (auto &cell_it : mod->cells_)
{
RTLIL::Cell *cell = cell_it.second;
if (sel && !sel->selected(mod, cell))
for (auto &conn : cell->connections())
{
RTLIL::SigSpec conn_sig = conn.second;
sigmap.apply(conn_sig);
for (auto &bit : conn_sig)
if (sig_bit_ref.count(bit) != 0) {
bit_ref_t &bit_ref = sig_bit_ref[bit];
graph.markExtern(bit_ref.cell, bit_ref.port, bit_ref.bit);
}
}
}
// mark external signals (used in module ports)
for (auto &wire_it : mod->wires_)
{
RTLIL::Wire *wire = wire_it.second;
if (wire->port_id > 0)
{
RTLIL::SigSpec conn_sig(wire);
sigmap.apply(conn_sig);
for (auto &bit : conn_sig)
if (sig_bit_ref.count(bit) != 0) {
bit_ref_t &bit_ref = sig_bit_ref[bit];
graph.markExtern(bit_ref.cell, bit_ref.port, bit_ref.bit);
}
}
}
// graph.print();
return true;
}
RTLIL::Cell *replace(RTLIL::Module *needle, RTLIL::Module *haystack, SubCircuit::Solver::Result &match)
{
SigMap sigmap(needle);
SigSet<std::pair<RTLIL::IdString, int>> sig2port;
// create new cell
RTLIL::Cell *cell = haystack->addCell(stringf("$extract$%s$%d", needle->name.c_str(), autoidx++), needle->name);
// create cell ports
for (auto &it : needle->wires_) {
RTLIL::Wire *wire = it.second;
if (wire->port_id > 0) {
for (int i = 0; i < wire->width; i++)
sig2port.insert(sigmap(RTLIL::SigSpec(wire, i)), std::pair<RTLIL::IdString, int>(wire->name, i));
cell->setPort(wire->name, RTLIL::SigSpec(RTLIL::State::Sz, wire->width));
}
}
// delete replaced cells and connect new ports
for (auto &it : match.mappings)
{
auto &mapping = it.second;
RTLIL::Cell *needle_cell = (RTLIL::Cell*)mapping.needleUserData;
RTLIL::Cell *haystack_cell = (RTLIL::Cell*)mapping.haystackUserData;
if (needle_cell == NULL)
continue;
for (auto &conn : needle_cell->connections()) {
RTLIL::SigSpec sig = sigmap(conn.second);
if (mapping.portMapping.count(conn.first.str()) > 0 && sig2port.has(sigmap(sig))) {
for (int i = 0; i < sig.size(); i++)
for (auto &port : sig2port.find(sig[i])) {
RTLIL::SigSpec bitsig = haystack_cell->getPort(mapping.portMapping[conn.first.str()]).extract(i, 1);
RTLIL::SigSpec new_sig = cell->getPort(port.first);
new_sig.replace(port.second, bitsig);
cell->setPort(port.first, new_sig);
}
}
}
haystack->remove(haystack_cell);
}
return cell;
}
bool compareSortNeedleList(RTLIL::Module *left, RTLIL::Module *right)
{
int left_idx = 0, right_idx = 0;
if (left->attributes.count("\\extract_order") > 0)
left_idx = left->attributes.at("\\extract_order").as_int();
if (right->attributes.count("\\extract_order") > 0)
right_idx = right->attributes.at("\\extract_order").as_int();
if (left_idx != right_idx)
return left_idx < right_idx;
return left->name < right->name;
}
struct ExtractPass : public Pass {
ExtractPass() : Pass("extract", "find subcircuits and replace them with cells") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" extract -map <map_file> [options] [selection]\n");
log(" extract -mine <out_file> [options] [selection]\n");
log("\n");
log("This pass looks for subcircuits that are isomorphic to any of the modules\n");
log("in the given map file and replaces them with instances of this modules. The\n");
log("map file can be a Verilog source file (*.v) or an ilang file (*.il).\n");
log("\n");
log(" -map <map_file>\n");
log(" use the modules in this file as reference. This option can be used\n");
log(" multiple times.\n");
log("\n");
log(" -map %%<design-name>\n");
log(" use the modules in this in-memory design as reference. This option can\n");
log(" be used multiple times.\n");
log("\n");
log(" -verbose\n");
log(" print debug output while analyzing\n");
log("\n");
log(" -constports\n");
log(" also find instances with constant drivers. this may be much\n");
log(" slower than the normal operation.\n");
log("\n");
log(" -nodefaultswaps\n");
log(" normally builtin port swapping rules for internal cells are used per\n");
log(" default. This turns that off, so e.g. 'a^b' does not match 'b^a'\n");
log(" when this option is used.\n");
log("\n");
log(" -compat <needle_type> <haystack_type>\n");
log(" Per default, the cells in the map file (needle) must have the\n");
log(" type as the cells in the active design (haystack). This option\n");
log(" can be used to register additional pairs of types that should\n");
log(" match. This option can be used multiple times.\n");
log("\n");
log(" -swap <needle_type> <port1>,<port2>[,...]\n");
log(" Register a set of swappable ports for a needle cell type.\n");
log(" This option can be used multiple times.\n");
log("\n");
log(" -perm <needle_type> <port1>,<port2>[,...] <portA>,<portB>[,...]\n");
log(" Register a valid permutation of swappable ports for a needle\n");
log(" cell type. This option can be used multiple times.\n");
log("\n");
log(" -cell_attr <attribute_name>\n");
log(" Attributes on cells with the given name must match.\n");
log("\n");
log(" -wire_attr <attribute_name>\n");
log(" Attributes on wires with the given name must match.\n");
log("\n");
log(" -ignore_parameters\n");
log(" Do not use parameters when matching cells.\n");
log("\n");
log(" -ignore_param <cell_type> <parameter_name>\n");
log(" Do not use this parameter when matching cells.\n");
log("\n");
log("This pass does not operate on modules with unprocessed processes in it.\n");
log("(I.e. the 'proc' pass should be used first to convert processes to netlists.)\n");
log("\n");
log("This pass can also be used for mining for frequent subcircuits. In this mode\n");
log("the following options are to be used instead of the -map option.\n");
log("\n");
log(" -mine <out_file>\n");
log(" mine for frequent subcircuits and write them to the given ilang file\n");
log("\n");
log(" -mine_cells_span <min> <max>\n");
log(" only mine for subcircuits with the specified number of cells\n");
log(" default value: 3 5\n");
log("\n");
log(" -mine_min_freq <num>\n");
log(" only mine for subcircuits with at least the specified number of matches\n");
log(" default value: 10\n");
log("\n");
log(" -mine_limit_matches_per_module <num>\n");
log(" when calculating the number of matches for a subcircuit, don't count\n");
log(" more than the specified number of matches per module\n");
log("\n");
log(" -mine_max_fanout <num>\n");
log(" don't consider internal signals with more than <num> connections\n");
log("\n");
log("The modules in the map file may have the attribute 'extract_order' set to an\n");
log("integer value. Then this value is used to determine the order in which the pass\n");
log("tries to map the modules to the design (ascending, default value is 0).\n");
log("\n");
log("See 'help techmap' for a pass that does the opposite thing.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
log_header(design, "Executing EXTRACT pass (map subcircuits to cells).\n");
log_push();
SubCircuitSolver solver;
std::vector<std::string> map_filenames;
std::string mine_outfile;
bool constports = false;
bool nodefaultswaps = false;
bool mine_mode = false;
int mine_cells_min = 3;
int mine_cells_max = 5;
int mine_min_freq = 10;
int mine_limit_mod = -1;
int mine_max_fanout = -1;
std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> mine_split;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-map" && argidx+1 < args.size()) {
if (mine_mode)
log_cmd_error("You cannot mix -map and -mine.\n");
map_filenames.push_back(args[++argidx]);
continue;
}
if (args[argidx] == "-mine" && argidx+1 < args.size()) {
if (!map_filenames.empty())
log_cmd_error("You cannot mix -map and -mine.\n");
mine_outfile = args[++argidx];
mine_mode = true;
continue;
}
if (args[argidx] == "-mine_cells_span" && argidx+2 < args.size()) {
mine_cells_min = atoi(args[++argidx].c_str());
mine_cells_max = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-mine_min_freq" && argidx+1 < args.size()) {
mine_min_freq = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-mine_limit_matches_per_module" && argidx+1 < args.size()) {
mine_limit_mod = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-mine_split" && argidx+2 < args.size()) {
mine_split.insert(std::pair<RTLIL::IdString, RTLIL::IdString>(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2])));
argidx += 2;
continue;
}
if (args[argidx] == "-mine_max_fanout" && argidx+1 < args.size()) {
mine_max_fanout = atoi(args[++argidx].c_str());
continue;
}
if (args[argidx] == "-verbose") {
solver.setVerbose();
continue;
}
if (args[argidx] == "-constports") {
constports = true;
continue;
}
if (args[argidx] == "-nodefaultswaps") {
nodefaultswaps = true;
continue;
}
if (args[argidx] == "-compat" && argidx+2 < args.size()) {
std::string needle_type = RTLIL::escape_id(args[++argidx]);
std::string haystack_type = RTLIL::escape_id(args[++argidx]);
solver.addCompatibleTypes(needle_type, haystack_type);
continue;
}
if (args[argidx] == "-swap" && argidx+2 < args.size()) {
std::string type = RTLIL::escape_id(args[++argidx]);
std::set<std::string> ports;
std::string ports_str = args[++argidx], p;
while (!(p = next_token(ports_str, ",\t\r\n ")).empty())
ports.insert(RTLIL::escape_id(p));
solver.addSwappablePorts(type, ports);
continue;
}
if (args[argidx] == "-perm" && argidx+3 < args.size()) {
std::string type = RTLIL::escape_id(args[++argidx]);
std::vector<std::string> map_left, map_right;
std::string left_str = args[++argidx];
std::string right_str = args[++argidx], p;
while (!(p = next_token(left_str, ",\t\r\n ")).empty())
map_left.push_back(RTLIL::escape_id(p));
while (!(p = next_token(right_str, ",\t\r\n ")).empty())
map_right.push_back(RTLIL::escape_id(p));
if (map_left.size() != map_right.size())
log_cmd_error("Arguments to -perm are not a valid permutation!\n");
std::map<std::string, std::string> map;
for (size_t i = 0; i < map_left.size(); i++)
map[map_left[i]] = map_right[i];
std::sort(map_left.begin(), map_left.end());
std::sort(map_right.begin(), map_right.end());
if (map_left != map_right)
log_cmd_error("Arguments to -perm are not a valid permutation!\n");
solver.addSwappablePortsPermutation(type, map);
continue;
}
if (args[argidx] == "-cell_attr" && argidx+1 < args.size()) {
solver.cell_attr.insert(RTLIL::escape_id(args[++argidx]));
continue;
}
if (args[argidx] == "-wire_attr" && argidx+1 < args.size()) {
solver.wire_attr.insert(RTLIL::escape_id(args[++argidx]));
continue;
}
if (args[argidx] == "-ignore_parameters") {
solver.ignore_parameters = true;
continue;
}
if (args[argidx] == "-ignore_param" && argidx+2 < args.size()) {
solver.ignored_parameters.insert(std::pair<RTLIL::IdString, RTLIL::IdString>(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2])));
argidx += 2;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!nodefaultswaps) {
solver.addSwappablePorts("$and", "\\A", "\\B");
solver.addSwappablePorts("$or", "\\A", "\\B");
solver.addSwappablePorts("$xor", "\\A", "\\B");
solver.addSwappablePorts("$xnor", "\\A", "\\B");
solver.addSwappablePorts("$eq", "\\A", "\\B");
solver.addSwappablePorts("$ne", "\\A", "\\B");
solver.addSwappablePorts("$eqx", "\\A", "\\B");
solver.addSwappablePorts("$nex", "\\A", "\\B");
solver.addSwappablePorts("$add", "\\A", "\\B");
solver.addSwappablePorts("$mul", "\\A", "\\B");
solver.addSwappablePorts("$logic_and", "\\A", "\\B");
solver.addSwappablePorts("$logic_or", "\\A", "\\B");
solver.addSwappablePorts("$_AND_", "\\A", "\\B");
solver.addSwappablePorts("$_OR_", "\\A", "\\B");
solver.addSwappablePorts("$_XOR_", "\\A", "\\B");
}
if (map_filenames.empty() && mine_outfile.empty())
log_cmd_error("Missing option -map <verilog_or_ilang_file> or -mine <output_ilang_file>.\n");
RTLIL::Design *map = NULL;
if (!mine_mode)
{
map = new RTLIL::Design;
for (auto &filename : map_filenames)
{
if (filename.substr(0, 1) == "%")
{
if (!saved_designs.count(filename.substr(1))) {
delete map;
log_cmd_error("Can't saved design `%s'.\n", filename.c_str()+1);
}
for (auto mod : saved_designs.at(filename.substr(1))->modules())
if (!map->has(mod->name))
map->add(mod->clone());
}
else
{
std::ifstream f;
rewrite_filename(filename);
f.open(filename.c_str());
if (f.fail()) {
delete map;
log_cmd_error("Can't open map file `%s'.\n", filename.c_str());
}
Frontend::frontend_call(map, &f, filename, (filename.size() > 3 && filename.substr(filename.size()-3) == ".il") ? "ilang" : "verilog");
f.close();
if (filename.size() <= 3 || filename.substr(filename.size()-3) != ".il") {
Pass::call(map, "proc");
Pass::call(map, "opt_clean");
}
}
}
}
std::map<std::string, RTLIL::Module*> needle_map, haystack_map;
std::vector<RTLIL::Module*> needle_list;
log_header(design, "Creating graphs for SubCircuit library.\n");
if (!mine_mode)
for (auto &mod_it : map->modules_) {
SubCircuit::Graph mod_graph;
std::string graph_name = "needle_" + RTLIL::unescape_id(mod_it.first);
log("Creating needle graph %s.\n", graph_name.c_str());
if (module2graph(mod_graph, mod_it.second, constports)) {
solver.addGraph(graph_name, mod_graph);
needle_map[graph_name] = mod_it.second;
needle_list.push_back(mod_it.second);
}
}
for (auto &mod_it : design->modules_) {
SubCircuit::Graph mod_graph;
std::string graph_name = "haystack_" + RTLIL::unescape_id(mod_it.first);
log("Creating haystack graph %s.\n", graph_name.c_str());
if (module2graph(mod_graph, mod_it.second, constports, design, mine_mode ? mine_max_fanout : -1, mine_mode ? &mine_split : NULL)) {
solver.addGraph(graph_name, mod_graph);
haystack_map[graph_name] = mod_it.second;
}
}
if (!mine_mode)
{
std::vector<SubCircuit::Solver::Result> results;
log_header(design, "Running solver from SubCircuit library.\n");
std::sort(needle_list.begin(), needle_list.end(), compareSortNeedleList);
for (auto needle : needle_list)
for (auto &haystack_it : haystack_map) {
log("Solving for %s in %s.\n", ("needle_" + RTLIL::unescape_id(needle->name)).c_str(), haystack_it.first.c_str());
solver.solve(results, "needle_" + RTLIL::unescape_id(needle->name), haystack_it.first, false);
}
log("Found %d matches.\n", GetSize(results));
if (results.size() > 0)
{
log_header(design, "Substitute SubCircuits with cells.\n");
for (int i = 0; i < int(results.size()); i++) {
auto &result = results[i];
log("\nMatch #%d: (%s in %s)\n", i, result.needleGraphId.c_str(), result.haystackGraphId.c_str());
for (const auto &it : result.mappings) {
log(" %s -> %s", it.first.c_str(), it.second.haystackNodeId.c_str());
for (const auto & it2 : it.second.portMapping)
log(" %s:%s", it2.first.c_str(), it2.second.c_str());
log("\n");
}
RTLIL::Cell *new_cell = replace(needle_map.at(result.needleGraphId), haystack_map.at(result.haystackGraphId), result);
design->select(haystack_map.at(result.haystackGraphId), new_cell);
log(" new cell: %s\n", id2cstr(new_cell->name));
}
}
}
else
{
std::vector<SubCircuit::Solver::MineResult> results;
log_header(design, "Running miner from SubCircuit library.\n");
solver.mine(results, mine_cells_min, mine_cells_max, mine_min_freq, mine_limit_mod);
map = new RTLIL::Design;
int needleCounter = 0;
for (auto &result: results)
{
log("\nFrequent SubCircuit with %d nodes and %d matches:\n", int(result.nodes.size()), result.totalMatchesAfterLimits);
log(" primary match in %s:", id2cstr(haystack_map.at(result.graphId)->name));
for (auto &node : result.nodes)
log(" %s", RTLIL::unescape_id(node.nodeId).c_str());
log("\n");
for (auto &it : result.matchesPerGraph)
log(" matches in %s: %d\n", id2cstr(haystack_map.at(it.first)->name), it.second);
RTLIL::Module *mod = haystack_map.at(result.graphId);
std::set<RTLIL::Cell*> cells;
std::set<RTLIL::Wire*> wires;
SigMap sigmap(mod);
for (auto &node : result.nodes)
cells.insert((RTLIL::Cell*)node.userData);
for (auto cell : cells)
for (auto &conn : cell->connections()) {
RTLIL::SigSpec sig = sigmap(conn.second);
for (auto &chunk : sig.chunks())
if (chunk.wire != NULL)
wires.insert(chunk.wire);
}
RTLIL::Module *newMod = new RTLIL::Module;
newMod->name = stringf("\\needle%05d_%s_%dx", needleCounter++, id2cstr(haystack_map.at(result.graphId)->name), result.totalMatchesAfterLimits);
map->add(newMod);
for (auto wire : wires) {
RTLIL::Wire *newWire = newMod->addWire(wire->name, wire->width);
newWire->port_input = true;
newWire->port_output = true;
}
newMod->fixup_ports();
for (auto cell : cells) {
RTLIL::Cell *newCell = newMod->addCell(cell->name, cell->type);
newCell->parameters = cell->parameters;
for (auto &conn : cell->connections()) {
std::vector<SigChunk> chunks = sigmap(conn.second);
for (auto &chunk : chunks)
if (chunk.wire != NULL)
chunk.wire = newMod->wires_.at(chunk.wire->name);
newCell->setPort(conn.first, chunks);
}
}
}
std::ofstream f;
rewrite_filename(mine_outfile);
f.open(mine_outfile.c_str(), std::ofstream::trunc);
if (f.fail())
log_error("Can't open output file `%s'.\n", mine_outfile.c_str());
Backend::backend_call(map, &f, mine_outfile, "ilang");
f.close();
}
delete map;
log_pop();
}
} ExtractPass;
PRIVATE_NAMESPACE_END
|
; A090816: a(n) = (3*n+1)!/((2*n)! * n!).
; 1,12,105,840,6435,48048,352716,2558160,18386775,131231100,931395465,6580248480,46312074900,324897017760,2272989850440,15863901576864,110487596768703,768095592509700,5330949171823275,36945070220658600,255702514854135195,1767643865751234240,12206272254777946800,84205588308323227200,580369101332499051300,3996729582727315915728,27502382411459573207436,189114914695151782223040,1299551029065872555438520,8924684381098478674735680,61255100680098795581935824,420201568494046312156991808
mov $2,1
add $2,$0
mul $0,2
add $0,$2
bin $0,$2
mul $0,$2
|
;******************************************************************************
;* Copyright (c) 2010 David Conrad
;*
;* This file is part of FFmpeg.
;*
;* FFmpeg is free software; you can redistribute it and/or
;* modify it under the terms of the GNU Lesser General Public
;* License as published by the Free Software Foundation; either
;* version 2.1 of the License, or (at your option) any later version.
;*
;* FFmpeg is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;* Lesser General Public License for more details.
;*
;* You should have received a copy of the GNU Lesser General Public
;* License along with FFmpeg; if not, write to the Free Software
;* 51, Inc., Foundation Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;******************************************************************************
%include "libavutil/x86/x86util.asm"
SECTION_RODATA
pw_7: times 8 dw 7
cextern pw_3
cextern pw_16
cextern pw_32
cextern pb_80
section .text
%macro UNPACK_ADD 6
mov%5 %1, %3
mov%6 m5, %4
mova m4, %1
mova %2, m5
punpcklbw %1, m7
punpcklbw m5, m7
punpckhbw m4, m7
punpckhbw %2, m7
paddw %1, m5
paddw %2, m4
%endmacro
%macro HPEL_FILTER 1
; dirac_hpel_filter_v_sse2(uint8_t *dst, uint8_t *src, int stride, int width);
cglobal dirac_hpel_filter_v_%1, 4,6,8, dst, src, stride, width, src0, stridex3
mov src0q, srcq
lea stridex3q, [3*strideq]
sub src0q, stridex3q
pxor m7, m7
.loop:
; 7*(src[0] + src[1])
UNPACK_ADD m0, m1, [srcq], [srcq + strideq], a,a
pmullw m0, [pw_7]
pmullw m1, [pw_7]
; 3*( ... + src[-2] + src[3])
UNPACK_ADD m2, m3, [src0q + strideq], [srcq + stridex3q], a,a
paddw m0, m2
paddw m1, m3
pmullw m0, [pw_3]
pmullw m1, [pw_3]
; ... - 7*(src[-1] + src[2])
UNPACK_ADD m2, m3, [src0q + strideq*2], [srcq + strideq*2], a,a
pmullw m2, [pw_7]
pmullw m3, [pw_7]
psubw m0, m2
psubw m1, m3
; ... - (src[-3] + src[4])
UNPACK_ADD m2, m3, [src0q], [srcq + strideq*4], a,a
psubw m0, m2
psubw m1, m3
paddw m0, [pw_16]
paddw m1, [pw_16]
psraw m0, 5
psraw m1, 5
packuswb m0, m1
mova [dstq], m0
add dstq, mmsize
add srcq, mmsize
add src0q, mmsize
sub widthd, mmsize
jg .loop
RET
; dirac_hpel_filter_h_sse2(uint8_t *dst, uint8_t *src, int width);
cglobal dirac_hpel_filter_h_%1, 3,3,8, dst, src, width
dec widthd
pxor m7, m7
and widthd, ~(mmsize-1)
.loop:
; 7*(src[0] + src[1])
UNPACK_ADD m0, m1, [srcq + widthq], [srcq + widthq + 1], u,u
pmullw m0, [pw_7]
pmullw m1, [pw_7]
; 3*( ... + src[-2] + src[3])
UNPACK_ADD m2, m3, [srcq + widthq - 2], [srcq + widthq + 3], u,u
paddw m0, m2
paddw m1, m3
pmullw m0, [pw_3]
pmullw m1, [pw_3]
; ... - 7*(src[-1] + src[2])
UNPACK_ADD m2, m3, [srcq + widthq - 1], [srcq + widthq + 2], u,u
pmullw m2, [pw_7]
pmullw m3, [pw_7]
psubw m0, m2
psubw m1, m3
; ... - (src[-3] + src[4])
UNPACK_ADD m2, m3, [srcq + widthq - 3], [srcq + widthq + 4], u,u
psubw m0, m2
psubw m1, m3
paddw m0, [pw_16]
paddw m1, [pw_16]
psraw m0, 5
psraw m1, 5
packuswb m0, m1
mova [dstq + widthq], m0
sub widthd, mmsize
jge .loop
RET
%endmacro
%macro PUT_RECT 1
; void put_rect_clamped(uint8_t *dst, int dst_stride, int16_t *src, int src_stride, int width, int height)
cglobal put_signed_rect_clamped_%1, 5,9,3, dst, dst_stride, src, src_stride, w, dst2, src2
mova m0, [pb_80]
add wd, (mmsize-1)
and wd, ~(mmsize-1)
%if ARCH_X86_64
movsxd dst_strideq, dst_strided
movsxd src_strideq, src_strided
mov r7d, r5m
mov r8d, wd
%define wspill r8d
%define hd r7d
%else
mov r4m, wd
%define wspill r4m
%define hd r5mp
%endif
.loopy:
lea src2q, [srcq+src_strideq*2]
lea dst2q, [dstq+dst_strideq]
.loopx:
sub wd, mmsize
mova m1, [srcq +2*wq]
mova m2, [src2q+2*wq]
packsswb m1, [srcq +2*wq+mmsize]
packsswb m2, [src2q+2*wq+mmsize]
paddb m1, m0
paddb m2, m0
mova [dstq +wq], m1
mova [dst2q+wq], m2
jg .loopx
lea srcq, [srcq+src_strideq*4]
lea dstq, [dstq+dst_strideq*2]
sub hd, 2
mov wd, wspill
jg .loopy
RET
%endm
%macro ADD_RECT 1
; void add_rect_clamped(uint8_t *dst, uint16_t *src, int stride, int16_t *idwt, int idwt_stride, int width, int height)
cglobal add_rect_clamped_%1, 7,9,3, dst, src, stride, idwt, idwt_stride, w, h
mova m0, [pw_32]
add wd, (mmsize-1)
and wd, ~(mmsize-1)
%if ARCH_X86_64
movsxd strideq, strided
movsxd idwt_strideq, idwt_strided
mov r8d, wd
%define wspill r8d
%else
mov r5m, wd
%define wspill r5m
%endif
.loop:
sub wd, mmsize
movu m1, [srcq +2*wq] ; FIXME: ensure alignment
paddw m1, m0
psraw m1, 6
movu m2, [srcq +2*wq+mmsize] ; FIXME: ensure alignment
paddw m2, m0
psraw m2, 6
paddw m1, [idwtq+2*wq]
paddw m2, [idwtq+2*wq+mmsize]
packuswb m1, m2
mova [dstq +wq], m1
jg .loop
lea srcq, [srcq + 2*strideq]
add dstq, strideq
lea idwtq, [idwtq+ 2*idwt_strideq]
sub hd, 1
mov wd, wspill
jg .loop
RET
%endm
%macro ADD_OBMC 2
; void add_obmc(uint16_t *dst, uint8_t *src, int stride, uint8_t *obmc_weight, int yblen)
cglobal add_dirac_obmc%1_%2, 6,6,5, dst, src, stride, obmc, yblen
pxor m4, m4
.loop:
%assign i 0
%rep %1 / mmsize
mova m0, [srcq+i]
mova m1, m0
punpcklbw m0, m4
punpckhbw m1, m4
mova m2, [obmcq+i]
mova m3, m2
punpcklbw m2, m4
punpckhbw m3, m4
pmullw m0, m2
pmullw m1, m3
movu m2, [dstq+2*i]
movu m3, [dstq+2*i+mmsize]
paddw m0, m2
paddw m1, m3
movu [dstq+2*i], m0
movu [dstq+2*i+mmsize], m1
%assign i i+mmsize
%endrep
lea srcq, [srcq+strideq]
lea dstq, [dstq+2*strideq]
add obmcq, 32
sub yblend, 1
jg .loop
RET
%endm
INIT_MMX
%if ARCH_X86_64 == 0
PUT_RECT mmx
ADD_RECT mmx
HPEL_FILTER mmx
ADD_OBMC 32, mmx
ADD_OBMC 16, mmx
%endif
ADD_OBMC 8, mmx
INIT_XMM
PUT_RECT sse2
ADD_RECT sse2
HPEL_FILTER sse2
ADD_OBMC 32, sse2
ADD_OBMC 16, sse2
|
;*******************************************************************************
; *
; Microchip licenses this software to you solely for use with Microchip *
; products. The software is owned by Microchip and/or its licensors, and is *
; protected under applicable copyright laws. All rights reserved. *
; *
; This software and any accompanying information is for suggestion only. *
; It shall not be deemed to modify Microchip?s standard warranty for its *
; products. It is your responsibility to ensure that this software meets *
; your requirements. *
; *
; SOFTWARE IS PROVIDED "AS IS". MICROCHIP AND ITS LICENSORS EXPRESSLY *
; DISCLAIM ANY WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING *
; BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS *
; FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL *
; MICROCHIP OR ITS LICENSORS BE LIABLE FOR ANY INCIDENTAL, SPECIAL, *
; INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, HARM TO *
; YOUR EQUIPMENT, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR *
; SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY *
; DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER *
; SIMILAR COSTS. *
; *
; To the fullest extend allowed by law, Microchip and its licensors *
; liability shall not exceed the amount of fee, if any, that you have paid *
; directly to Microchip to use this software. *
; *
; MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF *
; THESE TERMS. *
; *
;*******************************************************************************
; *
; Filename: *
; Date: *
; File Version: *
; Author: *
; Company: *
; Description: *
; *
;*******************************************************************************
; *
; Notes: In the MPLAB X Help, refer to the MPASM Assembler documentation *
; for information on assembly instructions. *
; *
;*******************************************************************************
; *
; Known Issues: This template is designed for relocatable code. As such, *
; build errors such as "Directive only allowed when generating an object *
; file" will result when the 'Build in Absolute Mode' checkbox is selected *
; in the project properties. Designing code in absolute mode is *
; antiquated - use relocatable mode. *
; *
;*******************************************************************************
; *
; Revision History: *
; *
;*******************************************************************************
;*******************************************************************************
; Processor Inclusion
;
; TODO Step #1 Open the task list under Window > Tasks. Include your
; device .inc file - e.g. #include <device_name>.inc. Available
; include files are in C:\Program Files\Microchip\MPLABX\mpasmx
; assuming the default installation path for MPLAB X. You may manually find
; the appropriate include file for your device here and include it, or
; simply copy the include generated by the configuration bits
; generator (see Step #2).
;
;*******************************************************************************
; TODO INSERT INCLUDE CODE HERE
;*******************************************************************************
;
; TODO Step #2 - Configuration Word Setup
;
; The 'CONFIG' directive is used to embed the configuration word within the
; .asm file. MPLAB X requires users to embed their configuration words
; into source code. See the device datasheet for additional information
; on configuration word settings. Device configuration bits descriptions
; are in C:\Program Files\Microchip\MPLABX\mpasmx\P<device_name>.inc
; (may change depending on your MPLAB X installation directory).
;
; MPLAB X has a feature which generates configuration bits source code. Go to
; Window > PIC Memory Views > Configuration Bits. Configure each field as
; needed and select 'Generate Source Code to Output'. The resulting code which
; appears in the 'Output Window' > 'Config Bits Source' tab may be copied
; below.
;
;*******************************************************************************
#include"p16f887.inc"
; TODO INSERT CONFIG HERE
__CONFIG _CONFIG1, _CP_OFF&_WDT_OFF&_XT_OSC
errorlevel -302
;*******************************************************************************
;
; TODO Step #3 - Variable Definitions
;
; Refer to datasheet for available data memory (RAM) organization assuming
; relocatible code organization (which is an option in project
; properties > mpasm (Global Options)). Absolute mode generally should
; be used sparingly.
;
; Example of using GPR Uninitialized Data
;
; GPR_VAR UDATA
; MYVAR1 RES 1 ; User variable linker places
; MYVAR2 RES 1 ; User variable linker places
; MYVAR3 RES 1 ; User variable linker places
;
; ; Example of using Access Uninitialized Data Section (when available)
; ; The variables for the context saving in the device datasheet may need
; ; memory reserved here.
; INT_VAR UDATA_ACS
; W_TEMP RES 1 ; w register for context saving (ACCESS)
; STATUS_TEMP RES 1 ; status used for context saving
; BSR_TEMP RES 1 ; bank select used for ISR context saving
;
;*******************************************************************************
; TODO PLACE VARIABLE DEFINITIONS GO HERE
;*******************************************************************************
; Reset Vector
;*******************************************************************************
RES_VECT CODE 0x0000 ; processor reset vector
GOTO START ; go to beginning of program
;*******************************************************************************
; TODO Step #4 - Interrupt Service Routines
;
; There are a few different ways to structure interrupt routines in the 8
; bit device families. On PIC18's the high priority and low priority
; interrupts are located at 0x0008 and 0x0018, respectively. On PIC16's and
; lower the interrupt is at 0x0004. Between device families there is subtle
; variation in the both the hardware supporting the ISR (for restoring
; interrupt context) as well as the software used to restore the context
; (without corrupting the STATUS bits).
;
; General formats are shown below in relocatible format.
;
;------------------------------PIC16's and below--------------------------------
;
; ISR CODE 0x0004 ; interrupt vector location
;
; <Search the device datasheet for 'context' and copy interrupt
; context saving code here. Older devices need context saving code,
; but newer devices like the 16F#### don't need context saving code.>
;
; RETFIE
;
;----------------------------------PIC18's--------------------------------------
;
; ISRHV CODE 0x0008
; GOTO HIGH_ISR
; ISRLV CODE 0x0018
; GOTO LOW_ISR
;
; ISRH CODE ; let linker place high ISR routine
; HIGH_ISR
; <Insert High Priority ISR Here - no SW context saving>
; RETFIE FAST
;
; ISRL CODE ; let linker place low ISR routine
; LOW_ISR
; <Search the device datasheet for 'context' and copy interrupt
; context saving code here>
; RETFIE
;
;*******************************************************************************
; TODO INSERT ISR HERE
;*******************************************************************************
; MAIN PROGRAM
;*******************************************************************************
MAIN_PROG CODE ; let linker place main program
START; INICIO DEL PROGRAMA
ORG 0x00 ; Comienzo del programa (Vector de Reset)
; SETEO DE PUERTOS
BANKSEL TRISA ; selecciona el banco conteniendo TRISA
CLRF TRISA ; puerto A configurado como salida
BANKSEL ANSEL
CLRF ANSEL ; configura puertos con entradas digitales
CLRF ANSELH ; configura puertos con entradas digitales
BANKSEL PORTA ; selecciona el puerto A como salida
CLRF PORTA
; DESARROLLO DEL PROGRAMA
;1
VALOR
BTFSS PORTB,0 ; prueba del bit 0 del puerto B
GOTO NUEVO_VALOR
MOVLW B'00000000' ; mueve 0xAA al registro W
MOVWF PORTA ; pasa el valor al puerto A
GOTO VALOR
NUEVO_VALOR
MOVLW B'00000001' ; mueve 0x55 al registro W
MOVWF PORTA ; pasa el valor al puerto A
GOTO VALOR2
VALOR2
BTFSS PORTB,0
GOTO NUEVO_VALOR
MOVLW B'00000000'
MOVWF PORTA
GOTO VALOR
END
|
//
// ScriptCache.cpp
// libraries/metavoxels/src
//
// Created by Andrzej Kapolka on 2/4/14.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <cmath>
#include <QNetworkReply>
#include <QScriptEngine>
#include <QScriptValueIterator>
#include <QTextStream>
#include "AttributeRegistry.h"
#include "ScriptCache.h"
static int scriptValueMetaTypeId = qRegisterMetaType<QScriptValue>();
static bool scriptValueComparators = QMetaType::registerComparators<QScriptValue>();
bool operator==(const QScriptValue& first, const QScriptValue& second) {
if (first.isUndefined()) {
return second.isUndefined();
} else if (first.isNull()) {
return second.isNull();
} else if (first.isBool()) {
return second.isBool() && first.toBool() == second.toBool();
} else if (first.isNumber()) {
return second.isNumber() && first.toNumber() == second.toNumber();
} else if (first.isString()) {
return second.isString() && first.toString() == second.toString();
} else if (first.isVariant()) {
return second.isVariant() && first.toVariant() == second.toVariant();
} else if (first.isQObject()) {
return second.isQObject() && first.toQObject() == second.toQObject();
} else if (first.isQMetaObject()) {
return second.isQMetaObject() && first.toQMetaObject() == second.toQMetaObject();
} else if (first.isDate()) {
return second.isDate() && first.toDateTime() == second.toDateTime();
} else if (first.isRegExp()) {
return second.isRegExp() && first.toRegExp() == second.toRegExp();
} else if (first.isArray()) {
if (!second.isArray()) {
return false;
}
int length = first.property(ScriptCache::getInstance()->getLengthString()).toInt32();
if (second.property(ScriptCache::getInstance()->getLengthString()).toInt32() != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (first.property(i) != second.property(i)) {
return false;
}
}
return true;
} else if (first.isObject()) {
if (!second.isObject()) {
return false;
}
int propertyCount = 0;
for (QScriptValueIterator it(first); it.hasNext(); ) {
it.next();
if (second.property(it.scriptName()) != it.value()) {
return false;
}
propertyCount++;
}
// make sure the second has exactly as many properties as the first
for (QScriptValueIterator it(second); it.hasNext(); ) {
it.next();
if (--propertyCount < 0) {
return false;
}
}
return true;
} else {
// if none of the above tests apply, first must be invalid
return !second.isValid();
}
}
bool operator!=(const QScriptValue& first, const QScriptValue& second) {
return !(first == second);
}
bool operator<(const QScriptValue& first, const QScriptValue& second) {
return first.lessThan(second);
}
ScriptCache* ScriptCache::getInstance() {
static ScriptCache cache;
return &cache;
}
ScriptCache::ScriptCache() :
_engine(NULL) {
setEngine(new QScriptEngine(this));
}
void ScriptCache::setEngine(QScriptEngine* engine) {
if (_engine && _engine->parent() == this) {
delete _engine;
}
AttributeRegistry::getInstance()->configureScriptEngine(_engine = engine);
_parametersString = engine->toStringHandle("parameters");
_lengthString = engine->toStringHandle("length");
_nameString = engine->toStringHandle("name");
_typeString = engine->toStringHandle("type");
_generatorString = engine->toStringHandle("generator");
}
QSharedPointer<NetworkValue> ScriptCache::getValue(const ParameterizedURL& url) {
QSharedPointer<NetworkValue> value = _networkValues.value(url);
if (value.isNull()) {
value = QSharedPointer<NetworkValue>(url.getParameters().isEmpty() ?
(NetworkValue*)new RootNetworkValue(getProgram(url.getURL())) :
(NetworkValue*)new DerivedNetworkValue(getValue(url.getURL()), url.getParameters()));
_networkValues.insert(url, value);
}
return value;
}
QSharedPointer<Resource> ScriptCache::createResource(const QUrl& url,
const QSharedPointer<Resource>& fallback, bool delayLoad, const void* extra) {
return QSharedPointer<Resource>(new NetworkProgram(this, url), &Resource::allReferencesCleared);
}
NetworkProgram::NetworkProgram(ScriptCache* cache, const QUrl& url) :
Resource(url),
_cache(cache) {
}
void NetworkProgram::downloadFinished(QNetworkReply* reply) {
_program = QScriptProgram(QTextStream(reply).readAll(), reply->url().toString());
reply->deleteLater();
finishedLoading(true);
emit loaded();
}
NetworkValue::~NetworkValue() {
}
RootNetworkValue::RootNetworkValue(const QSharedPointer<NetworkProgram>& program) :
_program(program) {
}
QScriptValue& RootNetworkValue::getValue() {
if (!_value.isValid() && _program->isLoaded()) {
_value = _program->getCache()->getEngine()->evaluate(_program->getProgram());
}
return _value;
}
const QList<ParameterInfo>& RootNetworkValue::getParameterInfo() {
if (isLoaded() && _parameterInfo.isEmpty()) {
ScriptCache* cache = _program->getCache();
QScriptEngine* engine = cache->getEngine();
QScriptValue parameters = _value.property(cache->getParametersString());
if (parameters.isArray()) {
int length = parameters.property(cache->getLengthString()).toInt32();
for (int i = 0; i < length; i++) {
QScriptValue parameter = parameters.property(i);
ParameterInfo info = { engine->toStringHandle(parameter.property(cache->getNameString()).toString()),
QMetaType::type(parameter.property(cache->getTypeString()).toString().toUtf8().constData()) };
_parameterInfo.append(info);
}
}
}
return _parameterInfo;
}
DerivedNetworkValue::DerivedNetworkValue(const QSharedPointer<NetworkValue>& baseValue, const ScriptHash& parameters) :
_baseValue(baseValue),
_parameters(parameters) {
}
QScriptValue& DerivedNetworkValue::getValue() {
if (!_value.isValid() && _baseValue->isLoaded()) {
RootNetworkValue* root = static_cast<RootNetworkValue*>(_baseValue.data());
ScriptCache* cache = root->getProgram()->getCache();
QScriptValue generator = _baseValue->getValue().property(cache->getGeneratorString());
if (generator.isFunction()) {
QScriptValueList arguments;
foreach (const ParameterInfo& parameter, root->getParameterInfo()) {
arguments.append(cache->getEngine()->newVariant(_parameters.value(parameter.name)));
}
_value = generator.call(QScriptValue(), arguments);
} else {
_value = _baseValue->getValue();
}
}
return _value;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.