text
stringlengths
1
1.05M
; A102394: A wicked odious sequence. ; 0,2,3,0,5,0,0,8,9,0,0,12,0,14,15,0,17,0,0,20,0,22,23,0,0,26,27,0,29,0,0,32,33,0,0,36,0,38,39,0,0,42,43,0,45,0,0,48,0,50,51,0,53,0,0,56,57,0,0,60,0,62,63,0,65,0,0,68,0,70,71,0,0,74,75,0,77,0,0,80,0,82,83,0,85,0 mov $1,$0 add $1,1 mov $3,$0 mov $4,$0 lpb $0 sub $0,1 div $4,2 sub $3,$4 lpe mov $2,$3 mod $2,2 mul $1,$2
;------------------------------------------------------------------------------ ; ; Copyright (c) 2014, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; AsmSaveSecContext.asm ; ; Abstract: ; ; Save Sec Conext before call FspInit API ; ;------------------------------------------------------------------------------ .686p .xmm .model flat,c .code ;---------------------------------------------------------------------------- ; MMX Usage: ; MM0 = BIST State ; MM5 = Save time-stamp counter value high32bit ; MM6 = Save time-stamp counter value low32bit. ; ; It should be same as SecEntry.asm and PeiCoreEntry.asm. ;---------------------------------------------------------------------------- AsmSaveBistValue PROC PUBLIC mov eax, [esp+4] movd mm0, eax ret AsmSaveBistValue ENDP AsmSaveTickerValue PROC PUBLIC mov eax, [esp+4] movd mm6, eax mov eax, [esp+8] movd mm5, eax ret AsmSaveTickerValue ENDP END
; S2E Selective Symbolic Execution Platform ; ; Copyright (c) 2013 Dependable Systems Laboratory, EPFL ; ; 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. .386 ; driver's code start .model flat, stdcall .code public S2EGetVersion S2EGetVersion proc near xor eax, eax db 0fh, 3fh db 00h, 00h, 00h, 00h db 00h, 00h, 00h, 00h ret S2EGetVersion endp .code public S2EGetPathId S2EGetPathId proc near xor eax, eax db 0fh, 3fh db 00h, 05h, 00h, 00h db 00h, 00h, 00h, 00h ret S2EGetPathId endp public S2EGetPathCount S2EGetPathCount proc near xor eax, eax db 0fh, 3fh db 00h, 30h, 00h, 00h db 00h, 00h, 00h, 00h ret S2EGetPathCount endp public S2EIsSymbolic S2EIsSymbolic proc near _Buffer: near ptr dword, _Size: dword mov ecx, _Buffer mov eax, _Size db 0fh, 3fh db 00h, 04h, 00h, 00h db 00h, 00h, 00h, 00h ret 08h S2EIsSymbolic endp public S2EGetExample S2EGetExample proc near _Buffer: near ptr dword, _Size: dword mov eax, _Buffer mov edx, _Size db 0fh, 3fh db 00h, 21h, 00h, 00h db 00h, 00h, 00h, 00h ret 08h S2EGetExample endp public S2EGetRange S2EGetRange proc near _Expr: dword, _Low: near ptr dword, _High: near ptr dword mov eax, _Expr mov ecx, _Low mov edx, _High db 0fh, 3fh db 00h, 34h, 00h, 00h db 00h, 00h, 00h, 00h ret 0ch S2EGetRange endp public S2EGetConstraintCount S2EGetConstraintCount proc near _Expr: dword mov eax, _Expr db 0fh, 3fh db 00h, 35h, 00h, 00h db 00h, 00h, 00h, 00h ret 04h S2EGetConstraintCount endp public S2EConcretize S2EConcretize proc near _Buffer: near ptr dword, _Size: dword mov eax, _Buffer mov edx, _Size db 0fh, 3fh db 00h, 20h, 00h, 00h db 00h, 00h, 00h, 00h ret 08h S2EConcretize endp public S2EMakeSymbolicRaw S2EMakeSymbolicRaw proc near uses ebx, _Buffer: near ptr dword, _Size: dword, _Name: near ptr dword push ebx mov eax, _Buffer mov ebx, _Size mov ecx, _Name db 0fh, 3fh db 00h, 03h, 00h, 00h db 00h, 00h, 00h, 00h pop ebx ret 0ch S2EMakeSymbolicRaw endp public S2EHexDump S2EHexDump proc near uses ebx, _Name: near ptr dword, _Buffer: near ptr dword, _Size: dword push ebx mov eax, _Buffer mov ebx, _Size mov ecx, _Name db 0fh, 3fh db 00h, 36h, 00h, 00h db 00h, 00h, 00h, 00h pop ebx ret 0ch S2EHexDump endp public S2EBeginAtomic S2EBeginAtomic proc near nop db 0fh, 3fh db 00h, 12h, 00h, 00h db 00h, 00h, 00h, 00h ret S2EBeginAtomic endp public S2EEndAtomic S2EEndAtomic proc near nop db 0fh, 3fh db 00h, 13h, 00h, 00h db 00h, 00h, 00h, 00h ret S2EEndAtomic endp public S2EAssume S2EAssume proc near, _Expression: dword mov eax, _Expression db 0fh, 3fh db 00h, 0ch, 00h, 00h db 00h, 00h, 00h, 00h ret 4h S2EAssume endp public S2EMessageRaw S2EMessageRaw proc near, _Message: near ptr dword mov eax, _Message db 0fh, 3fh db 00h, 10h, 00h, 00h db 00h, 00h, 00h, 00h ret 4h S2EMessageRaw endp ;Transmits a buffer of dataSize length to the plugin named in pluginName. ;eax contains the failure code upon return, 0 for success. public S2EInvokePluginRaw S2EInvokePluginRaw proc near, _PluginName: near ptr dword, _UserData: near ptr dword, _DataSize: dword mov eax, _PluginName mov ecx, _UserData mov edx, _DataSize db 0fh, 3fh db 00h, 0bh, 00h, 00h db 00h, 00h, 00h, 00h ret 0ch S2EInvokePluginRaw endp ;Transmits a buffer of dataSize length to the plugin named in pluginName. ;Sets all registers to a concrete value to ensure concrete mode ;eax contains the failure code upon return, 0 for success. public S2EInvokePluginConcreteModeRaw S2EInvokePluginConcreteModeRaw proc near, _PluginName: near ptr dword, _UserData: near ptr dword, _DataSize: dword mov eax, _PluginName mov ecx, _UserData mov edx, _DataSize push ebx push ebp push esi push edi xor ebx, ebx xor ebp, ebp xor esi, esi xor edi, edi ;Clear temp flags db 0fh, 3fh db 00h, 53h, 00h, 00h db 00h, 00h, 00h, 00h jmp __sipcmr ;Ensure switch to concrete mode __sipcmr: db 0fh, 3fh db 00h, 0bh, 00h, 00h db 00h, 00h, 00h, 00h pop edi pop esi pop ebp pop ebx ret 0ch S2EInvokePluginConcreteModeRaw endp ; Add a constraint of the form var == e1 || var == e2 || ... ; The first parameter contains the variable ; The second parameter has the number of passed expressions public S2EAssumeDisjunction S2EAssumeDisjunction proc c, _Variable: dword, _Count: dword, _Expressions: vararg mov eax, _Variable ;Dummy moves to supress unused variable mov eax, _Count mov eax, _Expressions db 0fh, 3fh db 00h, 0dh, 00h, 00h db 00h, 00h, 00h, 00h ret S2EAssumeDisjunction endp public S2EKillState S2EKillState proc near, _Status: near ptr dword, _Message: near ptr dword push ebx mov eax, _Status mov ebx, _Message db 0fh, 3fh db 00h, 06h, 00h, 00h db 00h, 00h, 00h, 00h pop ebx ret 08h S2EKillState endp public S2EPrintExpression S2EPrintExpression proc near, _Expression: near ptr dword, _Name: near ptr dword mov eax, _Expression mov ecx, _Name db 0fh, 3fh db 00h, 07h, 00h, 00h db 00h, 00h, 00h, 00h ret 08h S2EPrintExpression endp public S2EWriteMemory S2EWriteMemory proc near, _Dest: near ptr dword, _Source: near ptr dword, _Size: dword push esi push edi mov esi, _Source mov edi, _Dest mov ecx, _Size db 0fh, 3fh db 00h, 33h, 00h, 00h db 00h, 00h, 00h, 00h pop edi pop esi ret 0ch S2EWriteMemory endp __MergingSearcher db "MergingSearcher", 0 public S2EMergePointCallback S2EMergePointCallback proc near pushfd pusha sub esp, 8 ;Setup the start variable (set to 0) xor eax, eax mov [esp], eax mov [esp+4], eax lea eax, [esp] ;Invoke the merging searcher push 8 ; data size push eax; data pointer push dword ptr __MergingSearcher call S2EInvokePluginConcreteModeRaw call S2EEnableAllApicInterrupts ;Cleanup the mess and return add esp, 8 popa popfd ret S2EMergePointCallback endp public S2EDisableAllApicInterrupts S2EDisableAllApicInterrupts proc near xor eax, eax db 0fh, 3fh db 00h, 51h, 01h, 00h db 00h, 00h, 00h, 00h ret S2EDisableAllApicInterrupts endp public S2EEnableAllApicInterrupts S2EEnableAllApicInterrupts proc near xor eax, eax db 0fh, 3fh db 00h, 51h, 00h, 00h db 00h, 00h, 00h, 00h ret S2EEnableAllApicInterrupts endp end
// // Created by Hamza El-Kebir on 2/20/22. // #include "PandaArmBlock.hpp" namespace ls { namespace blocks { const ::std::array<::std::string, BlockTraits<PandaArmBlock>::kIns> BlockTraits<PandaArmBlock>::inTypes = {demangle(typeid(Eigen::Matrix<double, 7, 1>).name())}; const ::std::array<::std::string, BlockTraits<PandaArmBlock>::kOuts> BlockTraits<PandaArmBlock>::outTypes = {demangle(typeid(PandaState).name())}; const ::std::array<::std::string, BlockTraits<PandaArmBlock>::kPars> BlockTraits<PandaArmBlock>::parTypes = {demangle(typeid(::std::string).name())}; const ::std::array<::std::string, 0> BlockTraits<PandaArmBlock>::templateTypes = {}; } }
; ; Copyright (C) 2008-2020 Advanced Micro Devices, Inc. All rights reserved. ; ; Redistribution and use in source and binary forms, with or without modification, ; are permitted provided that the following conditions are met: ; 1. Redistributions of source code must retain the above copyright notice, ; this list of conditions and the following disclaimer. ; 2. Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; 3. Neither the name of the copyright holder 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 HOLDER 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. ; ; ; vrdacos.asm ; ; An array implementation of the cos libm function. ; ; Prototype: ; ; void vrda_cos(int n, double *x, double *y); ; ;Computes Cosine of x for an array of input values. ;Places the results into the supplied y array. ;Does not perform error checking. ;Denormal inputs may produce unexpected results ;Author: Harsha Jagasia ;Email: harsha.jagasia@amd.com CONST SEGMENT __real_7fffffffffffffff DQ 07fffffffffffffffh ;Sign bit zero DQ 07fffffffffffffffh __real_3ff0000000000000 DQ 03ff0000000000000h ; 1.0 DQ 03ff0000000000000h __real_v2p__27 DQ 03e40000000000000h ; 2p-27 DQ 03e40000000000000h __real_3fe0000000000000 DQ 03fe0000000000000h ; 0.5 DQ 03fe0000000000000h __real_3fc5555555555555 DQ 03fc5555555555555h ; 0.166666666666 DQ 03fc5555555555555h __real_3fe45f306dc9c883 DQ 03fe45f306dc9c883h ; twobypi DQ 03fe45f306dc9c883h __real_3ff921fb54400000 DQ 03ff921fb54400000h ; piby2_1 DQ 03ff921fb54400000h __real_3dd0b4611a626331 DQ 03dd0b4611a626331h ; piby2_1tail DQ 03dd0b4611a626331h __real_3dd0b4611a600000 DQ 03dd0b4611a600000h ; piby2_2 DQ 03dd0b4611a600000h __real_3ba3198a2e037073 DQ 03ba3198a2e037073h ; piby2_2tail DQ 03ba3198a2e037073h __real_fffffffff8000000 DQ 0fffffffff8000000h ; mask for stripping head and tail DQ 0fffffffff8000000h __real_8000000000000000 DQ 08000000000000000h ; -0 or signbit DQ 08000000000000000h __reald_one_one DQ 00000000100000001h ; dq 0 __reald_two_two DQ 00000000200000002h ; dq 0 __reald_one_zero DQ 00000000100000000h ; sin_cos_filter dq 0 __reald_zero_one DQ 00000000000000001h ; dq 0 __reald_two_zero DQ 00000000200000000h ; dq 0 __realq_one_one DQ 00000000000000001h ; DQ 00000000000000001h ; __realq_two_two DQ 00000000000000002h ; DQ 00000000000000002h ; __real_1_x_mask DQ 0ffffffffffffffffh ; DQ 03ff0000000000000h ; __real_zero DQ 00000000000000000h ; DQ 00000000000000000h ; __real_one DQ 00000000000000001h ; DQ 00000000000000001h ; cosarray: DQ 03fa5555555555555h ; 0.0416667 c1 DQ 03fa5555555555555h DQ 0bf56c16c16c16967h ; -0.00138889 c2 DQ 0bf56c16c16c16967h DQ 03efa01a019f4ec90h ; 2.48016e-005 c3 DQ 03efa01a019f4ec90h DQ 0be927e4fa17f65f6h ; -2.75573e-007 c4 DQ 0be927e4fa17f65f6h DQ 03e21eeb69037ab78h ; 2.08761e-009 c5 DQ 03e21eeb69037ab78h DQ 0bda907db46cc5e42h ; -1.13826e-011 c6 DQ 0bda907db46cc5e42h sinarray: DQ 0bfc5555555555555h ; -0.166667 s1 DQ 0bfc5555555555555h DQ 03f81111111110bb3h ; 0.00833333 s2 DQ 03f81111111110bb3h DQ 0bf2a01a019e83e5ch ; -0.000198413 s3 DQ 0bf2a01a019e83e5ch DQ 03ec71de3796cde01h ; 2.75573e-006 s4 DQ 03ec71de3796cde01h DQ 0be5ae600b42fdfa7h ; -2.50511e-008 s5 DQ 0be5ae600b42fdfa7h DQ 03de5e0b2f9a43bb8h ; 1.59181e-010 s6 DQ 03de5e0b2f9a43bb8h sincosarray: DQ 0bfc5555555555555h ; -0.166667 s1 DQ 03fa5555555555555h ; 0.0416667 c1 DQ 03f81111111110bb3h ; 0.00833333 s2 DQ 0bf56c16c16c16967h DQ 0bf2a01a019e83e5ch ; -0.000198413 s3 DQ 03efa01a019f4ec90h DQ 03ec71de3796cde01h ; 2.75573e-006 s4 DQ 0be927e4fa17f65f6h DQ 0be5ae600b42fdfa7h ; -2.50511e-008 s5 DQ 03e21eeb69037ab78h DQ 03de5e0b2f9a43bb8h ; 1.59181e-010 s6 DQ 0bda907db46cc5e42h cossinarray: DQ 03fa5555555555555h ; 0.0416667 c1 DQ 0bfc5555555555555h ; -0.166667 s1 DQ 0bf56c16c16c16967h DQ 03f81111111110bb3h ; 0.00833333 s2 DQ 03efa01a019f4ec90h DQ 0bf2a01a019e83e5ch ; -0.000198413 s3 DQ 0be927e4fa17f65f6h DQ 03ec71de3796cde01h ; 2.75573e-006 s4 DQ 03e21eeb69037ab78h DQ 0be5ae600b42fdfa7h ; -2.50511e-008 s5 DQ 0bda907db46cc5e42h DQ 03de5e0b2f9a43bb8h ; 1.59181e-010 s6 CONST ENDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; define local variable storage offsets p_temp equ 0h ; temporary for get/put bits operation p_temp1 equ 10h ; temporary for get/put bits operation save_xmm6 equ 20h ; temporary for get/put bits operation save_xmm7 equ 30h ; temporary for get/put bits operation save_xmm8 equ 40h ; temporary for get/put bits operation save_xmm9 equ 50h ; temporary for get/put bits operation save_xmm10 equ 60h ; temporary for get/put bits operation save_xmm11 equ 70h ; temporary for get/put bits operation save_xmm12 equ 80h ; temporary for get/put bits operation save_xmm13 equ 90h ; temporary for get/put bits operation save_xmm14 equ 0A0h ; temporary for get/put bits operation save_xmm15 equ 0B0h ; temporary for get/put bits operation save_rdi equ 0C0h save_rsi equ 0D0h r equ 0E0h ; pointer to r for remainder_piby2 rr equ 0F0h ; pointer to r for remainder_piby2 region equ 0100h ; pointer to r for remainder_piby2 r1 equ 0110h ; pointer to r for remainder_piby2 rr1 equ 0120h ; pointer to r for remainder_piby2 region1 equ 0130h ; pointer to r for remainder_piby2 p_temp2 equ 0140h ; temporary for get/put bits operation p_temp3 equ 0150h ; temporary for get/put bits operation p_temp4 equ 0160h ; temporary for get/put bits operation p_temp5 equ 0170h ; temporary for get/put bits operation p_original equ 0180h ; original x p_mask equ 0190h ; original x p_sign equ 01A0h ; original x p_original1 equ 01B0h ; original x p_mask1 equ 01C0h ; original x p_sign1 equ 01D0h ; original x save_xa equ 01E0h ;qword save_ya equ 01F0h ;qword save_nv equ 0200h ;qword p_iter equ 0210h ; qword storage for number of loop iterations stack_size equ 0228h ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; include fm.inc FN_PROTOTYPE_BAS64 vrda_cos EXTRN __amd_remainder_piby2:NEAR .DATA align 8 evencos_oddsin_tbl label qword dq coscos_coscos_piby4 ; 0 * dq coscos_cossin_piby4 ; 1 + dq coscos_sincos_piby4 ; 2 dq coscos_sinsin_piby4 ; 3 + dq cossin_coscos_piby4 ; 4 dq cossin_cossin_piby4 ; 5 * dq cossin_sincos_piby4 ; 6 dq cossin_sinsin_piby4 ; 7 dq sincos_coscos_piby4 ; 8 dq sincos_cossin_piby4 ; 9 dq sincos_sincos_piby4 ; 10 * dq sincos_sinsin_piby4 ; 11 dq sinsin_coscos_piby4 ; 12 dq sinsin_cossin_piby4 ; 13 + dq sinsin_sincos_piby4 ; 14 dq sinsin_sinsin_piby4 ; 15 * ;TEXT SEGMENT page 'CODE' .CODE ; parameters are passed in by Microsoft C as: ; ecx - int n ; rdx - double *x ; r8 - double *y PUBLIC fname fname proc frame cmp ecx ,00h jle L__return cmp rdx ,00h je L__return cmp r8 ,00h je L__return sub rsp,stack_size .ALLOCSTACK stack_size ; unwind data, needed since we call ; remainder_piby2 and could have exceptions ; but it costs no performance to include it. movdqa OWORD PTR [rsp+save_xmm6],xmm6 ; save xmm6 .SAVEXMM128 xmm6, 020h movdqa OWORD PTR [rsp+save_xmm7],xmm7 ; save xmm7 .SAVEXMM128 xmm7, 030h movdqa OWORD PTR [rsp+save_xmm8],xmm8 ; save xmm8 .SAVEXMM128 xmm8, 040h movdqa OWORD PTR [rsp+save_xmm9],xmm9 ; save xmm9 .SAVEXMM128 xmm9, 050h movdqa OWORD PTR [rsp+save_xmm10],xmm10 ; save xmm10 .SAVEXMM128 xmm10, 060h movdqa OWORD PTR [rsp+save_xmm11],xmm11 ; save xmm11 .SAVEXMM128 xmm11, 070h movdqa OWORD PTR [rsp+save_xmm12],xmm12 ; save xmm12 .SAVEXMM128 xmm12, 080h movdqa OWORD PTR [rsp+save_xmm13],xmm13 ; save xmm13 .SAVEXMM128 xmm13, 090h mov QWORD PTR [rsp+save_rsi],rsi ; save rsi .SAVEREG rsi, save_rsi mov QWORD PTR [rsp+save_rdi],rdi ; save rdi .SAVEREG rdi, save_rdi .ENDPROLOG ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;START PROCESS INPUT ; save the arguments mov QWORD PTR [rsp+save_xa],rdx ; save x_array pointer mov QWORD PTR [rsp+save_ya],r8 ; save y_array pointer mov rax,rcx mov QWORD PTR [rsp+save_nv],rcx ; save number of values ; see if too few values to call the main loop shr rax,2 ; get number of iterations jz __vrda_cleanup ; jump if only single calls ; prepare the iteration counts mov QWORD PTR [rsp+p_iter],rax ; save number of iterations shl rax,2 sub rcx,rax ; compute number of extra single calls mov QWORD PTR [rsp+save_nv],rcx ; save number of left over values ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;START LOOP align 16 __vrda_top: ; build the input _m128d movapd xmm2, OWORD PTR __real_7fffffffffffffff mov rsi,QWORD PTR [rsp+save_xa] ; get x_array pointer movlpd xmm0,QWORD PTR [rsi] movhpd xmm0,QWORD PTR [rsi+8] prefetch QWORD PTR [rsi+64] add rsi,32 mov QWORD PTR [rsp+save_xa],rsi ; save x_array pointer movdqa OWORD PTR p_original[rsp], xmm0 movlpd xmm1,QWORD PTR [rsi-16] movhpd xmm1,QWORD PTR [rsi-8] movdqa OWORD PTR p_original1[rsp], xmm1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;STARTMAIN ;movapd xmm2, OWORD PTR __real_7fffffffffffffff ;moved above ;movdqa OWORD PTR p_original[rsp], xmm0 ;moved above ;movdqa OWORD PTR p_original1[rsp], xmm1 andpd xmm0, xmm2 ;Unsign andpd xmm1, xmm2 ;Unsign movd rax, xmm0 ;rax is lower arg movhpd QWORD PTR p_temp[rsp+8], xmm0 ; mov rcx, QWORD PTR p_temp[rsp+8] ;rcx = upper arg movd r8, xmm1 ;rax is lower arg movhpd QWORD PTR p_temp1[rsp+8], xmm1 ; mov r9, QWORD PTR p_temp1[rsp+8] ;rcx = upper arg mov rdx, 3FE921FB54442D18h ;piby4 + mov r10, 411E848000000000h ;5e5 + movapd xmm4, OWORD PTR __real_3fe0000000000000 ;0.5 for later use movapd xmm2, xmm0 ;x0 movapd xmm3, xmm1 ;x1 movapd xmm6, xmm0 ;x0 movapd xmm7, xmm1 ;x1 ;DEBUG ; movapd xmm4, xmm0 ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; xmm2 = x, xmm4 =0.5/t, xmm6 =x ; xmm3 = x, xmm5 =0.5/t, xmm7 =x align 16 either_or_both_arg_gt_than_piby4: cmp rax, r10 jae first_or_next3_arg_gt_5e5 cmp rcx, r10 jae second_or_next2_arg_gt_5e5 cmp r8, r10 jae third_or_fourth_arg_gt_5e5 cmp r9, r10 jae fourth_arg_gt_5e5 ; /* Find out what multiple of piby2 */ ; npi2 = (int)(x * twobypi + 0.5); movapd xmm0, XMMWORD PTR __real_3fe45f306dc9c883 mulpd xmm2, xmm0 ; * twobypi mulpd xmm3, xmm0 ; * twobypi addpd xmm2,xmm4 ; +0.5, npi2 addpd xmm3,xmm4 ; +0.5, npi2 movapd xmm0,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 movapd xmm1,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm4,xmm2 ; convert packed double to packed integers cvttpd2dq xmm5,xmm3 ; convert packed double to packed integers movapd xmm8,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 movapd xmm9,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm2,xmm4 ; and back to double. cvtdq2pd xmm3,xmm5 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd rax, xmm4 ; Region movd rcx, xmm5 ; Region mov r8, rax mov r9, rcx ; rhead = x - npi2 * piby2_1; mulpd xmm0,xmm2 ; npi2 * piby2_1; mulpd xmm1,xmm3 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm8,xmm2 ; rtail mulpd xmm9,xmm3 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm6,xmm0 ; rhead = x - npi2 * piby2_1; subpd xmm7,xmm1 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm0, xmm6 ; t movapd xmm1, xmm7 ; t ; rhead = t - rtail; subpd xmm0, xmm8 ; rhead subpd xmm1, xmm9 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm2,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail mulpd xmm3,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm6,xmm0 ; t-rhead subpd xmm7,xmm1 ; t-rhead subpd xmm8,xmm6 ; - ((t - rhead) - rtail) subpd xmm9,xmm7 ; - ((t - rhead) - rtail) addpd xmm8,xmm2 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); addpd xmm9,xmm3 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; xmm4 = npi2 (int), xmm0 =rhead, xmm8 =rtail ; xmm5 = npi2 (int), xmm1 =rhead, xmm9 =rtail ; paddd xmm4, XMMWORD PTR __reald_one_one ; Sign ; paddd xmm5, XMMWORD PTR __reald_one_one ; Sign ; pand xmm4, XMMWORD PTR __reald_two_two ; pand xmm5, XMMWORD PTR __reald_two_two ; punpckldq xmm4, xmm4 ; punpckldq xmm5, xmm5 ; psllq xmm4, 62 ; psllq xmm5, 62 add r8, QWORD PTR __reald_one_one add r9, QWORD PTR __reald_one_one and r8, QWORD PTR __reald_two_two and r9, QWORD PTR __reald_two_two mov r10, r8 mov r11, r9 shl r8, 62 and r10,QWORD PTR __reald_two_zero shl r10, 30 shl r9, 62 and r11,QWORD PTR __reald_two_zero shl r11, 30 mov QWORD PTR p_sign[rsp], r8 mov QWORD PTR p_sign[rsp+8],r10 mov QWORD PTR p_sign1[rsp], r9 mov QWORD PTR p_sign1[rsp+8],r11 ; GET_BITS_DP64(rhead-rtail, uy); ; originally only rhead ; xmm4 = Sign, xmm0 =rhead, xmm8 =rtail ; xmm5 = Sign, xmm1 =rhead, xmm9 =rtail movapd xmm6,xmm0 ; rhead movapd xmm7,xmm1 ; rhead and rax, QWORD PTR __reald_one_one ; Region and rcx, QWORD PTR __reald_one_one ; Region subpd xmm0,xmm8 ; r = rhead - rtail subpd xmm1,xmm9 ; r = rhead - rtail ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; xmm4 = Sign, xmm0 = r, xmm6 =rhead, xmm8 =rtail ; xmm5 = Sign, xmm1 = r, xmm7 =rhead, xmm9 =rtail subpd xmm6, xmm0 ;rr=rhead-r subpd xmm7, xmm1 ;rr=rhead-r mov r8, rax mov r9, rcx movapd xmm2,xmm0 movapd xmm3,xmm1 mulpd xmm2,xmm0 ; r2 mulpd xmm3,xmm1 ; r2 subpd xmm6, xmm8 ;rr=(rhead-r) -rtail subpd xmm7, xmm9 ;rr=(rhead-r) -rtail and rax, QWORD PTR __reald_zero_one and rcx, QWORD PTR __reald_zero_one shr r8, 31 shr r9, 31 or rax, r8 or rcx, r9 shl rcx, 2 or rax, rcx lea rcx, QWORD PTR evencos_oddsin_tbl jmp QWORD PTR [rcx + rax*8] ;Jmp table for cos/sin calculation based on even/odd region ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 first_or_next3_arg_gt_5e5: ; rax, rcx, r8, r9 ;DEBUG ; movapd xmm4, xmm0 ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG cmp rcx, r10 ;is upper arg >= 5e5 jae both_arg_gt_5e5 lower_arg_gt_5e5: ; Upper Arg is < 5e5, Lower arg is >= 5e5 ; xmm0, xmm2, xmm6 = x, xmm4 = 0.5 ; Be sure not to use xmm1, xmm3 and xmm7 ; Use xmm5, xmm8, xmm10, xmm12 ; xmm9, xmm11, xmm13 ;DEBUG ; movapd xmm4, xmm0 ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG movlpd QWORD PTR r[rsp], xmm0 ;Save lower fp arg for remainder_piby2 call movhlps xmm0, xmm0 ;Needed since we want to work on upper arg movhlps xmm2, xmm2 movhlps xmm6, xmm6 ; Work on Upper arg ; Lower arg might contain nan/inf, to avoid exception use only scalar instructions on upper arg which has been moved to lower portions of fp regs mulsd xmm2,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm2,xmm4 ; xmm2 = npi2=(x*twobypi+0.5) movsd xmm8,QWORD PTR __real_3ff921fb54400000 ; xmm8 = piby2_1 cvttsd2si ecx,xmm2 ; ecx = npi2 trunc to ints movsd xmm10,QWORD PTR __real_3dd0b4611a600000 ; xmm10 = piby2_2 cvtsi2sd xmm2,ecx ; xmm2 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm8,xmm2 ; npi2 * piby2_1 subsd xmm6,xmm8 ; xmm6 = rhead =(x-npi2*piby2_1) movsd xmm12,QWORD PTR __real_3ba3198a2e037073 ; xmm12 =piby2_2tail ;t = rhead; movsd xmm5, xmm6 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm10,xmm2 ; xmm1 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm6, xmm10 ; xmm6 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm12,xmm2 ; npi2 * piby2_2tail subsd xmm5,xmm6 ; t-rhead subsd xmm10,xmm5 ; (rtail-(t-rhead)) addsd xmm10,xmm12 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region[rsp+4], ecx ; store upper region movsd xmm0,xmm6 subsd xmm0,xmm10 ; xmm0 = r=(rhead-rtail) subsd xmm6, xmm0 ; rr=rhead-r subsd xmm6, xmm10 ; xmm6 = rr=((rhead-r) -rtail) movlpd QWORD PTR r[rsp+8], xmm0 ; store upper r movlpd QWORD PTR rr[rsp+8], xmm6 ; store upper rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Note that volatiles will be trashed by the call ;We will construct r, rr, region and sign ; Work on Lower arg mov r11,07ff0000000000000h ; is lower arg nan/inf mov r10,r11 and r10,rax cmp r10,r11 jz __vrd4_cos_lower_naninf mov QWORD PTR p_temp[rsp], r8 mov QWORD PTR p_temp2[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 lea r9, QWORD PTR region[rsp] ; lower arg is **NOT** nan/inf lea r8, QWORD PTR rr[rsp] lea rdx, QWORD PTR r[rsp] movlpd xmm0, QWORD PTR r[rsp] ;Restore lower fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp[rsp] mov r9, QWORD PTR p_temp2[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7,OWORD PTR p_temp5[rsp] jmp @F __vrd4_cos_lower_naninf: mov rax, QWORD PTR p_original[rsp] ; upper arg is nan/inf mov r11,00008000000000000h or rax,r11 mov QWORD PTR r[rsp],rax ; r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr[rsp], r10 ; rr = 0 mov DWORD PTR region[rsp], r10d ; region =0 align 16 @@: ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG jmp check_next2_args ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 both_arg_gt_5e5: ;Upper Arg is >= 5e5, Lower arg is >= 5e5 ; rax, rcx, r8, r9 ; xmm0, xmm2, xmm6 = x, xmm4 = 0.5 ;DEBUG ; movapd xmm4, xmm0 ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG movhlps xmm6, xmm0 ;Save upper fp arg for remainder_piby2 call mov r11,07ff0000000000000h ;is lower arg nan/inf mov r10,r11 and r10,rax cmp r10,r11 jz __vrd4_cos_lower_naninf_of_both_gt_5e5 mov QWORD PTR p_temp[rsp], rcx ;Save upper arg mov QWORD PTR p_temp2[rsp], r8 mov QWORD PTR p_temp4[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 lea r9, QWORD PTR region[rsp] ;lower arg is **NOT** nan/inf lea r8, QWORD PTR rr[rsp] lea rdx, QWORD PTR r[rsp] ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h mov rcx, QWORD PTR p_temp[rsp] ;Restore upper arg mov r8, QWORD PTR p_temp2[rsp] mov r9, QWORD PTR p_temp4[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7,OWORD PTR p_temp5[rsp] jmp @F __vrd4_cos_lower_naninf_of_both_gt_5e5: ;lower arg is nan/inf mov rax, QWORD PTR p_original[rsp] mov r11,00008000000000000h or rax,r11 mov QWORD PTR r[rsp],rax ;r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr[rsp], r10 ;rr = 0 mov DWORD PTR region[rsp], r10d ;region = 0 align 16 @@: mov r11,07ff0000000000000h ;is upper arg nan/inf mov r10,r11 and r10,rcx cmp r10,r11 jz __vrd4_cos_upper_naninf_of_both_gt_5e5 mov QWORD PTR p_temp[rsp], r8 mov QWORD PTR p_temp2[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 lea r9, QWORD PTR region[rsp+4] ;upper arg is **NOT** nan/inf lea r8, QWORD PTR rr[rsp+8] lea rdx, QWORD PTR r[rsp+8] movapd xmm0, xmm6 ;Restore upper fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp[rsp] mov r9, QWORD PTR p_temp2[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7,OWORD PTR p_temp5[rsp] jmp @F __vrd4_cos_upper_naninf_of_both_gt_5e5: mov rcx, QWORD PTR p_original[rsp+8] ;upper arg is nan/inf ; movd rcx, xmm6 ;upper arg is nan/inf mov r11,00008000000000000h or rcx,r11 mov QWORD PTR r[rsp+8],rcx ;r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr[rsp+8], r10 ;rr = 0 mov DWORD PTR region[rsp+4], r10d ;region = 0 align 16 @@: jmp check_next2_args ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 second_or_next2_arg_gt_5e5: ; Upper Arg is >= 5e5, Lower arg is < 5e5 ; rax, rcx, r8, r9 ; xmm0, xmm2, xmm6 = x, xmm4 = 0.5 ; Do not use xmm1, xmm3, xmm7 ; Restore xmm4 and xmm1, xmm3, xmm7 ; Can use xmm8, xmm10, xmm12 ; xmm5, xmm9, xmm11, xmm13 movhpd QWORD PTR r[rsp+8], xmm0 ;Save upper fp arg for remainder_piby2 call ; movlhps xmm0, xmm0 ;Not needed since we want to work on lower arg, but done just to be safe and avoide exceptions due to nan/inf and to mirror the lower_arg_gt_5e5 case ; movlhps xmm2, xmm2 ; movlhps xmm6, xmm6 ; Work on Lower arg ; Upper arg might contain nan/inf, to avoid exception use only scalar instructions on lower arg mulsd xmm2,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm2,xmm4 ; xmm2 = npi2=(x*twobypi+0.5) movsd xmm8,QWORD PTR __real_3ff921fb54400000 ; xmm3 = piby2_1 cvttsd2si eax,xmm2 ; ecx = npi2 trunc to ints movsd xmm10,QWORD PTR __real_3dd0b4611a600000 ; xmm1 = piby2_2 cvtsi2sd xmm2,eax ; xmm2 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm8,xmm2 ; npi2 * piby2_1 subsd xmm6,xmm8 ; xmm6 = rhead =(x-npi2*piby2_1) movsd xmm12,QWORD PTR __real_3ba3198a2e037073 ; xmm7 =piby2_2tail ;t = rhead; movsd xmm5, xmm6 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm10,xmm2 ; xmm1 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm6, xmm10 ; xmm6 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm12,xmm2 ; npi2 * piby2_2tail subsd xmm5,xmm6 ; t-rhead subsd xmm10,xmm5 ; (rtail-(t-rhead)) addsd xmm10,xmm12 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region[rsp], eax ; store upper region movsd xmm0,xmm6 subsd xmm0,xmm10 ; xmm0 = r=(rhead-rtail) subsd xmm6, xmm0 ; rr=rhead-r subsd xmm6, xmm10 ; xmm6 = rr=((rhead-r) -rtail) movlpd QWORD PTR r[rsp], xmm0 ; store upper r movlpd QWORD PTR rr[rsp], xmm6 ; store upper rr ;Work on Upper arg ;Note that volatiles will be trashed by the call ;We do not care since this is the last check ;We will construct r, rr, region and sign mov r11,07ff0000000000000h ; is upper arg nan/inf mov r10,r11 and r10,rcx cmp r10,r11 jz __vrd4_cos_upper_naninf mov QWORD PTR p_temp[rsp], r8 mov QWORD PTR p_temp2[rsp], r9 movapd OWORD PTR p_temp1[rsp], xmm1 movapd OWORD PTR p_temp3[rsp], xmm3 movapd OWORD PTR p_temp5[rsp], xmm7 lea r9, QWORD PTR region[rsp+4] ; upper arg is **NOT** nan/inf lea r8, QWORD PTR rr[rsp+8] lea rdx, QWORD PTR r[rsp+8] movlpd xmm0, QWORD PTR r[rsp+8] ;Restore upper fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h mov r8, QWORD PTR p_temp[rsp] mov r9, QWORD PTR p_temp2[rsp] movapd xmm1, OWORD PTR p_temp1[rsp] movapd xmm3, OWORD PTR p_temp3[rsp] movapd xmm7, OWORD PTR p_temp5[rsp] jmp @F __vrd4_cos_upper_naninf: mov rcx, QWORD PTR p_original[rsp+8] ; upper arg is nan/inf ; mov rcx, QWORD PTR r[rsp+8] ; upper arg is nan/inf mov r11,00008000000000000h or rcx,r11 mov QWORD PTR r[rsp+8],rcx ; r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr[rsp+8], r10 ; rr = 0 mov DWORD PTR region[rsp+4], r10d ; region =0 align 16 @@: jmp check_next2_args ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 check_next2_args: ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG mov r10, 411E848000000000h ;5e5 + cmp r8, r10 jae first_second_done_third_or_fourth_arg_gt_5e5 cmp r9, r10 jae first_second_done_fourth_arg_gt_5e5 ; Work on next two args, both < 5e5 ; xmm1, xmm3, xmm5 = x, xmm4 = 0.5 movapd xmm4, OWORD PTR __real_3fe0000000000000 ; Restore 0.5 mulpd xmm3, XMMWORD PTR __real_3fe45f306dc9c883 ; * twobypi addpd xmm3,xmm4 ; +0.5, npi2 movapd xmm1,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm5,xmm3 ; convert packed double to packed integers movapd xmm9,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm3,xmm5 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd QWORD PTR region1[rsp], xmm5 ; Region ; rhead = x - npi2 * piby2_1; mulpd xmm1,xmm3 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm9,xmm3 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm7,xmm1 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm1, xmm7 ; t ; rhead = t - rtail; subpd xmm1, xmm9 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm3,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm7,xmm1 ; t-rhead subpd xmm9,xmm7 ; - ((t - rhead) - rtail) addpd xmm9,xmm3 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); movapd xmm7,xmm1 ; rhead subpd xmm1,xmm9 ; r = rhead - rtail movapd OWORD PTR r1[rsp], xmm1 subpd xmm7, xmm1 ; rr=rhead-r subpd xmm7, xmm9 ; rr=(rhead-r) -rtail movapd OWORD PTR rr1[rsp], xmm7 jmp __vrd4_cos_reconstruct ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 third_or_fourth_arg_gt_5e5: ;first two args are < 5e5, third arg >= 5e5, fourth arg >= 5e5 or < 5e5 ; rax, rcx, r8, r9 ; xmm0, xmm2, xmm6 = x, xmm4 = 0.5 ; Do not use xmm1, xmm3, xmm7 ; Can use xmm9, xmm11, xmm13 ; xmm5, xmm8, xmm10, xmm12 ; Restore xmm4 ; Work on first two args, both < 5e5 mulpd xmm2, XMMWORD PTR __real_3fe45f306dc9c883 ; * twobypi addpd xmm2,xmm4 ; +0.5, npi2 movapd xmm0,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm4,xmm2 ; convert packed double to packed integers movapd xmm8,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm2,xmm4 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd QWORD PTR region[rsp], xmm4 ; Region ; rhead = x - npi2 * piby2_1; mulpd xmm0,xmm2 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm8,xmm2 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm6,xmm0 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm0, xmm6 ; t ; rhead = t - rtail; subpd xmm0, xmm8 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm2,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm6,xmm0 ; t-rhead subpd xmm8,xmm6 ; - ((t - rhead) - rtail) addpd xmm8,xmm2 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); movapd xmm6,xmm0 ; rhead subpd xmm0,xmm8 ; r = rhead - rtail movapd OWORD PTR r[rsp], xmm0 subpd xmm6, xmm0 ; rr=rhead-r subpd xmm6, xmm8 ; rr=(rhead-r) -rtail movapd OWORD PTR rr[rsp], xmm6 ; Work on next two args, third arg >= 5e5, fourth arg >= 5e5 or < 5e5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; first_second_done_third_or_fourth_arg_gt_5e5: ; rax, rcx, r8, r9 ; xmm0, xmm2, xmm6 = x, xmm4 = 0.5 ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, xmm1 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG mov r10, 411E848000000000h ;5e5 + cmp r9, r10 jae both_arg_gt_5e5_higher ; Upper Arg is <5e5, Lower arg is >= 5e5 ; r8, r9 ; xmm1, xmm3, xmm7 = x, xmm4 = 0.5 movlpd QWORD PTR r1[rsp], xmm1 ;Save lower fp arg for remainder_piby2 call movhlps xmm1, xmm1 ;Needed since we want to work on upper arg movhlps xmm3, xmm3 movhlps xmm7, xmm7 movapd xmm4, OWORD PTR __real_3fe0000000000000 ;0.5 for later use ; Work on Upper arg ; Lower arg might contain nan/inf, to avoid exception use only scalar instructions on upper arg which has been moved to lower portions of fp regs mulsd xmm3,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm3,xmm4 ; xmm3 = npi2=(x*twobypi+0.5) movsd xmm2,QWORD PTR __real_3ff921fb54400000 ; xmm2 = piby2_1 cvttsd2si r9d,xmm3 ; r9d = npi2 trunc to ints movsd xmm0,QWORD PTR __real_3dd0b4611a600000 ; xmm0 = piby2_2 cvtsi2sd xmm3,r9d ; xmm3 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm2,xmm3 ; npi2 * piby2_1 subsd xmm7,xmm2 ; xmm7 = rhead =(x-npi2*piby2_1) movsd xmm6,QWORD PTR __real_3ba3198a2e037073 ; xmm6 =piby2_2tail ;t = rhead; movsd xmm5, xmm7 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm0,xmm3 ; xmm0 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm7, xmm0 ; xmm7 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm6,xmm3 ; npi2 * piby2_2tail subsd xmm5,xmm7 ; t-rhead subsd xmm0,xmm5 ; (rtail-(t-rhead)) addsd xmm0,xmm6 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region1[rsp+4], r9d ; store upper region movsd xmm1,xmm7 subsd xmm1,xmm0 ; xmm1 = r=(rhead-rtail) subsd xmm7, xmm1 ; rr=rhead-r subsd xmm7, xmm0 ; xmm7 = rr=((rhead-r) -rtail) movlpd QWORD PTR r1[rsp+8], xmm1 ; store upper r movlpd QWORD PTR rr1[rsp+8], xmm7 ; store upper rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Note that volatiles will be trashed by the call ;We do not care since this is the last check ;We will construct r, rr, region and sign ; Work on Lower arg mov r11,07ff0000000000000h ; is lower arg nan/inf mov r10,r11 and r10,r8 cmp r10,r11 jz __vrd4_cos_lower_naninf_higher lea r9, QWORD PTR region1[rsp] ; lower arg is **NOT** nan/inf lea r8, QWORD PTR rr1[rsp] lea rdx, QWORD PTR r1[rsp] movlpd xmm0, QWORD PTR r1[rsp] ;Restore lower fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h jmp @F __vrd4_cos_lower_naninf_higher: mov r8, QWORD PTR p_original1[rsp] ; upper arg is nan/inf mov r11,00008000000000000h or r8,r11 mov QWORD PTR r1[rsp],r8 ; r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr1[rsp], r10 ; rr = 0 mov DWORD PTR region1[rsp], r10d ; region =0 align 16 @@: jmp __vrd4_cos_reconstruct align 16 both_arg_gt_5e5_higher: ; Upper Arg is >= 5e5, Lower arg is >= 5e5 ; r8, r9 ; xmm1, xmm3, xmm7 = x, xmm4 = 0.5 ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movd xmm5, r8 ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG movhlps xmm7, xmm1 ;Save upper fp arg for remainder_piby2 call mov r11,07ff0000000000000h ;is lower arg nan/inf mov r10,r11 and r10,r8 cmp r10,r11 jz __vrd4_cos_lower_naninf_of_both_gt_5e5_higher mov QWORD PTR p_temp1[rsp], r9 ;Save upper arg lea r9, QWORD PTR region1[rsp] ;lower arg is **NOT** nan/inf lea r8, QWORD PTR rr1[rsp] lea rdx, QWORD PTR r1[rsp] movapd xmm0, xmm1 ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h mov r9, QWORD PTR p_temp1[rsp] ;Restore upper arg ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; mov QWORD PTR r1[rsp+8], r9 ; movapd xmm5, OWORD PTR r1[rsp] ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG jmp @F __vrd4_cos_lower_naninf_of_both_gt_5e5_higher: ;lower arg is nan/inf mov r8, QWORD PTR p_original1[rsp] mov r11,00008000000000000h or r8,r11 mov QWORD PTR r1[rsp],r8 ;r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr1[rsp], r10 ;rr = 0 mov DWORD PTR region1[rsp], r10d ;region = 0 align 16 @@: mov r11,07ff0000000000000h ;is upper arg nan/inf mov r10,r11 and r10,r9 cmp r10,r11 jz __vrd4_cos_upper_naninf_of_both_gt_5e5_higher lea r9, QWORD PTR region1[rsp+4] ;upper arg is **NOT** nan/inf lea r8, QWORD PTR rr1[rsp+8] lea rdx, QWORD PTR r1[rsp+8] movapd xmm0, xmm7 ;Restore upper fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h jmp @F __vrd4_cos_upper_naninf_of_both_gt_5e5_higher: mov r9, QWORD PTR p_original1[rsp+8] ;upper arg is nan/inf ; movd r9, xmm6 ;upper arg is nan/inf mov r11,00008000000000000h or r9,r11 mov QWORD PTR r1[rsp+8],r9 ;r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr1[rsp+8], r10 ;rr = 0 mov DWORD PTR region1[rsp+4], r10d ;region = 0 align 16 @@: ;DEBUG ; movapd xmm4, OWORD PTR r[rsp] ; movapd xmm5, OWORD PTR r1[rsp] ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG jmp __vrd4_cos_reconstruct ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 fourth_arg_gt_5e5: ;first two args are < 5e5, third arg < 5e5, fourth arg >= 5e5 ;rax, rcx, r8, r9 ;xmm0, xmm2, xmm6 = x, xmm4 = 0.5 ; Work on first two args, both < 5e5 mulpd xmm2, XMMWORD PTR __real_3fe45f306dc9c883 ; * twobypi addpd xmm2,xmm4 ; +0.5, npi2 movapd xmm0,XMMWORD PTR __real_3ff921fb54400000 ; piby2_1 cvttpd2dq xmm4,xmm2 ; convert packed double to packed integers movapd xmm8,XMMWORD PTR __real_3dd0b4611a600000 ; piby2_2 cvtdq2pd xmm2,xmm4 ; and back to double. ; /* Subtract the multiple from x to get an extra-precision remainder */ movd QWORD PTR region[rsp], xmm4 ; Region ; rhead = x - npi2 * piby2_1; mulpd xmm0,xmm2 ; npi2 * piby2_1; ; rtail = npi2 * piby2_2; mulpd xmm8,xmm2 ; rtail ; rhead = x - npi2 * piby2_1; subpd xmm6,xmm0 ; rhead = x - npi2 * piby2_1; ; t = rhead; movapd xmm0, xmm6 ; t ; rhead = t - rtail; subpd xmm0, xmm8 ; rhead ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulpd xmm2,XMMWORD PTR __real_3ba3198a2e037073 ; npi2 * piby2_2tail subpd xmm6,xmm0 ; t-rhead subpd xmm8,xmm6 ; - ((t - rhead) - rtail) addpd xmm8,xmm2 ; rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); movapd xmm6,xmm0 ; rhead subpd xmm0,xmm8 ; r = rhead - rtail movapd OWORD PTR r[rsp], xmm0 subpd xmm6, xmm0 ; rr=rhead-r subpd xmm6, xmm8 ; rr=(rhead-r) -rtail movapd OWORD PTR rr[rsp], xmm6 ; Work on next two args, third arg < 5e5, fourth arg >= 5e5 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; first_second_done_fourth_arg_gt_5e5: ; Upper Arg is >= 5e5, Lower arg is < 5e5 ; r8, r9 ; xmm1, xmm3, xmm7 = x, xmm4 = 0.5 movhpd QWORD PTR r1[rsp+8], xmm1 ;Save upper fp arg for remainder_piby2 call ; movlhps xmm1, xmm1 ;Not needed since we want to work on lower arg, but done just to be safe and avoide exceptions due to nan/inf and to mirror the lower_arg_gt_5e5 case ; movlhps xmm3, xmm3 ; movlhps xmm7, xmm7 movapd xmm4, OWORD PTR __real_3fe0000000000000 ;0.5 for later use ; Work on Lower arg ; Upper arg might contain nan/inf, to avoid exception use only scalar instructions on lower arg mulsd xmm3,QWORD PTR __real_3fe45f306dc9c883 ; x*twobypi addsd xmm3,xmm4 ; xmm3 = npi2=(x*twobypi+0.5) movsd xmm2,QWORD PTR __real_3ff921fb54400000 ; xmm2 = piby2_1 cvttsd2si r8d,xmm3 ; r8d = npi2 trunc to ints movsd xmm0,QWORD PTR __real_3dd0b4611a600000 ; xmm0 = piby2_2 cvtsi2sd xmm3,r8d ; xmm3 = npi2 trunc to doubles ;/* Subtract the multiple from x to get an extra-precision remainder */ ;rhead = x - npi2 * piby2_1; mulsd xmm2,xmm3 ; npi2 * piby2_1 subsd xmm7,xmm2 ; xmm7 = rhead =(x-npi2*piby2_1) movsd xmm6,QWORD PTR __real_3ba3198a2e037073 ; xmm6 =piby2_2tail ;t = rhead; movsd xmm5, xmm7 ; xmm5 = t = rhead ;rtail = npi2 * piby2_2; mulsd xmm0,xmm3 ; xmm0 =rtail=(npi2*piby2_2) ;rhead = t - rtail subsd xmm7, xmm0 ; xmm7 =rhead=(t-rtail) ;rtail = npi2 * piby2_2tail - ((t - rhead) - rtail); mulsd xmm6,xmm3 ; npi2 * piby2_2tail subsd xmm5,xmm7 ; t-rhead subsd xmm0,xmm5 ; (rtail-(t-rhead)) addsd xmm0,xmm6 ; rtail=npi2*piby2_2tail+(rtail-(t-rhead)); ;r = rhead - rtail ;rr = (rhead-r) -rtail mov DWORD PTR region1[rsp], r8d ; store lower region movsd xmm1, xmm7 subsd xmm1, xmm0 ; xmm0 = r=(rhead-rtail) subsd xmm7, xmm1 ; rr=rhead-r subsd xmm7, xmm0 ; xmm6 = rr=((rhead-r) -rtail) movlpd QWORD PTR r1[rsp], xmm1 ; store upper r movlpd QWORD PTR rr1[rsp], xmm7 ; store upper rr ;Work on Upper arg ;Note that volatiles will be trashed by the call ;We do not care since this is the last check ;We will construct r, rr, region and sign mov r11,07ff0000000000000h ; is upper arg nan/inf mov r10,r11 and r10,r9 cmp r10,r11 jz __vrd4_cos_upper_naninf_higher lea r9, QWORD PTR region1[rsp+4] ; upper arg is **NOT** nan/inf lea r8, QWORD PTR rr1[rsp+8] lea rdx, QWORD PTR r1[rsp+8] movlpd xmm0, QWORD PTR r1[rsp+8] ;Restore upper fp arg for remainder_piby2 call ;change to MS ABI - shadow space sub rsp,020h call __amd_remainder_piby2 ;change to MS ABI - shadow space add rsp,020h jmp @F __vrd4_cos_upper_naninf_higher: mov r9, QWORD PTR p_original1[rsp+8] ; upper arg is nan/inf ; mov r9, QWORD PTR r1[rsp+8] ; upper arg is nan/inf mov r11,00008000000000000h or r9,r11 mov QWORD PTR r1[rsp+8],r9 ; r = x | 0x0008000000000000 xor r10, r10 mov QWORD PTR rr1[rsp+8], r10 ; rr = 0 mov DWORD PTR region1[rsp+4], r10d ; region =0 align 16 @@: jmp __vrd4_cos_reconstruct ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 __vrd4_cos_reconstruct: ;Results ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;DEBUG ; movapd xmm4, OWORD PTR region[rsp] ; movapd xmm5, OWORD PTR region1[rsp] ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG movapd xmm0, OWORD PTR r[rsp] movapd xmm1, OWORD PTR r1[rsp] movapd xmm6, OWORD PTR rr[rsp] movapd xmm7, OWORD PTR rr1[rsp] mov rax,QWORD PTR region[rsp] mov rcx,QWORD PTR region1[rsp] mov r8, rax mov r9, rcx add r8, QWORD PTR __reald_one_one add r9, QWORD PTR __reald_one_one and r8, QWORD PTR __reald_two_two and r9, QWORD PTR __reald_two_two mov r10, r8 mov r11, r9 shl r8, 62 and r10,QWORD PTR __reald_two_zero shl r10, 30 shl r9, 62 and r11,QWORD PTR __reald_two_zero shl r11, 30 mov QWORD PTR p_sign[rsp], r8 mov QWORD PTR p_sign[rsp+8],r10 mov QWORD PTR p_sign1[rsp], r9 mov QWORD PTR p_sign1[rsp+8],r11 and rax, QWORD PTR __reald_one_one ; Region and rcx, QWORD PTR __reald_one_one ; Region mov r8, rax mov r9, rcx movapd xmm2,xmm0 movapd xmm3,xmm1 mulpd xmm2,xmm0 ; r2 mulpd xmm3,xmm1 ; r2 and rax, QWORD PTR __reald_zero_one and rcx, QWORD PTR __reald_zero_one shr r8, 31 shr r9, 31 or rax, r8 or rcx, r9 shl rcx, 2 or rax, rcx ;DEBUG ; movd xmm4, rax ; movd xmm5, rax ; xorpd xmm0, xmm0 ; xorpd xmm1, xmm1 ; jmp __vrda_cos_cleanup ;DEBUG lea rcx, QWORD PTR evencos_oddsin_tbl jmp QWORD PTR [rcx + rax*8] ;Jmp table for cos/sin calculation based on even/odd region ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 PUBLIC __vrda_cos_cleanup __vrda_cos_cleanup:: movapd xmm0, p_sign[rsp] movapd xmm1, p_sign1[rsp] xorpd xmm0, xmm4 ; (+) Sign xorpd xmm1, xmm5 ; (+) Sign __vrda_bottom1: ; store the result _m128d mov rdi,QWORD PTR [rsp+save_ya] ; get y_array pointer movlpd QWORD PTR [rdi],xmm0 movhpd QWORD PTR 8[rdi],xmm0 __vrda_bottom2: prefetch QWORD PTR [rdi+64] add rdi,32 mov QWORD PTR [rsp+save_ya],rdi ; save y_array pointer ; store the result _m128d movlpd QWORD PTR [rdi-16],xmm1 movhpd QWORD PTR [rdi-8],xmm1 mov rax,QWORD PTR [rsp+p_iter] ; get number of iterations sub rax,1 mov QWORD PTR [rsp+p_iter],rax ; save number of iterations jnz __vrda_top ; see if we need to do any extras mov rax,QWORD PTR [rsp+save_nv] ; get number of values test rax,rax jnz __vrda_cleanup __final_check: movdqa xmm6, OWORD PTR [rsp+save_xmm6] ; restore xmm6 movdqa xmm7, OWORD PTR [rsp+save_xmm7] ; restore xmm7 movdqa xmm8, OWORD PTR [rsp+save_xmm8] ; restore xmm8 movdqa xmm9, OWORD PTR [rsp+save_xmm9] ; restore xmm9 movdqa xmm10,OWORD PTR [rsp+save_xmm10]; restore xmm10 movdqa xmm11,OWORD PTR [rsp+save_xmm11]; restore xmm11 movdqa xmm12,OWORD PTR [rsp+save_xmm12]; restore xmm12 movdqa xmm13,OWORD PTR [rsp+save_xmm13]; restore xmm13 mov rsi,QWORD PTR [rsp+save_rsi] ; restore rsi mov rdi,QWORD PTR [rsp+save_rdi] ; restore rdi add rsp,stack_size L__return: ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; we jump here when we have an odd number of cos calls to make at the end ; we assume that rdx is pointing at the next x array element, r8 at the next y array element. ; The number of values left is in save_nv align 16 __vrda_cleanup: mov rax,save_nv[rsp] ; get number of values test rax,rax jz __final_check mov rsi,QWORD PTR [rsp+save_xa] mov rdi,QWORD PTR [rsp+save_ya] ; fill in a m128d with zeroes and the extra values and then make a recursive call. xorpd xmm0,xmm0 movlpd QWORD PTR p_temp[rsp+8],xmm0 movapd XMMWORD PTR p_temp[rsp+16],xmm0 mov rcx,[rsi] ; we know there's at least one mov QWORD PTR p_temp[rsp],rcx cmp rax,2 jl __vrdacg mov rcx,8[rsi] ; do the second value mov QWORD PTR p_temp[rsp+8],rcx cmp rax,3 jl __vrdacg mov rcx,16[rsi] ; do the third value mov QWORD PTR p_temp[rsp+16],rcx __vrdacg: mov rcx,4 ; parameter for N lea rdx,p_temp[rsp] ; &x parameter lea r8, p_temp2[rsp]; &y parameter call fname ; call recursively to compute four values ; now copy the results to the destination array mov rdi,save_ya[rsp] mov rax,save_nv[rsp] ; get number of values mov rcx,p_temp2[rsp] mov [rdi],rcx ; we know there's at least one cmp rax,2 jl __vrdacgf mov rcx,p_temp2[rsp+8] mov 8[rdi],rcx ; do the second value cmp rax,3 jl __vrdacgf mov rcx,p_temp2[rsp+16] mov 16[rdi],rcx ; do the third value __vrdacgf: jmp __final_check fname endp ;TEXT ENDS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;JUMP TABLE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 PUBLIC coscos_coscos_piby4 coscos_coscos_piby4: movapd xmm10, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR cosarray+50h ; c6 movdqa xmm5, OWORD PTR cosarray+50h ; c6 movapd xmm8, OWORD PTR cosarray+20h ; c3 movapd xmm9, OWORD PTR cosarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; r movapd OWORD PTR p_temp3[rsp], xmm11 ; r mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subpd xmm10, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 ;trash r subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 ;trash r movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR cosarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR cosarray+10h ; c2+x2C3 addpd xmm10, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) ;trash t addpd xmm11, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) ;trash t mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR cosarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR cosarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zc addpd xmm5, xmm9 ; zc mulpd xmm2, xmm2 ; x4 recalculate mulpd xmm3, xmm3 ; x4 recalculate movapd xmm12, OWORD PTR p_temp2[rsp] ; r movapd xmm13, OWORD PTR p_temp3[rsp] ; r mulpd xmm6, xmm0 ; x * xx mulpd xmm7, xmm1 ; x * xx subpd xmm10, xmm12 ; (1 + (-t)) - r subpd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x4 * zc mulpd xmm5, xmm3 ; x4 * zc subpd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx subpd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx addpd xmm4, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addpd xmm5, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) subpd xmm12, OWORD PTR __real_3ff0000000000000 ; t relaculate, -t = r-1 subpd xmm13, OWORD PTR __real_3ff0000000000000 ; t relaculate, -t = r-1 subpd xmm4, xmm12 ; + t subpd xmm5, xmm13 ; + t jmp __vrda_cos_cleanup ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 cossin_cossin_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd OWORD PTR p_temp[rsp], xmm6 ; Store rr movapd OWORD PTR p_temp1[rsp], xmm7 ; Store rr movdqa xmm4, OWORD PTR sincosarray+50h ; s6 movdqa xmm5, OWORD PTR sincosarray+50h ; s6 movapd xmm8, OWORD PTR sincosarray+20h ; s3 movapd xmm9, OWORD PTR sincosarray+20h ; s3 movapd xmm10, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 mulpd xmm4, xmm2 ; x2s6 mulpd xmm5, xmm3 ; x2s6 mulpd xmm8, xmm2 ; x2s3 mulpd xmm9, xmm3 ; x2s3 mulpd xmm10, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR sincosarray+40h ; s5+x2s6 addpd xmm5, OWORD PTR sincosarray+40h ; s5+x2s6 addpd xmm8, OWORD PTR sincosarray+10h ; s2+x2s3 addpd xmm9, OWORD PTR sincosarray+10h ; s2+x2s3 movapd xmm12, xmm2 ; move x2 for x6 movapd xmm13, xmm3 ; move x2 for x6 mulpd xmm4, xmm2 ; x2(s5+x2s6) mulpd xmm5, xmm3 ; x2(s5+x2s6) mulpd xmm8, xmm2 ; x2(s2+x2s3) mulpd xmm9, xmm3 ; x2(s2+x2s3) mulpd xmm12, xmm10 ; x6 mulpd xmm13, xmm11 ; x6 addpd xmm4, OWORD PTR sincosarray+30h ; s4+x2(s5+x2s6) addpd xmm5, OWORD PTR sincosarray+30h ; s4+x2(s5+x2s6) addpd xmm8, OWORD PTR sincosarray ; s1+x2(s2+x2s3) addpd xmm9, OWORD PTR sincosarray ; s1+x2(s2+x2s3) movhlps xmm10, xmm10 ; move high x4 for cos term movhlps xmm11, xmm11 ; move high x4 for cos term mulpd xmm4, xmm12 ; x6(s4+x2(s5+x2s6)) mulpd xmm5, xmm13 ; x6(s4+x2(s5+x2s6)) movsd xmm6, xmm2 ; move low x2 for x3 for sin term movsd xmm7, xmm3 ; move low x2 for x3 for sin term mulsd xmm6, xmm0 ; get low x3 for sin term mulsd xmm7, xmm1 ; get low x3 for sin term mulpd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm2 ; move high r for cos movhlps xmm13, xmm3 ; move high r for cos movhlps xmm8, xmm4 ; xmm4 = sin , xmm8 = cos movhlps xmm9, xmm5 ; xmm4 = sin , xmm8 = cos mulsd xmm4, xmm6 ; sin *x3 mulsd xmm5, xmm7 ; sin *x3 mulsd xmm8, xmm10 ; cos *x4 mulsd xmm9, xmm11 ; cos *x4 mulsd xmm2, QWORD PTR p_temp[rsp] ; 0.5 * x2 * xx for sin term mulsd xmm3, QWORD PTR p_temp1[rsp] ; 0.5 * x2 * xx for sin term movsd xmm6, xmm12 ; Keep high r for cos term movsd xmm7, xmm13 ; Keep high r for cos term subsd xmm12, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm13, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm4, xmm2 ; sin - 0.5 * x2 *xx subsd xmm5, xmm3 ; sin - 0.5 * x2 *xx movhlps xmm10, xmm0 ; move high x for x*xx for cos term movhlps xmm11, xmm1 ; move high x for x*xx for cos term mulsd xmm10, QWORD PTR p_temp[rsp+8] ; x * xx mulsd xmm11, QWORD PTR p_temp1[rsp+8] ; x * xx movsd xmm2, xmm12 ; move -t for cos term movsd xmm3, xmm13 ; move -t for cos term addsd xmm12, QWORD PTR __real_3ff0000000000000; 1+(-t) addsd xmm13, QWORD PTR __real_3ff0000000000000; 1+(-t) addsd xmm4, QWORD PTR p_temp[rsp] ; sin+xx addsd xmm5, QWORD PTR p_temp1[rsp] ; sin+xx subsd xmm12, xmm6 ; (1-t) - r subsd xmm13, xmm7 ; (1-t) - r subsd xmm12, xmm10 ; ((1 + (-t)) - r) - x*xx subsd xmm13, xmm11 ; ((1 + (-t)) - r) - x*xx addsd xmm4, xmm0 ; sin + x addsd xmm5, xmm1 ; sin + x addsd xmm8, xmm12 ; cos+((1-t)-r - x*xx) addsd xmm9, xmm13 ; cos+((1-t)-r - x*xx) subsd xmm8, xmm2 ; cos+t subsd xmm9, xmm3 ; cos+t movlhps xmm4, xmm8 movlhps xmm5, xmm9 jmp __vrda_cos_cleanup align 16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; sincos_cossin_piby4: ; changed from sincos_sincos ; xmm1 is cossin and xmm0 is sincos movapd OWORD PTR p_temp[rsp], xmm6 ; Store rr movapd OWORD PTR p_temp1[rsp], xmm7 ; Store rr movapd OWORD PTR p_temp3[rsp], xmm1 ; Store r for the sincos term movapd xmm4, OWORD PTR sincosarray+50h ; s6 movapd xmm5, OWORD PTR cossinarray+50h ; s6 movdqa xmm8, OWORD PTR sincosarray+20h ; s3 movdqa xmm9, OWORD PTR cossinarray+20h ; s3 movapd xmm10, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 mulpd xmm4, xmm2 ; x2s6 mulpd xmm5, xmm3 ; x2s6 mulpd xmm8, xmm2 ; x2s3 mulpd xmm9, xmm3 ; x2s3 mulpd xmm10, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR sincosarray+40h ; s5+x2s6 addpd xmm5, OWORD PTR cossinarray+40h ; s5+x2s6 addpd xmm8, OWORD PTR sincosarray+10h ; s2+x2s3 addpd xmm9, OWORD PTR cossinarray+10h ; s2+x2s3 movapd xmm12, xmm2 ; move x2 for x6 movapd xmm13, xmm3 ; move x2 for x6 mulpd xmm4, xmm2 ; x2(s5+x2s6) mulpd xmm5, xmm3 ; x2(s5+x2s6) mulpd xmm8, xmm2 ; x2(s2+x2s3) mulpd xmm9, xmm3 ; x2(s2+x2s3) mulpd xmm12, xmm10 ; x6 mulpd xmm13, xmm11 ; x6 addpd xmm4, OWORD PTR sincosarray+30h ; s4+x2(s5+x2s6) addpd xmm5, OWORD PTR cossinarray+30h ; s4+x2(s5+x2s6) addpd xmm8, OWORD PTR sincosarray ; s1+x2(s2+x2s3) addpd xmm9, OWORD PTR cossinarray ; s1+x2(s2+x2s3) movhlps xmm10, xmm10 ; move high x4 for cos term mulpd xmm4, xmm12 ; x6(s4+x2(s5+x2s6)) mulpd xmm5, xmm13 ; x6(s4+x2(s5+x2s6)) movsd xmm6, xmm2 ; move low x2 for x3 for sin term (cossin) movhlps xmm7, xmm3 ; move high x2 for x3 for sin term (sincos) mulsd xmm6, xmm0 ; get low x3 for sin term mulsd xmm7, QWORD PTR p_temp3[rsp+8] ; get high x3 for sin term mulpd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm2 ; move high r for cos (cossin) movhlps xmm13, xmm3 ; move high 0.5*x2 for sin term (sincos) movhlps xmm8, xmm4 ; xmm8 = cos , xmm4 = sin (cossin) movhlps xmm9, xmm5 ; xmm9 = sin , xmm5 = cos (sincos) mulsd xmm4, xmm6 ; sin *x3 mulsd xmm5, xmm11 ; cos *x4 mulsd xmm8, xmm10 ; cos *x4 mulsd xmm9, xmm7 ; sin *x3 mulsd xmm2, QWORD PTR p_temp[rsp] ; low 0.5 * x2 * xx for sin term (cossin) mulsd xmm13, QWORD PTR p_temp1[rsp+8] ; high 0.5 * x2 * xx for sin term (sincos) movsd xmm6, xmm12 ; Keep high r for cos term movsd xmm7, xmm3 ; Keep low r for cos term subsd xmm12, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm3, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 subsd xmm4, xmm2 ; sin - 0.5 * x2 *xx (cossin) subsd xmm9, xmm13 ; sin - 0.5 * x2 *xx (sincos) movhlps xmm10, xmm0 ; move high x for x*xx for cos term (cossin) movhlps xmm11, xmm1 ; move high x for x for sin term (sincos) mulsd xmm10, QWORD PTR p_temp[rsp+8] ; x * xx mulsd xmm1, QWORD PTR p_temp1[rsp] ; x * xx movsd xmm2, xmm12 ; move -t for cos term movsd xmm13, xmm3 ; move -t for cos term addsd xmm12,QWORD PTR __real_3ff0000000000000 ; 1+(-t) addsd xmm3, QWORD PTR __real_3ff0000000000000 ; 1+(-t) addsd xmm4, QWORD PTR p_temp[rsp] ; sin+xx + addsd xmm9, QWORD PTR p_temp1[rsp+8] ; sin+xx + subsd xmm12,xmm6 ; (1-t) - r subsd xmm3, xmm7 ; (1-t) - r subsd xmm12,xmm10 ; ((1 + (-t)) - r) - x*xx subsd xmm3, xmm1 ; ((1 + (-t)) - r) - x*xx addsd xmm4, xmm0 ; sin + x + addsd xmm9, xmm11 ; sin + x + addsd xmm8, xmm12 ; cos+((1-t)-r - x*xx) addsd xmm5, xmm3 ; cos+((1-t)-r - x*xx) subsd xmm8, xmm2 ; cos+t subsd xmm5, xmm13 ; cos+t movlhps xmm4, xmm8 ; cossin movlhps xmm5, xmm9 ; sincos jmp __vrda_cos_cleanup align 16 sincos_sincos_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd OWORD PTR p_temp[rsp], xmm6 ; Store rr movapd OWORD PTR p_temp1[rsp], xmm7 ; Store rr movapd OWORD PTR p_temp2[rsp], xmm0 ; Store r movapd OWORD PTR p_temp3[rsp], xmm1 ; Store r movapd xmm4, OWORD PTR cossinarray+50h ; s6 movapd xmm5, OWORD PTR cossinarray+50h ; s6 movdqa xmm8, OWORD PTR cossinarray+20h ; s3 movdqa xmm9, OWORD PTR cossinarray+20h ; s3 movapd xmm10, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 mulpd xmm4, xmm2 ; x2s6 mulpd xmm5, xmm3 ; x2s6 mulpd xmm8, xmm2 ; x2s3 mulpd xmm9, xmm3 ; x2s3 mulpd xmm10, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR cossinarray+40h ; s5+x2s6 addpd xmm5, OWORD PTR cossinarray+40h ; s5+x2s6 addpd xmm8, OWORD PTR cossinarray+10h ; s2+x2s3 addpd xmm9, OWORD PTR cossinarray+10h ; s2+x2s3 movapd xmm12, xmm2 ; move x2 for x6 movapd xmm13, xmm3 ; move x2 for x6 mulpd xmm4, xmm2 ; x2(s5+x2s6) mulpd xmm5, xmm3 ; x2(s5+x2s6) mulpd xmm8, xmm2 ; x2(s2+x2s3) mulpd xmm9, xmm3 ; x2(s2+x2s3) mulpd xmm12, xmm10 ; x6 mulpd xmm13, xmm11 ; x6 addpd xmm4, OWORD PTR cossinarray+30h ; s4+x2(s5+x2s6) addpd xmm5, OWORD PTR cossinarray+30h ; s4+x2(s5+x2s6) addpd xmm8, OWORD PTR cossinarray ; s1+x2(s2+x2s3) addpd xmm9, OWORD PTR cossinarray ; s1+x2(s2+x2s3) mulpd xmm4, xmm12 ; x6(s4+x2(s5+x2s6)) mulpd xmm5, xmm13 ; x6(s4+x2(s5+x2s6)) movhlps xmm6, xmm2 ; move low x2 for x3 for sin term movhlps xmm7, xmm3 ; move low x2 for x3 for sin term mulsd xmm6, QWORD PTR p_temp2[rsp+8] ; get low x3 for sin term mulsd xmm7, QWORD PTR p_temp3[rsp+8] ; get low x3 for sin term mulpd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm2 ; move high 0.5*x2 for sin term movhlps xmm13, xmm3 ; move high 0.5*x2 for sin term ; Reverse 12 and 2 movhlps xmm8, xmm4 ; xmm8 = sin , xmm4 = cos movhlps xmm9, xmm5 ; xmm9 = sin , xmm5 = cos mulsd xmm8, xmm6 ; sin *x3 mulsd xmm9, xmm7 ; sin *x3 mulsd xmm4, xmm10 ; cos *x4 mulsd xmm5, xmm11 ; cos *x4 mulsd xmm12, QWORD PTR p_temp[rsp+8] ; 0.5 * x2 * xx for sin term mulsd xmm13, QWORD PTR p_temp1[rsp+8] ; 0.5 * x2 * xx for sin term movsd xmm6, xmm2 ; Keep high r for cos term movsd xmm7, xmm3 ; Keep high r for cos term subsd xmm2, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm3, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm8, xmm12 ; sin - 0.5 * x2 *xx subsd xmm9, xmm13 ; sin - 0.5 * x2 *xx movhlps xmm10, xmm0 ; move high x for x for sin term movhlps xmm11, xmm1 ; move high x for x for sin term ; Reverse 10 and 0 mulsd xmm0, QWORD PTR p_temp[rsp] ; x * xx mulsd xmm1, QWORD PTR p_temp1[rsp] ; x * xx movsd xmm12, xmm2 ; move -t for cos term movsd xmm13, xmm3 ; move -t for cos term addsd xmm2, QWORD PTR __real_3ff0000000000000; 1+(-t) addsd xmm3, QWORD PTR __real_3ff0000000000000; 1+(-t) addsd xmm8, QWORD PTR p_temp[rsp+8] ; sin+xx addsd xmm9, QWORD PTR p_temp1[rsp+8] ; sin+xx subsd xmm2, xmm6 ; (1-t) - r subsd xmm3, xmm7 ; (1-t) - r subsd xmm2, xmm0 ; ((1 + (-t)) - r) - x*xx subsd xmm3, xmm1 ; ((1 + (-t)) - r) - x*xx addsd xmm8, xmm10 ; sin + x addsd xmm9, xmm11 ; sin + x addsd xmm4, xmm2 ; cos+((1-t)-r - x*xx) addsd xmm5, xmm3 ; cos+((1-t)-r - x*xx) subsd xmm4, xmm12 ; cos+t subsd xmm5, xmm13 ; cos+t movlhps xmm4, xmm8 movlhps xmm5, xmm9 jmp __vrda_cos_cleanup align 16 cossin_sincos_piby4: ; changed from sincos_sincos ; xmm1 is cossin and xmm0 is sincos ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd OWORD PTR p_temp[rsp], xmm6 ; Store rr movapd OWORD PTR p_temp1[rsp], xmm7 ; Store rr movapd OWORD PTR p_temp2[rsp], xmm0 ; Store r movapd xmm4, OWORD PTR cossinarray+50h ; s6 movapd xmm5, OWORD PTR sincosarray+50h ; s6 movdqa xmm8, OWORD PTR cossinarray+20h ; s3 movdqa xmm9, OWORD PTR sincosarray+20h ; s3 movapd xmm10, xmm2 ; move x2 for x4 movapd xmm11, xmm3 ; move x2 for x4 mulpd xmm4, xmm2 ; x2s6 mulpd xmm5, xmm3 ; x2s6 mulpd xmm8, xmm2 ; x2s3 mulpd xmm9, xmm3 ; x2s3 mulpd xmm10, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR cossinarray+40h ; s5+x2s6 addpd xmm5, OWORD PTR sincosarray+40h ; s5+x2s6 addpd xmm8, OWORD PTR cossinarray+10h ; s2+x2s3 addpd xmm9, OWORD PTR sincosarray+10h ; s2+x2s3 movapd xmm12, xmm2 ; move x2 for x6 movapd xmm13, xmm3 ; move x2 for x6 mulpd xmm4, xmm2 ; x2(s5+x2s6) mulpd xmm5, xmm3 ; x2(s5+x2s6) mulpd xmm8, xmm2 ; x2(s2+x2s3) mulpd xmm9, xmm3 ; x2(s2+x2s3) mulpd xmm12, xmm10 ; x6 mulpd xmm13, xmm11 ; x6 addpd xmm4, OWORD PTR cossinarray+30h ; s4+x2(s5+x2s6) addpd xmm5, OWORD PTR sincosarray+30h ; s4+x2(s5+x2s6) addpd xmm8, OWORD PTR cossinarray ; s1+x2(s2+x2s3) addpd xmm9, OWORD PTR sincosarray ; s1+x2(s2+x2s3) movhlps xmm11, xmm11 ; move high x4 for cos term + mulpd xmm4, xmm12 ; x6(s4+x2(s5+x2s6)) mulpd xmm5, xmm13 ; x6(s4+x2(s5+x2s6)) movhlps xmm6, xmm2 ; move low x2 for x3 for sin term movsd xmm7, xmm3 ; move low x2 for x3 for sin term + mulsd xmm6, QWORD PTR p_temp2[rsp+8] ; get low x3 for sin term mulsd xmm7, xmm1 ; get low x3 for sin term + mulpd xmm2, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms mulpd xmm3, QWORD PTR __real_3fe0000000000000 ; 0.5*x2 for sin and cos terms addpd xmm4, xmm8 ; z addpd xmm5, xmm9 ; z movhlps xmm12, xmm2 ; move high 0.5*x2 for sin term movhlps xmm13, xmm3 ; move high r for cos movhlps xmm8, xmm4 ; xmm8 = sin , xmm4 = cos movhlps xmm9, xmm5 ; xmm9 = cos , xmm5 = sin mulsd xmm8, xmm6 ; sin *x3 mulsd xmm9, xmm11 ; cos *x4 mulsd xmm4, xmm10 ; cos *x4 mulsd xmm5, xmm7 ; sin *x3 mulsd xmm12, QWORD PTR p_temp[rsp+8] ; 0.5 * x2 * xx for sin term mulsd xmm3, QWORD PTR p_temp1[rsp] ; 0.5 * x2 * xx for sin term movsd xmm6, xmm2 ; Keep high r for cos term movsd xmm7, xmm13 ; Keep high r for cos term subsd xmm2, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm13, QWORD PTR __real_3ff0000000000000; -t=r-1.0 subsd xmm8, xmm12 ; sin - 0.5 * x2 *xx subsd xmm5, xmm3 ; sin - 0.5 * x2 *xx movhlps xmm10, xmm0 ; move high x for x for sin term movhlps xmm11, xmm1 ; move high x for x*xx for cos term mulsd xmm0, QWORD PTR p_temp[rsp] ; x * xx mulsd xmm11, QWORD PTR p_temp1[rsp+8] ; x * xx movsd xmm12, xmm2 ; move -t for cos term movsd xmm3, xmm13 ; move -t for cos term addsd xmm2, QWORD PTR __real_3ff0000000000000 ; 1+(-t) addsd xmm13, QWORD PTR __real_3ff0000000000000; 1+(-t) addsd xmm8, QWORD PTR p_temp[rsp+8] ; sin+xx addsd xmm5, QWORD PTR p_temp1[rsp] ; sin+xx subsd xmm2, xmm6 ; (1-t) - r subsd xmm13, xmm7 ; (1-t) - r subsd xmm2, xmm0 ; ((1 + (-t)) - r) - x*xx subsd xmm13, xmm11 ; ((1 + (-t)) - r) - x*xx addsd xmm8, xmm10 ; sin + x addsd xmm5, xmm1 ; sin + x addsd xmm4, xmm2 ; cos+((1-t)-r - x*xx) addsd xmm9, xmm13 ; cos+((1-t)-r - x*xx) subsd xmm4, xmm12 ; cos+t subsd xmm9, xmm3 ; cos+t movlhps xmm4, xmm8 movlhps xmm5, xmm9 jmp __vrda_cos_cleanup ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 coscos_sinsin_piby4: movapd xmm10, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR sinarray+50h ; c6 movdqa xmm5, OWORD PTR cosarray+50h ; c6 movapd xmm8, OWORD PTR sinarray+20h ; c3 movapd xmm9, OWORD PTR cosarray+20h ; c3 movapd OWORD PTR p_temp2[rsp], xmm2 ; store x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp3[rsp], xmm11 ; store r mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 mulpd xmm10, xmm2 ; x4 subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 movapd xmm12, xmm2 ; copy of x2 for 0.5*x2 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR sinarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR cosarray+10h ; c2+x2C3 addpd xmm11, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) mulpd xmm10, xmm2 ; x6 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR sinarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR cosarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm10 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zc mulpd xmm2, xmm0 ; x3 recalculate mulpd xmm3, xmm3 ; x4 recalculate movapd xmm13, OWORD PTR p_temp3[rsp] ; r mulpd xmm12, xmm6 ; 0.5 * x2 *xx mulpd xmm7, xmm1 ; x * xx subpd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm3 ; x4 * zc subpd xmm4, xmm12 ; -0.5 * x2 *xx subpd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx addpd xmm4, xmm6 ; x3 * zs +xx addpd xmm5, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) subpd xmm13, OWORD PTR __real_3ff0000000000000 ; t relaculate, -t = r-1 addpd xmm4, xmm0 ; +x subpd xmm5, xmm13 ; + t jmp __vrda_cos_cleanup align 16 sinsin_coscos_piby4: movapd xmm10, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR cosarray+50h ; c6 movdqa xmm5, OWORD PTR sinarray+50h ; c6 movapd xmm8, OWORD PTR cosarray+20h ; c3 movapd xmm9, OWORD PTR sinarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 movapd OWORD PTR p_temp3[rsp], xmm3 ; store x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; store r mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subpd xmm10, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 mulpd xmm11, xmm3 ; x4 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for 0.5*x2 addpd xmm4, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR cosarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR sinarray+10h ; c2+x2C3 addpd xmm10, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) mulpd xmm12, xmm2 ; x4 mulpd xmm11, xmm3 ; x6 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 addpd xmm4, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR cosarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR sinarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm11 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zc addpd xmm5, xmm9 ; zs mulpd xmm2, xmm2 ; x4 recalculate mulpd xmm3, xmm1 ; x3 recalculate movapd xmm12, OWORD PTR p_temp2[rsp] ; r mulpd xmm6, xmm0 ; x * xx mulpd xmm13, xmm7 ; 0.5 * x2 *xx subpd xmm10, xmm12 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x4 * zc mulpd xmm5, xmm3 ; x3 * zs subpd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx;;;;;;;;;;;;;;;;;;;;; subpd xmm5, xmm13 ; -0.5 * x2 *xx addpd xmm4, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addpd xmm5, xmm7 ; +xx subpd xmm12, OWORD PTR __real_3ff0000000000000 ; t relaculate, -t = r-1 addpd xmm5, xmm1 ; +x subpd xmm4, xmm12 ; + t jmp __vrda_cos_cleanup ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; align 16 coscos_cossin_piby4: ;Derive from cossin_coscos movapd xmm10, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR sincosarray+50h ; c6 movdqa xmm5, OWORD PTR cosarray+50h ; c6 movapd xmm8, OWORD PTR sincosarray+20h ; c3 movapd xmm9, OWORD PTR cosarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; r movapd OWORD PTR p_temp3[rsp], xmm11 ; r movapd OWORD PTR p_temp[rsp], xmm6 ; rr movhlps xmm10, xmm10 ; get upper r for t for cos mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subsd xmm10, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR sincosarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR sincosarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR cosarray+10h ; c2+x2C3 addsd xmm10, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) addpd xmm11, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12,xmm2 ; x6 mulpd xmm13,xmm3 ; x6 addpd xmm4, OWORD PTR sincosarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR sincosarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR cosarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zc movsd xmm8, xmm0 ; lower x for sin mulsd xmm8, xmm2 ; lower x3 for sin mulpd xmm2, xmm2 ; x4 mulpd xmm3, xmm3 ; upper x4 for cos movsd xmm2, xmm8 ; lower x3 for sin movsd xmm9, xmm6 ; lower xx ; note using odd reg movlpd xmm12, QWORD PTR p_temp2[rsp+8] ; upper r for cos term movapd xmm13, OWORD PTR p_temp3[rsp] ; r mulpd xmm6, xmm0 ; x * xx for upper cos term mulpd xmm7, xmm1 ; x * xx movhlps xmm6, xmm6 mulsd xmm9, QWORD PTR p_temp2[rsp] ; xx * 0.5*x2 for sin term subsd xmm10, xmm12 ; (1 + (-t)) - r subpd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x4 * zc mulpd xmm5, xmm3 ; x4 * zc ; x3 * zs movhlps xmm8, xmm4 ; xmm8= cos, xmm4= sin subsd xmm4, xmm9 ; x3zs - 0.5*x2*xx subsd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx subpd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx addsd xmm8, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addpd xmm5, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm4, QWORD PTR p_temp[rsp] ; +xx subsd xmm12, QWORD PTR __real_3ff0000000000000 ; -t = r-1 subpd xmm13, OWORD PTR __real_3ff0000000000000 ; -t = r-1 subsd xmm8, xmm12 ; + t addsd xmm4, xmm0 ; +x subpd xmm5, xmm13 ; + t movlhps xmm4, xmm8 jmp __vrda_cos_cleanup align 16 coscos_sincos_piby4: ;Derive from sincos_coscos movapd xmm10, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR cossinarray+50h ; c6 movdqa xmm5, OWORD PTR cosarray+50h ; c6 movapd xmm8, OWORD PTR cossinarray+20h ; c3 movapd xmm9, OWORD PTR cosarray+20h ; c3 mulpd xmm10,OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11,OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; r movapd OWORD PTR p_temp3[rsp], xmm11 ; r movapd OWORD PTR p_temp[rsp], xmm6 ; rr mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subsd xmm10, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos subpd xmm11, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR cossinarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR cossinarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR cosarray+10h ; c2+x2C3 addsd xmm10, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) for cos addpd xmm11, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR cossinarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR cossinarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR cosarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zszc addpd xmm5, xmm9 ; z mulpd xmm2, xmm0 ; upper x3 for sin mulsd xmm2, xmm0 ; lower x4 for cos mulpd xmm3, xmm3 ; x4 movhlps xmm9, xmm6 ; upper xx for sin term ; note using odd reg movlpd xmm12, QWORD PTR p_temp2[rsp] ; lower r for cos term movapd xmm13, OWORD PTR p_temp3[rsp] ; r mulpd xmm6, xmm0 ; x * xx for lower cos term mulpd xmm7, xmm1 ; x * xx mulsd xmm9, QWORD PTR p_temp2[rsp+8] ; xx * 0.5*x2 for upper sin term subsd xmm10, xmm12 ; (1 + (-t)) - r subpd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; lower=x4 * zc ; upper=x3 * zs mulpd xmm5, xmm3 ; x4 * zc movhlps xmm8, xmm4 ; xmm8= sin, xmm4= cos subsd xmm8, xmm9 ; x3zs - 0.5*x2*xx subsd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx subpd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx addsd xmm4, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addpd xmm5, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm8, QWORD PTR p_temp[rsp+8] ; +xx movhlps xmm0, xmm0 ; upper x for sin subsd xmm12, QWORD PTR __real_3ff0000000000000 ; -t = r-1 subpd xmm13, OWORD PTR __real_3ff0000000000000 ; -t = r-1 subsd xmm4, xmm12 ; + t subpd xmm5, xmm13 ; + t addsd xmm8, xmm0 ; +x movlhps xmm4, xmm8 jmp __vrda_cos_cleanup align 16 cossin_coscos_piby4: movapd xmm10, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR cosarray+50h ; c6 movdqa xmm5, OWORD PTR sincosarray+50h ; c6 movapd xmm8, OWORD PTR cosarray+20h ; c3 movapd xmm9, OWORD PTR sincosarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; r movapd OWORD PTR p_temp3[rsp], xmm11 ; r movapd OWORD PTR p_temp1[rsp], xmm7 ; rr movhlps xmm11, xmm11 ; get upper r for t for cos mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subpd xmm10, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 subsd xmm11, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR sincosarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR cosarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR sincosarray+10h ; c2+x2C3 addpd xmm10, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) ;trash t addsd xmm11, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) ;trash t mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR sincosarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR cosarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR sincosarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zc addpd xmm5, xmm9 ; zcs ;;; movsd xmm9, xmm1 ; lower x for sin mulsd xmm9, xmm3 ; lower x3 for sin mulpd xmm2, xmm2 ; x4 mulpd xmm3, xmm3 ; upper x4 for cos movsd xmm3, xmm9 ; lower x3 for sin movsd xmm8, xmm7 ; lower xx ; note using even reg movapd xmm12, OWORD PTR p_temp2[rsp] ; r movlpd xmm13, QWORD PTR p_temp3[rsp+8] ; upper r for cos term mulpd xmm6, xmm0 ; x * xx mulpd xmm7, xmm1 ; x * xx for upper cos term movhlps xmm7, xmm7 mulsd xmm8, QWORD PTR p_temp3[rsp] ; xx * 0.5*x2 for sin term subpd xmm10, xmm12 ; (1 + (-t)) - r subsd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x4 * zc mulpd xmm5, xmm3 ; x4 * zc ; x3 * zs movhlps xmm9, xmm5 ; xmm9= cos, xmm5= sin subsd xmm5, xmm8 ; x3zs - 0.5*x2*xx subpd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx subsd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx addpd xmm4, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm9, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm5, QWORD PTR p_temp1[rsp] ; +xx subpd xmm12, OWORD PTR __real_3ff0000000000000 ; t relaculate, -t = r-1 subsd xmm13, QWORD PTR __real_3ff0000000000000 ; t relaculate, -t = r-1 subpd xmm4, xmm12 ; + t subsd xmm9, xmm13 ; + t addsd xmm5, xmm1 ; +x movlhps xmm5, xmm9 jmp __vrda_cos_cleanup align 16 cossin_sinsin_piby4: ; Derived from sincos_sinsin movapd xmm10, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR sinarray+50h ; c6 movdqa xmm5, OWORD PTR sincosarray+50h ; c6 movapd xmm8, OWORD PTR sinarray+20h ; c3 movapd xmm9, OWORD PTR sincosarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp3[rsp], xmm11 ; r movapd OWORD PTR p_temp1[rsp], xmm7 ; rr movhlps xmm11, xmm11 mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subsd xmm11, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR sincosarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR sinarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR sincosarray+10h ; c2+x2C3 mulpd xmm10, xmm6 ; 0.5*x2*xx addsd xmm11, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) for cos mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR sincosarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR sinarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR sincosarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zczs movsd xmm12, xmm3 mulsd xmm12, xmm1 ; low x3 for sin mulpd xmm2, xmm0 ; x3 mulpd xmm3, xmm3 ; high x4 for cos movsd xmm3, xmm12 ; low x3 for sin movhlps xmm8, xmm1 ; upper x for cos term ; note using even reg movlpd xmm13, QWORD PTR p_temp3[rsp+8] ; upper r for cos term mulsd xmm8, QWORD PTR p_temp1[rsp+8] ; x * xx for upper cos term mulsd xmm7, QWORD PTR p_temp3[rsp] ; xx * 0.5*x2 for lower sin term subsd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm3 ; lower=x4 * zc ; upper=x3 * zs movhlps xmm9, xmm5 ; xmm9= cos, xmm5= sin subsd xmm5, xmm7 ; x3zs - 0.5*x2*xx subsd xmm11, xmm8 ; ((1 + (-t)) - r) - x*xx subpd xmm4, xmm10 ; x3*zs - 0.5*x2*xx addsd xmm9, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm5, QWORD PTR p_temp1[rsp] ; +xx addpd xmm4, xmm6 ; +xx subsd xmm13, QWORD PTR __real_3ff0000000000000 ; -t = r-1 addsd xmm5, xmm1 ; +x addpd xmm4, xmm0 ; +x subsd xmm9, xmm13 ; + t movlhps xmm5, xmm9 jmp __vrda_cos_cleanup align 16 sincos_coscos_piby4: movapd xmm10, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR cosarray+50h ; c6 movdqa xmm5, OWORD PTR cossinarray+50h ; c6 movapd xmm8, OWORD PTR cosarray+20h ; c3 movapd xmm9, OWORD PTR cossinarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; r movapd OWORD PTR p_temp3[rsp], xmm11 ; r movapd OWORD PTR p_temp1[rsp], xmm7 ; rr mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subpd xmm10, OWORD PTR __real_3ff0000000000000 ; -t=r-1.0 subsd xmm11, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR cosarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR cossinarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR cosarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR cossinarray+10h ; c2+x2C3 addpd xmm10, OWORD PTR __real_3ff0000000000000 ; 1 + (-t) addsd xmm11, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) for cos mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR cosarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR cossinarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR cosarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR cossinarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zc addpd xmm5, xmm9 ; zszc mulpd xmm2, xmm2 ; x4 mulpd xmm3, xmm1 ; upper x3 for sin mulsd xmm3, xmm1 ; lower x4 for cos movhlps xmm8, xmm7 ; upper xx for sin term ; note using even reg movapd xmm12, OWORD PTR p_temp2[rsp] ; r movlpd xmm13, QWORD PTR p_temp3[rsp] ; lower r for cos term mulpd xmm6, xmm0 ; x * xx mulpd xmm7, xmm1 ; x * xx for lower cos term mulsd xmm8, QWORD PTR p_temp3[rsp+8] ; xx * 0.5*x2 for upper sin term subpd xmm10, xmm12 ; (1 + (-t)) - r subsd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x4 * zc mulpd xmm5, xmm3 ; lower=x4 * zc ; upper=x3 * zs movhlps xmm9, xmm5 ; xmm9= sin, xmm5= cos subsd xmm9, xmm8 ; x3zs - 0.5*x2*xx subpd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx subsd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx addpd xmm4, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm5, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm9, QWORD PTR p_temp1[rsp+8] ; +xx movhlps xmm1, xmm1 ; upper x for sin subpd xmm12, OWORD PTR __real_3ff0000000000000 ; -t = r-1 subsd xmm13, QWORD PTR __real_3ff0000000000000 ; -t = r-1 subpd xmm4, xmm12 ; + t subsd xmm5, xmm13 ; + t addsd xmm9, xmm1 ; +x movlhps xmm5, xmm9 jmp __vrda_cos_cleanup align 16 sincos_sinsin_piby4: ; Derived from sincos_coscos movapd xmm10, xmm2 ; r movapd xmm11, xmm3 ; r movdqa xmm4, OWORD PTR sinarray+50h ; c6 movdqa xmm5, OWORD PTR cossinarray+50h ; c6 movapd xmm8, OWORD PTR sinarray+20h ; c3 movapd xmm9, OWORD PTR cossinarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp3[rsp], xmm11 ; r movapd OWORD PTR p_temp1[rsp], xmm7 ; rr mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subsd xmm11, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR cossinarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR sinarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR cossinarray+10h ; c2+x2C3 mulpd xmm10, xmm6 ; 0.5x2*xx addsd xmm11, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) for cos mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR cossinarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR sinarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR cossinarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zszc mulpd xmm2, xmm0 ; x3 mulpd xmm3, xmm1 ; upper x3 for sin mulsd xmm3, xmm1 ; lower x4 for cos movhlps xmm8, xmm7 ; upper xx for sin term ; note using even reg movlpd xmm13, QWORD PTR p_temp3[rsp] ; lower r for cos term mulpd xmm7, xmm1 ; x * xx for lower cos term mulsd xmm8, QWORD PTR p_temp3[rsp+8] ; xx * 0.5*x2 for upper sin term subsd xmm11, xmm13 ; (1 + (-t)) - r mulpd xmm4, xmm2 ; x3 * zs mulpd xmm5, xmm3 ; lower=x4 * zc ; upper=x3 * zs movhlps xmm9, xmm5 ; xmm9= sin, xmm5= cos subsd xmm9, xmm8 ; x3zs - 0.5*x2*xx subsd xmm11, xmm7 ; ((1 + (-t)) - r) - x*xx subpd xmm4, xmm10 ; x3*zs - 0.5*x2*xx addsd xmm5, xmm11 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm9, QWORD PTR p_temp1[rsp+8] ; +xx movhlps xmm1, xmm1 ; upper x for sin addpd xmm4, xmm6 ; +xx subsd xmm13, QWORD PTR __real_3ff0000000000000 ; -t = r-1 addsd xmm9, xmm1 ; +x addpd xmm4, xmm0 ; +x subsd xmm5, xmm13 ; + t movlhps xmm5, xmm9 jmp __vrda_cos_cleanup align 16 sinsin_cossin_piby4: ; Derived from sincos_sinsin movapd xmm10, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR sincosarray+50h ; c6 movdqa xmm5, OWORD PTR sinarray+50h ; c6 movapd xmm8, OWORD PTR sincosarray+20h ; c3 movapd xmm9, OWORD PTR sinarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; x2 movapd OWORD PTR p_temp[rsp], xmm6 ; xx movhlps xmm10, xmm10 mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subsd xmm10, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR sincosarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR sincosarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR sinarray+10h ; c2+x2C3 mulpd xmm11, xmm7 ; 0.5*x2*xx addsd xmm10, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) for cos mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR sincosarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR sincosarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR sinarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zczs addpd xmm5, xmm9 ; zs movsd xmm13, xmm2 mulsd xmm13, xmm0 ; low x3 for sin mulpd xmm3, xmm1 ; x3 mulpd xmm2, xmm2 ; high x4 for cos movsd xmm2, xmm13 ; low x3 for sin movhlps xmm9, xmm0 ; upper x for cos term ; note using even reg movlpd xmm12, QWORD PTR p_temp2[rsp+8] ; upper r for cos term mulsd xmm9, QWORD PTR p_temp[rsp+8] ; x * xx for upper cos term mulsd xmm6, QWORD PTR p_temp2[rsp] ; xx * 0.5*x2 for lower sin term subsd xmm10, xmm12 ; (1 + (-t)) - r mulpd xmm5, xmm3 ; x3 * zs mulpd xmm4, xmm2 ; lower=x4 * zc ; upper=x3 * zs movhlps xmm8, xmm4 ; xmm8= cos, xmm4= sin subsd xmm4, xmm6 ; x3zs - 0.5*x2*xx subsd xmm10, xmm9 ; ((1 + (-t)) - r) - x*xx subpd xmm5, xmm11 ; x3*zs - 0.5*x2*xx addsd xmm8, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm4, QWORD PTR p_temp[rsp] ; +xx addpd xmm5, xmm7 ; +xx subsd xmm12, QWORD PTR __real_3ff0000000000000 ; -t = r-1 addsd xmm4, xmm0 ; +x addpd xmm5, xmm1 ; +x subsd xmm8, xmm12 ; + t movlhps xmm4, xmm8 jmp __vrda_cos_cleanup align 16 sinsin_sincos_piby4: ; Derived from sincos_coscos movapd xmm10, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR cossinarray+50h ; c6 movdqa xmm5, OWORD PTR sinarray+50h ; c6 movapd xmm8, OWORD PTR cossinarray+20h ; c3 movapd xmm9, OWORD PTR sinarray+20h ; c3 mulpd xmm10, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm11, OWORD PTR __real_3fe0000000000000 ; r = 0.5 *x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 movapd OWORD PTR p_temp2[rsp], xmm10 ; r movapd OWORD PTR p_temp[rsp], xmm6 ; rr mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 subsd xmm10, QWORD PTR __real_3ff0000000000000 ; -t=r-1.0 for cos movapd xmm12, xmm2 ; copy of x2 for x4 movapd xmm13, xmm3 ; copy of x2 for x4 addpd xmm4, OWORD PTR cossinarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR cossinarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR sinarray+10h ; c2+x2C3 mulpd xmm11, xmm7 ; 0.5x2*xx addsd xmm10, QWORD PTR __real_3ff0000000000000 ; 1 + (-t) for cos mulpd xmm12, xmm2 ; x4 mulpd xmm13, xmm3 ; x4 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm12, xmm2 ; x6 mulpd xmm13, xmm3 ; x6 addpd xmm4, OWORD PTR cossinarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR cossinarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR sinarray ; c1 + x2(c2+x2C3) mulpd xmm4, xmm12 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm13 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zszc mulpd xmm3, xmm1 ; x3 mulpd xmm2, xmm0 ; upper x3 for sin mulsd xmm2, xmm0 ; lower x4 for cos movhlps xmm9, xmm6 ; upper xx for sin term ; note using even reg movlpd xmm12, QWORD PTR p_temp2[rsp] ; lower r for cos term mulpd xmm6, xmm0 ; x * xx for lower cos term mulsd xmm9, QWORD PTR p_temp2[rsp+8] ; xx * 0.5*x2 for upper sin term subsd xmm10, xmm12 ; (1 + (-t)) - r mulpd xmm5, xmm3 ; x3 * zs mulpd xmm4, xmm2 ; lower=x4 * zc ; upper=x3 * zs movhlps xmm8, xmm4 ; xmm9= sin, xmm5= cos subsd xmm8, xmm9 ; x3zs - 0.5*x2*xx subsd xmm10, xmm6 ; ((1 + (-t)) - r) - x*xx subpd xmm5, xmm11 ; x3*zs - 0.5*x2*xx addsd xmm4, xmm10 ; x4*zc + (((1 + (-t)) - r) - x*xx) addsd xmm8, QWORD PTR p_temp[rsp+8] ; +xx movhlps xmm0, xmm0 ; upper x for sin addpd xmm5, xmm7 ; +xx subsd xmm12, QWORD PTR __real_3ff0000000000000 ; -t = r-1 addsd xmm8, xmm0 ; +x addpd xmm5, xmm1 ; +x subsd xmm4, xmm12 ; + t movlhps xmm4, xmm8 jmp __vrda_cos_cleanup align 16 sinsin_sinsin_piby4: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; p_sign0 = Sign, xmm0 = r, xmm2 = r2, xmm6 =rr ; p_sign1 = Sign, xmm1 = r, xmm3 = r2, xmm7 =rr ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; movapd xmm10, xmm2 ; x2 movapd xmm11, xmm3 ; x2 movdqa xmm4, OWORD PTR sinarray+50h ; c6 movdqa xmm5, OWORD PTR sinarray+50h ; c6 movapd xmm8, OWORD PTR sinarray+20h ; c3 movapd xmm9, OWORD PTR sinarray+20h ; c3 movapd OWORD PTR p_temp2[rsp], xmm2 ; copy of x2 movapd OWORD PTR p_temp3[rsp], xmm3 ; copy of x2 mulpd xmm4, xmm2 ; c6*x2 mulpd xmm5, xmm3 ; c6*x2 mulpd xmm8, xmm2 ; c3*x2 mulpd xmm9, xmm3 ; c3*x2 mulpd xmm10, xmm2 ; x4 mulpd xmm11, xmm3 ; x4 addpd xmm4, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm5, OWORD PTR sinarray+40h ; c5+x2c6 addpd xmm8, OWORD PTR sinarray+10h ; c2+x2C3 addpd xmm9, OWORD PTR sinarray+10h ; c2+x2C3 mulpd xmm10, xmm2 ; x6 mulpd xmm11, xmm3 ; x6 mulpd xmm4, xmm2 ; x2(c5+x2c6) mulpd xmm5, xmm3 ; x2(c5+x2c6) mulpd xmm8, xmm2 ; x2(c2+x2C3) mulpd xmm9, xmm3 ; x2(c2+x2C3) mulpd xmm2, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 mulpd xmm3, OWORD PTR __real_3fe0000000000000 ; 0.5 *x2 addpd xmm4, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm5, OWORD PTR sinarray+30h ; c4 + x2(c5+x2c6) addpd xmm8, OWORD PTR sinarray ; c1 + x2(c2+x2C3) addpd xmm9, OWORD PTR sinarray ; c1 + x2(c2+x2C3) mulpd xmm2, xmm6 ; 0.5 * x2 *xx mulpd xmm3, xmm7 ; 0.5 * x2 *xx mulpd xmm4, xmm10 ; x6(c4 + x2(c5+x2c6)) mulpd xmm5, xmm11 ; x6(c4 + x2(c5+x2c6)) addpd xmm4, xmm8 ; zs addpd xmm5, xmm9 ; zs movapd xmm10, OWORD PTR p_temp2[rsp] ; x2 movapd xmm11, OWORD PTR p_temp3[rsp] ; x2 mulpd xmm10, xmm0 ; x3 mulpd xmm11, xmm1 ; x3 mulpd xmm4, xmm10 ; x3 * zs mulpd xmm5, xmm11 ; x3 * zs subpd xmm4, xmm2 ; -0.5 * x2 *xx subpd xmm5, xmm3 ; -0.5 * x2 *xx addpd xmm4, xmm6 ; +xx addpd xmm5, xmm7 ; +xx addpd xmm4, xmm0 ; +x addpd xmm5, xmm1 ; +x jmp __vrda_cos_cleanup END
inventory_check: andi a0, a0, 0xFF li t0, SAVE_CONTEXT beq a0, 0x8C, @@return ; Deku Nuts (5) lbu v0, 0x75 (t0) beq a0, 0x8D, @@return ; Deku Nuts (10) lbu v0, 0x75 (t0) beq a0, 0x00, @@return ; Deku Stick lbu v0, 0x74 (t0) beq a0, 0x8A, @@return ; Deku Sticks (5) lbu v0, 0x74 (t0) beq a0, 0x8B, @@return ; Deku Sticks (10) lbu v0, 0x74 (t0) beq a0, 0x58, @@return ; Deku Seeds (5) li v0, 0x00 beq a0, 0x78, @@return ; Small Magic Jar li v0, 0x00 beq a0, 0x79, @@return ; Large Magic Jar li v0, 0x00 li v0, 0xFF @@return: jr ra nop ;================================================================================================== override_object_npc: lw a2, 0x0030 (sp) lh a1, 0x0004 (a2) j override_object nop override_object_chest: lw t9, 0x002C (sp) lh a1, 0x0004 (t9) j override_object nop override_object: li t2, EXTENDED_ITEM_DATA lw t3, ITEM_ROW_IS_EXTENDED (t2) beqz t3, @@return nop ; Override Object ID lhu a1, ITEM_ROW_OBJECT_ID (t2) @@return: ; Clear any pending special item, now that it's being received li t2, PENDING_SPECIAL_ITEM sb r0, 0x00 (t2) ; Re-enable warping (disabled by pending item) li t2, GLOBAL_CONTEXT + 0x104E4 sh r0, 0x00 (t2) jr ra nop ;================================================================================================== override_graphic: li t0, EXTENDED_ITEM_DATA lw t1, ITEM_ROW_IS_EXTENDED (t0) beqz t1, @@return nop ; Override Graphic ID lb v1, ITEM_ROW_GRAPHIC_ID (t0) @@return: ; Displaced code abs t0, v1 sb t0, 0x0852 (a0) jr ra nop ;================================================================================================== override_text: lbu a1, 0x03 (v0) ; Displaced code li t0, EXTENDED_ITEM_DATA lw t1, ITEM_ROW_IS_EXTENDED (t0) beqz t1, @@return nop ; Override Text ID lbu a1, ITEM_ROW_TEXT_ID (t0) @@return: jr ra nop ;================================================================================================== override_action: ; Displaced code lw v0, 0x24 (sp) lbu a1, 0x0000 (v0) li t0, EXTENDED_ITEM_DATA lw t1, ITEM_ROW_IS_EXTENDED (t0) beqz t1, @@return nop ; Override Action ID lbu a1, ITEM_ROW_ACTION_ID (t0) sw a0, 0x00 (sp) sw a1, 0x04 (sp) sw a2, 0x08 (sp) addiu sp, sp, -0x18 sw ra, 0x10 (sp) ; Run effect function li a0, SAVE_CONTEXT lbu a1, ITEM_ROW_EFFECT_ARG1 (t0) lbu a2, ITEM_ROW_EFFECT_ARG2 (t0) lw t1, ITEM_ROW_EFFECT_FN (t0) jalr t1 nop lw ra, 0x10 (sp) addiu sp, sp, 0x18 lw a0, 0x00 (sp) lw a1, 0x04 (sp) lw a2, 0x08 (sp) @@return: jr ra nop ;================================================================================================== store_item_data_hook: sb a2, 0x0424 (a3) ; Displaced code addiu sp, sp, -0x20 sw v0, 0x10 (sp) sw v1, 0x14 (sp) sw ra, 0x18 (sp) jal store_item_data nop lw v0, 0x10 (sp) lw v1, 0x14 (sp) lw ra, 0x18 (sp) addiu sp, sp, 0x20 jr ra nop ;================================================================================================== store_item_data: addiu sp, sp, -0x18 sw ra, 0x10 (sp) ; Clear current item data li t0, EXTENDED_ITEM_DATA sw r0, 0x00 (t0) sw r0, 0x04 (t0) sw r0, 0x08 (t0) sw r0, 0x0C (t0) li t0, PLAYER_ACTOR lb t1, 0x0424 (t0) ; t1 = item ID being received beqz t1, @@return nop abs a0, t1 lw a1, 0x0428 (t0) ; a1 = actor giving the item jal lookup_override ; v0 = new item ID from override nop bltz v0, @@return nop ori a0, v0, 0 jal resolve_extended_item ; v0 = resolved item ID, v1 = ITEM_TABLE entry nop beqz v1, @@update_base_game nop ; Store extended item data li t0, EXTENDED_ITEM_DATA lw t1, 0x00 (v1) sw t1, 0x00 (t0) lw t1, 0x04 (v1) sw t1, 0x04 (t0) lw t1, 0x08 (v1) sw t1, 0x08 (t0) ; Mark the extended item data as active li t1, 1 sw t1, ITEM_ROW_IS_EXTENDED (t0) ; Load the base item to be stored back in the player actor / chest lbu v0, ITEM_ROW_BASE_ITEM (v1) @@update_base_game: li t0, PLAYER_ACTOR ; If the giving actor is a chest, update it with new contents lw t1, 0x0428 (t0) lhu t2, 0x00 (t1) bne t2, 0x000A, @@not_chest nop lhu t2, 0x1C (t1) andi t2, t2, 0xF01F sll t3, v0, 5 or t2, t2, t3 sh t2, 0x1C (t1) @@not_chest: ; Update player actor lb t1, 0x0424 (t0) bgez t1, @@not_negative nop ; The input was negative (item is in a nearby chest), so make the result negative subu v0, r0, v0 @@not_negative: sb v0, 0x0424 (t0) @@return: lw ra, 0x10 (sp) addiu sp, sp, 0x18 jr ra nop ;================================================================================================== lookup_override: ; a0 = item ID being received ; a1 = actor giving the item addiu sp, sp, -0x18 sw ra, 0x10 (sp) jal get_override_search_key nop beq v0, -1, @@return nop ori a0, v0, 0 jal scan_override_table nop @@return: lw ra, 0x10 (sp) addiu sp, sp, 0x18 jr ra nop ;================================================================================================== get_override_search_key: ; a0 = item ID being received ; a1 = actor giving the item ; Load the current scene number li v0, GLOBAL_CONTEXT lhu v0, 0xA4 (v0) li t0, 0x00 ; t0 = override type ori t1, a0, 0 ; t1 = override ID lhu t2, 0x00 (a1) ; t2 = actor ID bne t2, 0x000A, @@not_chest nop lhu t3, 0x1C (a1) bne v0, 0x10, @@valid_chest nop ; Current scene is the treasure chest game. ; Don't apply the override if the chest contains 0x75 (Winner! purple rupee) andi t4, t3, (0x7F << 5) bne t4, (0x75 << 5), @@valid_chest nop li v0, -1 b @@return nop @@valid_chest: li t0, 0x01 andi t1, t3, 0x1F ; t1 = chest flag @@not_chest: bne t2, 0x0015, @@not_collectable nop beq a0, 0x3E, @@valid_collectable nop beq a0, 0x42, @@valid_collectable nop li v0, -1 b @@return nop @@valid_collectable: li t0, 0x02 lbu t1, 0x0141 (a1) ; t1 = collectable flag @@not_collectable: ; Construct ID used to search the override table ; v0 = (scene << 16) | (override_type << 8) | override_id sll v0, v0, 8 or v0, v0, t0 sll v0, v0, 8 or v0, v0, t1 @@return: jr ra nop ;================================================================================================== scan_override_table: ; a0 = override search key li v0, -1 ; Look up override li t0, (ITEM_OVERRIDES - 0x04) @@lookup_loop: addiu t0, t0, 0x04 lw t1, 0x00 (t0) ; t1 = override entry beqz t1, @@return ; Reached end of override table nop srl t2, t1, 8 ; t2 = override key bne t2, a0, @@lookup_loop nop andi v0, t1, 0xFF ; v0 = found item ID @@return: jr ra nop ;================================================================================================== resolve_extended_item: ; a0 = input item ID addiu sp, sp, -0x20 sw s0, 0x10 (sp) sw s1, 0x14 (sp) sw ra, 0x18 (sp) ori v0, a0, 0 ; Return resolved item ID in v0 @@loop: ori s0, v0, 0 addiu t0, s0, -0x80 ; t0 = index into extended ITEM_TABLE bltz t0, @@not_extended ; Item IDs in range 0x00 - 0x7F are not extended nop ; Load table entry li s1, ITEM_TABLE li t1, ITEM_TABLE_ROW_SIZE mult t0, t1 mflo t0 addu s1, s1, t0 ; s1 = pointer to table entry ; Check whether this item will upgrade into another item ; Conventions for upgrade functions: ; - They receive a pointer to the save context in a0 ; - They receive their item ID in a1 ; - They store their result in v0 li a0, SAVE_CONTEXT ori a1, s0, 0 lw t0, ITEM_ROW_UPGRADE_FN (s1) jalr t0 ; v0 = upgraded item ID nop ; If the upgrade function returned a new item ID, start resolution over again bne v0, s0, @@loop nop ori v1, s1, 0 ; Return pointer to ITEM_TABLE entry in v1 b @@return nop @@not_extended: li v1, 0 @@return: lw s0, 0x10 (sp) lw s1, 0x14 (sp) lw ra, 0x18 (sp) addiu sp, sp, 0x20 jr ra nop
; A066490: Number of primes of the form 4m+3 <= n. ; 0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,11,11,11,11,11,11,11,11,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28 mov $10,1 lpb $10,1 mov $5,$0 mov $7,$0 add $7,1 sub $10,1 lpb $7,1 clr $0,5 mov $0,$5 sub $7,4 sub $0,$7 add $2,1 sub $0,$2 mov $3,$2 cal $0,10051 ; Characteristic function of primes: 1 if n is prime, else 0. mov $2,6 sub $2,$3 add $0,$2 mov $1,$0 sub $1,5 mul $1,2 add $6,$1 lpe lpe mov $1,$6 div $1,2
/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ // [[CITE]] ABC // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification // http://www.eecs.berkeley.edu/~alanmi/abc/ // [[CITE]] Berkeley Logic Interchange Format (BLIF) // University of California. Berkeley. July 28, 1992 // http://www.ece.cmu.edu/~ee760/760docs/blif.pdf // [[CITE]] Kahn's Topological sorting algorithm // Kahn, Arthur B. (1962), "Topological sorting of large networks", Communications of the ACM 5 (11): 558-562, doi:10.1145/368996.369025 // http://en.wikipedia.org/wiki/Topological_sorting #define ABC_COMMAND_LIB "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put" #define ABC_COMMAND_CTR "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p" #define ABC_COMMAND_LUT "strash; ifraig; scorr; dc2; dretime; strash; dch -f; if; mfs2" #define ABC_COMMAND_SOP "strash; ifraig; scorr; dc2; dretime; strash; dch -f; cover {I} {P}" #define ABC_COMMAND_DFL "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put" #define ABC_FAST_COMMAND_LIB "strash; dretime; map {D}" #define ABC_FAST_COMMAND_CTR "strash; dretime; map {D}; buffer; upsize {D}; dnsize {D}; stime -p" #define ABC_FAST_COMMAND_LUT "strash; dretime; if" #define ABC_FAST_COMMAND_SOP "strash; dretime; cover {I} {P}" #define ABC_FAST_COMMAND_DFL "strash; dretime; map" #include "kernel/register.h" #include "kernel/sigtools.h" #include "kernel/celltypes.h" #include "kernel/ffinit.h" #include "kernel/ff.h" #include "kernel/cost.h" #include "kernel/log.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <cctype> #include <cerrno> #include <sstream> #include <climits> #include <vector> #ifndef _WIN32 # include <unistd.h> # include <dirent.h> #endif #include "frontends/blif/blifparse.h" #ifdef YOSYS_LINK_ABC extern "C" int Abc_RealMain(int argc, char *argv[]); #endif USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN enum class gate_type_t { G_NONE, G_FF, G_FF0, G_FF1, G_BUF, G_NOT, G_AND, G_NAND, G_OR, G_NOR, G_XOR, G_XNOR, G_ANDNOT, G_ORNOT, G_MUX, G_NMUX, G_AOI3, G_OAI3, G_AOI4, G_OAI4 }; #define G(_name) gate_type_t::G_ ## _name struct gate_t { int id; gate_type_t type; int in1, in2, in3, in4; bool is_port; RTLIL::SigBit bit; RTLIL::State init; }; bool map_mux4; bool map_mux8; bool map_mux16; bool markgroups; int map_autoidx; SigMap assign_map; RTLIL::Module *module; std::vector<gate_t> signal_list; dict<RTLIL::SigBit, int> signal_map; FfInitVals initvals; pool<std::string> enabled_gates; bool cmos_cost; bool had_init; bool clk_polarity, en_polarity, arst_polarity, srst_polarity; RTLIL::SigSpec clk_sig, en_sig, arst_sig, srst_sig; dict<int, std::string> pi_map, po_map; int map_signal(RTLIL::SigBit bit, gate_type_t gate_type = G(NONE), int in1 = -1, int in2 = -1, int in3 = -1, int in4 = -1) { assign_map.apply(bit); if (signal_map.count(bit) == 0) { gate_t gate; gate.id = signal_list.size(); gate.type = G(NONE); gate.in1 = -1; gate.in2 = -1; gate.in3 = -1; gate.in4 = -1; gate.is_port = false; gate.bit = bit; gate.init = initvals(bit); signal_list.push_back(gate); signal_map[bit] = gate.id; } gate_t &gate = signal_list[signal_map[bit]]; if (gate_type != G(NONE)) gate.type = gate_type; if (in1 >= 0) gate.in1 = in1; if (in2 >= 0) gate.in2 = in2; if (in3 >= 0) gate.in3 = in3; if (in4 >= 0) gate.in4 = in4; return gate.id; } void mark_port(RTLIL::SigSpec sig) { for (auto &bit : assign_map(sig)) if (bit.wire != nullptr && signal_map.count(bit) > 0) signal_list[signal_map[bit]].is_port = true; } void extract_cell(RTLIL::Cell *cell, bool keepff) { if (RTLIL::builtin_ff_cell_types().count(cell->type)) { FfData ff(&initvals, cell); gate_type_t type = G(FF); if (!ff.has_clk) return; if (ff.has_gclk) return; if (ff.has_aload) return; if (ff.has_sr) return; if (!ff.is_fine) return; if (clk_polarity != ff.pol_clk) return; if (clk_sig != assign_map(ff.sig_clk)) return; if (ff.has_ce) { if (en_polarity != ff.pol_ce) return; if (en_sig != assign_map(ff.sig_ce)) return; } else { if (GetSize(en_sig) != 0) return; } if (ff.val_init == State::S1) { type = G(FF1); had_init = true; } else if (ff.val_init == State::S0) { type = G(FF0); had_init = true; } if (ff.has_arst) { if (arst_polarity != ff.pol_arst) return; if (arst_sig != assign_map(ff.sig_arst)) return; if (ff.val_arst == State::S1) { if (type == G(FF0)) return; type = G(FF1); } else if (ff.val_arst == State::S0) { if (type == G(FF1)) return; type = G(FF0); } } else { if (GetSize(arst_sig) != 0) return; } if (ff.has_srst) { if (srst_polarity != ff.pol_srst) return; if (srst_sig != assign_map(ff.sig_srst)) return; if (ff.val_srst == State::S1) { if (type == G(FF0)) return; type = G(FF1); } else if (ff.val_srst == State::S0) { if (type == G(FF1)) return; type = G(FF0); } } else { if (GetSize(srst_sig) != 0) return; } if (keepff) for (auto &c : ff.sig_q.chunks()) if (c.wire != nullptr) c.wire->attributes[ID::keep] = 1; map_signal(ff.sig_q, type, map_signal(ff.sig_d)); ff.remove(); return; } if (cell->type.in(ID($_BUF_), ID($_NOT_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); assign_map.apply(sig_a); assign_map.apply(sig_y); map_signal(sig_y, cell->type == ID($_BUF_) ? G(BUF) : G(NOT), map_signal(sig_a)); module->remove(cell); return; } if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); assign_map.apply(sig_a); assign_map.apply(sig_b); assign_map.apply(sig_y); int mapped_a = map_signal(sig_a); int mapped_b = map_signal(sig_b); if (cell->type == ID($_AND_)) map_signal(sig_y, G(AND), mapped_a, mapped_b); else if (cell->type == ID($_NAND_)) map_signal(sig_y, G(NAND), mapped_a, mapped_b); else if (cell->type == ID($_OR_)) map_signal(sig_y, G(OR), mapped_a, mapped_b); else if (cell->type == ID($_NOR_)) map_signal(sig_y, G(NOR), mapped_a, mapped_b); else if (cell->type == ID($_XOR_)) map_signal(sig_y, G(XOR), mapped_a, mapped_b); else if (cell->type == ID($_XNOR_)) map_signal(sig_y, G(XNOR), mapped_a, mapped_b); else if (cell->type == ID($_ANDNOT_)) map_signal(sig_y, G(ANDNOT), mapped_a, mapped_b); else if (cell->type == ID($_ORNOT_)) map_signal(sig_y, G(ORNOT), mapped_a, mapped_b); else log_abort(); module->remove(cell); return; } if (cell->type.in(ID($_MUX_), ID($_NMUX_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_s = cell->getPort(ID::S); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); assign_map.apply(sig_a); assign_map.apply(sig_b); assign_map.apply(sig_s); assign_map.apply(sig_y); int mapped_a = map_signal(sig_a); int mapped_b = map_signal(sig_b); int mapped_s = map_signal(sig_s); map_signal(sig_y, cell->type == ID($_MUX_) ? G(MUX) : G(NMUX), mapped_a, mapped_b, mapped_s); module->remove(cell); return; } if (cell->type.in(ID($_AOI3_), ID($_OAI3_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_c = cell->getPort(ID::C); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); assign_map.apply(sig_a); assign_map.apply(sig_b); assign_map.apply(sig_c); assign_map.apply(sig_y); int mapped_a = map_signal(sig_a); int mapped_b = map_signal(sig_b); int mapped_c = map_signal(sig_c); map_signal(sig_y, cell->type == ID($_AOI3_) ? G(AOI3) : G(OAI3), mapped_a, mapped_b, mapped_c); module->remove(cell); return; } if (cell->type.in(ID($_AOI4_), ID($_OAI4_))) { RTLIL::SigSpec sig_a = cell->getPort(ID::A); RTLIL::SigSpec sig_b = cell->getPort(ID::B); RTLIL::SigSpec sig_c = cell->getPort(ID::C); RTLIL::SigSpec sig_d = cell->getPort(ID::D); RTLIL::SigSpec sig_y = cell->getPort(ID::Y); assign_map.apply(sig_a); assign_map.apply(sig_b); assign_map.apply(sig_c); assign_map.apply(sig_d); assign_map.apply(sig_y); int mapped_a = map_signal(sig_a); int mapped_b = map_signal(sig_b); int mapped_c = map_signal(sig_c); int mapped_d = map_signal(sig_d); map_signal(sig_y, cell->type == ID($_AOI4_) ? G(AOI4) : G(OAI4), mapped_a, mapped_b, mapped_c, mapped_d); module->remove(cell); return; } } std::string remap_name(RTLIL::IdString abc_name, RTLIL::Wire **orig_wire = nullptr) { std::string abc_sname = abc_name.substr(1); bool isnew = false; if (abc_sname.compare(0, 4, "new_") == 0) { abc_sname.erase(0, 4); isnew = true; } if (abc_sname.compare(0, 5, "ys__n") == 0) { abc_sname.erase(0, 5); if (std::isdigit(abc_sname.at(0))) { int sid = std::atoi(abc_sname.c_str()); size_t postfix_start = abc_sname.find_first_not_of("0123456789"); std::string postfix = postfix_start != std::string::npos ? abc_sname.substr(postfix_start) : ""; if (sid < GetSize(signal_list)) { auto sig = signal_list.at(sid); if (sig.bit.wire != nullptr) { std::string s = stringf("$abc$%d$%s", map_autoidx, sig.bit.wire->name.c_str()+1); if (sig.bit.wire->width != 1) s += stringf("[%d]", sig.bit.offset); if (isnew) s += "_new"; s += postfix; if (orig_wire != nullptr) *orig_wire = sig.bit.wire; return s; } } } } return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str()+1); } void dump_loop_graph(FILE *f, int &nr, dict<int, pool<int>> &edges, pool<int> &workpool, std::vector<int> &in_counts) { if (f == nullptr) return; log("Dumping loop state graph to slide %d.\n", ++nr); fprintf(f, "digraph \"slide%d\" {\n", nr); fprintf(f, " label=\"slide%d\";\n", nr); fprintf(f, " rankdir=\"TD\";\n"); pool<int> nodes; for (auto &e : edges) { nodes.insert(e.first); for (auto n : e.second) nodes.insert(n); } for (auto n : nodes) fprintf(f, " ys__n%d [label=\"%s\\nid=%d, count=%d\"%s];\n", n, log_signal(signal_list[n].bit), n, in_counts[n], workpool.count(n) ? ", shape=box" : ""); for (auto &e : edges) for (auto n : e.second) fprintf(f, " ys__n%d -> ys__n%d;\n", e.first, n); fprintf(f, "}\n"); } void handle_loops() { // http://en.wikipedia.org/wiki/Topological_sorting // (Kahn, Arthur B. (1962), "Topological sorting of large networks") dict<int, pool<int>> edges; std::vector<int> in_edges_count(signal_list.size()); pool<int> workpool; FILE *dot_f = nullptr; int dot_nr = 0; // uncomment for troubleshooting the loop detection code // dot_f = fopen("test.dot", "w"); for (auto &g : signal_list) { if (g.type == G(NONE) || g.type == G(FF) || g.type == G(FF0) || g.type == G(FF1)) { workpool.insert(g.id); } else { if (g.in1 >= 0) { edges[g.in1].insert(g.id); in_edges_count[g.id]++; } if (g.in2 >= 0 && g.in2 != g.in1) { edges[g.in2].insert(g.id); in_edges_count[g.id]++; } if (g.in3 >= 0 && g.in3 != g.in2 && g.in3 != g.in1) { edges[g.in3].insert(g.id); in_edges_count[g.id]++; } if (g.in4 >= 0 && g.in4 != g.in3 && g.in4 != g.in2 && g.in4 != g.in1) { edges[g.in4].insert(g.id); in_edges_count[g.id]++; } } } dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count); while (workpool.size() > 0) { int id = *workpool.begin(); workpool.erase(id); // log("Removing non-loop node %d from graph: %s\n", id, log_signal(signal_list[id].bit)); for (int id2 : edges[id]) { log_assert(in_edges_count[id2] > 0); if (--in_edges_count[id2] == 0) workpool.insert(id2); } edges.erase(id); dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count); while (workpool.size() == 0) { if (edges.size() == 0) break; int id1 = edges.begin()->first; for (auto &edge_it : edges) { int id2 = edge_it.first; RTLIL::Wire *w1 = signal_list[id1].bit.wire; RTLIL::Wire *w2 = signal_list[id2].bit.wire; if (w1 == nullptr) id1 = id2; else if (w2 == nullptr) continue; else if (w1->name[0] == '$' && w2->name[0] == '\\') id1 = id2; else if (w1->name[0] == '\\' && w2->name[0] == '$') continue; else if (edges[id1].size() < edges[id2].size()) id1 = id2; else if (edges[id1].size() > edges[id2].size()) continue; else if (w2->name.str() < w1->name.str()) id1 = id2; } if (edges[id1].size() == 0) { edges.erase(id1); continue; } log_assert(signal_list[id1].bit.wire != nullptr); std::stringstream sstr; sstr << "$abcloop$" << (autoidx++); RTLIL::Wire *wire = module->addWire(sstr.str()); bool first_line = true; for (int id2 : edges[id1]) { if (first_line) log("Breaking loop using new signal %s: %s -> %s\n", log_signal(RTLIL::SigSpec(wire)), log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit)); else log(" %*s %s -> %s\n", int(strlen(log_signal(RTLIL::SigSpec(wire)))), "", log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit)); first_line = false; } int id3 = map_signal(RTLIL::SigSpec(wire)); signal_list[id1].is_port = true; signal_list[id3].is_port = true; log_assert(id3 == int(in_edges_count.size())); in_edges_count.push_back(0); workpool.insert(id3); for (int id2 : edges[id1]) { if (signal_list[id2].in1 == id1) signal_list[id2].in1 = id3; if (signal_list[id2].in2 == id1) signal_list[id2].in2 = id3; if (signal_list[id2].in3 == id1) signal_list[id2].in3 = id3; if (signal_list[id2].in4 == id1) signal_list[id2].in4 = id3; } edges[id1].swap(edges[id3]); module->connect(RTLIL::SigSig(signal_list[id3].bit, signal_list[id1].bit)); dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count); } } if (dot_f != nullptr) fclose(dot_f); } std::string add_echos_to_abc_cmd(std::string str) { std::string new_str, token; for (size_t i = 0; i < str.size(); i++) { token += str[i]; if (str[i] == ';') { while (i+1 < str.size() && str[i+1] == ' ') i++; new_str += "echo + " + token + " " + token + " "; token.clear(); } } if (!token.empty()) { if (!new_str.empty()) new_str += "echo + " + token + "; "; new_str += token; } return new_str; } std::string fold_abc_cmd(std::string str) { std::string token, new_str = " "; int char_counter = 10; for (size_t i = 0; i <= str.size(); i++) { if (i < str.size()) token += str[i]; if (i == str.size() || str[i] == ';') { if (char_counter + token.size() > 75) new_str += "\n ", char_counter = 14; new_str += token, char_counter += token.size(); token.clear(); } } return new_str; } std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir) { if (show_tempdir) return text; while (1) { size_t pos = text.find(tempdir_name); if (pos == std::string::npos) break; text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name)); } std::string selfdir_name = proc_self_dirname(); if (selfdir_name != "/") { while (1) { size_t pos = text.find(selfdir_name); if (pos == std::string::npos) break; text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name)); } } return text; } struct abc_output_filter { bool got_cr; int escape_seq_state; std::string linebuf; std::string tempdir_name; bool show_tempdir; abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir) { got_cr = false; escape_seq_state = 0; } void next_char(char ch) { if (escape_seq_state == 0 && ch == '\033') { escape_seq_state = 1; return; } if (escape_seq_state == 1) { escape_seq_state = ch == '[' ? 2 : 0; return; } if (escape_seq_state == 2) { if ((ch < '0' || '9' < ch) && ch != ';') escape_seq_state = 0; return; } escape_seq_state = 0; if (ch == '\r') { got_cr = true; return; } if (ch == '\n') { log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str()); got_cr = false, linebuf.clear(); return; } if (got_cr) got_cr = false, linebuf.clear(); linebuf += ch; } void next_line(const std::string &line) { int pi, po; if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) { log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n", pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???", po, po_map.count(po) ? po_map.at(po).c_str() : "???"); return; } for (char ch : line) next_char(ch); } }; void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file, std::vector<std::string> &liberty_files, std::vector<std::string> &genlib_files, std::string constr_file, bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str, bool keepff, std::string delay_target, std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode, const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode, bool abc_dress) { module = current_module; map_autoidx = autoidx++; signal_map.clear(); signal_list.clear(); pi_map.clear(); po_map.clear(); if (clk_str != "$") { clk_polarity = true; clk_sig = RTLIL::SigSpec(); en_polarity = true; en_sig = RTLIL::SigSpec(); arst_polarity = true; arst_sig = RTLIL::SigSpec(); srst_polarity = true; srst_sig = RTLIL::SigSpec(); } if (!clk_str.empty() && clk_str != "$") { std::string en_str; std::string arst_str; std::string srst_str; if (clk_str.find(',') != std::string::npos) { int pos = clk_str.find(','); en_str = clk_str.substr(pos+1); clk_str = clk_str.substr(0, pos); } if (en_str.find(',') != std::string::npos) { int pos = en_str.find(','); arst_str = en_str.substr(pos+1); arst_str = en_str.substr(0, pos); } if (arst_str.find(',') != std::string::npos) { int pos = arst_str.find(','); srst_str = arst_str.substr(pos+1); srst_str = arst_str.substr(0, pos); } if (clk_str[0] == '!') { clk_polarity = false; clk_str = clk_str.substr(1); } if (module->wire(RTLIL::escape_id(clk_str)) != nullptr) clk_sig = assign_map(module->wire(RTLIL::escape_id(clk_str))); if (en_str != "") { if (en_str[0] == '!') { en_polarity = false; en_str = en_str.substr(1); } if (module->wire(RTLIL::escape_id(en_str)) != nullptr) en_sig = assign_map(module->wire(RTLIL::escape_id(en_str))); } if (arst_str != "") { if (arst_str[0] == '!') { arst_polarity = false; arst_str = arst_str.substr(1); } if (module->wire(RTLIL::escape_id(arst_str)) != nullptr) arst_sig = assign_map(module->wire(RTLIL::escape_id(arst_str))); } if (srst_str != "") { if (srst_str[0] == '!') { srst_polarity = false; srst_str = srst_str.substr(1); } if (module->wire(RTLIL::escape_id(srst_str)) != nullptr) srst_sig = assign_map(module->wire(RTLIL::escape_id(srst_str))); } } if (dff_mode && clk_sig.empty()) log_cmd_error("Clock domain %s not found.\n", clk_str.c_str()); std::string tempdir_name = "/tmp/" + proc_program_prefix()+ "yosys-abc-XXXXXX"; if (!cleanup) tempdir_name[0] = tempdir_name[4] = '_'; tempdir_name = make_temp_dir(tempdir_name); log_header(design, "Extracting gate netlist of module `%s' to `%s/input.blif'..\n", module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str()); std::string abc_script = stringf("read_blif %s/input.blif; ", tempdir_name.c_str()); if (!liberty_files.empty() || !genlib_files.empty()) { for (std::string liberty_file : liberty_files) abc_script += stringf("read_lib -w %s; ", liberty_file.c_str()); for (std::string liberty_file : genlib_files) abc_script += stringf("read_library %s; ", liberty_file.c_str()); if (!constr_file.empty()) abc_script += stringf("read_constr -v %s; ", constr_file.c_str()); } else if (!lut_costs.empty()) abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str()); else abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str()); if (!script_file.empty()) { if (script_file[0] == '+') { for (size_t i = 1; i < script_file.size(); i++) if (script_file[i] == '\'') abc_script += "'\\''"; else if (script_file[i] == ',') abc_script += " "; else abc_script += script_file[i]; } else abc_script += stringf("source %s", script_file.c_str()); } else if (!lut_costs.empty()) { bool all_luts_cost_same = true; for (int this_cost : lut_costs) if (this_cost != lut_costs.front()) all_luts_cost_same = false; abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT; if (all_luts_cost_same && !fast_mode) abc_script += "; lutpack {S}"; } else if (!liberty_files.empty() || !genlib_files.empty()) abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR); else if (sop_mode) abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP; else abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL; if (script_file.empty() && !delay_target.empty()) for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1)) abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8); for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos)) abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3); for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{I}", pos)) abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3); for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{P}", pos)) abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3); for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos)) abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3); if (abc_dress) abc_script += "; dress"; abc_script += stringf("; write_blif %s/output.blif", tempdir_name.c_str()); abc_script = add_echos_to_abc_cmd(abc_script); for (size_t i = 0; i+1 < abc_script.size(); i++) if (abc_script[i] == ';' && abc_script[i+1] == ' ') abc_script[i+1] = '\n'; std::string buffer = stringf("%s/abc.script", tempdir_name.c_str()); FILE *f = fopen(buffer.c_str(), "wt"); if (f == nullptr) log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno)); fprintf(f, "%s\n", abc_script.c_str()); fclose(f); if (dff_mode || !clk_str.empty()) { if (clk_sig.size() == 0) log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching"); else { log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig)); if (en_sig.size() != 0) log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig)); if (arst_sig.size() != 0) log(", asynchronously reset by %s%s", arst_polarity ? "" : "!", log_signal(arst_sig)); if (srst_sig.size() != 0) log(", synchronously reset by %s%s", srst_polarity ? "" : "!", log_signal(srst_sig)); log("\n"); } } had_init = false; for (auto c : cells) extract_cell(c, keepff); for (auto wire : module->wires()) { if (wire->port_id > 0 || wire->get_bool_attribute(ID::keep)) mark_port(wire); } for (auto cell : module->cells()) for (auto &port_it : cell->connections()) mark_port(port_it.second); if (clk_sig.size() != 0) mark_port(clk_sig); if (en_sig.size() != 0) mark_port(en_sig); if (arst_sig.size() != 0) mark_port(arst_sig); if (srst_sig.size() != 0) mark_port(srst_sig); handle_loops(); buffer = stringf("%s/input.blif", tempdir_name.c_str()); f = fopen(buffer.c_str(), "wt"); if (f == nullptr) log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno)); fprintf(f, ".model netlist\n"); int count_input = 0; fprintf(f, ".inputs"); for (auto &si : signal_list) { if (!si.is_port || si.type != G(NONE)) continue; fprintf(f, " ys__n%d", si.id); pi_map[count_input++] = log_signal(si.bit); } if (count_input == 0) fprintf(f, " dummy_input\n"); fprintf(f, "\n"); int count_output = 0; fprintf(f, ".outputs"); for (auto &si : signal_list) { if (!si.is_port || si.type == G(NONE)) continue; fprintf(f, " ys__n%d", si.id); po_map[count_output++] = log_signal(si.bit); } fprintf(f, "\n"); for (auto &si : signal_list) fprintf(f, "# ys__n%-5d %s\n", si.id, log_signal(si.bit)); for (auto &si : signal_list) { if (si.bit.wire == nullptr) { fprintf(f, ".names ys__n%d\n", si.id); if (si.bit == RTLIL::State::S1) fprintf(f, "1\n"); } } int count_gates = 0; for (auto &si : signal_list) { if (si.type == G(BUF)) { fprintf(f, ".names ys__n%d ys__n%d\n", si.in1, si.id); fprintf(f, "1 1\n"); } else if (si.type == G(NOT)) { fprintf(f, ".names ys__n%d ys__n%d\n", si.in1, si.id); fprintf(f, "0 1\n"); } else if (si.type == G(AND)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "11 1\n"); } else if (si.type == G(NAND)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "0- 1\n"); fprintf(f, "-0 1\n"); } else if (si.type == G(OR)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "-1 1\n"); fprintf(f, "1- 1\n"); } else if (si.type == G(NOR)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "00 1\n"); } else if (si.type == G(XOR)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "01 1\n"); fprintf(f, "10 1\n"); } else if (si.type == G(XNOR)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "00 1\n"); fprintf(f, "11 1\n"); } else if (si.type == G(ANDNOT)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "10 1\n"); } else if (si.type == G(ORNOT)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id); fprintf(f, "1- 1\n"); fprintf(f, "-0 1\n"); } else if (si.type == G(MUX)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id); fprintf(f, "1-0 1\n"); fprintf(f, "-11 1\n"); } else if (si.type == G(NMUX)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id); fprintf(f, "0-0 1\n"); fprintf(f, "-01 1\n"); } else if (si.type == G(AOI3)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id); fprintf(f, "-00 1\n"); fprintf(f, "0-0 1\n"); } else if (si.type == G(OAI3)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id); fprintf(f, "00- 1\n"); fprintf(f, "--0 1\n"); } else if (si.type == G(AOI4)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.in4, si.id); fprintf(f, "-0-0 1\n"); fprintf(f, "-00- 1\n"); fprintf(f, "0--0 1\n"); fprintf(f, "0-0- 1\n"); } else if (si.type == G(OAI4)) { fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.in4, si.id); fprintf(f, "00-- 1\n"); fprintf(f, "--00 1\n"); } else if (si.type == G(FF)) { fprintf(f, ".latch ys__n%d ys__n%d 2\n", si.in1, si.id); } else if (si.type == G(FF0)) { fprintf(f, ".latch ys__n%d ys__n%d 0\n", si.in1, si.id); } else if (si.type == G(FF1)) { fprintf(f, ".latch ys__n%d ys__n%d 1\n", si.in1, si.id); } else if (si.type != G(NONE)) log_abort(); if (si.type != G(NONE)) count_gates++; } fprintf(f, ".end\n"); fclose(f); log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n", count_gates, GetSize(signal_list), count_input, count_output); log_push(); if (count_output > 0) { log_header(design, "Executing ABC.\n"); auto &cell_cost = cmos_cost ? CellCosts::cmos_gate_cost() : CellCosts::default_gate_cost(); buffer = stringf("%s/stdcells.genlib", tempdir_name.c_str()); f = fopen(buffer.c_str(), "wt"); if (f == nullptr) log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno)); fprintf(f, "GATE ZERO 1 Y=CONST0;\n"); fprintf(f, "GATE ONE 1 Y=CONST1;\n"); fprintf(f, "GATE BUF %d Y=A; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_BUF_))); fprintf(f, "GATE NOT %d Y=!A; PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NOT_))); if (enabled_gates.count("AND")) fprintf(f, "GATE AND %d Y=A*B; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_AND_))); if (enabled_gates.count("NAND")) fprintf(f, "GATE NAND %d Y=!(A*B); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NAND_))); if (enabled_gates.count("OR")) fprintf(f, "GATE OR %d Y=A+B; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_OR_))); if (enabled_gates.count("NOR")) fprintf(f, "GATE NOR %d Y=!(A+B); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NOR_))); if (enabled_gates.count("XOR")) fprintf(f, "GATE XOR %d Y=(A*!B)+(!A*B); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_XOR_))); if (enabled_gates.count("XNOR")) fprintf(f, "GATE XNOR %d Y=(A*B)+(!A*!B); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_XNOR_))); if (enabled_gates.count("ANDNOT")) fprintf(f, "GATE ANDNOT %d Y=A*!B; PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_ANDNOT_))); if (enabled_gates.count("ORNOT")) fprintf(f, "GATE ORNOT %d Y=A+!B; PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_ORNOT_))); if (enabled_gates.count("AOI3")) fprintf(f, "GATE AOI3 %d Y=!((A*B)+C); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_AOI3_))); if (enabled_gates.count("OAI3")) fprintf(f, "GATE OAI3 %d Y=!((A+B)*C); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_OAI3_))); if (enabled_gates.count("AOI4")) fprintf(f, "GATE AOI4 %d Y=!((A*B)+(C*D)); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_AOI4_))); if (enabled_gates.count("OAI4")) fprintf(f, "GATE OAI4 %d Y=!((A+B)*(C+D)); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_OAI4_))); if (enabled_gates.count("MUX")) fprintf(f, "GATE MUX %d Y=(A*B)+(S*B)+(!S*A); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_MUX_))); if (enabled_gates.count("NMUX")) fprintf(f, "GATE NMUX %d Y=!((A*B)+(S*B)+(!S*A)); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_NMUX_))); if (map_mux4) fprintf(f, "GATE MUX4 %d Y=(!S*!T*A)+(S*!T*B)+(!S*T*C)+(S*T*D); PIN * UNKNOWN 1 999 1 0 1 0\n", 2*cell_cost.at(ID($_MUX_))); if (map_mux8) fprintf(f, "GATE MUX8 %d Y=(!S*!T*!U*A)+(S*!T*!U*B)+(!S*T*!U*C)+(S*T*!U*D)+(!S*!T*U*E)+(S*!T*U*F)+(!S*T*U*G)+(S*T*U*H); PIN * UNKNOWN 1 999 1 0 1 0\n", 4*cell_cost.at(ID($_MUX_))); if (map_mux16) fprintf(f, "GATE MUX16 %d Y=(!S*!T*!U*!V*A)+(S*!T*!U*!V*B)+(!S*T*!U*!V*C)+(S*T*!U*!V*D)+(!S*!T*U*!V*E)+(S*!T*U*!V*F)+(!S*T*U*!V*G)+(S*T*U*!V*H)+(!S*!T*!U*V*I)+(S*!T*!U*V*J)+(!S*T*!U*V*K)+(S*T*!U*V*L)+(!S*!T*U*V*M)+(S*!T*U*V*N)+(!S*T*U*V*O)+(S*T*U*V*P); PIN * UNKNOWN 1 999 1 0 1 0\n", 8*cell_cost.at(ID($_MUX_))); fclose(f); if (!lut_costs.empty()) { buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str()); f = fopen(buffer.c_str(), "wt"); if (f == nullptr) log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno)); for (int i = 0; i < GetSize(lut_costs); i++) fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i)); fclose(f); } buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str()); log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str()); #ifndef YOSYS_LINK_ABC abc_output_filter filt(tempdir_name, show_tempdir); int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1)); #else // These needs to be mutable, supposedly due to getopt char *abc_argv[5]; string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str()); abc_argv[0] = strdup(exe_file.c_str()); abc_argv[1] = strdup("-s"); abc_argv[2] = strdup("-f"); abc_argv[3] = strdup(tmp_script_name.c_str()); abc_argv[4] = 0; int ret = Abc_RealMain(4, abc_argv); free(abc_argv[0]); free(abc_argv[1]); free(abc_argv[2]); free(abc_argv[3]); #endif if (ret != 0) log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret); buffer = stringf("%s/%s", tempdir_name.c_str(), "output.blif"); std::ifstream ifs; ifs.open(buffer); if (ifs.fail()) log_error("Can't open ABC output file `%s'.\n", buffer.c_str()); bool builtin_lib = liberty_files.empty() && genlib_files.empty(); RTLIL::Design *mapped_design = new RTLIL::Design; parse_blif(mapped_design, ifs, builtin_lib ? ID(DFF) : ID(_dff_), false, sop_mode); ifs.close(); log_header(design, "Re-integrating ABC results.\n"); RTLIL::Module *mapped_mod = mapped_design->module(ID(netlist)); if (mapped_mod == nullptr) log_error("ABC output file does not contain a module `netlist'.\n"); for (auto w : mapped_mod->wires()) { RTLIL::Wire *orig_wire = nullptr; RTLIL::Wire *wire = module->addWire(remap_name(w->name, &orig_wire)); if (orig_wire != nullptr && orig_wire->attributes.count(ID::src)) wire->attributes[ID::src] = orig_wire->attributes[ID::src]; if (markgroups) wire->attributes[ID::abcgroup] = map_autoidx; design->select(module, wire); } SigMap mapped_sigmap(mapped_mod); FfInitVals mapped_initvals(&mapped_sigmap, mapped_mod); dict<std::string, int> cell_stats; for (auto c : mapped_mod->cells()) { if (builtin_lib) { cell_stats[RTLIL::unescape_id(c->type)]++; if (c->type.in(ID(ZERO), ID(ONE))) { RTLIL::SigSig conn; RTLIL::IdString name_y = remap_name(c->getPort(ID::Y).as_wire()->name); conn.first = module->wire(name_y); conn.second = RTLIL::SigSpec(c->type == ID(ZERO) ? 0 : 1, 1); module->connect(conn); continue; } if (c->type == ID(BUF)) { RTLIL::SigSig conn; RTLIL::IdString name_y = remap_name(c->getPort(ID::Y).as_wire()->name); RTLIL::IdString name_a = remap_name(c->getPort(ID::A).as_wire()->name); conn.first = module->wire(name_y); conn.second = module->wire(name_a); module->connect(conn); continue; } if (c->type == ID(NOT)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_NOT_)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type.in(ID(AND), ID(OR), ID(XOR), ID(NAND), ID(NOR), ID(XNOR), ID(ANDNOT), ID(ORNOT))) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type.in(ID(MUX), ID(NMUX))) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::S, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type == ID(MUX4)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX4_)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::S, ID::T, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type == ID(MUX8)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX8_)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::S, ID::T, ID::U, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type == ID(MUX16)) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX16_)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::I, ID::J, ID::K, ID::L, ID::M, ID::N, ID::O, ID::P, ID::S, ID::T, ID::U, ID::V, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type.in(ID(AOI3), ID(OAI3))) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type.in(ID(AOI4), ID(OAI4))) { RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1)); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::Y}) { RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name); cell->setPort(name, module->wire(remapped_name)); } design->select(module, cell); continue; } if (c->type == ID(DFF)) { log_assert(clk_sig.size() == 1); FfData ff(module, &initvals, remap_name(c->name)); ff.width = 1; ff.is_fine = true; ff.has_clk = true; ff.pol_clk = clk_polarity; ff.sig_clk = clk_sig; if (en_sig.size() != 0) { log_assert(en_sig.size() == 1); ff.has_ce = true; ff.pol_ce = en_polarity; ff.sig_ce = en_sig; } RTLIL::Const init = mapped_initvals(c->getPort(ID::Q)); if (had_init) ff.val_init = init; else ff.val_init = State::Sx; if (arst_sig.size() != 0) { log_assert(arst_sig.size() == 1); ff.has_arst = true; ff.pol_arst = arst_polarity; ff.sig_arst = arst_sig; ff.val_arst = init; } if (srst_sig.size() != 0) { log_assert(srst_sig.size() == 1); ff.has_srst = true; ff.pol_srst = srst_polarity; ff.sig_srst = srst_sig; ff.val_srst = init; } ff.sig_d = module->wire(remap_name(c->getPort(ID::D).as_wire()->name)); ff.sig_q = module->wire(remap_name(c->getPort(ID::Q).as_wire()->name)); RTLIL::Cell *cell = ff.emit(); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; design->select(module, cell); continue; } } else cell_stats[RTLIL::unescape_id(c->type)]++; if (c->type.in(ID(_const0_), ID(_const1_))) { RTLIL::SigSig conn; conn.first = module->wire(remap_name(c->connections().begin()->second.as_wire()->name)); conn.second = RTLIL::SigSpec(c->type == ID(_const0_) ? 0 : 1, 1); module->connect(conn); continue; } if (c->type == ID(_dff_)) { log_assert(clk_sig.size() == 1); FfData ff(module, &initvals, remap_name(c->name)); ff.width = 1; ff.is_fine = true; ff.has_clk = true; ff.pol_clk = clk_polarity; ff.sig_clk = clk_sig; if (en_sig.size() != 0) { log_assert(en_sig.size() == 1); ff.pol_ce = en_polarity; ff.sig_ce = en_sig; } RTLIL::Const init = mapped_initvals(c->getPort(ID::Q)); if (had_init) ff.val_init = init; else ff.val_init = State::Sx; if (arst_sig.size() != 0) { log_assert(arst_sig.size() == 1); ff.pol_arst = arst_polarity; ff.sig_arst = arst_sig; ff.val_arst = init; } if (srst_sig.size() != 0) { log_assert(srst_sig.size() == 1); ff.pol_srst = srst_polarity; ff.sig_srst = srst_sig; ff.val_srst = init; } ff.sig_d = module->wire(remap_name(c->getPort(ID::D).as_wire()->name)); ff.sig_q = module->wire(remap_name(c->getPort(ID::Q).as_wire()->name)); RTLIL::Cell *cell = ff.emit(); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; design->select(module, cell); continue; } if (c->type == ID($lut) && GetSize(c->getPort(ID::A)) == 1 && c->getParam(ID::LUT).as_int() == 2) { SigSpec my_a = module->wire(remap_name(c->getPort(ID::A).as_wire()->name)); SigSpec my_y = module->wire(remap_name(c->getPort(ID::Y).as_wire()->name)); module->connect(my_y, my_a); continue; } RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type); if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx; cell->parameters = c->parameters; for (auto &conn : c->connections()) { RTLIL::SigSpec newsig; for (auto &c : conn.second.chunks()) { if (c.width == 0) continue; log_assert(c.width == 1); newsig.append(module->wire(remap_name(c.wire->name))); } cell->setPort(conn.first, newsig); } design->select(module, cell); } for (auto conn : mapped_mod->connections()) { if (!conn.first.is_fully_const()) conn.first = module->wire(remap_name(conn.first.as_wire()->name)); if (!conn.second.is_fully_const()) conn.second = module->wire(remap_name(conn.second.as_wire()->name)); module->connect(conn); } for (auto &it : cell_stats) log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second); int in_wires = 0, out_wires = 0; for (auto &si : signal_list) if (si.is_port) { char buffer[100]; snprintf(buffer, 100, "\\ys__n%d", si.id); RTLIL::SigSig conn; if (si.type != G(NONE)) { conn.first = si.bit; conn.second = module->wire(remap_name(buffer)); out_wires++; } else { conn.first = module->wire(remap_name(buffer)); conn.second = si.bit; in_wires++; } module->connect(conn); } log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires); log("ABC RESULTS: input signals: %8d\n", in_wires); log("ABC RESULTS: output signals: %8d\n", out_wires); delete mapped_design; } else { log("Don't call ABC as there is nothing to map.\n"); } if (cleanup) { log("Removing temp directory.\n"); remove_directory(tempdir_name); } log_pop(); } struct AbcPass : public Pass { AbcPass() : Pass("abc", "use ABC for technology mapping") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" abc [options] [selection]\n"); log("\n"); log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n"); log("library to a target architecture.\n"); log("\n"); log(" -exe <command>\n"); #ifdef ABCEXTERNAL log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n"); #else log(" use the specified command instead of \"<yosys-bindir>/%syosys-abc\" to execute ABC.\n", proc_program_prefix().c_str()); #endif log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n"); log("\n"); log(" -script <file>\n"); log(" use the specified ABC script file instead of the default script.\n"); log("\n"); log(" if <file> starts with a plus sign (+), then the rest of the filename\n"); log(" string is interpreted as the command string to be passed to ABC. The\n"); log(" leading plus sign is removed and all commas (,) in the string are\n"); log(" replaced with blanks before the string is passed to ABC.\n"); log("\n"); log(" if no -script parameter is given, the following scripts are used:\n"); log("\n"); log(" for -liberty/-genlib without -constr:\n"); log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str()); log("\n"); log(" for -liberty/-genlib with -constr:\n"); log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str()); log("\n"); log(" for -lut/-luts (only one LUT size):\n"); log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str()); log("\n"); log(" for -lut/-luts (different LUT sizes):\n"); log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str()); log("\n"); log(" for -sop:\n"); log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str()); log("\n"); log(" otherwise:\n"); log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str()); log("\n"); log(" -fast\n"); log(" use different default scripts that are slightly faster (at the cost\n"); log(" of output quality):\n"); log("\n"); log(" for -liberty/-genlib without -constr:\n"); log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str()); log("\n"); log(" for -liberty/-genlib with -constr:\n"); log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str()); log("\n"); log(" for -lut/-luts:\n"); log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str()); log("\n"); log(" for -sop:\n"); log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str()); log("\n"); log(" otherwise:\n"); log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str()); log("\n"); log(" -liberty <file>\n"); log(" generate netlists for the specified cell library (using the liberty\n"); log(" file format).\n"); log("\n"); log(" -genlib <file>\n"); log(" generate netlists for the specified cell library (using the SIS Genlib\n"); log(" file format).\n"); log("\n"); log(" -constr <file>\n"); log(" pass this file with timing constraints to ABC.\n"); log(" use with -liberty/-genlib.\n"); log("\n"); log(" a constr file contains two lines:\n"); log(" set_driving_cell <cell_name>\n"); log(" set_load <floating_point_number>\n"); log("\n"); log(" the set_driving_cell statement defines which cell type is assumed to\n"); log(" drive the primary inputs and the set_load statement sets the load in\n"); log(" femtofarads for each primary output.\n"); log("\n"); log(" -D <picoseconds>\n"); log(" set delay target. the string {D} in the default scripts above is\n"); log(" replaced by this option when used, and an empty string otherwise.\n"); log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n"); log(" default scripts above.\n"); log("\n"); log(" -I <num>\n"); log(" maximum number of SOP inputs.\n"); log(" (replaces {I} in the default scripts above)\n"); log("\n"); log(" -P <num>\n"); log(" maximum number of SOP products.\n"); log(" (replaces {P} in the default scripts above)\n"); log("\n"); log(" -S <num>\n"); log(" maximum number of LUT inputs shared.\n"); log(" (replaces {S} in the default scripts above, default: -S 1)\n"); log("\n"); log(" -lut <width>\n"); log(" generate netlist using luts of (max) the specified width.\n"); log("\n"); log(" -lut <w1>:<w2>\n"); log(" generate netlist using luts of (max) the specified width <w2>. All\n"); log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n"); log(" the area cost doubles with each additional input bit. the delay cost\n"); log(" is still constant for all lut widths.\n"); log("\n"); log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n"); log(" generate netlist using luts. Use the specified costs for luts with 1,\n"); log(" 2, 3, .. inputs.\n"); log("\n"); log(" -sop\n"); log(" map to sum-of-product cells and inverters\n"); log("\n"); // log(" -mux4, -mux8, -mux16\n"); // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n"); // log(" (ignored when used with -liberty/-genlib or -lut)\n"); // log("\n"); log(" -g type1,type2,...\n"); log(" Map to the specified list of gate types. Supported gates types are:\n"); // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX,\n"); log(" NMUX, AOI3, OAI3, AOI4, OAI4.\n"); log(" (The NOT gate is always added to this list automatically.)\n"); log("\n"); log(" The following aliases can be used to reference common sets of gate types:\n"); log(" simple: AND OR XOR MUX\n"); log(" cmos2: NAND NOR\n"); log(" cmos3: NAND NOR AOI3 OAI3\n"); log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n"); log(" cmos: NAND NOR AOI3 OAI3 AOI4 OAI4 NMUX MUX XOR XNOR\n"); log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n"); log(" aig: AND NAND OR NOR ANDNOT ORNOT\n"); log("\n"); log(" The alias 'all' represent the full set of all gate types.\n"); log("\n"); log(" Prefix a gate type with a '-' to remove it from the list. For example\n"); log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n"); log("\n"); log(" The default is 'all,-NMUX,-AOI3,-OAI3,-AOI4,-OAI4'.\n"); log("\n"); log(" -dff\n"); log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n"); log(" clock domains are automatically partitioned in clock domains and each\n"); log(" domain is passed through ABC independently.\n"); log("\n"); log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n"); log(" use only the specified clock domain. this is like -dff, but only FF\n"); log(" cells that belong to the specified clock domain are used.\n"); log("\n"); log(" -keepff\n"); log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n"); log(" them, for example for equivalence checking.)\n"); log("\n"); log(" -nocleanup\n"); log(" when this option is used, the temporary files created by this pass\n"); log(" are not removed. this is useful for debugging.\n"); log("\n"); log(" -showtmp\n"); log(" print the temp dir name in log. usually this is suppressed so that the\n"); log(" command output is identical across runs.\n"); log("\n"); log(" -markgroups\n"); log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n"); log(" this attribute is a unique integer for each ABC process started. This\n"); log(" is useful for debugging the partitioning of clock domains.\n"); log("\n"); log(" -dress\n"); log(" run the 'dress' command after all other ABC commands. This aims to\n"); log(" preserve naming by an equivalence check between the original and post-ABC\n"); log(" netlists (experimental).\n"); log("\n"); log("When no target cell library is specified the Yosys standard cell library is\n"); log("loaded into ABC before the ABC script is executed.\n"); log("\n"); log("Note that this is a logic optimization pass within Yosys that is calling ABC\n"); log("internally. This is not going to \"run ABC on your design\". It will instead run\n"); log("ABC on logic snippets extracted from your design. You will not get any useful\n"); log("output when passing an ABC script that writes a file. Instead write your full\n"); log("design as BLIF file with write_blif and then load that into ABC externally if\n"); log("you want to use ABC to convert your design into another format.\n"); log("\n"); log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { log_header(design, "Executing ABC pass (technology mapping using ABC).\n"); log_push(); assign_map.clear(); signal_list.clear(); signal_map.clear(); initvals.clear(); pi_map.clear(); po_map.clear(); std::string exe_file = yosys_abc_executable; std::string script_file, default_liberty_file, constr_file, clk_str; std::vector<std::string> liberty_files, genlib_files; std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1"; bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true; bool show_tempdir = false, sop_mode = false; bool abc_dress = false; vector<int> lut_costs; markgroups = false; map_mux4 = false; map_mux8 = false; map_mux16 = false; enabled_gates.clear(); cmos_cost = false; // get arguments from scratchpad first, then override by command arguments std::string lut_arg, luts_arg, g_arg; exe_file = design->scratchpad_get_string("abc.exe", exe_file /* inherit default value if not set */); script_file = design->scratchpad_get_string("abc.script", script_file); default_liberty_file = design->scratchpad_get_string("abc.liberty", default_liberty_file); constr_file = design->scratchpad_get_string("abc.constr", constr_file); if (design->scratchpad.count("abc.D")) { delay_target = "-D " + design->scratchpad_get_string("abc.D"); } if (design->scratchpad.count("abc.I")) { sop_inputs = "-I " + design->scratchpad_get_string("abc.I"); } if (design->scratchpad.count("abc.P")) { sop_products = "-P " + design->scratchpad_get_string("abc.P"); } if (design->scratchpad.count("abc.S")) { lutin_shared = "-S " + design->scratchpad_get_string("abc.S"); } lut_arg = design->scratchpad_get_string("abc.lut", lut_arg); luts_arg = design->scratchpad_get_string("abc.luts", luts_arg); sop_mode = design->scratchpad_get_bool("abc.sop", sop_mode); map_mux4 = design->scratchpad_get_bool("abc.mux4", map_mux4); map_mux8 = design->scratchpad_get_bool("abc.mux8", map_mux8); map_mux16 = design->scratchpad_get_bool("abc.mux16", map_mux16); abc_dress = design->scratchpad_get_bool("abc.dress", abc_dress); g_arg = design->scratchpad_get_string("abc.g", g_arg); fast_mode = design->scratchpad_get_bool("abc.fast", fast_mode); dff_mode = design->scratchpad_get_bool("abc.dff", dff_mode); if (design->scratchpad.count("abc.clk")) { clk_str = design->scratchpad_get_string("abc.clk"); dff_mode = true; } keepff = design->scratchpad_get_bool("abc.keepff", keepff); cleanup = !design->scratchpad_get_bool("abc.nocleanup", !cleanup); keepff = design->scratchpad_get_bool("abc.keepff", keepff); show_tempdir = design->scratchpad_get_bool("abc.showtmp", show_tempdir); markgroups = design->scratchpad_get_bool("abc.markgroups", markgroups); if (design->scratchpad_get_bool("abc.debug")) { cleanup = false; show_tempdir = true; } size_t argidx, g_argidx; bool g_arg_from_cmd = false; #if defined(__wasm) const char *pwd = "."; #else char pwd [PATH_MAX]; if (!getcwd(pwd, sizeof(pwd))) { log_cmd_error("getcwd failed: %s\n", strerror(errno)); log_abort(); } #endif for (argidx = 1; argidx < args.size(); argidx++) { std::string arg = args[argidx]; if (arg == "-exe" && argidx+1 < args.size()) { exe_file = args[++argidx]; continue; } if (arg == "-script" && argidx+1 < args.size()) { script_file = args[++argidx]; continue; } if (arg == "-liberty" && argidx+1 < args.size()) { liberty_files.push_back(args[++argidx]); continue; } if (arg == "-genlib" && argidx+1 < args.size()) { genlib_files.push_back(args[++argidx]); continue; } if (arg == "-constr" && argidx+1 < args.size()) { constr_file = args[++argidx]; continue; } if (arg == "-D" && argidx+1 < args.size()) { delay_target = "-D " + args[++argidx]; continue; } if (arg == "-I" && argidx+1 < args.size()) { sop_inputs = "-I " + args[++argidx]; continue; } if (arg == "-P" && argidx+1 < args.size()) { sop_products = "-P " + args[++argidx]; continue; } if (arg == "-S" && argidx+1 < args.size()) { lutin_shared = "-S " + args[++argidx]; continue; } if (arg == "-lut" && argidx+1 < args.size()) { lut_arg = args[++argidx]; continue; } if (arg == "-luts" && argidx+1 < args.size()) { luts_arg = args[++argidx]; continue; } if (arg == "-sop") { sop_mode = true; continue; } if (arg == "-mux4") { map_mux4 = true; continue; } if (arg == "-mux8") { map_mux8 = true; continue; } if (arg == "-mux16") { map_mux16 = true; continue; } if (arg == "-dress") { abc_dress = true; continue; } if (arg == "-g" && argidx+1 < args.size()) { if (g_arg_from_cmd) log_cmd_error("Can only use -g once. Please combine."); g_arg = args[++argidx]; g_argidx = argidx; g_arg_from_cmd = true; continue; } if (arg == "-fast") { fast_mode = true; continue; } if (arg == "-dff") { dff_mode = true; continue; } if (arg == "-clk" && argidx+1 < args.size()) { clk_str = args[++argidx]; dff_mode = true; continue; } if (arg == "-keepff") { keepff = true; continue; } if (arg == "-nocleanup") { cleanup = false; continue; } if (arg == "-showtmp") { show_tempdir = true; continue; } if (arg == "-markgroups") { markgroups = true; continue; } break; } extra_args(args, argidx, design); if (genlib_files.empty() && liberty_files.empty() && !default_liberty_file.empty()) liberty_files.push_back(default_liberty_file); rewrite_filename(script_file); if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+') script_file = std::string(pwd) + "/" + script_file; for (int i = 0; i < GetSize(liberty_files); i++) { rewrite_filename(liberty_files[i]); if (!liberty_files[i].empty() && !is_absolute_path(liberty_files[i])) liberty_files[i] = std::string(pwd) + "/" + liberty_files[i]; } for (int i = 0; i < GetSize(genlib_files); i++) { rewrite_filename(genlib_files[i]); if (!genlib_files[i].empty() && !is_absolute_path(genlib_files[i])) genlib_files[i] = std::string(pwd) + "/" + genlib_files[i]; } rewrite_filename(constr_file); if (!constr_file.empty() && !is_absolute_path(constr_file)) constr_file = std::string(pwd) + "/" + constr_file; // handle -lut argument if (!lut_arg.empty()) { size_t pos = lut_arg.find_first_of(':'); int lut_mode = 0, lut_mode2 = 0; if (pos != string::npos) { lut_mode = atoi(lut_arg.substr(0, pos).c_str()); lut_mode2 = atoi(lut_arg.substr(pos+1).c_str()); } else { lut_mode = atoi(lut_arg.c_str()); lut_mode2 = lut_mode; } lut_costs.clear(); for (int i = 0; i < lut_mode; i++) lut_costs.push_back(1); for (int i = lut_mode; i < lut_mode2; i++) lut_costs.push_back(2 << (i - lut_mode)); } //handle -luts argument if (!luts_arg.empty()){ lut_costs.clear(); for (auto &tok : split_tokens(luts_arg, ",")) { auto parts = split_tokens(tok, ":"); if (GetSize(parts) == 0 && !lut_costs.empty()) lut_costs.push_back(lut_costs.back()); else if (GetSize(parts) == 1) lut_costs.push_back(atoi(parts.at(0).c_str())); else if (GetSize(parts) == 2) while (GetSize(lut_costs) < std::atoi(parts.at(0).c_str())) lut_costs.push_back(atoi(parts.at(1).c_str())); else log_cmd_error("Invalid -luts syntax.\n"); } } // handle -g argument if (!g_arg.empty()){ for (auto g : split_tokens(g_arg, ",")) { vector<string> gate_list; bool remove_gates = false; if (GetSize(g) > 0 && g[0] == '-') { remove_gates = true; g = g.substr(1); } if (g == "AND") goto ok_gate; if (g == "NAND") goto ok_gate; if (g == "OR") goto ok_gate; if (g == "NOR") goto ok_gate; if (g == "XOR") goto ok_gate; if (g == "XNOR") goto ok_gate; if (g == "ANDNOT") goto ok_gate; if (g == "ORNOT") goto ok_gate; if (g == "MUX") goto ok_gate; if (g == "NMUX") goto ok_gate; if (g == "AOI3") goto ok_gate; if (g == "OAI3") goto ok_gate; if (g == "AOI4") goto ok_gate; if (g == "OAI4") goto ok_gate; if (g == "simple") { gate_list.push_back("AND"); gate_list.push_back("OR"); gate_list.push_back("XOR"); gate_list.push_back("MUX"); goto ok_alias; } if (g == "cmos2") { if (!remove_gates) cmos_cost = true; gate_list.push_back("NAND"); gate_list.push_back("NOR"); goto ok_alias; } if (g == "cmos3") { if (!remove_gates) cmos_cost = true; gate_list.push_back("NAND"); gate_list.push_back("NOR"); gate_list.push_back("AOI3"); gate_list.push_back("OAI3"); goto ok_alias; } if (g == "cmos4") { if (!remove_gates) cmos_cost = true; gate_list.push_back("NAND"); gate_list.push_back("NOR"); gate_list.push_back("AOI3"); gate_list.push_back("OAI3"); gate_list.push_back("AOI4"); gate_list.push_back("OAI4"); goto ok_alias; } if (g == "cmos") { if (!remove_gates) cmos_cost = true; gate_list.push_back("NAND"); gate_list.push_back("NOR"); gate_list.push_back("AOI3"); gate_list.push_back("OAI3"); gate_list.push_back("AOI4"); gate_list.push_back("OAI4"); gate_list.push_back("NMUX"); gate_list.push_back("MUX"); gate_list.push_back("XOR"); gate_list.push_back("XNOR"); goto ok_alias; } if (g == "gates") { gate_list.push_back("AND"); gate_list.push_back("NAND"); gate_list.push_back("OR"); gate_list.push_back("NOR"); gate_list.push_back("XOR"); gate_list.push_back("XNOR"); gate_list.push_back("ANDNOT"); gate_list.push_back("ORNOT"); goto ok_alias; } if (g == "aig") { gate_list.push_back("AND"); gate_list.push_back("NAND"); gate_list.push_back("OR"); gate_list.push_back("NOR"); gate_list.push_back("ANDNOT"); gate_list.push_back("ORNOT"); goto ok_alias; } if (g == "all") { gate_list.push_back("AND"); gate_list.push_back("NAND"); gate_list.push_back("OR"); gate_list.push_back("NOR"); gate_list.push_back("XOR"); gate_list.push_back("XNOR"); gate_list.push_back("ANDNOT"); gate_list.push_back("ORNOT"); gate_list.push_back("AOI3"); gate_list.push_back("OAI3"); gate_list.push_back("AOI4"); gate_list.push_back("OAI4"); gate_list.push_back("MUX"); gate_list.push_back("NMUX"); goto ok_alias; } if (g_arg_from_cmd) cmd_error(args, g_argidx, stringf("Unsupported gate type: %s", g.c_str())); else log_cmd_error("Unsupported gate type: %s", g.c_str()); ok_gate: gate_list.push_back(g); ok_alias: for (auto gate : gate_list) { if (remove_gates) enabled_gates.erase(gate); else enabled_gates.insert(gate); } } } if (!lut_costs.empty() && !(liberty_files.empty() && genlib_files.empty())) log_cmd_error("Got -lut and -liberty/-genlib! These two options are exclusive.\n"); if (!constr_file.empty() && (liberty_files.empty() && genlib_files.empty())) log_cmd_error("Got -constr but no -liberty/-genlib!\n"); if (enabled_gates.empty()) { enabled_gates.insert("AND"); enabled_gates.insert("NAND"); enabled_gates.insert("OR"); enabled_gates.insert("NOR"); enabled_gates.insert("XOR"); enabled_gates.insert("XNOR"); enabled_gates.insert("ANDNOT"); enabled_gates.insert("ORNOT"); // enabled_gates.insert("AOI3"); // enabled_gates.insert("OAI3"); // enabled_gates.insert("AOI4"); // enabled_gates.insert("OAI4"); enabled_gates.insert("MUX"); // enabled_gates.insert("NMUX"); } for (auto mod : design->selected_modules()) { if (mod->processes.size() > 0) { log("Skipping module %s as it contains processes.\n", log_id(mod)); continue; } assign_map.set(mod); initvals.set(&assign_map, mod); if (!dff_mode || !clk_str.empty()) { abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode, abc_dress); continue; } CellTypes ct(design); std::vector<RTLIL::Cell*> all_cells = mod->selected_cells(); pool<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end()); pool<RTLIL::Cell*> expand_queue, next_expand_queue; pool<RTLIL::Cell*> expand_queue_up, next_expand_queue_up; pool<RTLIL::Cell*> expand_queue_down, next_expand_queue_down; typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec, bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t; dict<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells; dict<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse; dict<RTLIL::Cell*, pool<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down; dict<RTLIL::SigBit, pool<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down; for (auto cell : all_cells) { clkdomain_t key; for (auto &conn : cell->connections()) for (auto bit : conn.second) { bit = assign_map(bit); if (bit.wire != nullptr) { cell_to_bit[cell].insert(bit); bit_to_cell[bit].insert(cell); if (ct.cell_input(cell->type, conn.first)) { cell_to_bit_up[cell].insert(bit); bit_to_cell_down[bit].insert(cell); } if (ct.cell_output(cell->type, conn.first)) { cell_to_bit_down[cell].insert(bit); bit_to_cell_up[bit].insert(cell); } } } if (!RTLIL::builtin_ff_cell_types().count(cell->type)) continue; FfData ff(&initvals, cell); if (!ff.has_clk) continue; if (ff.has_gclk) continue; if (ff.has_aload) continue; if (ff.has_sr) continue; if (!ff.is_fine) continue; key = clkdomain_t( ff.pol_clk, ff.sig_clk, ff.has_ce ? ff.pol_ce : true, ff.has_ce ? assign_map(ff.sig_ce) : RTLIL::SigSpec(), ff.has_arst ? ff.pol_arst : true, ff.has_arst ? assign_map(ff.sig_arst) : RTLIL::SigSpec(), ff.has_srst ? ff.pol_srst : true, ff.has_srst ? assign_map(ff.sig_srst) : RTLIL::SigSpec() ); unassigned_cells.erase(cell); expand_queue.insert(cell); expand_queue_up.insert(cell); expand_queue_down.insert(cell); assigned_cells[key].push_back(cell); assigned_cells_reverse[cell] = key; } while (!expand_queue_up.empty() || !expand_queue_down.empty()) { if (!expand_queue_up.empty()) { RTLIL::Cell *cell = *expand_queue_up.begin(); clkdomain_t key = assigned_cells_reverse.at(cell); expand_queue_up.erase(cell); for (auto bit : cell_to_bit_up[cell]) for (auto c : bit_to_cell_up[bit]) if (unassigned_cells.count(c)) { unassigned_cells.erase(c); next_expand_queue_up.insert(c); assigned_cells[key].push_back(c); assigned_cells_reverse[c] = key; expand_queue.insert(c); } } if (!expand_queue_down.empty()) { RTLIL::Cell *cell = *expand_queue_down.begin(); clkdomain_t key = assigned_cells_reverse.at(cell); expand_queue_down.erase(cell); for (auto bit : cell_to_bit_down[cell]) for (auto c : bit_to_cell_down[bit]) if (unassigned_cells.count(c)) { unassigned_cells.erase(c); next_expand_queue_up.insert(c); assigned_cells[key].push_back(c); assigned_cells_reverse[c] = key; expand_queue.insert(c); } } if (expand_queue_up.empty() && expand_queue_down.empty()) { expand_queue_up.swap(next_expand_queue_up); expand_queue_down.swap(next_expand_queue_down); } } while (!expand_queue.empty()) { RTLIL::Cell *cell = *expand_queue.begin(); clkdomain_t key = assigned_cells_reverse.at(cell); expand_queue.erase(cell); for (auto bit : cell_to_bit.at(cell)) { for (auto c : bit_to_cell[bit]) if (unassigned_cells.count(c)) { unassigned_cells.erase(c); next_expand_queue.insert(c); assigned_cells[key].push_back(c); assigned_cells_reverse[c] = key; } bit_to_cell[bit].clear(); } if (expand_queue.empty()) expand_queue.swap(next_expand_queue); } clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec(), true, RTLIL::SigSpec(), true, RTLIL::SigSpec()); for (auto cell : unassigned_cells) { assigned_cells[key].push_back(cell); assigned_cells_reverse[cell] = key; } log_header(design, "Summary of detected clock domains:\n"); for (auto &it : assigned_cells) log(" %d cells in clk=%s%s, en=%s%s, arst=%s%s, srst=%s%s\n", GetSize(it.second), std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)), std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)), std::get<4>(it.first) ? "" : "!", log_signal(std::get<5>(it.first)), std::get<6>(it.first) ? "" : "!", log_signal(std::get<7>(it.first))); for (auto &it : assigned_cells) { clk_polarity = std::get<0>(it.first); clk_sig = assign_map(std::get<1>(it.first)); en_polarity = std::get<2>(it.first); en_sig = assign_map(std::get<3>(it.first)); arst_polarity = std::get<4>(it.first); arst_sig = assign_map(std::get<5>(it.first)); srst_polarity = std::get<6>(it.first); srst_sig = assign_map(std::get<7>(it.first)); abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$", keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode, abc_dress); assign_map.set(mod); } } assign_map.clear(); signal_list.clear(); signal_map.clear(); initvals.clear(); pi_map.clear(); po_map.clear(); log_pop(); } } AbcPass; PRIVATE_NAMESPACE_END
#include "Halide.h" #include "daubechies_constants.h" namespace { Halide::Var x("x"), y("y"), c("c"); class daubechies_x : public Halide::Generator<daubechies_x> { public: Input<Buffer<float>> in_{"in", 2}; Output<Buffer<float>> out_{"out", 3}; void generate() { Func in = Halide::BoundaryConditions::repeat_edge(in_); out_(x, y, c) = select(c == 0, D0 * in(2 * x - 1, y) + D1 * in(2 * x, y) + D2 * in(2 * x + 1, y) + D3 * in(2 * x + 2, y), D3 * in(2 * x - 1, y) - D2 * in(2 * x, y) + D1 * in(2 * x + 1, y) - D0 * in(2 * x + 2, y)); out_.unroll(c, 2); } }; } // namespace HALIDE_REGISTER_GENERATOR(daubechies_x, daubechies_x)
; A227466: E.g.f. equals the series reversion of tanh(x) / exp(x). ; Submitted by Christian Krause ; 1,2,11,96,1149,17520,324855,7096320,178495065,5081045760,161485639875,5668185600000,217773547039125,9090267234048000,409648199646660975,19822083757572096000,1025047834112461784625,56415976360602034176000,3292602426688307236378875 lpb $0 sub $0,1 add $2,$3 add $3,1 mov $1,$3 mul $1,$0 add $2,$1 add $1,$3 mul $1,$0 add $4,1 mul $3,$4 add $3,$2 mov $2,$1 lpe mov $0,$3 add $0,1
; A065367: Replace 3^k with (-3)^k in balanced ternary expansion of n. ; Submitted by Christian Krause ; 1,-4,-3,-2,11,12,13,8,9,10,5,6,7,-34,-33,-32,-37,-36,-35,-40,-39,-38,-25,-24,-23,-28,-27,-26,-31,-30,-29,-16,-15,-14,-19,-18,-17,-22,-21,-20,101,102,103,98,99,100,95,96,97,110,111,112,107,108,109,104,105,106,119,120,121,116,117,118,113 add $0,2 mov $2,4 lpb $0 mul $2,3 sub $1,$2 mov $3,$0 div $0,3 add $3,$0 add $0,1 mod $3,4 mul $3,$2 add $1,$3 div $2,-1 lpe mov $0,$1 div $0,12
COMMENT @----------------------------------------------------------------------- Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: Text Library FILE: uiSearchReplaceControl.asm ROUTINES: Name Description ---- ----------- GLB SearchReplaceControlClass Style menu object REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 3/92 Initial version DESCRIPTION: This file contains routines to implement SearchReplaceControlClass $Id: uiSearchReplace.asm,v 1.1 97/04/07 11:17:48 newdeal Exp $ -------------------------------------------------------------------------------@ ;--------------------------------------------------- TextClassStructures segment resource SearchReplaceControlClass ;declare the class record ifdef GPC_SEARCH OverrideCenterOnMonikersClass endif TextClassStructures ends ;--------------------------------------------------- if not NO_CONTROLLERS TextSRControlCommon segment resource COMMENT @---------------------------------------------------------------------- MESSAGE: SearchReplaceControlScanFeatureHints -- MSG_GEN_CONTROL_SCAN_FEATURE_HINTS for SearchReplaceControlClass DESCRIPTION: Alter SRCF_REPLACE_ALL_IN_SELECTION based on .ini file. PASS: *ds:si - instance data es - segment of SearchReplaceControlClass ax - The message RETURN: DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 1/4/98 Initial version ------------------------------------------------------------------------------@ ifdef GPC_SEARCH SearchReplaceControlScanFeatureHints method dynamic SearchReplaceControlClass, MSG_GEN_CONTROL_SCAN_FEATURE_HINTS mov di, offset SearchReplaceControlClass call ObjCallSuperNoLock push dx segmov ds, cs, cx mov si, offset replaceInSelectionStringCat mov dx, offset replaceInSelectionStringKey call InitFileReadBoolean ; C clr if found pop dx jc removeReplaceInSelection cmp ax, TRUE je leaveReplaceInSelection removeReplaceInSelection: mov ds, dx mov si, bp ornf ds:[si].GCSI_appProhibited, mask SRCF_REPLACE_ALL_IN_SELECTION leaveReplaceInSelection: ; ; build feature flags to determine if we should have close button ; mov ds, dx mov si, bp mov ax, SRC_DEFAULT_FEATURES ornf ax, ds:[si].GCSI_userAdded mov bx, ds:[si].GCSI_userRemoved not bx andnf ax, bx ornf ax, ds:[si].GCSI_appRequired mov bx, ds:[si].GCSI_appProhibited not bx andnf ax, bx call SR_CheckFullHeight jnc notFullHeight ornf ds:[si].GCSI_appProhibited, mask SRCF_CLOSE notFullHeight: ret SearchReplaceControlScanFeatureHints endm replaceInSelectionStringCat char "text",0 replaceInSelectionStringKey char "ReplaceInSelection",0 endif ; GPC_SEARCH COMMENT @---------------------------------------------------------------------- MESSAGE: SearchReplaceControlGetInfo -- MSG_GEN_CONTROL_GET_INFO for SearchReplaceControlClass DESCRIPTION: Return group PASS: *ds:si - instance data es - segment of SearchReplaceControlClass ax - The message RETURN: cx:dx - list of children DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 10/31/91 Initial version ------------------------------------------------------------------------------@ SearchReplaceControlGetInfo method dynamic SearchReplaceControlClass, MSG_GEN_CONTROL_GET_INFO mov si, offset SRC_dupInfo GOTO SR_CopyDupInfoCommon SearchReplaceControlGetInfo endm SR_CopyDupInfoCommon proc far mov es, cx mov di, dx ;es:di = dest segmov ds, cs mov cx, size GenControlBuildInfo rep movsb ret SR_CopyDupInfoCommon endp SRC_dupInfo GenControlBuildInfo < mask GCBF_DO_NOT_DESTROY_CHILDREN_WHEN_CLOSED, ; GCBI_flags offset SRC_IniFileKey, ; GCBI_initFileKey offset SRC_gcnList, ; GCBI_gcnList length SRC_gcnList, ; GCBI_gcnCount offset SRC_notifyTypeList, ; GCBI_notificationList length SRC_notifyTypeList, ; GCBI_notificationCount SRCName, ; GCBI_controllerName handle SearchReplaceControlUI, ; GCBI_dupBlock offset SRC_childList, ; GCBI_childList length SRC_childList, ; GCBI_childCount offset SRC_featuresList, ; GCBI_featuresList length SRC_featuresList, ; GCBI_featuresCount SRC_DEFAULT_FEATURES, ; GCBI_features handle SearchReplaceControlToolboxUI, ; GCBI_toolBlock offset SRC_toolList, ; GCBI_toolList length SRC_toolList, ; GCBI_toolCount offset SRC_toolFeaturesList, ; GCBI_toolFeaturesList length SRC_toolFeaturesList, ; GCBI_toolFeaturesCount SRC_DEFAULT_TOOLBOX_FEATURES, ; GCBI_toolFeatures SRC_helpContext> ; GCBI_helpContext if FULL_EXECUTE_IN_PLACE ControlInfoXIP segment resource endif SRC_helpContext char "dbFindRepl", 0 SRC_IniFileKey char "searchreplace", 0 SRC_gcnList GCNListType \ <MANUFACTURER_ID_GEOWORKS, GAGCNLT_APP_TARGET_NOTIFY_SEARCH_REPLACE_CHANGE>, <MANUFACTURER_ID_GEOWORKS, GAGCNLT_APP_TARGET_NOTIFY_SELECT_STATE_CHANGE> SRC_notifyTypeList NotificationType \ <MANUFACTURER_ID_GEOWORKS, GWNT_SEARCH_REPLACE_ENABLE_CHANGE> ;--- ifdef GPC_SEARCH SEARCH_TOP_FEATURES equ mask SRCF_FIND_NEXT or mask SRCF_FIND_PREV or mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION or mask SRCF_FIND_FROM_TOP or mask SRCF_SPECIAL_CHARS or mask SRCF_WILDCARDS SEARCH_BOTTOM_FEATURES equ mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION SRC_childList GenControlChildInfo \ <offset SearchReplyBar, mask SRCF_CLOSE, 0>, <offset SearchTop, SEARCH_TOP_FEATURES, 0>, <offset SearchReplaceMisc, mask SRCF_IGNORE_CASE or mask SRCF_PARTIAL_WORDS, 0>, <offset SearchBottom, SEARCH_BOTTOM_FEATURES, 0> else SRC_childList GenControlChildInfo \ <offset SearchReplyBar, mask SRCF_FIND_NEXT or mask SRCF_FIND_PREV or mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION or mask SRCF_CLOSE or mask SRCF_FIND_FROM_TOP, 0>, <offset SearchText, mask SRCF_FIND_NEXT or mask SRCF_FIND_PREV or mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION or mask SRCF_FIND_FROM_TOP, 0>, <offset ReplaceText, mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION, 0>, <offset SearchReplaceMisc, mask SRCF_SPECIAL_CHARS or mask SRCF_WILDCARDS or mask SRCF_IGNORE_CASE or mask SRCF_PARTIAL_WORDS, 0> endif ; Careful, this table is in the *opposite* order as the record which ; it corresponds to. SRC_featuresList GenControlFeaturesInfo \ <offset MiscChars, MiscCharsName, 0>, <offset WildcardChars, WildcardName, 0>, <offset CaseSensitiveOption, IgnoreCaseName, 0>, <offset PartialWordOption, PartialWordName, 0>, <offset ReplaceAllTrigger, ReplaceAllName, 0>, <offset ReplaceAllInSelectionTrigger, ReplaceAllInSelectionName, 0>, <offset ReplaceTrigger, ReplaceCurrentName, 0>, <offset FindPrevTrigger, FindPrevName, 0>, <offset FindNextTrigger, FindNextName, 0>, <offset CloseTrigger, CloseName, 0>, <offset FindFromTopTrigger, FindFromTopName, 0>, <offset SearchNoteOptions, SearchNoteOptionsName, 0> SRC_toolList GenControlChildInfo \ <offset SearchReplaceToolTrigger, mask SRCTF_SEARCH_REPLACE, mask GCCF_IS_DIRECTLY_A_FEATURE> SRC_toolFeaturesList GenControlFeaturesInfo \ <offset SearchReplaceToolTrigger, SRCName, 0> if FULL_EXECUTE_IN_PLACE ControlInfoXIP ends endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AddOrRemoveToGCNList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If the app has supplied a selection type (via the appropriate vardata entry), we add ourselves to the select state list. CALLED BY: GLOBAL PASS: ax - MSG_META_GCN_LIST_ADD/REMOVE *ds:si - object RETURN: nada DESTROYED: ax, cx, dx, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AddOrRemoveToGCNList proc far .enter ; If the user has set this attribute, this means that we need to update ; the REPLACE_IN_SELECTION trigger, so add ourselves to the SELECT_STATE ; GCN list. push ax mov ax, ATTR_SEARCH_CONTROL_SELECTION_TYPE call ObjVarFindData pop ax jnc exit sub sp, size GCNListParams mov bp, sp mov cx, ds:[LMBH_handle] movdw ss:[bp].GCNLP_optr, cxsi mov ss:[bp].GCNLP_ID.GCNLT_manuf, MANUFACTURER_ID_GEOWORKS mov ss:[bp].GCNLP_ID.GCNLT_type, dx call GenCallApplication add sp, size GCNListParams exit: .leave ret AddOrRemoveToGCNList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlAddToGCNList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This method will allow the object to be added to/removed from the GCNLists only if the appropriate vardata entry is present: ATTR_SEARCH_CONTROL_INTERACT_ONLY_WITH_TARGETED_TEXT_OBJECTS. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 8/26/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlAddToGCNList method SearchReplaceControlClass, MSG_GEN_CONTROL_ADD_TO_GCN_LISTS .enter push ax mov ax, ATTR_SEARCH_CONTROL_INTERACT_ONLY_WITH_TARGETED_TEXT_OBJECTS call ObjVarFindData pop ax jnc exit ; The ATTR is present, then pass the message to our superclass, thereby ; putting ourselves on the enable/disable list. mov di, offset SearchReplaceControlClass call ObjCallSuperNoLock exit: ; Add ourselves to the GAGCNLT_APP_TARGET_NOTIFY_SEARCH_SPELL_CHANGE list ; so we can get MSG_ABORT_ACTIVE_SEARCH. mov ax, MSG_META_GCN_LIST_ADD mov dx, GAGCNLT_APP_TARGET_NOTIFY_SEARCH_SPELL_CHANGE call AddOrRemoveToGCNList ; Now, add ourselves from the SelectionState list if the app ; has supplied a selectionType mov ax, MSG_META_GCN_LIST_ADD mov dx, GAGCNLT_APP_TARGET_NOTIFY_SELECT_STATE_CHANGE call AddOrRemoveToGCNList .leave ret SearchReplaceControlAddToGCNList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlNotifyWithDataBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This is a handler for the GWNT_SELECT_STATE_CHANGE notification - all others are ignored. CALLED BY: GLOBAL PASS: cx - manuf id dx - type bp - block RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlNotifyWithDataBlock method SearchReplaceControlClass, MSG_META_NOTIFY_WITH_DATA_BLOCK .enter cmp dx, GWNT_SELECT_STATE_CHANGE jne callSuper cmp cx, MANUFACTURER_ID_GEOWORKS je handleIt callSuper: mov di, offset SearchReplaceControlClass call ObjCallSuperNoLock .leave ret handleIt: ; There has been a change in selection in the targeted object. Update ; the ReplaceAllInSelection trigger appropriately. ; ; If the app provided a selection type to compare, use it, otherwise ; use SDT_TEXT by default. ; push ax, cx, dx, bp, es clr dl ;Assume no selection tst bp ;If no target, then there is jz noBlock ; no selection. ; Lock down the notification block and check to see if there is a ; selection of the appropriate type. mov bx, bp call MemLock mov es, ax mov ax, ATTR_SEARCH_CONTROL_SELECTION_TYPE call ObjVarFindData mov ax, SDT_TEXT jnc noTypeSet mov ax, ds:[bx] ;AX <- type of selection we ; will operate on. noTypeSet: cmp ax, es:[NSSC_selectionType] ;If we can't operate on the jnz noSelection ; current selection, then ; assume no selection. mov dl, es:[NSSC_clipboardableSelection] noSelection: mov bx, bp call MemUnlock ;Unlock the data block noBlock: ; If the new selection state is different from the old selection state, ; then update the search/replace triggers accordingly. cmp dl, ds:[di].SRCI_haveSelection je gotoSuper mov ds:[di].SRCI_haveSelection, dl call UpdateSearchReplaceTriggers gotoSuper: pop ax, cx, dx, bp, es jmp callSuper SearchReplaceControlNotifyWithDataBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlResolveVariantSuperclass %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: We subclass MSG_META_RESOLVE_VARIANT_SUPERCLASS here to add our hints before we are built CALLED BY: GLOBAL PASS: same as MSG_META_RESOLVE_VARIANT_SUPERCLASS RETURN: same as MSG_META_RESOLVE_VARIANT_SUPERCLASS DESTROYED: same as MSG_META_RESOLVE_VARIANT_SUPERCLASS PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/12/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlResolveVariantSuperclass method SearchReplaceControlClass, MSG_META_RESOLVE_VARIANT_SUPERCLASS push ax, cx, dx, bp ; Set up size hints for this critter mov ax, HINT_SIZE_WINDOW_AS_RATIO_OF_FIELD mov cx, size SpecWinSizePair call ObjVarAddData mov ds:[bx].SWSP_x, mask SWSS_RATIO or PCT_55 mov ds:[bx].SWSP_y, 0 if 0 mov ax, HINT_MINIMUM_SIZE mov cx, size CompSizeHintArgs call ObjVarAddData mov ds:[bx].CSHA_width, SpecWidth<SST_PIXELS, 250> mov ds:[bx].CSHA_height, 0 mov ds:[bx].CSHA_count, 0 endif pop ax, cx, dx, bp mov di, offset SearchReplaceControlClass GOTO ObjCallSuperNoLock SearchReplaceControlResolveVariantSuperclass endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlInitiate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Brings up the search box CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/25/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlInitiate method SearchReplaceControlClass, MSG_GEN_CONTROL_NOTIFY_INTERACTABLE mov di, offset SearchReplaceControlClass call ObjCallSuperNoLock if 0 call UpdateSearchControlUI ;Make different portions of ; the UI visible depending ; on the flags passed in. ; ENABLE OR DISABLE THE UI OF THE BOX DEPENDING UPON WHETHER OR NOT THERE ; IS AN OBJECT THAT HANDLES SEARCH METHODS AVAILABLE mov di, ds:[si] add di, ds:[di].SearchReplaceControl_offset test ds:[di].DBI_state, mask DBS_OPEN jnz alreadyOpen ornf ds:[di].DBI_state, mask DBS_OPEN clr cx ;Disable all the UI call UpdateSearchUIForTargetObject mov ax, MSG_QUERY_IF_HANDLES_SEARCH_SPELL_METHODS clrdw bxdi call GenControlOutputActionRegs alreadyOpen: endif ; SELECT THE SEARCH AND REPLACE TEXT ENTRIES call SR_GetFeaturesAndChildBlock mov_tr cx, ax test cx, mask SRCF_FIND_NEXT or mask SRCF_FIND_PREV or mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL jz exit push si mov ax, MSG_VIS_TEXT_SELECT_ALL mov si, offset SearchText mov di, mask MF_FIXUP_DS call ObjMessage push dx mov ax, MSG_VIS_TEXT_GET_TEXT_SIZE ;dxax = size mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage pop dx pop si mov_tr bp, ax ;BP <- # chars in search text mov cx, bx ;CX:DX <- optr of SearchText object mov dx, offset SearchText mov ax, MSG_META_TEXT_EMPTY_STATUS_CHANGED call ObjCallInstanceNoLock call SR_GetFeaturesAndChildBlock test ax, mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL jz exit mov ax, MSG_VIS_TEXT_SELECT_ALL mov si, offset ReplaceText mov di, mask MF_FIXUP_DS call ObjMessage exit: ret SearchReplaceControlInitiate endp ;--- SR_GetFeaturesAndChildBlock proc far EC < push es, di > EC < mov di, segment GenControlClass > EC < mov es, di > EC < mov di, offset GenControlClass > EC < call ObjIsObjectInClass > EC < ERROR_NC CONTROLLER_OBJECT_INTERNAL_ERROR > EC < pop es, di > mov ax, TEMP_GEN_CONTROL_INSTANCE call ObjVarDerefData ;ds:bx = data mov ax, ds:[bx].TGCI_features mov bx, ds:[bx].TGCI_childBlock ret SR_GetFeaturesAndChildBlock endp TextSRControlCommon ends ;--- TextSRControlCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlRemoveFromGCNList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This method will allow the object to be added to/removed from the GCNLists only if the appropriate vardata entry is present: ATTR_SEARCH_CONTROL_INTERACT_ONLY_WITH_TARGETED_TEXT_OBJECTS. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 8/26/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlRemoveFromGCNList method SearchReplaceControlClass, MSG_GEN_CONTROL_REMOVE_FROM_GCN_LISTS .enter push ax mov ax, ATTR_SEARCH_CONTROL_INTERACT_ONLY_WITH_TARGETED_TEXT_OBJECTS call ObjVarFindData pop ax jnc exit ; The ATTR is present, then pass the message to our superclass, thereby ; putting ourselves on the enable/disable list. mov di, offset SearchReplaceControlClass call ObjCallSuperNoLock exit: ; Remove ourselves from the GAGCNLT_APP_TARGET_NOTIFY_SEARCH_SPELL_CHANGE ; list so we can get MSG_ABORT_ACTIVE_SEARCH. mov ax, MSG_META_GCN_LIST_REMOVE mov dx, GAGCNLT_APP_TARGET_NOTIFY_SEARCH_SPELL_CHANGE call AddOrRemoveToGCNList ; Now, remove ourselves from the SelectionState list if the app ; has supplied a selectionType mov ax, MSG_META_GCN_LIST_REMOVE mov dx, GAGCNLT_APP_TARGET_NOTIFY_SELECT_STATE_CHANGE call AddOrRemoveToGCNList .leave ret SearchReplaceControlRemoveFromGCNList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% QueryUserForGlobalDelete %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine puts up a standard error dialog box containing the passed text. CALLED BY: GLOBAL PASS: bx - chunk in string resource containing text to display *DS:SI <- SearchReplaceControl RETURN: nada DESTROYED: ax, bx, cx, di PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 2/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ QueryUserForGlobalDelete proc near uses dx, bp, si .enter mov dx, size GenAppDoDialogParams sub sp, dx mov bp, sp mov ss:[bp].GADDP_dialog.SDP_customFlags, (CDT_QUESTION shl offset CDBF_DIALOG_TYPE or GIT_AFFIRMATION shl offset CDBF_INTERACTION_TYPE) mov di, offset GlobalDeleteQueryString mov bx, handle GlobalDeleteQueryString call MemLock push ds assume ds:TextStrings mov ds, ax mov di, ds:[di] ;DS:SI <- ptr to string to display assume ds:dgroup pop ds mov ss:[bp].GADDP_dialog.SDP_customString.segment, ax mov ss:[bp].GADDP_dialog.SDP_customString.offset, di clr ss:[bp].GADDP_dialog.SDP_helpContext.segment mov ax, ds:[LMBH_handle] mov ss:[bp].GADDP_finishOD.handle, ax mov ss:[bp].GADDP_finishOD.offset, si mov ss:[bp].GADDP_message, MSG_SRC_REPLACE_ALL_OCCURRENCES_QUERY_RESPONSE mov ax, MSG_GEN_APPLICATION_DO_STANDARD_DIALOG call GenCallApplication add sp, size GenAppDoDialogParams mov bx, handle TextStrings call MemUnlock .leave ret QueryUserForGlobalDelete endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetSearchReplaceOptions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Gets search and replace options from the list items in the box. CALLED BY: GLOBAL PASS: ds - segment of block SearchReplaceControl is in RETURN: cl - SearchOptions DESTROYED: nothing PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/25/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetSearchReplaceOptions proc near uses ax, bx, dx, di, si, bp .enter ifdef GPC_SEARCH mov cx, mask SO_IGNORE_CASE or mask SO_PARTIAL_WORD else mov cx, mask SO_IGNORE_CASE ; default SearchOptions endif mov ax, ATTR_SEARCH_CONTROL_DEFAULT_SEARCH_OPTIONS call ObjVarFindData jnc gotDefaultOptions mov cl, {SearchOptions}ds:[bx] andnf cl, mask SO_IGNORE_CASE or mask SO_PARTIAL_WORD gotDefaultOptions: call SR_GetFeaturesAndChildBlock test ax, mask SRCF_IGNORE_CASE or mask SRCF_PARTIAL_WORDS jz exit mov ax, MSG_GEN_BOOLEAN_GROUP_GET_SELECTED_BOOLEANS mov si, offset SearchReplaceOptions mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage mov_tr cx, ax exit: .leave ret GetSearchReplaceOptions endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlReplaceAllResponse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If the user clicked "YES" in the query dialog box, this continues with the global search and replace. CALLED BY: GLOBAL PASS: cx - InteractionCommand IC_YES, IC_NO, IC_NULL (if dismissed by system) RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/26/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlReplaceAllResponse method SearchReplaceControlClass, MSG_SRC_REPLACE_ALL_OCCURRENCES_QUERY_RESPONSE cmp cx, IC_YES jne exit mov ax, MSG_SRC_REPLACE_ALL_OCCURRENCES_NO_QUERY call ObjCallInstanceNoLock exit: ret SearchReplaceControlReplaceAllResponse endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendMessageToReplaceTrigger %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends the passed method off to the replace trigger. CALLED BY: GLOBAL PASS: ax - method to send cx, dx, bp - data *ds:si - SearchReplaceControl RETURN: nada DESTROYED: ax, cx, dx PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/29/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendMessageToReplaceTrigger proc near uses si,bp, di .enter push ax call SR_GetFeaturesAndChildBlock test ax, mask SRCF_REPLACE_CURRENT pop ax jz exit mov si, offset ReplaceTrigger mov di, mask MF_FIXUP_DS call ObjMessage exit: .leave ret SendMessageToReplaceTrigger endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlSearchAborted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Disables the UI gadgetry that depends on a search being active. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/29/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlSearchAborted method SearchReplaceControlClass, MSG_SRC_SEARCH_ABORTED, MSG_ABORT_ACTIVE_SEARCH mov ax, MSG_GEN_SET_NOT_ENABLED mov dl, VUM_NOW call SendMessageToReplaceTrigger ret SearchReplaceControlSearchAborted endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UpdateIfFeatureExists %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine calls ObjMessage if the zero flag is clear. CALLED BY: GLOBAL PASS: z flag clear if we want to send a message ^lbx:di - object ax - message RETURN: nada DESTROYED: di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ UpdateIfFeatureExists proc near .enter jz exit push ax, cx, dx, bp, si mov si, di mov dl, VUM_NOW mov di, mask MF_FIXUP_DS call ObjMessage pop ax, cx, dx, bp, si exit: .leave ret UpdateIfFeatureExists endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UpdateSearchReplaceTriggers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Update the search and replace triggers. CALLED BY: GLOBAL PASS: *ds:si - SearchReplaceControl object RETURN: nada DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 8/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ UpdateSearchReplaceTriggers proc far class SearchReplaceControlClass .enter ; We update the search and replace triggers - their enabled status ; depends upon 2 factors: ; ; 1) The flags set in SRCI_enableFlags ; 2) Whether or not there is text in the SearchText box ; ; And, for the ReplaceAllInSelectionTrigger, ; ; 3) Whether or not there is a selection or not (SRCI_haveSelection) ; call SR_GetFeaturesAndChildBlock push ax ;Save features ; Determine whether or not there is text in the SearchText box. If not, ; all the triggers should be disabled. push si mov ax, MSG_VIS_TEXT_GET_TEXT_SIZE mov si, offset SearchText mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage ;Returns AX = text size pop si mov_tr bp, ax ;BP <- # chars in the text object mov ax, MSG_GEN_SET_NOT_ENABLED tst bp ;If no search text, jz setSearchObjects ; disable all the triggers ; If searching is not allowed in this object, then branch to disable ; the triggers (else, enable them). mov di, ds:[si] ; add di, ds:[di].SearchReplaceControl_offset test ds:[di].SRCI_enableFlags, mask SREF_SEARCH jz setSearchObjects ;Branch if searching is not allowed mov ax, MSG_GEN_SET_ENABLED setSearchObjects: pop dx ;DX <- SearchReplaceControlFeatures mov di, offset FindNextTrigger test dx, mask SRCF_FIND_NEXT call UpdateIfFeatureExists mov di, offset FindPrevTrigger test dx, mask SRCF_FIND_PREV call UpdateIfFeatureExists mov di, offset FindFromTopTrigger test dx, mask SRCF_FIND_FROM_TOP call UpdateIfFeatureExists ; Now, do the "replace all" trigger - it should be enabled if there is ; search text and the SSEF_REPLACE bit is set. mov ax, MSG_GEN_SET_NOT_ENABLED tst bp ;Branch to disable if no text jz setReplaceObjects mov di, ds:[si] ; add di, ds:[di].SearchReplaceControl_offset test ds:[di].SRCI_enableFlags, mask SREF_REPLACE jz setReplaceObjects ;Branch if replaces are not allowed mov ax, MSG_GEN_SET_ENABLED setReplaceObjects: mov di, offset ReplaceAllTrigger test dx, mask SRCF_REPLACE_ALL call UpdateIfFeatureExists ; Now, do the "replace all in selection" trigger - it should match ; the state of the "replace all" trigger, except that we force it ; to be disabled if there is no selection. mov di, ds:[si] ; add di, ds:[di].SearchReplaceControl_offset tst ds:[di].SRCI_haveSelection jnz haveSelection mov ax, MSG_GEN_SET_NOT_ENABLED haveSelection: test dx, mask SRCF_REPLACE_ALL_IN_SELECTION mov di, offset ReplaceAllInSelectionTrigger call UpdateIfFeatureExists .leave ret UpdateSearchReplaceTriggers endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlSearchTextEmptyStatusChanged %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If there is *no* text in the search text object, this method handler disables the search/replace all triggers CALLED BY: GLOBAL PASS: CX:DX <- object that was made dirty - ignore this method if it ain't the search object. bp - non-zero if text object is empty RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 6/ 4/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlSearchTextEmptyStatusChanged method SearchReplaceControlClass, MSG_META_TEXT_EMPTY_STATUS_CHANGED cmp dx, offset SearchText jne exit call UpdateSearchReplaceTriggers exit: ret SearchReplaceControlSearchTextEmptyStatusChanged endm if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlTextLostFocus %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This method handler is called when the search or replace box loses the focus. It disables various triggers. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 7/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlTextLostFocus method SearchReplaceControlClass, MSG_META_TEXT_LOST_FOCUS clr ds:[di].SRCI_focusInfo mov ax, MSG_SRC_UPDATE_SPECIAL_CHARS_BY_FOCUS_INFO mov bx, ds:[LMBH_handle] mov di, mask MF_FORCE_QUEUE or mask MF_INSERT_AT_FRONT GOTO ObjMessage SearchReplaceControlTextLostFocus endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlUpdateSpecialCharsByFocusInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Updates the current UI state of the special chars buttons, depending upon what has the focus. CALLED BY: GLOBAL PASS: *ds:si <- search box RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 7/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlUpdateSpecialCharsByFocusInfo method SearchReplaceControlClass, MSG_SRC_UPDATE_SPECIAL_CHARS_BY_FOCUS_INFO call UpdateSpecialCharsByFocusInfo ret SearchReplaceControlUpdateSpecialCharsByFocusInfo endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% UpdateSpecialCharsByFocusInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine checks to see which item has the focus, and updates the special char UI accordingly. CALLED BY: GLOBAL PASS: *ds:si <- SearchReplaceControl object RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 7/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ UpdateSpecialCharsByFocusInfo proc near class SearchReplaceControlClass mov bx, ds:[si] add bx, ds:[bx].SearchReplaceControl_offset mov dl, ds:[bx].SRCI_focusInfo call SR_GetFeaturesAndChildBlock mov_tr cx, ax test cl, mask SRCF_SPECIAL_CHARS or mask SRCF_WILDCARDS jz exit mov ax, MSG_GEN_SET_ENABLED cmp dl, SRFI_SEARCH_TEXT ;If the search text has the jz enableSearchGadgets ; focus, enable all UI EC < cmp dl, SRFI_REPLACE_TEXT > EC < ERROR_NZ BAD_FOCUS_INFO > ; DISABLE THE CHARS NOT ALLOWED IN THE REPLACE STRING ; (Wildcards and Graphics chars) ifndef GPC_SEARCH ; separate lists, no disabling mov ax, MSG_GEN_SET_NOT_ENABLED mov di, offset justWildcardsList test cl, mask SRCF_SPECIAL_CHARS jz disable mov di, offset disableWildcardsAndGraphicsList test cl, mask SRCF_WILDCARDS jnz disable mov di, offset disableJustGraphicsList disable: mov dl, VUM_NOW mov si, cs call SendMessageToItemsInList endif mov ax, MSG_GEN_SET_ENABLED ;Enable other special chars mov di, offset nonGraphicsList ; test cl, mask SRCF_SPECIAL_CHARS jz exit doCall: mov dl, VUM_NOW mov si, cs ifdef GPC_SEARCH push di call SendMessageToItemsInList pop di cmp di, offset justWildcardsList je exit test cl, mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION jz exit mov di, offset replaceList mov si, cs call SendMessageToItemsInList else call SendMessageToItemsInList endif exit: ret enableSearchGadgets: mov di, offset miscCharsList ;Enable all but wildcards test cl, mask SRCF_WILDCARDS ; if wildcard bit is clear. jz doCall mov di, offset allCharsList ;Else, enable all chars if test cl, mask SRCF_SPECIAL_CHARS ; both bits set. jnz doCall mov di, offset justWildcardsList ;Else, just enable the jmp doCall ; wildcards UpdateSpecialCharsByFocusInfo endp allCharsList lptr WildcardChars miscCharsList lptr GraphicSpecialChar nonGraphicsList lptr PageBreakSpecialChar lptr CRSpecialChar lptr TabSpecialChar lptr 0 ifdef GPC_SEARCH replaceList lptr RPageBreakSpecialChar lptr RCRSpecialChar lptr RTabSpecialChar lptr 0 endif justWildcardsList lptr WildcardChars lptr 0 disableWildcardsAndGraphicsList lptr WildcardChars disableJustGraphicsList lptr GraphicSpecialChar lptr 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlTextGainedFocus %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This method handler is called when the search or replace box loses the focus. It disables various triggers. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 7/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlTextGainedFocus method SearchReplaceControlClass, MSG_META_TEXT_GAINED_FOCUS mov al, SRFI_SEARCH_TEXT cmp dx, offset SearchText je 10$ mov al, SRFI_REPLACE_TEXT 10$: mov ds:[di].SRCI_focusInfo, al call UpdateSpecialCharsByFocusInfo ret SearchReplaceControlTextGainedFocus endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CheckIfLowercase %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Just a front end to the DR_LOCAL_IS_LOWER function. CALLED BY: GLOBAL PASS: ax - char to check RETURN: z flag clear if is lowercase DESTROYED: nothing PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CheckIfLowercase proc near .enter call LocalIsLower .leave ret CheckIfLowercase endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CheckIfUppercase %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Just a front end to the DR_LOCAL_IS_UPPER function. CALLED BY: GLOBAL PASS: ax - char to check RETURN: z flag clear if is uppercase DESTROYED: nothing PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CheckIfUppercase proc near .enter call LocalIsUpper .leave ret CheckIfUppercase endp StringCaseInfo etype byte SCI_ALL_LOWER enum StringCaseInfo ;String is all lower case SCI_INITIAL_CAP enum StringCaseInfo ;String has only one capital - the first character SCI_ALL_CAP enum StringCaseInfo ;String has more than one capital and no lower case chars SCI_MIXED_CASE enum StringCaseInfo ;String has a non-initial capital *and* at least one lower case ; character COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetStringCaseInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine returns StringCaseInfo for the passed string. CALLED BY: GLOBAL PASS: ds:si <- ptr to string to get info for RETURN: cl - StringCaseInfo DESTROYED: ax, si PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 6/11/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetStringCaseInfo proc near uses bx .enter SBCS < clr ah > clr bx ;bx = upper case count mov cl, SCI_ALL_LOWER LocalGetChar ax, dssi LocalIsNull ax jz exit ;Exit if null string call CheckIfLowercase ;If begins with lowercase, branch jnz checkForMixedCase ; to just check for mixed case call CheckIfUppercase ;Branch if first character is *not* jz checkForAllCaps ; upper case. mov cl, SCI_INITIAL_CAP ;Else, set flag. checkForAllCaps: LocalGetChar ax, dssi ;Get next char LocalIsNull ax ;If at end of string, branch jz endString ; call CheckIfLowercase ;Branch if lowercase char found jnz notAllCaps ; (check if mixed case). call CheckIfUppercase ;If not upper case, branch back up jz checkForAllCaps ; inc bx ;BX <- # uppercase chars found jmp checkForAllCaps endString: tst bx ;If we found no non-initial caps, jz exit ; exit mov cl, SCI_ALL_CAP ;Else, we have "all caps". jmp exit notAllCaps: tst bx ;If we found multiple upper case chars jnz isMixedCase ; followed by a lower case char, ; branch (this is mixed case). Else, ; we either have an initial cap, or ; some random char followed by ; lowercase chars (like %andrew). checkForMixedCase: LocalGetChar ax, dssi ;Scan to end of string. If we encounter LocalIsNull ax ; an upper case character, then this jz exit ; is mixed case, so exit. call CheckIfUppercase jz checkForMixedCase isMixedCase: mov cl, SCI_MIXED_CASE exit: .leave ret GetStringCaseInfo endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateSearchReplaceStruct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine creates a search/replace structure. CALLED BY: GLOBAL PASS: ss:bp <- ptr to inherited local vars *ds:si - object to set as OD of SearchReplaceStruct ah - SearchSpellOptions to set SO_PRESERVE_CASE_OF_DOCUMENT_STRING will be set if necessary RETURN: dx, bx <- handle of block containing this data: SearchReplaceStruct<> data Null-Terminated Search String data Null-Terminated Replace string DESTROYED: ax, cx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 7/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CreateSearchReplaceStruct proc near uses si SBCS < searchString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (char)> SBCS < replaceString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (char)> DBCS < searchString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (wchar)> DBCS < replaceString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (wchar)> searchLength local word replaceLength local word .enter inherit far push ax mov ax, replaceLength ; DBCS < shl ax, 1 ; # chars -> # bytes > add ax, searchLength ; DBCS < add ax, searchLength ; # chars -> # bytes > add ax, size SearchReplaceStruct ;Add space for structure at ; beginning of buffer. mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK or mask HF_SHARABLE call MemAlloc mov es, ax mov ax, ds:[LMBH_handle] mov es:[SRS_replyObject].handle, ax mov es:[SRS_replyObject].chunk, si ; ; NOTE: The following code is different than the code in the spell ; library. We don't want to preserve document case in most ; cases. ; ; ; The following table lists whether or not we should preserve the case ; of the document string or just use the case of the replace string. ; ; Search String Replace String Preserve Document Case? ; ; All Caps all caps yes ; All Caps all lower/mixed case/ ; initial cap no ; ; Initial Cap initial cap yes ; Initial Cap all lower/all caps/ ; mixed case no ; ; All Lower all lower yes ; All Lower initial cap/ all caps/ ; mixed case no ; ; Mixed Case all never ; ; Basically, if the replace string has the same case as the search ; string, we want to maintain whatever case existed in the document. ; ; Otherwise, the replace string overrides the document case. ; push ds, si segmov ds, ss lea si, replaceString ;DS:SI <- replace string call GetStringCaseInfo ;CL <- StringCaseFlags for passed ; string mov ch, cl lea si, searchString call GetStringCaseInfo clr ah cmp cl, SCI_MIXED_CASE je noPreserveCase cmp cl, ch ;If case flags match, then preserve jne noPreserveCase ; case of document string. Else, branch mov ah, mask SO_PRESERVE_CASE_OF_DOCUMENT_STRING noPreserveCase: pop ds, si ; pop cx ;Restore passed SearchSpellOptions or ah, ch ; mov es:[SRS_params], ah ; mov cx, replaceLength ; mov es:[SRS_replaceSize], cx; mov cx, searchLength ;CX <- size of search text mov es:[SRS_searchSize], cx mov di, offset SRS_searchString ; COPY OVER THE SOURCE STRING push ds segmov ds, ss lea si, searchString if DBCS_PCGEOS rep movsw else shr cx jnc 15$ movsb 15$: rep movsw endif mov cx, replaceLength lea si, replaceString if DBCS_PCGEOS rep movsw else shr cx jnc 20$ movsb 20$: rep movsw endif pop ds mov dx, bx call MemUnlock ;Unlock the block .leave ret CreateSearchReplaceStruct endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ConvertGraphicToSpecialChar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Converts the graphics char to the appropriate char CALLED BY: GLOBAL PASS: es:di - ptr to char *past* graphics char es:bp - ptr to first char in string RETURN: al - special char DESTROYED: dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/25/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ConvertGraphicToSpecialChar proc near uses bp, es, di, cx .enter mov ax, di sub ax, bp DBCS < shr ax, 1 ;byte offset -> char offset > DBCS < EC <ERROR_C ODD_SIZE_FOR_DBCS_TEXT >> dec ax ;AX <- position in text mov dx, size VisTextGetGraphicAtPositionParams sub sp, dx mov bp, sp mov ss:[bp].VTGGAPP_position.low, ax clr ss:[bp].VTGGAPP_position.high sub sp, size VisTextGraphic movdw ss:[bp].VTGGAPP_retPtr, sssp mov ax, MSG_VIS_TEXT_GET_GRAPHIC_AT_POSITION mov di, mask MF_CALL or mask MF_FIXUP_DS or mask MF_STACK call ObjMessage mov bp, sp mov ax, ss:[bp].VTG_vmChain.low add sp, size VisTextGetGraphicAtPositionParams + size VisTextGraphic mov cx, length specialCharChunks segmov es, cs mov di, offset specialCharChunks repne scasw EC < ERROR_NZ CONTROLLER_OBJECT_INTERNAL_ERROR > sub di, offset specialCharChunks+2 SBCS < shr di, 1 > SBCS < mov al, cs:[specialChars][di] > DBCS < mov ax, cs:[specialChars][di] > .leave ret ConvertGraphicToSpecialChar endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextStringWithSpecialChars %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Gets the text string from the passed object, and maps all graphic chars to the appropriate special char CALLED BY: GLOBAL PASS: ss:dx - ptr to store string ^lbx:si - text object to get string from RETURN: cx - # chars in string (including null) buffer filled with data DESTROYED: ax, dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/25/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextStringWithSpecialChars proc near uses bp, es .enter mov bp, dx mov dx, ss ;DX:BP <- ptr to dest for text mov ax, MSG_VIS_TEXT_GET_ALL_PTR mov di, mask MF_FIXUP_DS or mask MF_CALL call ObjMessage jcxz exit push cx ;Save # chars in string segmov es, ss mov di, bp ;ES:DI <- ptr to string loopTop: SBCS < mov al, C_GRAPHIC > SBCS < repne scasb > DBCS < mov ax, C_GRAPHIC > DBCS < repne scasw > jne endLoop call ConvertGraphicToSpecialChar SBCS < mov es:[di][-1], al > DBCS < mov es:[di][-2], ax > tst cx jnz loopTop endLoop: pop cx ;Restore # chars in string exit: inc cx .leave ret GetTextStringWithSpecialChars endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlPassToOutput %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Passes the passed search/replace methods off to the output. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/22/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ replaceAllWithNullKeyString char "QueryGlobalDelete",0 textCategoryString char "text",0 SearchReplaceControlPassToOutput method SearchReplaceControlClass, MSG_SRC_FIND_NEXT, MSG_SRC_FIND_PREV, MSG_REPLACE_CURRENT, MSG_REPLACE_ALL_OCCURRENCES, MSG_REPLACE_ALL_OCCURRENCES_IN_SELECTION, MSG_SRC_REPLACE_ALL_OCCURRENCES_NO_QUERY, MSG_SRC_FIND_FROM_TOP SBCS < searchString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (char)> SBCS < replaceString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (char)> DBCS < searchString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (wchar)> DBCS < replaceString local SEARCH_REPLACE_MAX_WORD_LENGTH dup (wchar)> searchLength local word replaceLength local word ; ; The 4 local vars above are inherited ; methodNumber local word .enter mov methodNumber, ax push si ; Create block with data in this format: ; ; SearchReplaceStruct<> ; data Null-Terminated Search String ; data Null-Terminated Replace string ; ; GET REPLACEMENT TEXT call SR_GetFeaturesAndChildBlock SBCS< mov {char} searchString, 0 > DBCS< mov {wchar} searchString, 0 > SBCS< mov {char} replaceString, 0 > DBCS< mov {wchar} replaceString, 0 > clr cx cmp methodNumber, MSG_SRC_FIND_NEXT je skipReplace cmp methodNumber, MSG_SRC_FIND_PREV je skipReplace cmp methodNumber, MSG_SRC_FIND_FROM_TOP je skipReplace mov si, offset ReplaceText lea dx, replaceString ;SS:DX <- ptr to dest for text call GetTextStringWithSpecialChars skipReplace: mov replaceLength, cx EC < cmp cx, SEARCH_REPLACE_TEXT_MAXIMUM > EC < ERROR_A REPLACE_STRING_TOO_LARGE > ; GET SEARCH TEXT mov si, offset SearchText lea dx, searchString ;SS:DX <- ptr to dest for text call GetTextStringWithSpecialChars EC < cmp cx,1 > EC < ERROR_Z NO_SEARCH_STRING > mov searchLength, cx EC < cmp cx, SEARCH_REPLACE_TEXT_MAXIMUM > EC < ERROR_A SEARCH_STRING_TOO_LARGE > cmp replaceLength,1 jnz haveReplaceString cmp methodNumber, MSG_REPLACE_ALL_OCCURRENCES jnz haveReplaceString ; IF THE .INI FILE FLAG IS NOT SET, QUERY THE USER BEFORE DOING A GLOBAL ; REPLACE WITH AN EMPTY STRING push ds, cx, dx segmov ds, cs, cx mov si, offset textCategoryString mov dx, offset replaceAllWithNullKeyString call InitFileReadBoolean pop ds, cx, dx jc doQuery tst ax jz haveReplaceString doQuery: pop si call QueryUserForGlobalDelete jmp exit haveReplaceString: pop si call GetSearchReplaceOptions mov ah, cl cmp methodNumber, MSG_SRC_FIND_FROM_TOP jne checkFindPrev ornf ah, mask SO_START_FROM_TOP checkFindPrev: cmp methodNumber, MSG_SRC_FIND_PREV jne 10$ ornf ah, mask SO_BACKWARD_SEARCH 10$: ornf ah, mask SO_IGNORE_SOFT_HYPHENS call CreateSearchReplaceStruct call MemLock mov es, ax mov ax, methodNumber cmp ax, MSG_SRC_REPLACE_ALL_OCCURRENCES_NO_QUERY jne 80$ mov ax, MSG_REPLACE_ALL_OCCURRENCES jmp sendToOutput 80$: cmp ax, MSG_SRC_FIND_FROM_TOP je 90$ cmp ax, MSG_SRC_FIND_NEXT je 90$ cmp ax, MSG_SRC_FIND_PREV jne sendToOutput 90$: mov ax,MSG_SEARCH sendToOutput: ; Set the appropriate reply msg mov cx, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_REPLACE_ALL cmp ax, MSG_REPLACE_ALL_OCCURRENCES je unlock mov cx, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_REPLACE_ALL_IN_SELECTION cmp ax, MSG_REPLACE_ALL_OCCURRENCES_IN_SELECTION je unlock mov cx, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_SEARCH unlock: mov es:[SRS_replyMsg], cx call MemUnlock ; Before we activate the seach command, we need to set the ; state of the ReplaceTrigger or else the output of the controller ; could reply back with a result (thereby setting the ReplaceTrigger's ; new state which we would then inadvertently overwrite). -Don 9/4/00 push ax, dx cmp ax, MSG_SEARCH mov ax, MSG_GEN_SET_NOT_ENABLED jne setReplaceTrigger mov di, ds:[si] add di, ds:[di].SearchReplaceControl_offset test ds:[di].SRCI_enableFlags, mask SREF_REPLACE je setReplaceTrigger mov ax, MSG_GEN_SET_ENABLED setReplaceTrigger: mov dl, VUM_NOW call SendMessageToReplaceTrigger pop ax, dx ; OK - do something! mov cx,TRUE ;Set "replace all from start" clrdw bxdi ; flag call GenControlOutputActionRegs exit: .leave ret SearchReplaceControlPassToOutput endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendMessageToItemsInList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Passes a method to all the objects in the passed table. CALLED BY: GLOBAL PASS: SI:DI <- far ptr to null-terminated list of chunk handles BX - handle of block containing objects AX - method to send CX,DX,BP - data DS - controller segment (to be fixed up) RETURN: nada DESTROYED: si, di PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 4/ 3/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendMessageToItemsInList proc near uses es .enter EC < tst bx > EC < ERROR_Z CONTROLLER_OBJECT_INTERNAL_ERROR > mov es, si 10$: mov si, es:[di] ;*DS:SI <- next object in list tst si ;If at end of list, exit jz exit push ax, cx, dx, bp, di mov di, mask MF_FIXUP_DS call ObjMessage pop ax, cx, dx, bp, di inc di inc di jmp 10$ exit: .leave ret SendMessageToItemsInList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlSearchStringNotFound %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This method puts up a standard box telling the user that the search string has *not* been found. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/29/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlSearchStringNotFound method SearchReplaceControlClass, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_SEARCH, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_REPLACE_ALL, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_REPLACE_ALL_IN_SELECTION mov bx, offset SearchStringNotFoundString cmp ax, MSG_SRC_SEARCH_STRING_NOT_FOUND_FOR_REPLACE_ALL_IN_SELECTION jne 10$ mov bx, offset ReplaceAllInSelectionStringNotFoundString 10$: mov ax, (CDT_NOTIFICATION shl offset CDBF_DIALOG_TYPE or GIT_NOTIFICATION shl offset CDBF_INTERACTION_TYPE) call SearchPutupBox mov ax, MSG_SRC_SEARCH_ABORTED GOTO ObjCallInstanceNoLock SearchReplaceControlSearchStringNotFound endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchPutupBox %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine puts up a standard error dialog box containing the passed text. CALLED BY: GLOBAL PASS: bx - chunk in string resource containing text to display ax - type of box to display RETURN: nada DESTROYED: ax, bx, cx, di PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 2/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchPutupBox proc near uses dx, bp, si .enter mov dx, size GenAppDoDialogParams sub sp, dx mov bp, sp mov ss:[bp].GADDP_dialog.SDP_customFlags, ax mov si, bx mov bx, handle TextStrings call MemLock push ds assume ds:TextStrings mov ds, ax mov si, ds:[si] ;DS:SI <- ptr to string to display assume ds:dgroup pop ds mov ss:[bp].GADDP_dialog.SDP_customString.segment, ax mov ss:[bp].GADDP_dialog.SDP_customString.offset, si clr ss:[bp].GADDP_finishOD.handle clr ss:[bp].GADDP_finishOD.offset clr ss:[bp].GADDP_dialog.SDP_helpContext.segment mov ax, MSG_GEN_APPLICATION_DO_STANDARD_DIALOG call GenCallApplication add sp, size GenAppDoDialogParams mov bx, handle TextStrings call MemUnlock .leave ret SearchPutupBox endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlUpdateUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Updates the UI. CALLED BY: GLOBAL PASS: ss:bp - GenControlUpdateUIParams RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/12/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlUpdateUI method SearchReplaceControlClass, MSG_GEN_CONTROL_UPDATE_UI .enter EC < cmp ss:[bp].GCUUIP_changeType, GWNT_SEARCH_REPLACE_ENABLE_CHANGE > EC < ERROR_NZ CONTROLLER_OBJECT_INTERNAL_ERROR > mov bx, ss:[bp].GCUUIP_dataBlock call MemLock mov es, ax mov cl, es:[NSREC_flags] call MemUnlock mov ds:[di].SRCI_enableFlags, cl mov bx, ss:[bp].GCUUIP_childBlock ; If none of the search/replace features are allowed, just exit. test ss:[bp].GCUUIP_features, mask SRCF_FIND_NEXT or mask SRCF_FIND_PREV or mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION jz exit ; Enable or disable the search gadgetry depending upon whether or not ; search/replace is enabled on the current object. ; ; The search text needs to be enabled if *either* search or replace is ; allowed. ; push si mov ax, MSG_GEN_SET_NOT_ENABLED test cl, mask SREF_SEARCH or mask SREF_REPLACE jz 10$ mov ax, MSG_GEN_SET_ENABLED 10$: mov dl, VUM_NOW mov si, offset SearchText mov di, mask MF_FIXUP_DS call ObjMessage test ss:[bp].GCUUIP_features, mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION jz noReplaceFeatures ; Enable or disable the replace text object depending upon whether or not ; there are replace options available. mov ax, MSG_GEN_SET_NOT_ENABLED test cl, mask SREF_REPLACE jz 20$ mov ax, MSG_GEN_SET_ENABLED 20$: mov dl, VUM_NOW mov si, offset ReplaceText mov di, mask MF_FIXUP_DS call ObjMessage noReplaceFeatures: ; ENABLE/DISABLE THE GADGETS USED BY BOTH SEARCH AND REPLACE test ss:[bp].GCUUIP_features, mask SRCF_PARTIAL_WORDS or mask SRCF_IGNORE_CASE jz updateNoteOptions mov ax, MSG_GEN_SET_NOT_ENABLED test cl, mask SREF_REPLACE or mask SREF_SEARCH jz 30$ mov ax, MSG_GEN_SET_ENABLED 30$: mov dl, VUM_NOW mov si, offset SearchReplaceOptions mov di, mask MF_FIXUP_DS call ObjMessage updateNoteOptions: test ss:[bp].GCUUIP_features, mask SRCF_NOTES_OPTIONS jz updateTriggers mov ax, MSG_GEN_SET_ENABLED mov dl, VUM_NOW mov si, offset SearchNoteOptions clr di call ObjMessage updateTriggers: pop si call UpdateSearchReplaceTriggers exit: .leave ret SearchReplaceControlUpdateUI endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SetObjMonikerFromVardata %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sets the moniker for the passed object to the vismoniker set in the lmem chunk. CALLED BY: GLOBAL PASS: ^lbp:dx - object to set moniker for ax - vardata type RETURN: nada DESTROYED: ax, bx, dx, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/23/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SetObjMonikerFromVardata proc near .enter call ObjVarFindData jnc exit mov ax, ds:[bx] ;*DS:AX - VisMoniker to set for object push cx, bp, si movdw bxsi, bpdx ;^lBX:SI <- optr of object to set moniker ; Set the moniker of the passed object mov cx, ds:[LMBH_handle] mov dx, ax mov bp, VUM_DELAYED_VIA_UI_QUEUE mov ax, MSG_GEN_REPLACE_VIS_MONIKER_OPTR mov di, mask MF_FIXUP_DS call ObjMessage pop cx, bp, si exit: .leave ret SetObjMonikerFromVardata endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlGenerateUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This subclass changes the vis monikers of various triggers if the app specifies them. CALLED BY: GLOBAL PASS: *ds:si - SearchReplaceControl object es - segment of SearchReplaceControl class RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/23/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlGenerateUI method SearchReplaceControlClass, MSG_GEN_CONTROL_GENERATE_UI .enter mov di, offset SearchReplaceControlClass call ObjCallSuperNoLock ifdef GPC_SEARCH ; If dialog, add HINT_CENTER_CHILDREN_ON_MONIKERS mov di, ds:[si] add di, ds:[di].Gen_offset cmp ds:[di].GII_visibility, GIV_DIALOG jne notDialog mov ax, HINT_CENTER_CHILDREN_ON_MONIKERS clr cx call ObjVarAddData mov ax, HINT_LEFT_JUSTIFY_MONIKERS clr cx call ObjVarAddData ; ; if all vertical elements are enabled, ; display search window at bottom of screen to make room to show ; misspelled word in document ; call SR_GetFeaturesAndChildBlock call SR_CheckFullHeight jnc notDialog mov ax, HINT_POSITION_WINDOW_AT_RATIO_OF_PARENT mov cx, size SpecWinSizePair call ObjVarAddData mov ds:[bx].SWSP_x, 0 mov ds:[bx].SWSP_y, mask SWSS_RATIO or PCT_90 ; auto bump up mov ax, MSG_SPEC_SCAN_GEOMETRY_HINTS mov cl, mask VOF_GEOMETRY_INVALID mov dl, VUM_MANUAL call ObjCallInstanceNoLock notDialog: endif ifdef GPC_SEARCH ; Mirror SCRF_SPECIAL_CHARS for Replace call SR_GetFeaturesAndChildBlock test ax, SEARCH_BOTTOM_FEATURES jz leaveReplace test ax, mask SRCF_SPECIAL_CHARS jnz leaveReplace mov ax, MSG_GEN_SET_NOT_USABLE push si mov si, offset ReplaceSpecialCharsMenu mov dl, VUM_NOW mov di, mask MF_FIXUP_DS call ObjMessage pop si leaveReplace: endif ; If all of the special features bits are off, remove the ; SearchReplaceSpecialCharsMenu call SR_GetFeaturesAndChildBlock mov bp, bx mov_tr cx, ax ifdef GPC_SEARCH test cx, SEARCH_TOP_FEATURES jz menuExists test cx, mask SRCF_SPECIAL_CHARS or mask SRCF_WILDCARDS jnz menuExists else test cx, mask SRCF_SPECIAL_CHARS or mask SRCF_WILDCARDS jnz menuExists test cx, mask SRCF_IGNORE_CASE or mask SRCF_PARTIAL_WORDS jz menuExists ;Branch if the menu has already been deleted endif push si mov ax, MSG_GEN_SET_NOT_USABLE ifdef GPC_SEARCH mov si, offset SearchSpecialCharsMenu else mov si, offset SearchReplaceSpecialCharsMenu endif mov dl, VUM_NOW mov di, mask MF_FIXUP_DS call ObjMessage pop si menuExists: test cx, mask SRCF_FIND_NEXT jz checkFindPrev mov ax, ATTR_SEARCH_CONTROL_SET_FIND_NEXT_MONIKER mov dx, offset FindNextTrigger call SetObjMonikerFromVardata checkFindPrev: test cx, mask SRCF_FIND_PREV jz checkFindFromTop mov ax, ATTR_SEARCH_CONTROL_SET_FIND_PREV_MONIKER mov dx, offset FindPrevTrigger call SetObjMonikerFromVardata checkFindFromTop: test cx, mask SRCF_FIND_FROM_TOP jz checkReplaceCurrent mov ax, ATTR_SEARCH_CONTROL_SET_FIND_FROM_TOP_MONIKER mov dx, offset FindFromTopTrigger call SetObjMonikerFromVardata checkReplaceCurrent: test cx, mask SRCF_REPLACE_CURRENT jz checkReplaceAllInSelection mov ax, ATTR_SEARCH_CONTROL_SET_REPLACE_CURRENT_MONIKER mov dx, offset ReplaceTrigger call SetObjMonikerFromVardata checkReplaceAllInSelection: test cx, mask SRCF_REPLACE_ALL_IN_SELECTION jz checkReplaceAll mov ax, ATTR_SEARCH_CONTROL_SET_REPLACE_ALL_IN_SELECTION_MONIKER mov dx, offset ReplaceAllInSelectionTrigger call SetObjMonikerFromVardata checkReplaceAll: test cx, mask SRCF_REPLACE_ALL jz checkNoteOptions mov ax, ATTR_SEARCH_CONTROL_SET_REPLACE_ALL_MONIKER mov dx, offset ReplaceAllTrigger call SetObjMonikerFromVardata checkNoteOptions: test cx, mask SRCF_NOTES_OPTIONS jz checkReplaceWith mov ax, ATTR_SEARCH_CONTROL_SET_INCLUDE_NOTE_MONIKER mov dx, offset IncludeNote call SetObjMonikerFromVardata mov ax, ATTR_SEARCH_CONTROL_SET_EXCLUDE_NOTE_MONIKER mov dx, offset ExcludeNote call SetObjMonikerFromVardata mov ax, ATTR_SEARCH_CONTROL_SET_NOTE_ONLY_MONIKER mov dx, offset NoteOnly call SetObjMonikerFromVardata checkReplaceWith: test cx, mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or \ mask SRCF_REPLACE_ALL_IN_SELECTION jz exit mov ax, ATTR_SEARCH_CONTROL_SET_REPLACE_WITH_MONIKER mov dx, offset ReplaceText call SetObjMonikerFromVardata exit: .leave ret SearchReplaceControlGenerateUI endp ifdef GPC_SEARCH SR_CheckFullHeight proc far test ax, mask SRCF_FIND_NEXT jz haveFullHeight ; not full height, C clr test ax, mask SRCF_FIND_PREV jz haveFullHeight ; not full height, C clr test ax, mask SRCF_IGNORE_CASE or mask SRCF_PARTIAL_WORDS jz haveFullHeight ; not full height, C clr test ax, mask SRCF_REPLACE_CURRENT jz haveFullHeight ; not full height, C clr test ax, mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION jz haveFullHeight ; not full height, C clr stc ; else full height haveFullHeight: ret SR_CheckFullHeight endp endif ifdef GPC_SEARCH COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlTweakDuplicatedUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set trigger sizes CALLED BY: GLOBAL PASS: *ds:si - SearchReplaceControl object es - segment of SearchReplaceControl class cx - block handle dx - features RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 1/4/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlTweakDuplicatedUI method SearchReplaceControlClass, MSG_GEN_CONTROL_TWEAK_DUPLICATED_UI .enter ; ; get widest trigger ; mov bx, cx ; bx = block handle mov cx, 0 mov si, offset FindNextTrigger mov ax, mask SRCF_FIND_NEXT call updateMonikerWidth ; cx = widest trigger mov si, offset FindPrevTrigger mov ax, mask SRCF_FIND_PREV call updateMonikerWidth ; cx = widest trigger mov si, offset ReplaceTrigger mov ax, mask SRCF_REPLACE_CURRENT call updateMonikerWidth ; cx = widest trigger mov si, offset ReplaceAllTrigger mov ax, mask SRCF_REPLACE_ALL call updateMonikerWidth ; cx = widest trigger mov si, offset ReplaceAllInSelectionTrigger mov ax, mask SRCF_REPLACE_ALL_IN_SELECTION call updateMonikerWidth ; cx = widest trigger mov ax, mask SRCF_FIND_FROM_TOP mov si, offset FindFromTopTrigger call updateMonikerWidth ; cx = widest trigger ; ; set all triggers to that width ; mov si, cs mov di, offset triggerList mov ax, MSG_GEN_SET_FIXED_SIZE sub sp, size SetSizeArgs mov bp, sp mov ss:[bp].SSA_width, cx mov ss:[bp].SSA_height, 0 mov ss:[bp].SSA_count, 0 mov ss:[bp].SSA_updateMode, VUM_MANUAL mov dx, size SetSizeArgs call SendMessageToItemsInList add sp, size SetSizeArgs .leave ret updateMonikerWidth label near test dx, ax jz updateExit ; trigger not used push dx, di push cx ; save widest so far mov ax, MSG_GEN_GET_MONIKER_SIZE clr dx, bp mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage ; cx = width pop di cmp cx, di jae updateDone ; new width larger, return it mov cx, di ; return previous widest updateDone: pop dx, di updateExit: retn SearchReplaceControlTweakDuplicatedUI endm triggerList lptr FindNextTrigger lptr FindPrevTrigger lptr ReplaceTrigger lptr ReplaceAllTrigger lptr ReplaceAllInSelectionTrigger lptr FindFromTopTrigger lptr 0 endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlAddSpecialCharToFocusText %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Adds the passed special char to the focus text object. CALLED BY: GLOBAL PASS: cx - SpecialChar GPC <dx - 0 for SearchText, 1 for ReplaceText> RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 3/24/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlAddSpecialCharToFocusText method SearchReplaceControlClass, MSG_SRC_ADD_SPECIAL_CHAR_TO_FOCUS_TEXT .enter SPECIAL_CHAR_WIDTH equ 15 SPECIAL_CHAR_HEIGHT equ 10 call SR_GetFeaturesAndChildBlock ; Get the OD of the current focus text object mov si, offset SearchText ifdef GPC_SEARCH tst dx jz 10$ else cmp ds:[di].SRCI_focusInfo, SRFI_SEARCH_TEXT jz 10$ endif mov si, offset ReplaceText ifndef GPC_SEARCH ; don't check in case message send by app instead of UI gadget EC < cmp ds:[di].SRCI_focusInfo, SRFI_REPLACE_TEXT > EC < ERROR_NZ BAD_FOCUS_INFO > endif 10$: ; Replace the current selection with a graphic mov dx, size ReplaceWithGraphicParams sub sp, dx mov bp, sp mov ss:[bp].RWGP_range.VTR_start.high, VIS_TEXT_RANGE_SELECTION mov di, cx mov ax, cs:[specialCharChunks][di] mov ss:[bp].RWGP_graphic.VTG_vmChain.low, ax mov ss:[bp].RWGP_graphic.VTG_size.XYS_width, SPECIAL_CHAR_WIDTH mov ss:[bp].RWGP_graphic.VTG_size.XYS_height, SPECIAL_CHAR_HEIGHT mov ss:[bp].RWGP_graphic.VTG_type, VTGT_GSTRING mov ss:[bp].RWGP_graphic.VTG_flags, mask VTGF_DRAW_FROM_BASELINE clr ax mov ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_drawOffset.XYO_y, ax mov ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_drawOffset.XYO_x, ax mov ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e11.WWF_int, 1 mov ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e11.WWF_frac, ax clrwwf ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e12, ax clrwwf ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e21, ax mov ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e22.WWF_int, 1 mov ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e22.WWF_frac, ax clrdwf ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e31, ax clrdwf ss:[bp].RWGP_graphic.VTG_data.VTGD_gstring.VTGG_tmatrix.TM_e32, ax mov ss:[bp].RWGP_graphic.VTG_vmChain.high, ax mov ss:[bp].RWGP_pasteFrame, ax mov ss:[bp].RWGP_sourceFile, ax mov ax, MSG_VIS_TEXT_REPLACE_WITH_GRAPHIC mov di, mask MF_STACK or mask MF_FIXUP_DS call ObjMessage add sp, dx .leave ret SearchReplaceControlAddSpecialCharToFocusText endp specialCharChunks lptr WildcardGString, WildcharGString, \ GraphicGString, CRGString, PageBreakGString, \ TabGString specialChars Chars WC_MATCH_MULTIPLE_CHARS, WC_MATCH_SINGLE_CHAR,\ C_GRAPHIC, C_CR, C_PAGE_BREAK, C_TAB if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TextSendSearchNotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends the appropriate search/spell notifications out. CALLED BY: GLOBAL PASS: CL - SearchReplaceEnableFlags RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ global TextSendSearchNotification:far TextSendSearchNotification proc far uses ax, bx, cx, dx, bp, di .enter clr bx tst cl jz 5$ push es mov dl, cl mov ax, size NotifySearchReplaceEnableChange mov cx, ALLOC_DYNAMIC_NO_ERR_LOCK or mask HF_SHARABLE call MemAlloc mov es, ax mov es:[NSREC_flags], dl call MemUnlock pop es 5$: ; Record a notification event mov bp, bx mov ax, MSG_META_NOTIFY_WITH_DATA_BLOCK mov cx, MANUFACTURER_ID_GEOWORKS mov dx, GWNT_SEARCH_REPLACE_ENABLE_CHANGE mov di, mask MF_RECORD call ObjMessage ;DI <- event handle ; Send it to the appropriate gcn list mov dx, size GCNListMessageParams sub sp, dx mov bp, sp mov ss:[bp].GCNLMP_ID.GCNLT_manuf, MANUFACTURER_ID_GEOWORKS mov ss:[bp].GCNLMP_ID.GCNLT_type, GAGCNLT_APP_TARGET_NOTIFY_SEARCH_REPLACE_CHANGE mov ss:[bp].GCNLMP_block, bx mov ss:[bp].GCNLMP_event, di mov ss:[bp].GCNLMP_flags, mask GCNLSF_SET_STATUS tst bx jnz 10$ ornf ss:[bp].GCNLMP_flags, mask GCNLSF_IGNORE_IF_STATUS_TRANSITIONING 10$: mov ax, MSG_GEN_PROCESS_SEND_TO_APP_GCN_LIST call GeodeGetProcessHandle mov di, mask MF_STACK call ObjMessage add sp, dx .leave ret TextSendSearchNotification endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlSendEventToSearchText %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends an event to the search text object CALLED BY: GLOBAL PASS: *ds:si - SearchReplaceControl obj bp - event handle RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 10/21/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlSendEventToSearchText method SearchReplaceControlClass, MSG_SRC_SEND_EVENT_TO_SEARCH_TEXT .enter call SR_GetFeaturesAndChildBlock mov cx, bx mov bx, bp test ax, mask SRCF_FIND_NEXT or mask SRCF_FIND_PREV or mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION jz freeMsg mov si, offset SearchText call MessageSetDestination mov di, mask MF_FIXUP_DS or mask MF_CALL call MessageDispatch exit: .leave ret freeMsg: call ObjFreeMessage jmp exit SearchReplaceControlSendEventToSearchText endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlSendEventToReplaceText %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends an event to the replace text obj CALLED BY: GLOBAL PASS: *ds:si - SearchReplaceControl obj bp - event handle RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 10/21/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlSendEventToReplaceText method SearchReplaceControlClass, MSG_SRC_SEND_EVENT_TO_REPLACE_TEXT .enter call SR_GetFeaturesAndChildBlock mov cx, bx mov bx, bp test ax, mask SRCF_REPLACE_CURRENT or mask SRCF_REPLACE_ALL or mask SRCF_REPLACE_ALL_IN_SELECTION jz freeMsg mov si, offset ReplaceText call MessageSetDestination mov di, mask MF_FIXUP_DS or mask MF_CALL call MessageDispatch exit: .leave ret freeMsg: call ObjFreeMessage jmp exit SearchReplaceControlSendEventToReplaceText endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SearchReplaceControlGetNoteSearchState %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the note options (include/exclude notes, note only) chosen by the user. CALLED BY: MSG_SRC_GET_NOTE_SEARCH_STATE PASS: *ds:si = SearchReplaceControlClass object ds:di = SearchReplaceControlClass instance data es = segment of SearchReplaceControlClass ax = message # RETURN: cl = SearchNoteOptionType DESTROYED: ax, ch SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- CL 11/ 8/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SearchReplaceControlGetNoteSearchState method dynamic SearchReplaceControlClass, MSG_SRC_GET_NOTE_SEARCH_STATE uses dx, bp .enter ; ; Find out what selection is chosen. ; call SR_GetFeaturesAndChildBlock ;ax = features ;^hbx = child block ; ; If we don't have note options, then we return the default ; note option. ; test ax, mask SRCF_NOTES_OPTIONS mov cl, SNOT_EXCLUDE_NOTE jz exit mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION mov si, offset SearchNoteOptions ;^lbx:si = item group mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage ;cx,dx,bp trashed ;ax = selection Assert etype al, SearchNoteOptionType mov_tr cx, ax ;cx = selection exit: .leave ret SearchReplaceControlGetNoteSearchState endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% OverrideCenterOnMonikersGetMargins %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Hack to override HINT_CENTER_ON_MONIKERS CALLED BY: MSG_VIS_COMP_GET_MARGINS PASS: *ds:si = OverrideCenterOnMonikersClass object ds:di = OverrideCenterOnMonikersClass instance data es = segment of OverrideCenterOnMonikersClass RETURN: ax = left margin see MSG_VIS_COMP_GET_MARGINS DESTROYED: ax, ch SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 1/4/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ifdef GPC_SEARCH OverrideCenterOnMonikersGetMargins method dynamic OverrideCenterOnMonikersClass, MSG_VIS_COMP_GET_MARGINS ; ; hack to override HINT_CENTER_ON_MONIKERS ; mov di, offset OverrideCenterOnMonikersClass call ObjCallSuperNoLock mov ax, 0 ret OverrideCenterOnMonikersGetMargins endp endif TextSRControlCode ends endif ; not NO_CONTROLLERS
/* * Copyright (C) 2020 The Android Open Source Project * * 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 "src/trace_processor/dynamic/experimental_counter_dur_generator.h" #include "test/gtest_and_gmock.h" namespace perfetto { namespace trace_processor { namespace { tables::CounterTable::Row CounterRow(int64_t ts, uint32_t track_id) { tables::CounterTable::Row row; row.ts = ts; row.track_id = tables::TrackTable::Id{track_id}; return row; } TEST(ExperimentalCounterDurGenerator, SmokeDur) { StringPool pool; tables::CounterTable table(&pool, nullptr); table.Insert(CounterRow(100 /* ts */, 1 /* track_id */)); table.Insert(CounterRow(102 /* ts */, 2 /* track_id */)); table.Insert(CounterRow(105 /* ts */, 1 /* track_id */)); table.Insert(CounterRow(105 /* ts */, 3 /* track_id */)); table.Insert(CounterRow(105 /* ts */, 2 /* track_id */)); table.Insert(CounterRow(110 /* ts */, 2 /* track_id */)); auto dur = ExperimentalCounterDurGenerator::ComputeDurColumn(table); ASSERT_EQ(dur.size(), table.row_count()); ASSERT_EQ(dur.GetNonNull(0), 5); ASSERT_EQ(dur.GetNonNull(1), 3); ASSERT_EQ(dur.GetNonNull(2), -1); ASSERT_EQ(dur.GetNonNull(3), -1); ASSERT_EQ(dur.GetNonNull(4), 5); ASSERT_EQ(dur.GetNonNull(5), -1); } } // namespace } // namespace trace_processor } // namespace perfetto
; Program B.1 ; Template - NASM (32-bit) ; Copyright (c) 2017 Hall & Slonka SECTION .data num: dd 80 SECTION .bss sum: resd 1 SECTION .text global _main _main: mov eax, [num] add eax, 20 mov [sum], eax mov eax, 1 mov ebx, 0 int 80h
#include <morphene/blockchain_statistics/blockchain_statistics_api.hpp> #include <morphene/app/impacted.hpp> #include <morphene/chain/account_object.hpp> #include <morphene/chain/history_object.hpp> #include <morphene/chain/database.hpp> #include <morphene/chain/index.hpp> #include <morphene/chain/operation_notification.hpp> namespace morphene { namespace blockchain_statistics { namespace detail { using namespace morphene::protocol; class blockchain_statistics_plugin_impl { public: blockchain_statistics_plugin_impl( blockchain_statistics_plugin& plugin ) :_self( plugin ) {} virtual ~blockchain_statistics_plugin_impl() {} void on_block( const signed_block& b ); void pre_operation( const operation_notification& o ); void post_operation( const operation_notification& o ); blockchain_statistics_plugin& _self; flat_set< uint32_t > _tracked_buckets = { 60, 3600, 21600, 86400, 604800, 2592000 }; flat_set< bucket_id_type > _current_buckets; uint32_t _maximum_history_per_bucket_size = 100; }; struct operation_process { const blockchain_statistics_plugin& _plugin; const bucket_object& _bucket; chain::database& _db; operation_process( blockchain_statistics_plugin& bsp, const bucket_object& b ) :_plugin( bsp ), _bucket( b ), _db( bsp.database() ) {} typedef void result_type; template< typename T > void operator()( const T& )const {} void operator()( const transfer_operation& op )const { _db.modify( _bucket, [&]( bucket_object& b ) { b.transfers++; if( op.amount.symbol == MORPH_SYMBOL ) b.morph_transferred += op.amount.amount; }); } void operator()( const account_create_operation& op )const { _db.modify( _bucket, [&]( bucket_object& b ) { b.paid_accounts_created++; }); } void operator()( const transfer_to_vesting_operation& op )const { _db.modify( _bucket, [&]( bucket_object& b ) { b.transfers_to_vesting++; b.morph_vested += op.amount.amount; }); } void operator()( const fill_vesting_withdraw_operation& op )const { auto& account = _db.get_account( op.from_account ); _db.modify( _bucket, [&]( bucket_object& b ) { b.vesting_withdrawals_processed++; if( op.deposited.symbol == MORPH_SYMBOL ) b.vests_withdrawn += op.withdrawn.amount; else b.vests_transferred += op.withdrawn.amount; if( account.vesting_withdraw_rate.amount == 0 ) b.finished_vesting_withdrawals++; }); } }; void blockchain_statistics_plugin_impl::on_block( const signed_block& b ) { auto& db = _self.database(); if( b.block_num() == 1 ) { db.create< bucket_object >( [&]( bucket_object& bo ) { bo.open = b.timestamp; bo.seconds = 0; bo.blocks = 1; }); } else { db.modify( db.get( bucket_id_type() ), [&]( bucket_object& bo ) { bo.blocks++; }); } _current_buckets.clear(); _current_buckets.insert( bucket_id_type() ); const auto& bucket_idx = db.get_index< bucket_index >().indices().get< by_bucket >(); uint32_t trx_size = 0; uint32_t num_trx =b.transactions.size(); for( const auto& trx : b.transactions ) { trx_size += fc::raw::pack_size( trx ); } for( const auto& bucket : _tracked_buckets ) { auto open = fc::time_point_sec( ( db.head_block_time().sec_since_epoch() / bucket ) * bucket ); auto itr = bucket_idx.find( boost::make_tuple( bucket, open ) ); if( itr == bucket_idx.end() ) { _current_buckets.insert( db.create< bucket_object >( [&]( bucket_object& bo ) { bo.open = open; bo.seconds = bucket; bo.blocks = 1; }).id ); if( _maximum_history_per_bucket_size > 0 ) { try { auto cutoff = fc::time_point_sec( ( safe< uint32_t >( db.head_block_time().sec_since_epoch() ) - safe< uint32_t >( bucket ) * safe< uint32_t >( _maximum_history_per_bucket_size ) ).value ); itr = bucket_idx.lower_bound( boost::make_tuple( bucket, fc::time_point_sec() ) ); while( itr->seconds == bucket && itr->open < cutoff ) { auto old_itr = itr; ++itr; db.remove( *old_itr ); } } catch( fc::overflow_exception& e ) {} catch( fc::underflow_exception& e ) {} } } else { db.modify( *itr, [&]( bucket_object& bo ) { bo.blocks++; }); _current_buckets.insert( itr->id ); } db.modify( *itr, [&]( bucket_object& bo ) { bo.transactions += num_trx; bo.bandwidth += trx_size; }); } } void blockchain_statistics_plugin_impl::pre_operation( const operation_notification& o ) { auto& db = _self.database(); for( const auto& bucket_id : _current_buckets ) { if( o.op.which() == operation::tag< withdraw_vesting_operation >::value ) { withdraw_vesting_operation op = o.op.get< withdraw_vesting_operation >(); auto& account = db.get_account( op.account ); const auto& bucket = db.get(bucket_id); auto new_vesting_withdrawal_rate = op.vesting_shares.amount / MORPHENE_VESTING_WITHDRAW_INTERVALS; if( op.vesting_shares.amount > 0 && new_vesting_withdrawal_rate == 0 ) new_vesting_withdrawal_rate = 1; db.modify( bucket, [&]( bucket_object& b ) { if( account.vesting_withdraw_rate.amount > 0 ) b.modified_vesting_withdrawal_requests++; else b.new_vesting_withdrawal_requests++; // TODO: Figure out how to change delta when a vesting withdraw finishes. Have until March 24th 2018 to figure that out... b.vesting_withdraw_rate_delta += new_vesting_withdrawal_rate - account.vesting_withdraw_rate.amount; }); } } } void blockchain_statistics_plugin_impl::post_operation( const operation_notification& o ) { try { auto& db = _self.database(); for( const auto& bucket_id : _current_buckets ) { const auto& bucket = db.get(bucket_id); if( !is_virtual_operation( o.op ) ) { db.modify( bucket, [&]( bucket_object& b ) { b.operations++; }); } o.op.visit( operation_process( _self, bucket ) ); } } FC_CAPTURE_AND_RETHROW() } } // detail blockchain_statistics_plugin::blockchain_statistics_plugin( application* app ) :plugin( app ), _my( new detail::blockchain_statistics_plugin_impl( *this ) ) {} blockchain_statistics_plugin::~blockchain_statistics_plugin() {} void blockchain_statistics_plugin::plugin_set_program_options( boost::program_options::options_description& cli, boost::program_options::options_description& cfg ) { cli.add_options() ("chain-stats-bucket-size", boost::program_options::value<string>()->default_value("[60,3600,21600,86400,604800,2592000]"), "Track blockchain statistics by grouping orders into buckets of equal size measured in seconds specified as a JSON array of numbers") ("chain-stats-history-per-bucket", boost::program_options::value<uint32_t>()->default_value(100), "How far back in time to track history for each bucket size, measured in the number of buckets (default: 100)") ; cfg.add(cli); } void blockchain_statistics_plugin::plugin_initialize( const boost::program_options::variables_map& options ) { try { ilog( "chain_stats_plugin: plugin_initialize() begin" ); chain::database& db = database(); db.applied_block_proxy( [&]( const signed_block& b ){ _my->on_block( b ); }, *this ); db.pre_apply_operation_proxy( [&]( const operation_notification& o ){ _my->pre_operation( o ); }, *this ); db.post_apply_operation_proxy( [&]( const operation_notification& o ){ _my->post_operation( o ); }, *this ); add_plugin_index< bucket_index >(db); if( options.count( "chain-stats-bucket-size" ) ) { const std::string& buckets = options[ "chain-stats-bucket-size" ].as< string >(); _my->_tracked_buckets = fc::json::from_string( buckets ).as< flat_set< uint32_t > >(); } if( options.count( "chain-stats-history-per-bucket" ) ) _my->_maximum_history_per_bucket_size = options[ "chain-stats-history-per-bucket" ].as< uint32_t >(); wlog( "chain-stats-bucket-size: ${b}", ("b", _my->_tracked_buckets) ); wlog( "chain-stats-history-per-bucket: ${h}", ("h", _my->_maximum_history_per_bucket_size) ); ilog( "chain_stats_plugin: plugin_initialize() end" ); } FC_CAPTURE_AND_RETHROW() } void blockchain_statistics_plugin::plugin_startup() { ilog( "chain_stats plugin: plugin_startup() begin" ); app().register_api_factory< blockchain_statistics_api >( "chain_stats_api" ); ilog( "chain_stats plugin: plugin_startup() end" ); } const flat_set< uint32_t >& blockchain_statistics_plugin::get_tracked_buckets() const { return _my->_tracked_buckets; } uint32_t blockchain_statistics_plugin::get_max_history_per_bucket() const { return _my->_maximum_history_per_bucket_size; } } } // morphene::blockchain_statistics MORPHENE_DEFINE_PLUGIN( blockchain_statistics, morphene::blockchain_statistics::blockchain_statistics_plugin );
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r15 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0x31c, %r9 nop xor $15724, %r11 vmovups (%r9), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $0, %xmm0, %r15 nop nop add %r14, %r14 lea addresses_normal_ht+0x1c612, %rbx nop nop nop and $40957, %rdi movl $0x61626364, (%rbx) xor %r11, %r11 lea addresses_WC_ht+0x1271c, %rbx nop add $10878, %r11 mov (%rbx), %r14d nop nop sub %r11, %r11 lea addresses_D_ht+0x4d7c, %r11 nop nop nop nop cmp $4657, %r9 movb (%r11), %r14b nop nop nop nop cmp %r11, %r11 lea addresses_UC_ht+0xd81c, %r14 nop nop nop nop cmp $22697, %r8 vmovups (%r14), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $1, %xmm7, %r9 nop nop nop nop and $56815, %r11 lea addresses_A_ht+0x189bc, %r11 nop nop add %r14, %r14 mov (%r11), %di nop nop add %r9, %r9 lea addresses_normal_ht+0x1ea9c, %r14 cmp %r9, %r9 mov $0x6162636465666768, %rbx movq %rbx, %xmm0 movups %xmm0, (%r14) nop add $26763, %r11 lea addresses_normal_ht+0x4c93, %rdi sub %r15, %r15 movups (%rdi), %xmm2 vpextrq $1, %xmm2, %r11 nop nop nop cmp $17385, %rdi lea addresses_WC_ht+0x571c, %rsi lea addresses_D_ht+0x523c, %rdi clflush (%rdi) add $1717, %r15 mov $114, %rcx rep movsb nop nop xor $27515, %rdi lea addresses_WT_ht+0x671c, %rsi lea addresses_UC_ht+0x1485c, %rdi nop nop nop and %r9, %r9 mov $87, %rcx rep movsq cmp %rcx, %rcx lea addresses_UC_ht+0xe11c, %rsi lea addresses_normal_ht+0x1ea1c, %rdi nop and $58394, %r11 mov $13, %rcx rep movsb nop nop add %rsi, %rsi lea addresses_WT_ht+0x15b1c, %r11 nop and $49875, %rsi mov $0x6162636465666768, %r8 movq %r8, %xmm6 and $0xffffffffffffffc0, %r11 movaps %xmm6, (%r11) nop add %r9, %r9 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r15 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r13 push %r8 push %r9 push %rcx push %rsi // Load lea addresses_A+0xb464, %r10 sub %r9, %r9 movb (%r10), %r13b nop nop nop sub $62158, %rcx // Load lea addresses_normal+0x761c, %r11 nop nop nop nop nop inc %rcx mov (%r11), %r13w nop nop nop nop nop and %rcx, %rcx // Faulty Load lea addresses_normal+0xdf1c, %rcx nop inc %r8 movb (%rcx), %r9b lea oracles, %rsi and $0xff, %r9 shlq $12, %r9 mov (%rsi,%r9,1), %r9 pop %rsi pop %rcx pop %r9 pop %r8 pop %r13 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_A', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_normal', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 1, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': True, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False}} {'src': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_UC_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': True, 'congruent': 4, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_WT_ht', 'size': 16, 'AVXalign': True}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
; Namespace ; Compile with: nasm -f elf namespace.asm ; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 namespace.o -o namespace ; Run with: ./namespace %include 'functions.asm' SECTION .data msg1 db 'Jumping to finished label.', 0h ; a message string msg2 db 'Inside subroutine number: ', 0h ; a message string msg3 db 'Inside subroutine "finished".', 0h ; a message string SECTION .text global _start _start: subrountineOne: mov eax, msg1 ; move the address of msg1 into eax call sprintLF ; call our string printing with linefeed function jmp .finished ; jump to the local label under the subrountineOne scope .finished: mov eax, msg2 ; move the address of msg2 into eax call sprint ; call our string printing function mov eax, 1 ; move the value one into eax (for subroutine number one) call iprintLF ; call our integer printing function with linefeed function subrountineTwo: mov eax, msg1 ; move the address of msg1 into eax call sprintLF ; call our string print with linefeed function jmp .finished ; jump to the local label under the subrountineTwo scope .finished: mov eax, msg2 ; move the address of msg2 into eax call sprint ; call our string printing function mov eax, 2 ; move the value two into eax (for subroutine number two) call iprintLF ; call our integer printing function with linefeed function mov eax, msg1 ; move the address of msg1 into eax call sprintLF ; call our string printing with linefeed function jmp finished ; jump to the global label finished finished: mov eax, msg3 ; move the address of msg3 into eax call sprintLF ; call our string printing with linefeed function call quit ; call our quit function
<% from pwnlib.shellcraft.powerpc.linux import syscall %> <%page args="fd, vmessages, vlen, flags, tmo"/> <%docstring> Invokes the syscall recvmmsg. See 'man 2 recvmmsg' for more information. Arguments: fd(int): fd vmessages(mmsghdr): vmessages vlen(unsigned): vlen flags(int): flags tmo(timespec): tmo </%docstring> ${syscall('SYS_recvmmsg', fd, vmessages, vlen, flags, tmo)}
; A290492: Maximal number of binary vectors of length n such that the unions (or bitwise ORs) of any 3 distinct vectors are all distinct. ; Submitted by Jon Maiga ; 1,2,3,4,5,6,7,8,9,10,11,12,14 mov $6,$0 add $6,1 mov $9,$0 lpb $6 mov $0,$9 sub $6,1 sub $0,$6 pow $0,3 mov $2,2 mov $5,1 mov $8,0 lpb $0 sub $0,1440 mov $3,$0 add $8,6 lpb $3 mov $4,$0 mod $4,$2 mov $2,$8 add $2,1 cmp $4,0 cmp $4,0 sub $3,$4 mov $9,1 lpe mul $5,$2 lpe add $7,$5 lpe mov $0,$7
; A104739: Positions of records in A104717. ; 1,2,3,4,6,7,8,11,12,14,16,19,20,23,24,27,31,32,35,38,43,44,47,48,51,56,60,62,64,70,71,75,80,83,87,88,91,96,103,107,110,111,115,123,124,127,135,139,140,147,148,152,163,164,166,174,179,180,184,188,192 mul $0,2 lpb $0 add $1,1 mul $1,$0 sub $0,1 div $1,$0 sub $0,1 lpe div $1,2 add $1,1 mov $0,$1
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "IntroTutorialsPrivatePCH.h" #include "STutorialRoot.h" #include "SEditorTutorials.h" #include "EditorTutorialSettings.h" #include "TutorialStateSettings.h" #include "AssetEditorManager.h" #include "ToolkitManager.h" #include "IToolkit.h" #include "IToolkitHost.h" #include "EngineAnalytics.h" #include "Runtime/Analytics/Analytics/Public/Interfaces/IAnalyticsProvider.h" #include "Editor/MainFrame/Public/Interfaces/IMainFrameModule.h" #include "NotificationManager.h" #include "SNotificationList.h" #include "Kismet/GameplayStatics.h" #define LOCTEXT_NAMESPACE "STutorialRoot" void STutorialRoot::Construct(const FArguments& InArgs) { CurrentTutorial = nullptr; CurrentTutorialStage = 0; CurrentTutorialStartTime = FPlatformTime::Seconds(); ChildSlot [ SNullWidget::NullWidget ]; } void STutorialRoot::AttachWidget(TSharedPtr<SWidget> Widget) { //This checkSlow is just here to ensure we know what we're doing checkSlow(ChildSlot.GetWidget() == SNullWidget::NullWidget); ChildSlot.AttachWidget(Widget.ToSharedRef()); } void STutorialRoot::DetachWidget() { ChildSlot.DetachWidget(); } void STutorialRoot::MaybeAddOverlay(TSharedRef<SWindow> InWindow) { if(InWindow->HasOverlay()) { // check we don't already have a widget overlay for this window TWeakPtr<SEditorTutorials>* FoundWidget = TutorialWidgets.Find(InWindow); if(FoundWidget == nullptr) { TSharedPtr<SEditorTutorials> TutorialWidget = nullptr; InWindow->AddOverlaySlot() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) [ SAssignNew(TutorialWidget, SEditorTutorials) .ParentWindow(InWindow) .OnNextClicked(FOnNextClicked::CreateSP(this, &STutorialRoot::HandleNextClicked)) .OnBackClicked(FSimpleDelegate::CreateSP(this, &STutorialRoot::HandleBackClicked)) .OnHomeClicked(FSimpleDelegate::CreateSP(this, &STutorialRoot::HandleHomeClicked)) .OnCloseClicked(FSimpleDelegate::CreateSP(this, &STutorialRoot::HandleCloseClicked)) .OnGetCurrentTutorial(FOnGetCurrentTutorial::CreateSP(this, &STutorialRoot::HandleGetCurrentTutorial)) .OnGetCurrentTutorialStage(FOnGetCurrentTutorialStage::CreateSP(this, &STutorialRoot::HandleGetCurrentTutorialStage)) .OnLaunchTutorial(FOnLaunchTutorial::CreateSP(this, &STutorialRoot::LaunchTutorial)) .OnWasWidgetDrawn(FOnWasWidgetDrawn::CreateSP(this, &STutorialRoot::WasWidgetDrawn)) .OnWidgetWasDrawn(FOnWidgetWasDrawn::CreateSP(this, &STutorialRoot::WidgetWasDrawn)) ] ]; FoundWidget = &TutorialWidgets.Add(InWindow, TutorialWidget); FoundWidget->Pin()->RebuildCurrentContent(); } } TArray<TSharedRef<SWindow>> ChildWindows = InWindow->GetChildWindows(); for(auto& ChildWindow : ChildWindows) { MaybeAddOverlay(ChildWindow); } } void STutorialRoot::Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) { TArray<TSharedRef<SWindow>> Windows = FSlateApplication::Get().GetInteractiveTopLevelWindows(); for(auto& Window : Windows) { MaybeAddOverlay(Window); } // empty array but leave us the slack (we dont want to reallocate all the time, and this array should never grow too large) PreviouslyDrawnWidgets.Empty(PreviouslyDrawnWidgets.Max()); PreviouslyDrawnWidgets.Append(MoveTemp(DrawnWidgets)); DrawnWidgets.Empty(DrawnWidgets.Max()); } void STutorialRoot::LaunchTutorial(UEditorTutorial* InTutorial, IIntroTutorials::ETutorialStartType InStartType, TWeakPtr<SWindow> InNavigationWindow, FSimpleDelegate InOnTutorialClosed, FSimpleDelegate InOnTutorialExited) { if(InTutorial != nullptr) { CurrentTutorial = InTutorial; // we force a restart if this tutorial was completed if (GetDefault<UTutorialStateSettings>()->HaveCompletedTutorial(CurrentTutorial) && (InStartType == IIntroTutorials::ETutorialStartType::TST_CONTINUE)) { InStartType = IIntroTutorials::ETutorialStartType::TST_RESTART; } bool bHaveSeenTutorial = false; switch (InStartType) { case IIntroTutorials::ETutorialStartType::TST_RESTART: CurrentTutorialStage = 0; break; case IIntroTutorials::ETutorialStartType::TST_LASTSTAGE: CurrentTutorialStage = FMath::Max(0, (CurrentTutorial->Stages.Num() - 1)); break; default: case IIntroTutorials::ETutorialStartType::TST_CONTINUE: CurrentTutorialStage = GetDefault<UTutorialStateSettings>()->GetProgress(CurrentTutorial, bHaveSeenTutorial); break; } // check if we should be launching this tutorial for an asset editor if(InTutorial->AssetToUse.IsValid()) { TArray<FString> AssetPaths; AssetPaths.Add(InTutorial->AssetToUse.AssetLongPathname); FAssetEditorManager::Get().OpenEditorsForAssets(AssetPaths); UObject* Asset = InTutorial->AssetToUse.ResolveObject(); if(Asset != nullptr) { TSharedPtr<IToolkit> Toolkit = FToolkitManager::Get().FindEditorForAsset( Asset ); if(Toolkit.IsValid()) { InNavigationWindow = FSlateApplication::Get().FindWidgetWindow(Toolkit->GetToolkitHost()->GetParentWidget()); // make sure we have a valid tutorial overlay if(InNavigationWindow.IsValid()) { MaybeAddOverlay(InNavigationWindow.Pin().ToSharedRef()); } } } } CurrentTutorialStartTime = FPlatformTime::Seconds(); // launch tutorial for all windows we wrap - any tutorial can display over any window for(auto& TutorialWidget : TutorialWidgets) { if(TutorialWidget.Value.IsValid()) { bool bIsNavigationWindow = false; if (!InNavigationWindow.IsValid()) { bIsNavigationWindow = TutorialWidget.Value.Pin()->IsNavigationVisible(); } else { bIsNavigationWindow = (TutorialWidget.Value.Pin()->GetParentWindow() == InNavigationWindow.Pin()); } TutorialWidget.Value.Pin()->LaunchTutorial(bIsNavigationWindow, InOnTutorialClosed, InOnTutorialExited); } } if (CurrentTutorial != nullptr) { CurrentTutorial->HandleTutorialLaunched(); } if (CurrentTutorial != nullptr && CurrentTutorialStage < CurrentTutorial->Stages.Num()) { CurrentTutorial->HandleTutorialStageStarted(CurrentTutorial->Stages[CurrentTutorialStage].Name); } } } void STutorialRoot::CloseAllTutorialContent() { for (auto& TutorialWidget : TutorialWidgets) { if (TutorialWidget.Value.IsValid()) { TutorialWidget.Value.Pin()->HideContent(); } } } void STutorialRoot::HandleNextClicked(TWeakPtr<SWindow> InNavigationWindow) { GoToNextStage(InNavigationWindow); } void STutorialRoot::HandleBackClicked() { if( FEngineAnalytics::IsAvailable() && CurrentTutorial != nullptr) { TArray<FAnalyticsEventAttribute> EventAttributes; EventAttributes.Add(FAnalyticsEventAttribute(TEXT("Context.Tutorial"), FIntroTutorials::AnalyticsEventNameFromTutorial(CurrentTutorial))); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("Context.StageIndex"), CurrentTutorialStage)); FEngineAnalytics::GetProvider().RecordEvent( TEXT("Rocket.Tutorials.ClickedBackButton"), EventAttributes ); } GoToPreviousStage(); for(auto& TutorialWidget : TutorialWidgets) { if(TutorialWidget.Value.IsValid()) { TSharedPtr<SEditorTutorials> PinnedTutorialWidget = TutorialWidget.Value.Pin(); PinnedTutorialWidget->RebuildCurrentContent(); } } } void STutorialRoot::HandleHomeClicked() { if(CurrentTutorial != nullptr) { CurrentTutorial->HandleTutorialClosed(); GetMutableDefault<UTutorialStateSettings>()->RecordProgress(CurrentTutorial, CurrentTutorialStage); GetMutableDefault<UTutorialStateSettings>()->SaveProgress(); } // submit analytics data if( FEngineAnalytics::IsAvailable() && CurrentTutorial != nullptr && CurrentTutorialStage < CurrentTutorial->Stages.Num() ) { FString const CurrentExcerptTitle = CurrentTutorial->Stages[CurrentTutorialStage].Name.ToString(); int32 const CurrentExcerptIndex = CurrentTutorialStage; float const CurrentPageElapsedTime = (float)(FPlatformTime::Seconds() - CurrentTutorialStartTime); TArray<FAnalyticsEventAttribute> EventAttributes; EventAttributes.Add(FAnalyticsEventAttribute(TEXT("LastStageIndex"), CurrentExcerptIndex)); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("LastStageTitle"), CurrentExcerptTitle)); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("TimeSpentInTutorial"), CurrentPageElapsedTime)); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("TutorialAsset"), FIntroTutorials::AnalyticsEventNameFromTutorial(CurrentTutorial))); FEngineAnalytics::GetProvider().RecordEvent( TEXT("Rocket.Tutorials.Home"), EventAttributes ); } CurrentTutorial = nullptr; CurrentTutorialStage = 0; for(auto& TutorialWidget : TutorialWidgets) { if(TutorialWidget.Value.IsValid()) { TSharedPtr<SEditorTutorials> PinnedTutorialWidget = TutorialWidget.Value.Pin(); PinnedTutorialWidget->RebuildCurrentContent(); } } } UEditorTutorial* STutorialRoot::HandleGetCurrentTutorial() { return CurrentTutorial; } int32 STutorialRoot::HandleGetCurrentTutorialStage() { return CurrentTutorialStage; } void STutorialRoot::AddReferencedObjects( FReferenceCollector& Collector ) { if(CurrentTutorial != nullptr) { Collector.AddReferencedObject(CurrentTutorial); } } void STutorialRoot::GoToPreviousStage() { if (CurrentTutorial != nullptr) { UEditorTutorial* OldTutorial = CurrentTutorial; int32 OldTutorialStage = CurrentTutorialStage; if (CurrentTutorialStage < CurrentTutorial->Stages.Num()) { CurrentTutorial->HandleTutorialStageEnded(CurrentTutorial->Stages[CurrentTutorialStage].Name); } FString PlatformName = UGameplayStatics::GetPlatformName(); for (--CurrentTutorialStage; CurrentTutorialStage >= 0; --CurrentTutorialStage) { bool bPlatformFoundInList = false; for (FString PlatformToTest : CurrentTutorial->Stages[CurrentTutorialStage].PlatformsToTest) { if (!PlatformName.Compare(PlatformToTest, ESearchCase::IgnoreCase)) { bPlatformFoundInList = true; break; } } if (bPlatformFoundInList != CurrentTutorial->Stages[CurrentTutorialStage].bInvertPlatformTest) { // Skip this stage continue; } // We hit a page that we don't want to skip. Record progress and stop looking. GetMutableDefault<UTutorialStateSettings>()->RecordProgress(CurrentTutorial, CurrentTutorialStage); break; } if (CurrentTutorialStage < 0) { // We went out of bounds for this tutorial, so see if we want to go to another one. CurrentTutorialStage = 0; if (FName(*CurrentTutorial->PreviousTutorial.AssetLongPathname) != NAME_None) { TSubclassOf<UEditorTutorial> PreviousTutorialClass = LoadClass<UEditorTutorial>(NULL, *CurrentTutorial->PreviousTutorial.AssetLongPathname, NULL, LOAD_None, NULL); if (PreviousTutorialClass != nullptr) { LaunchTutorial(PreviousTutorialClass->GetDefaultObject<UEditorTutorial>(), IIntroTutorials::ETutorialStartType::TST_LASTSTAGE, nullptr, FSimpleDelegate(), FSimpleDelegate()); } else { FSlateNotificationManager::Get().AddNotification(FNotificationInfo(FText::Format(LOCTEXT("TutorialNotFound", "Could not start previous tutorial {0}"), FText::FromString(CurrentTutorial->PreviousTutorial.AssetLongPathname)))); } } } if (CurrentTutorial != nullptr && CurrentTutorialStage < CurrentTutorial->Stages.Num() && (CurrentTutorial != OldTutorial || CurrentTutorialStage != OldTutorialStage)) { CurrentTutorial->HandleTutorialStageStarted(CurrentTutorial->Stages[CurrentTutorialStage].Name); } } for (auto& TutorialWidget : TutorialWidgets) { if (TutorialWidget.Value.IsValid()) { TSharedPtr<SEditorTutorials> PinnedTutorialWidget = TutorialWidget.Value.Pin(); PinnedTutorialWidget->RebuildCurrentContent(); } } } void STutorialRoot::GoToNextStage(TWeakPtr<SWindow> InNavigationWindow) { if(CurrentTutorial != nullptr) { UEditorTutorial* OldTutorial = CurrentTutorial; int32 OldTutorialStage = CurrentTutorialStage; if(CurrentTutorialStage < CurrentTutorial->Stages.Num()) { CurrentTutorial->HandleTutorialStageEnded(CurrentTutorial->Stages[CurrentTutorialStage].Name); } FString PlatformName = UGameplayStatics::GetPlatformName(); for (++CurrentTutorialStage; CurrentTutorialStage < CurrentTutorial->Stages.Num(); ++CurrentTutorialStage) { bool bPlatformFoundInList = false; for (FString PlatformToTest : CurrentTutorial->Stages[CurrentTutorialStage].PlatformsToTest) { if (!PlatformName.Compare(PlatformToTest, ESearchCase::IgnoreCase)) { bPlatformFoundInList = true; break; } } if (bPlatformFoundInList != CurrentTutorial->Stages[CurrentTutorialStage].bInvertPlatformTest) { // Skip this stage continue; } // We hit a page that we don't want to skip. Record progress and stop looking. GetMutableDefault<UTutorialStateSettings>()->RecordProgress(CurrentTutorial, CurrentTutorialStage); break; } if (CurrentTutorialStage + 1 >= CurrentTutorial->Stages.Num()) { // We went out of bounds for this tutorial, so see if we want to go to another one. CurrentTutorialStage = CurrentTutorial->Stages.Num() - 1; if (FName(*CurrentTutorial->PreviousTutorial.AssetLongPathname) != NAME_None) { TSubclassOf<UEditorTutorial> NextTutorialClass = LoadClass<UEditorTutorial>(NULL, *CurrentTutorial->NextTutorial.AssetLongPathname, NULL, LOAD_None, NULL); if (NextTutorialClass != nullptr) { LaunchTutorial(NextTutorialClass->GetDefaultObject<UEditorTutorial>(), IIntroTutorials::ETutorialStartType::TST_RESTART, InNavigationWindow, FSimpleDelegate(), FSimpleDelegate()); } else { FSlateNotificationManager::Get().AddNotification(FNotificationInfo(FText::Format(LOCTEXT("TutorialNotFound", "Could not start next tutorial {0}"), FText::FromString(CurrentTutorial->NextTutorial.AssetLongPathname)))); } } } if (CurrentTutorial != nullptr && CurrentTutorialStage < CurrentTutorial->Stages.Num() && (CurrentTutorial != OldTutorial || CurrentTutorialStage != OldTutorialStage)) { CurrentTutorial->HandleTutorialStageStarted(CurrentTutorial->Stages[CurrentTutorialStage].Name); } } for(auto& TutorialWidget : TutorialWidgets) { if(TutorialWidget.Value.IsValid()) { TSharedPtr<SEditorTutorials> PinnedTutorialWidget = TutorialWidget.Value.Pin(); PinnedTutorialWidget->RebuildCurrentContent(); } } } void STutorialRoot::HandleCloseClicked() { if(CurrentTutorial != nullptr) { CurrentTutorial->HandleTutorialClosed(); // Update the current stage when we close bool bHaveSeenTutorial = false; CurrentTutorialStage = GetDefault<UTutorialStateSettings>()->GetProgress(CurrentTutorial, bHaveSeenTutorial); GetMutableDefault<UTutorialStateSettings>()->RecordProgress(CurrentTutorial, CurrentTutorialStage); GetMutableDefault<UTutorialStateSettings>()->SaveProgress(); } // submit analytics data if( FEngineAnalytics::IsAvailable() && CurrentTutorial != nullptr && CurrentTutorialStage < CurrentTutorial->Stages.Num() ) { UEditorTutorial* AttractTutorial = nullptr; UEditorTutorial* LaunchTutorial = nullptr; FString BrowserFilter; GetDefault<UEditorTutorialSettings>()->FindTutorialInfoForContext(TEXT("LevelEditor"), AttractTutorial, LaunchTutorial, BrowserFilter); // prepare and send analytics data bool const bClosedInitialAttract = (CurrentTutorial == AttractTutorial); FString const CurrentExcerptTitle = bClosedInitialAttract ? TEXT("InitialAttract") : CurrentTutorial->Stages[CurrentTutorialStage].Name.ToString(); int32 const CurrentExcerptIndex = bClosedInitialAttract ? -1 : CurrentTutorialStage; float const CurrentPageElapsedTime = bClosedInitialAttract ? 0.f : (float)(FPlatformTime::Seconds() - CurrentTutorialStartTime); TArray<FAnalyticsEventAttribute> EventAttributes; EventAttributes.Add(FAnalyticsEventAttribute(TEXT("LastStageIndex"), CurrentExcerptIndex)); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("LastStageTitle"), CurrentExcerptTitle)); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("TimeSpentInTutorial"), CurrentPageElapsedTime)); EventAttributes.Add(FAnalyticsEventAttribute(TEXT("TutorialAsset"), FIntroTutorials::AnalyticsEventNameFromTutorial(CurrentTutorial))); FEngineAnalytics::GetProvider().RecordEvent( TEXT("Rocket.Tutorials.Closed"), EventAttributes ); } //Tutorial is no longer current CurrentTutorial = nullptr; } bool STutorialRoot::WasWidgetDrawn(const FName& InName) const { for(const auto& WidgetName : PreviouslyDrawnWidgets) { if(InName == WidgetName) { return true; } } return false; } void STutorialRoot::WidgetWasDrawn(const FName& InName) { DrawnWidgets.Add(InName); } #undef LOCTEXT_NAMESPACE
// // jurat.hpp // // Created by Subodh Sharma on 12/29/21. // #ifndef jurat_hpp #define jurat_hpp #include <stdio.h> #include <hash.h> #include <core_io.h> #include <primitives/transaction.h> #include <script/interpreter.h> #include <key.h> #include <algorithm> #include <set> #include <base58.h> #include <key_io.h> #include <script/standard.h> #include <iostream> #include <fstream> #include <univalue.h> namespace jurat { ///jurat keys int N_JURAT_MIN_SIGS = 2; std::string JURAT_WITNESS_KEYFILE_PATH = "./witness_keys.json"; std::string JURAT_WITNESS_KEYFILE_PATH_TEST = "./witness_keys_test.json"; std::string JURAT_WITNESS_KEYFILE_PATH_ENV = "JURAT_WITNESS_PUBKEYS"; std::string JSON_TOKEN_VERIFIER_PUBKEYS = "witness_public_keys"; std::string JSON_TOKEN_MIN_VERIFIERS = "min_verifiers"; bool isWitnessKeysInitialized = false; std::vector<std::string> judicialVerifierPubKeys; //const std::string judicialVerifierPubKeys[] = {"024a5d2b6ceb5d8291b6d97fdec2de4b50024d981c4a13f31673c0bd8bc493f70c", // "02b5efb6fa70adbe1aa9a70347699ed6948a660bf8eca9826cb4824b644a1484bb"}; ///the bitcoin transaction hash for jurat transactions are signed by this and attached as part of segwit const std::string bitcoinSignPubKey = "03b8c53308a5ed31dea6733ee267c546872be4d2903100d5eabf4f154bed0b944d"; ///all jurat transaction builders should sign the bitcoin-tx hash with the below private key [ for the above pub key ] ///given here in mainnet and testnet compatible format ///const std::string mainnetFormatPrivKey = "KypcjQrjKKfGN6gf6HYLa2Qn9T7mKR4N3zdqHUoPQmRTNiTCUBaz"; ///const std::string testnetFormatPrivKey = "cQBcCKrakPMXXY9vUhMTwLuqmgRAysA482nJPuFtut5TdTU4TXjT"; static void printJson(UniValue& out); static void initWitnessKeys() { if(isWitnessKeysInitialized) return; std::string keyFilePath; if(Params().IsTestChain()){ keyFilePath = JURAT_WITNESS_KEYFILE_PATH_TEST; }else{ keyFilePath = JURAT_WITNESS_KEYFILE_PATH; } //check override in env property char* witness_keyfile_path = std::getenv(JURAT_WITNESS_KEYFILE_PATH_ENV.c_str()); if(witness_keyfile_path){ keyFilePath = witness_keyfile_path; } tfm::format(std::cout, "opening witness public keys file... %s\n", witness_keyfile_path); std::ifstream keyFile; UniValue val; keyFile.open(keyFilePath); if(keyFile.is_open()){ std::string strJson; std::string line; while(getline(keyFile, line)){ strJson.append(line); } keyFile.close(); if (!val.read(strJson)) { throw std::runtime_error("error parsing jurat witness pubkeys json"); } printJson(val); } UniValue keys = find_value(val, JSON_TOKEN_VERIFIER_PUBKEYS); const std::vector<UniValue>& pubKeys = keys.getValues(); judicialVerifierPubKeys.clear(); for(const UniValue& k : pubKeys){ std::string strPubKey = k.get_str(); judicialVerifierPubKeys.push_back(strPubKey); } UniValue uniMinVerifiers = find_value(val, JSON_TOKEN_MIN_VERIFIERS); N_JURAT_MIN_SIGS = uniMinVerifiers.get_int(); tfm::format(std::cout,"jurat witness %d keys loaded from...%s\n", judicialVerifierPubKeys.size(),keyFilePath); int keyCount=0; for(std::string& key : judicialVerifierPubKeys){ tfm::format(std::cout, "pub key[%d]=%s\n", keyCount,key); keyCount++; } tfm::format(std::cout, "min no of verifiers %d of %d\n",N_JURAT_MIN_SIGS, keyCount); isWitnessKeysInitialized = true; } static void printJson(UniValue& out) { std::string json = out.write(4); std::cout << "begin:\n" << json << "\nend\n"; std::cout.flush(); } ///declarations ///jurat verifier class JuratVerifier { private: const CTransaction& m_tx; const CScript& prevScriptPubKey; int32_t vin; int32_t vout; int nLockBlockHeight; uint32_t nonce; std::vector<int> verifiedKeys; bool isVerified; public: JuratVerifier() = delete; JuratVerifier(const CTransaction& tx, const CScript& scriptPubKey):m_tx(tx),prevScriptPubKey(scriptPubKey){ initWitnessKeys(); } bool isJuratTx(); ///needs ECDSA library to be initialized before calling this bool verify(); ///for jurat verified tx this will return the scriptPubKey compatible with the witness CScript getScriptPubKey(); ///strip out jutar sigs and retain onlybitcoin format sigs CScriptWitness getModifiedWitness(); }; ///jurat enum for various jurat constants enum class enumJurat:uint8_t { JURAT_MARKER1 = 0xAB, JURAT_MARKER2 = 0xCD, JURAT_ACTION_FREEZE_WITH_TIMELOCK = 0x01, JURAT_ACTION_MOVE_FUND_WITH_TIMLOCK = 0x02, JURAT_ACTION_MOVE_FUND_IMMEDIATE = 0x03 }; ///implementations ///checks if bitcoin address is supported for jurat freeze etc bool checkAddr(std::string addr, std::vector<unsigned char>& vchHash, CScript& addrScriptPubKey,std::string& err) { vchHash.clear(); std::string errMsg; CTxDestination dest = DecodeDestination(addr, errMsg); const bool isValid = IsValidDestination(dest); if(!isValid) { //invalid address err = addr + " ...invalid address"; return false; } CScript scriptPubKey = GetScriptForDestination(dest); std::vector<std::vector<unsigned char>> vSolutionsRet; TxoutType txOutType = Solver(scriptPubKey, vSolutionsRet); std::string strSrcAddrType = GetTxnOutputType(txOutType); std::vector<unsigned char> vchPKHash; if (txOutType == TxoutType::PUBKEY){ uint160 pubKeyHash = Hash160(vSolutionsRet[0]); vchPKHash = std::vector<unsigned char>(pubKeyHash.begin(), pubKeyHash.end()); } else if(txOutType == TxoutType::PUBKEYHASH){ vchPKHash =vSolutionsRet[0]; } else if(txOutType == TxoutType::WITNESS_V0_KEYHASH){ vchPKHash =vSolutionsRet[0]; } else { //address is unsupported err = "unsupported address type: " + GetTxnOutputType(txOutType); return false; } copy(vchPKHash.begin(), vchPKHash.end(), back_inserter(vchHash)); addrScriptPubKey = scriptPubKey; return true; } ///helper function to create the vout with OP_RETURN and jurat info bool createJuratMarker(const enumJurat juratAction, uint8_t vin, uint8_t vout, int nBlockLockHeigt, uint32_t nonce, std::vector<unsigned char> vchData,CScript& outScript) { outScript << OP_RETURN; std::vector<unsigned char> markerPayload; markerPayload.push_back((unsigned char)enumJurat::JURAT_MARKER1); markerPayload.push_back((unsigned char)enumJurat::JURAT_MARKER2); markerPayload.push_back((unsigned char)juratAction); markerPayload.push_back(vin); markerPayload.push_back(vout); //4 bytes for blockheight unsigned char* pBlockHeight = static_cast<unsigned char*>(static_cast<void*>(&nBlockLockHeigt)); copy(pBlockHeight, pBlockHeight+4,back_inserter(markerPayload)); //4 bytes for nonce unsigned char* pNonce = static_cast<unsigned char*>(static_cast<void*>(&nonce)); copy(pNonce, pNonce+4,back_inserter(markerPayload)); //copy upto 20 bytes of data unsigned char copy_len = (unsigned char)vchData.size(); copy_len = copy_len > 20 ? 20:copy_len; markerPayload.push_back(copy_len); if (copy_len>0){ copy(vchData.begin(), vchData.begin()+copy_len,back_inserter(markerPayload)); } outScript << markerPayload; std::cout << "createJuratMarker: final=" << HexStr(outScript) << std::endl; return true; } ///create the time lock script. the freeze tx will send the coin to this scripthash bool createLockingScript(int nLockBlockHeight, std::vector<unsigned char>& vchPKHash, CScript& script, CScript& pshScriptPubKey) { //naive check for block height and 20 byte pubkey hash if (nLockBlockHeight < 0 || vchPKHash.size()!=20){ return false; } script << nLockBlockHeight << OP_CHECKLOCKTIMEVERIFY << OP_DROP << OP_DUP; script << OP_HASH160 << vchPKHash << OP_EQUALVERIFY << OP_CHECKSIG; std::cout << "createLockingScript: pkhash=" << HexStr(vchPKHash) << " blockheight=" << nLockBlockHeight << std::endl; ScriptHash scriptHash(script); pshScriptPubKey = GetScriptForDestination(scriptHash); return true; } ///<OP_RETURN 2 byte> <Jurat Marker1 1 byte> <Jurat Marker2 1 byte> <Jurat Action 1 byte> ///<OP_RETURN 2 byte> <Jurat Marker1 1 byte> <Jurat Marker2 1 byte> <Jurat Action 1 byte> ///<vin 1 byte> <vout 1 byte> <block-height 4 bytes> ///<trailing data length 1 byte> <trailing data bytes upto 20 bytes> ///minimum length = 2 + 1 + 1 + 1 + 1 + 1 + 4 + 1 = 12 bytes ///maximum length = 12 + 20 = 32 bytes ///allowed maximum length = OP_RETURN + 40 bytes of data = 42 bytes bool identifyJuratTx(const CTransaction& tx, int32_t& vin, int32_t& vout, int32_t& nLockBlockHeight, uint32_t& nonce, std::vector<unsigned char>& targetAddrPKHash) { bool found = false; std::cout << "looking for jurat tx...." << std::endl; const int minScriptPubKeyLength = 12; for (const CTxOut& out: tx.vout) { const CScript& scriptPubKey = out.scriptPubKey; int len = scriptPubKey.end() - scriptPubKey.begin(); if (len < minScriptPubKeyLength){ continue; } //check OP_RETURN CScript::const_iterator pc = scriptPubKey.begin(); if (*pc != OP_RETURN){ continue; } std::cout << "identifyJuratTx: scriptPubKey len = " << len << std::endl; pc = pc+2; uint8_t marker1 = *(pc); uint8_t marker2 = *(pc+1); uint8_t action = *(pc+2); vin = (int32_t)*(pc+3); vout = (int32_t)*(pc+4); unsigned char ch[4]; for(int i=0;i<4;i++) ch[i] = *(pc+5+i); int32_t blockHeight=*((int*)ch); unsigned char noncech[4]; for(int i=0;i<4;i++) noncech[i] = *(pc+9+i); uint32_t decodedNonce = *( (uint32_t*)noncech); std::cout << "nonce = " << nonce << std::endl; nonce = decodedNonce; int32_t datalen = (int32_t)*(pc+13); //check jurat markers if((uint8_t)enumJurat::JURAT_MARKER1 != marker1 || (uint8_t)enumJurat::JURAT_MARKER2 != marker2 || datalen < 0 ){ break; } //check jurat action if((uint8_t)enumJurat::JURAT_ACTION_FREEZE_WITH_TIMELOCK != action){ std::cout << "jurat action not supported = " << (int)action << std::endl; break; } std::cout << "identifyJuratTx: [verified] jurat marker1 = " << marker1 << std::endl; std::cout << "identifyJuratTx: [verified] jurat marker2 = " << marker2 << std::endl; std::cout << "identifyJuratTx: [verified] jurat action = " << (int)action << std::endl; if (blockHeight < 0 || vin < 0 || vin >= (int)tx.vin.size() || vout < 0 || vout >= (int)tx.vout.size()){ std::cout << "invalid jurat marker payload..." << blockHeight << std::endl; break; } std::cout << "identifyJuratTx: [verified] vin = " << vin << std::endl; std::cout << "identifyJuratTx: [verified] vout = " << vout << std::endl; std::cout << "identifyJuratTx: [verified] blockHeight = " << blockHeight << std::endl; std::cout << "identifyJuratTx: [verified] nonce = " << nonce << std::endl; std::cout << "identifyJuratTx: [verified] trailing data length = " << datalen << std::endl; pc = pc+14; if(datalen > 0){ std::vector<unsigned char> vchData(pc,pc+datalen); CScript script; CScript pshScriptPubKey; createLockingScript(blockHeight, vchData, script, pshScriptPubKey); if (pshScriptPubKey != tx.vout[vout].scriptPubKey){ std::cout << "identifyJuratTx: tx.vout[vout].scriptPubKey did not match... " << HexStr(pshScriptPubKey) << std::endl; break; } ///this confirms that this vout is sent to script hash tied to target-address pub keyhash targetAddrPKHash = vchData; std::cout << "identifyJuratTx: [verified] tx.vout[vout].scriptPubKey " << HexStr(pshScriptPubKey) << std::endl; } nLockBlockHeight = blockHeight; found = true; break; } return found; } ///this verifies the witness that has the following expected format ///witness.stack[0] ="" ///witness.stack[1] = jurat_specific_sig_judicial_verifier_pvt_key0 ///witness.stack[2] = witnesssi_V0_sig_judicial_verifier_pvt_key0 ///witness.stack[3] = jurat_specific_sig_judicial_verifier_pvt_key1 ///witness.stack[4] = witnesssi_V0_sig_judicial_verifier_pvt_key1 ///witness.stack[2n] = jurat_specific_sig_judicial_verifier_pvt_keyn ///witness.stack[2n+1] = witnesssi_V0_sig_judicial_verifier_pvt_keyn ///witness.stack[2(n+1)] = redeemScript ///redeemScript = <pub_key_n> OP_CHECKSIGVERIFY OP_DROP .... <pub_key_0> OP_CHECKSIGVERIFY OP_DROP OP_0 OP_ADD OP_VERIFY bool verifyJuratTxSig(const CTransaction& tx, int32_t& vin, int32_t& vout, int nLockBlockHeight, uint32_t nonce, const CScript& srcScriptPubKey, std::vector<unsigned char>& targetAddrPKHash, std::vector<int>& verifiedKeys) { if (vin < 0 || vin >= (int32_t)tx.vin.size() || vout < 0 || vout >= (int32_t)tx.vout.size()) { return false; } CScriptWitness witness = tx.vin[vin].scriptWitness; int len = (int)witness.stack.size(); std::cout << "[verifier] witness stack size = " << len << std::endl; //witness stack size = one empty chunk + num of jurat witness sigs + one bitcoin sig + one unlock script if (len < N_JURAT_MIN_SIGS+3) { return false; } std::vector<std::vector<unsigned char>> vSolutionsRet; TxoutType txOutType = Solver(srcScriptPubKey, vSolutionsRet); std::string strSrcAddrType = GetTxnOutputType(txOutType); std::vector<unsigned char> srcAddrPKHash; if (txOutType == TxoutType::PUBKEY){ uint160 pubKeyHash = Hash160(vSolutionsRet[0]); srcAddrPKHash = std::vector<unsigned char>(pubKeyHash.begin(), pubKeyHash.end()); } else if(txOutType == TxoutType::PUBKEYHASH){ srcAddrPKHash =vSolutionsRet[0]; } else if(txOutType == TxoutType::WITNESS_V0_KEYHASH){ srcAddrPKHash =vSolutionsRet[0]; } else { //address is unsupported std::cout << "unsupported address type: " << GetTxnOutputType(txOutType) << std::endl; return false; } const CAmount& satoshis = tx.vout[vout].nValue; //use srcAddrPKHash and targetAddrPKHash CHashWriter ss(SER_GETHASH, 0); ss << srcAddrPKHash; ss << targetAddrPKHash; ss << satoshis; ss << nLockBlockHeight; ss << nonce; std::cout << "[verifier] sig-data srcAddr=" << HexStr(targetAddrPKHash) << std::endl; std::cout << "[verifier] sig-data targetAddr=" << HexStr(targetAddrPKHash) << std::endl; std::cout << "[verifier] sig-data satoshis=" << satoshis << std::endl; std::cout << "[verifier] sig-data nLockBlockHeight=" << nLockBlockHeight << std::endl; std::cout << "[verifier] sig-data nonce=" << nonce << std::endl; uint256 juratSigDataHash = ss.GetHash(); std::cout << "[verifier] sig-data hash=" << HexStr(juratSigDataHash) << std::endl; ///to prevent double counting of two sigs from same key std::set<int> keySet; verifiedKeys.clear(); bool verified = true; for(int i=1; i<len-2;i++){ std::vector<unsigned char> sigData = witness.stack[i]; if(sigData.size() == 0 ) { verified = false; break; } int verifierIdx = sigData[sigData.size()-1]; if(verifierIdx < 0 || verifierIdx >= (int)judicialVerifierPubKeys.size()) { verified = false; break; } std::string strVerifierPubKey = judicialVerifierPubKeys[verifierIdx]; std::vector<unsigned char> vchPubKey = ParseHex(strVerifierPubKey); CPubKey verifierPubKey(vchPubKey.begin(), vchPubKey.end()); std::vector<unsigned char> vchSignature(sigData.begin(), sigData.end()-1); bool isVerified = verifierPubKey.Verify(juratSigDataHash, vchSignature); if(!isVerified){ verified = false; break; } std::cout << "[verifier] verified with pub-key: " << strVerifierPubKey << std::endl; verifiedKeys.insert(verifiedKeys.begin(),verifierIdx); keySet.insert(verifierIdx); } if((int)keySet.size() < N_JURAT_MIN_SIGS){ verified = false; } std::cout << "[verifier] #sigs verified = " << verifiedKeys.size() << std::endl; return verified; } CScript getMultiSigRedeemScript() { ///designed for multisig but currenty using a signle signature as a special case 1 of 1 Multisig CScript script; script << 1; std::vector<unsigned char> vchPubKey = ParseHex(bitcoinSignPubKey); script << vchPubKey; script << 1 << OP_CHECKMULTISIG; return script; } ///lightweight verification that checks if this tx is a jurat tx by verifying the a vout with OP_RETURN and jurat marker data bool JuratVerifier::isJuratTx() { int32_t vin; int32_t vout; int nLockBlockHeight; uint32_t nonce; std::vector<unsigned char> targetAddrPKHash; bool isJuratTx = identifyJuratTx(m_tx, vin, vout, nLockBlockHeight, nonce, targetAddrPKHash); return isJuratTx; } ///does full jurat verification using jurat public keys. ///needs crypto ecdsa library to be initialized before calling this bool JuratVerifier::verify() { std::vector<unsigned char> targetAddrPKHash; bool isJuratTx = identifyJuratTx(m_tx, vin, vout, nLockBlockHeight, nonce,targetAddrPKHash); if(!isJuratTx){ return false; } isVerified = false; verifiedKeys.clear(); isVerified = verifyJuratTxSig(m_tx, vin, vout, nLockBlockHeight, nonce, prevScriptPubKey,targetAddrPKHash, verifiedKeys); return isVerified; } CScript JuratVerifier::getScriptPubKey() { CScript script = getMultiSigRedeemScript(); const WitnessV0ScriptHash witnessScriptHash(script); std::vector<unsigned char> scriptHash256(witnessScriptHash.begin(), witnessScriptHash.end()); CScript scriptPubKey; scriptPubKey << OP_0 << scriptHash256; return scriptPubKey; } CScriptWitness JuratVerifier::getModifiedWitness() { int witness_stack_size = (int) m_tx.vin[vin].scriptWitness.stack.size(); CScriptWitness witness; witness.stack.push_back(m_tx.vin[vin].scriptWitness.stack[0]);//emty chunk witness.stack.push_back(m_tx.vin[vin].scriptWitness.stack[witness_stack_size-2]);//sig witness.stack.push_back(m_tx.vin[vin].scriptWitness.stack[witness_stack_size-1]);//unlock script return witness; } } #endif /* jurat_hpp */
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r14 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x1b5bc, %rsi lea addresses_D_ht+0x313c, %rdi nop nop nop nop inc %r12 mov $42, %rcx rep movsq nop nop nop nop sub $58130, %r13 lea addresses_UC_ht+0x120bb, %rsi lea addresses_D_ht+0xebfc, %rdi nop nop cmp $29079, %rbx mov $77, %rcx rep movsl nop sub %r13, %r13 lea addresses_A_ht+0x175f8, %r13 xor $47557, %r9 movb $0x61, (%r13) nop nop nop nop dec %rcx lea addresses_normal_ht+0x91fc, %r13 nop nop nop nop nop sub $54640, %rcx movw $0x6162, (%r13) nop nop and %r9, %r9 lea addresses_D_ht+0x1b5fc, %r13 nop cmp $62324, %r12 mov $0x6162636465666768, %r9 movq %r9, (%r13) nop nop add %r9, %r9 lea addresses_UC_ht+0xb5fc, %r12 cmp $24257, %r9 mov $0x6162636465666768, %rsi movq %rsi, %xmm7 vmovups %ymm7, (%r12) nop nop nop nop and $15816, %rdi lea addresses_UC_ht+0x4fac, %rsi lea addresses_WT_ht+0x59fc, %rdi nop nop nop nop cmp $31943, %r14 mov $112, %rcx rep movsb nop nop nop nop nop dec %rsi lea addresses_D_ht+0x1eada, %rsi lea addresses_normal_ht+0xd3fc, %rdi nop nop nop nop cmp %r14, %r14 mov $75, %rcx rep movsw nop nop nop nop nop xor %rdi, %rdi lea addresses_UC_ht+0x1fc, %rsi lea addresses_A_ht+0x5fbc, %rdi nop nop nop nop xor %r9, %r9 mov $108, %rcx rep movsb nop nop nop nop nop and $41561, %rsi lea addresses_WC_ht+0x77fc, %rsi lea addresses_normal_ht+0x1440c, %rdi nop nop sub $32430, %r13 mov $77, %rcx rep movsl nop add $33889, %rsi lea addresses_WC_ht+0xd494, %r9 nop nop cmp $19539, %r14 mov (%r9), %r12d add $24584, %rsi lea addresses_WC_ht+0x142bc, %rsi lea addresses_D_ht+0xd5bc, %rdi nop nop nop and $63418, %rbx mov $34, %rcx rep movsl nop nop dec %rdi lea addresses_A_ht+0x8fb6, %rsi nop nop cmp $43795, %r12 mov (%rsi), %rcx nop nop nop nop and $4531, %rcx lea addresses_WT_ht+0x110fc, %rsi clflush (%rsi) nop nop nop sub $54053, %rcx vmovups (%rsi), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $1, %xmm2, %rbx nop nop nop nop nop xor %r13, %r13 lea addresses_D_ht+0xd57c, %r12 nop nop nop nop nop sub $58439, %rcx vmovups (%r12), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $0, %xmm7, %rsi and %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r14 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %r9 push %rdx push %rsi // Faulty Load lea addresses_D+0xf5fc, %r13 nop nop nop nop xor $31812, %rdx mov (%r13), %r14w lea oracles, %r9 and $0xff, %r14 shlq $12, %r14 mov (%r9,%r14,1), %r14 pop %rsi pop %rdx pop %r9 pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_D', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_D', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC_ht', 'size': 32, 'AVXalign': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}} {'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}} {'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
preset_kpdr21_crateria_ship: dw #$0000 dl $7E078B : db $02 : dw $0000 ; Elevator Index dl $7E078D : db $02 : dw $88FE ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $91F8 ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E07F3 : db $02 : dw $0006 ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0400 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $03D0 ; Screen Y position in pixels dl $7E093F : db $02 : dw $0000 ; Ceres escape flag dl $7E09A2 : db $02 : dw $0000 ; Equipped Items dl $7E09A4 : db $02 : dw $0000 ; Collected Items dl $7E09A6 : db $02 : dw $0000 ; Beams dl $7E09A8 : db $02 : dw $0000 ; Beams dl $7E09C0 : db $02 : dw $0000 ; Manual/Auto reserve tank dl $7E09C2 : db $02 : dw $0063 ; Health dl $7E09C4 : db $02 : dw $0063 ; Max health dl $7E09C6 : db $02 : dw $0000 ; Missiles dl $7E09C8 : db $02 : dw $0000 ; Max missiles dl $7E09CA : db $02 : dw $0000 ; Supers dl $7E09CC : db $02 : dw $0000 ; Max supers dl $7E09CE : db $02 : dw $0000 ; Pbs dl $7E09D0 : db $02 : dw $0000 ; Max pbs dl $7E09D2 : db $02 : dw $0000 ; Currently selected item dl $7E09D4 : db $02 : dw $0000 ; Max reserves dl $7E09D6 : db $02 : dw $0000 ; Reserves dl $7E0A1C : db $02 : dw $0000 ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0A68 : db $02 : dw $0000 ; Flash suit dl $7E0A76 : db $02 : dw $0000 ; Hyper beam dl $7E0AF6 : db $02 : dw $0481 ; Samus X dl $7E0AFA : db $02 : dw $0440 ; Samus Y dl $7E0B3F : db $02 : dw $0000 ; Blue suit dl $7ED7C0 : db $02 : dw $0000 ; SRAM copy dl $7ED7C2 : db $02 : dw $0000 ; SRAM copy dl $7ED7C4 : db $02 : dw $0000 ; SRAM copy dl $7ED7C6 : db $02 : dw $0000 ; SRAM copy dl $7ED7C8 : db $02 : dw $0800 ; SRAM copy dl $7ED7CA : db $02 : dw $0400 ; SRAM copy dl $7ED7CC : db $02 : dw $0200 ; SRAM copy dl $7ED7CE : db $02 : dw $0100 ; SRAM copy dl $7ED7D0 : db $02 : dw $4000 ; SRAM copy dl $7ED7D2 : db $02 : dw $0080 ; SRAM copy dl $7ED7D4 : db $02 : dw $8000 ; SRAM copy dl $7ED7D6 : db $02 : dw $0040 ; SRAM copy dl $7ED7D8 : db $02 : dw $2000 ; SRAM copy dl $7ED7DA : db $02 : dw $0020 ; SRAM copy dl $7ED7DC : db $02 : dw $0010 ; SRAM copy dl $7ED7DE : db $02 : dw $0000 ; SRAM copy dl $7ED7E0 : db $02 : dw $0063 ; SRAM copy dl $7ED7E2 : db $02 : dw $0063 ; SRAM copy dl $7ED7E4 : db $02 : dw $0000 ; SRAM copy dl $7ED7E6 : db $02 : dw $0000 ; SRAM copy dl $7ED7E8 : db $02 : dw $0000 ; SRAM copy dl $7ED7EA : db $02 : dw $0000 ; SRAM copy dl $7ED7EC : db $02 : dw $0000 ; SRAM copy dl $7ED7EE : db $02 : dw $0000 ; SRAM copy dl $7ED7F0 : db $02 : dw $0000 ; SRAM copy dl $7ED7F2 : db $02 : dw $0000 ; SRAM copy dl $7ED7F4 : db $02 : dw $0000 ; SRAM copy dl $7ED7F6 : db $02 : dw $0000 ; SRAM copy dl $7ED7F8 : db $02 : dw $0026 ; SRAM copy dl $7ED7FA : db $02 : dw $0006 ; SRAM copy dl $7ED7FC : db $02 : dw $0001 ; SRAM copy dl $7ED7FE : db $02 : dw $0000 ; SRAM copy dl $7ED800 : db $02 : dw $0000 ; SRAM copy dl $7ED802 : db $02 : dw $0000 ; SRAM copy dl $7ED804 : db $02 : dw $0001 ; SRAM copy dl $7ED806 : db $02 : dw $0001 ; SRAM copy dl $7ED808 : db $02 : dw $0000 ; SRAM copy dl $7ED80A : db $02 : dw $0000 ; SRAM copy dl $7ED80C : db $02 : dw $0000 ; SRAM copy dl $7ED80E : db $02 : dw $0000 ; SRAM copy dl $7ED810 : db $02 : dw $0000 ; SRAM copy dl $7ED812 : db $02 : dw $0000 ; SRAM copy dl $7ED814 : db $02 : dw $0000 ; SRAM copy dl $7ED816 : db $02 : dw $0000 ; SRAM copy dl $7ED818 : db $02 : dw $0000 ; SRAM copy dl $7ED81A : db $02 : dw $0000 ; SRAM copy dl $7ED81C : db $02 : dw $0000 ; SRAM copy dl $7ED81E : db $02 : dw $0000 ; SRAM copy dl $7ED820 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED822 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED824 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED826 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED828 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED82A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED82C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED82E : db $02 : dw $0001 ; Events, Items, Doors dl $7ED830 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED832 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED834 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED836 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED838 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED83A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED83C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED83E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED840 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED842 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED844 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED846 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED848 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED84A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED84C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED84E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED850 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED852 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED854 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED856 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED858 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED85A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED85C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED85E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED860 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED862 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED864 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED866 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED868 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED86A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED86C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED86E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED870 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED872 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED874 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED876 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED878 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED87A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED87C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED87E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED880 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED882 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED884 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED886 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED888 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED88A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED88C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED88E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED890 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED892 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED894 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED896 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED898 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED89A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED89C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED89E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8A0 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8A2 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8A4 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8A6 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8A8 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8AA : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8AC : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8AE : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8B0 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8B2 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8B4 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8B6 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8B8 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8BA : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8BC : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8BE : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8C0 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8C2 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8C4 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8C6 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8C8 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8CA : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8CC : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8CE : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8D0 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8D2 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8D4 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8D6 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8D8 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8DA : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8DC : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8DE : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8E0 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8E2 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8E4 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8E6 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8E8 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8EA : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8EC : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8EE : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8F0 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8F2 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8F4 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8F6 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8F8 : db $02 : dw $0001 ; Events, Items, Doors dl $7ED8FA : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8FC : db $02 : dw $0000 ; Events, Items, Doors dl $7ED8FE : db $02 : dw $0000 ; Events, Items, Doors dl $7ED900 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED902 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED904 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED906 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED908 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED90A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED90C : db $02 : dw $0000 ; Events, Items, Doors dl $7ED90E : db $02 : dw $0000 ; Events, Items, Doors dl $7ED910 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED912 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED914 : db $02 : dw $0005 ; Events, Items, Doors dl $7ED916 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED918 : db $02 : dw $0000 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0000 ; Events, Items, Doors dl $7ED91C : db $02 : dw $1010 ; Events, Items, Doors dl $7ED91E : db $02 : dw $0000 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_parlor: dw #preset_kpdr21_crateria_ship ; Crateria: Ship dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $1400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0400 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0079 ; Samus X dl $7E0AFA : db $02 : dw $049B ; Samus Y dw #$FFFF .after preset_kpdr21_crateria_parlor_downback: dw #preset_kpdr21_crateria_parlor ; Crateria: Parlor dl $7E078D : db $02 : dw $8916 ; DDB dl $7E079B : db $02 : dw $92FD ; MDB dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $02E9 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $01A7 ; Samus X dl $7E0AFA : db $02 : dw $035B ; Samus Y dw #$FFFF .after preset_kpdr21_crateria_climb_down: dw #preset_kpdr21_crateria_parlor_downback ; Crateria: Parlor Downback dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $4000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $041F ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $01A8 ; Samus X dl $7E0AFA : db $02 : dw $04BB ; Samus Y dw #$FFFF .after preset_kpdr21_crateria_pit_room: dw #preset_kpdr21_crateria_climb_down ; Crateria: Climb Down dl $7E078D : db $02 : dw $898E ; DDB dl $7E078F : db $02 : dw $0004 ; DoorOut Index dl $7E079B : db $02 : dw $96BA ; MDB dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $15BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B0 ; GFX Pointers dl $7E090F : db $02 : dw $6FFF ; Screen subpixel X position. dl $7E0913 : db $02 : dw $3800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0800 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $01DB ; Samus X dl $7E0AFA : db $02 : dw $088B ; Samus Y dw #$FFFF .after preset_kpdr21_crateria_morph: dw #preset_kpdr21_crateria_pit_room ; Crateria: Pit Room dl $7E078D : db $02 : dw $8B9E ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $9E9F ; MDB dl $7E079F : db $02 : dw $0001 ; Region dl $7E07C3 : db $02 : dw $E6B0 ; GFX Pointers dl $7E07C5 : db $02 : dw $64BB ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B2 ; GFX Pointers dl $7E07F5 : db $02 : dw $0007 ; Music Track dl $7E090F : db $02 : dw $6000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0500 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0200 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0000 ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0580 ; Samus X dl $7E0AFA : db $02 : dw $02A8 ; Samus Y dl $7ED91A : db $02 : dw $0001 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_construction_zone: dw #preset_kpdr21_crateria_morph ; Crateria: Morph dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E090F : db $02 : dw $2000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0700 ; Screen X position in pixels dl $7E0913 : db $02 : dw $E400 ; Screen subpixel Y position dl $7E09A2 : db $02 : dw $0004 ; Equipped Items dl $7E09A4 : db $02 : dw $0004 ; Collected Items dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $07AC ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dl $7ED872 : db $02 : dw $0400 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_construction_zone_revisit: dw #preset_kpdr21_crateria_construction_zone ; Crateria: Construction Zone dl $7E078D : db $02 : dw $8EDA ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $A107 ; MDB dl $7E090F : db $02 : dw $D000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $6800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0005 ; Missiles dl $7E09C8 : db $02 : dw $0005 ; Max missiles dl $7E0AF6 : db $02 : dw $0055 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED874 : db $02 : dw $0004 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0002 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_pit_room_revisit: dw #preset_kpdr21_crateria_construction_zone_revisit ; Crateria: Construction Zone Revisit dl $7E078D : db $02 : dw $8EB6 ; DDB dl $7E079B : db $02 : dw $97B5 ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $0000 ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0080 ; Samus X dl $7E0AFA : db $02 : dw $0088 ; Samus Y dl $7ED91A : db $02 : dw $0003 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_climb_up: dw #preset_kpdr21_crateria_pit_room_revisit ; Crateria: Pit Room Revisit dl $7E078D : db $02 : dw $8B92 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $975C ; MDB dl $7E07F3 : db $02 : dw $0009 ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $CC00 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0083 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED820 : db $02 : dw $0001 ; Events, Items, Doors dl $7ED8B2 : db $02 : dw $0400 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0004 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_parlor_revisit: dw #preset_kpdr21_crateria_climb_up ; Crateria: Climb Up dl $7E078D : db $02 : dw $8B7A ; DDB dl $7E079B : db $02 : dw $96BA ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $C000 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $01A0 ; Samus X dl $7E0AFA : db $02 : dw $005B ; Samus Y dw #$FFFF .after preset_kpdr21_crateria_flyway: dw #preset_kpdr21_crateria_parlor_revisit ; Crateria: Parlor Revisit dl $7E078D : db $02 : dw $8B3E ; DDB dl $7E079B : db $02 : dw $92FD ; MDB dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0300 ; Screen X position in pixels dl $7E0913 : db $02 : dw $2BFF ; Screen subpixel Y position dl $7E0915 : db $02 : dw $01E6 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $0369 ; Samus X dl $7E0AFA : db $02 : dw $026B ; Samus Y dw #$FFFF .after preset_kpdr21_crateria_bomb_torizo: dw #preset_kpdr21_crateria_flyway ; Crateria: Flyway dl $7E078D : db $02 : dw $8982 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $9879 ; MDB dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $D000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0000 ; Missiles dl $7E0AF6 : db $02 : dw $02BE ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8B2 : db $02 : dw $2400 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_alcatraz: dw #preset_kpdr21_crateria_bomb_torizo ; Crateria: Bomb Torizo dl $7E078D : db $02 : dw $8BAA ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E090F : db $02 : dw $2001 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E09A2 : db $02 : dw $1004 ; Equipped Items dl $7E09A4 : db $02 : dw $1004 ; Collected Items dl $7E09C6 : db $02 : dw $0005 ; Missiles dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0040 ; Samus X dl $7ED828 : db $02 : dw $0004 ; Events, Items, Doors dl $7ED870 : db $02 : dw $0080 ; Events, Items, Doors dl $7ED8B2 : db $02 : dw $2C00 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0005 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_crateria_terminator: dw #preset_kpdr21_crateria_alcatraz ; Crateria: Alcatraz dl $7E078D : db $02 : dw $8BB6 ; DDB dl $7E079B : db $02 : dw $92FD ; MDB dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E090F : db $02 : dw $F400 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $8800 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $0115 ; Samus X dl $7E0B3F : db $02 : dw $0104 ; Blue suit dw #$FFFF .after preset_kpdr21_crateria_green_pirate_shaft: dw #preset_kpdr21_crateria_terminator ; Crateria: Terminator dl $7E078D : db $02 : dw $895E ; DDB dl $7E079B : db $02 : dw $990D ; MDB dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E090F : db $02 : dw $9F00 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $01FC ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00C7 ; Health dl $7E09C4 : db $02 : dw $00C7 ; Max health dl $7E0AF6 : db $02 : dw $0063 ; Samus X dl $7E0AFA : db $02 : dw $029B ; Samus Y dl $7E0B3F : db $02 : dw $0000 ; Blue suit dl $7ED870 : db $02 : dw $0180 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0006 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_green_brinstar_elevator: dw #preset_kpdr21_crateria_green_pirate_shaft ; Crateria: Green Pirate Shaft dl $7E078D : db $02 : dw $8C22 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $9938 ; MDB dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $C400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $008B ; Health dl $7E0AF6 : db $02 : dw $007E ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED91A : db $02 : dw $0008 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_early_supers: dw #preset_kpdr21_brinstar_green_brinstar_elevator ; Brinstar: Green Brinstar Elevator dl $7E078D : db $02 : dw $8C0A ; DDB dl $7E078F : db $02 : dw $0009 ; DoorOut Index dl $7E079B : db $02 : dw $9AD9 ; MDB dl $7E079F : db $02 : dw $0001 ; Region dl $7E07C3 : db $02 : dw $E6B0 ; GFX Pointers dl $7E07C5 : db $02 : dw $64BB ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B2 ; GFX Pointers dl $7E07F3 : db $02 : dw $000F ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $041B ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0000 ; Missiles dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $00A5 ; Samus X dl $7E0AFA : db $02 : dw $048B ; Samus Y dl $7ED8B4 : db $02 : dw $0002 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0009 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_dachora_room: dw #preset_kpdr21_brinstar_early_supers ; Brinstar: Early Supers dl $7E078D : db $02 : dw $8D4E ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E090F : db $02 : dw $B000 ; Screen subpixel X position. dl $7E0915 : db $02 : dw $061B ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0081 ; Health dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E09CC : db $02 : dw $0005 ; Max supers dl $7E0AF6 : db $02 : dw $0057 ; Samus X dl $7E0AFA : db $02 : dw $068B ; Samus Y dl $7ED872 : db $02 : dw $0401 ; Events, Items, Doors dl $7ED8B4 : db $02 : dw $0006 ; Events, Items, Doors dl $7ED91A : db $02 : dw $000C ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_big_pink: dw #preset_kpdr21_brinstar_dachora_room ; Brinstar: Dachora Room dl $7E078D : db $02 : dw $8CE2 ; DDB dl $7E078F : db $02 : dw $0005 ; DoorOut Index dl $7E079B : db $02 : dw $9CB3 ; MDB dl $7E090F : db $02 : dw $5000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0600 ; Screen X position in pixels dl $7E0913 : db $02 : dw $8000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0002 ; Missiles dl $7E0AF6 : db $02 : dw $069C ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_brinstar_green_hill_zone: dw #preset_kpdr21_brinstar_big_pink ; Brinstar: Big Pink dl $7E078D : db $02 : dw $8DAE ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $9D19 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0300 ; Screen X position in pixels dl $7E0913 : db $02 : dw $8C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0611 ; Screen Y position in pixels dl $7E09A6 : db $02 : dw $1000 ; Beams dl $7E09A8 : db $02 : dw $1000 ; Beams dl $7E09C6 : db $02 : dw $0007 ; Missiles dl $7E09C8 : db $02 : dw $000A ; Max missiles dl $7E09CA : db $02 : dw $0003 ; Supers dl $7E0AF6 : db $02 : dw $0365 ; Samus X dl $7E0AFA : db $02 : dw $068B ; Samus Y dl $7ED872 : db $02 : dw $04C1 ; Events, Items, Doors dl $7ED8B4 : db $02 : dw $0206 ; Events, Items, Doors dl $7ED91A : db $02 : dw $000F ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_noob_bridge: dw #preset_kpdr21_brinstar_green_hill_zone ; Brinstar: Green Hill Zone dl $7E078D : db $02 : dw $8DEA ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $9E52 ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0700 ; Screen X position in pixels dl $7E0913 : db $02 : dw $4000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0300 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0077 ; Health dl $7E0AF6 : db $02 : dw $07B9 ; Samus X dl $7E0AFA : db $02 : dw $038B ; Samus Y dl $7ED91A : db $02 : dw $0010 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_red_tower: dw #preset_kpdr21_brinstar_noob_bridge ; Brinstar: Noob Bridge dl $7E078D : db $02 : dw $8E92 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $9FBA ; MDB dl $7E0911 : db $02 : dw $0482 ; Screen X position in pixels dl $7E0913 : db $02 : dw $E000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0AF6 : db $02 : dw $0522 ; Samus X dl $7E0AFA : db $02 : dw $00AB ; Samus Y dl $7ED8B6 : db $02 : dw $0008 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_skree_boost: dw #preset_kpdr21_brinstar_red_tower ; Brinstar: Red Tower dl $7E078D : db $02 : dw $8F0A ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A253 ; MDB dl $7E07C3 : db $02 : dw $A5AA ; GFX Pointers dl $7E07C5 : db $02 : dw $5FBC ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B3 ; GFX Pointers dl $7E07F3 : db $02 : dw $0012 ; Music Bank dl $7E090F : db $02 : dw $3001 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $091A ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0056 ; Samus X dl $7E0AFA : db $02 : dw $098B ; Samus Y dw #$FFFF .after preset_kpdr21_brinstar_below_spazer: dw #preset_kpdr21_brinstar_skree_boost ; Brinstar: Skree Boost dl $7E078D : db $02 : dw $9042 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $A3DD ; MDB dl $7E090F : db $02 : dw $2FFF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $4400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $006D ; Health dl $7E0AF6 : db $02 : dw $01DC ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_brinstar_entering_kraids_lair: dw #preset_kpdr21_brinstar_below_spazer ; Brinstar: Below Spazer dl $7E078D : db $02 : dw $A348 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $CF80 ; MDB dl $7E079F : db $02 : dw $0004 ; Region dl $7E07C3 : db $02 : dw $B130 ; GFX Pointers dl $7E07C5 : db $02 : dw $3CBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B8 ; GFX Pointers dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $CC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0006 ; Missiles dl $7E09CA : db $02 : dw $0005 ; Supers dl $7E0AF6 : db $02 : dw $002E ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dw #$FFFF .after preset_kpdr21_brinstar_kraid_kihunters: dw #preset_kpdr21_brinstar_entering_kraids_lair ; Brinstar: Entering Kraids Lair dl $7E078D : db $02 : dw $923A ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A471 ; MDB dl $7E079F : db $02 : dw $0001 ; Region dl $7E07C3 : db $02 : dw $A5AA ; GFX Pointers dl $7E07C5 : db $02 : dw $5FBC ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B3 ; GFX Pointers dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $8000 ; Screen subpixel Y position dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0AF6 : db $02 : dw $0167 ; Samus X dw #$FFFF .after preset_kpdr21_brinstar_mini_kraid: dw #preset_kpdr21_brinstar_kraid_kihunters ; Brinstar: Kraid Kihunters dl $7E078D : db $02 : dw $9156 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $A4DA ; MDB dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $FC00 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $0059 ; Health dl $7E0AF6 : db $02 : dw $016B ; Samus X dl $7ED91A : db $02 : dw $0011 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_kraid: dw #preset_kpdr21_brinstar_mini_kraid ; Brinstar: Mini Kraid dl $7E078D : db $02 : dw $919E ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A56B ; MDB dl $7E07F3 : db $02 : dw $0027 ; Music Bank dl $7E07F5 : db $02 : dw $0006 ; Music Track dl $7E090F : db $02 : dw $7000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0800 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $0043 ; Health dl $7E09C6 : db $02 : dw $0005 ; Missiles dl $7E0AF6 : db $02 : dw $01C1 ; Samus X dl $7ED8B8 : db $02 : dw $0024 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_leaving_varia: dw #preset_kpdr21_brinstar_kraid ; Brinstar: Kraid dl $7E078D : db $02 : dw $91DA ; DDB dl $7E079B : db $02 : dw $A6E2 ; MDB dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $5800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09A2 : db $02 : dw $1005 ; Equipped Items dl $7E09A4 : db $02 : dw $1005 ; Collected Items dl $7E09C2 : db $02 : dw $0084 ; Health dl $7E09C6 : db $02 : dw $0007 ; Missiles dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0078 ; Samus X dl $7E0AFA : db $02 : dw $0088 ; Samus Y dl $7ED828 : db $02 : dw $0104 ; Events, Items, Doors dl $7ED876 : db $02 : dw $0001 ; Events, Items, Doors dl $7ED8B8 : db $02 : dw $0064 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0012 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_mini_kraid_revisit: dw #preset_kpdr21_brinstar_leaving_varia ; Brinstar: Leaving Varia dl $7E078D : db $02 : dw $91CE ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $A56B ; MDB dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $7800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $007C ; Health dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0058 ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED8B8 : db $02 : dw $00E4 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_kraid_kihunters_revisit: dw #preset_kpdr21_brinstar_mini_kraid_revisit ; Brinstar: Mini Kraid Revisit dl $7E078D : db $02 : dw $91AA ; DDB dl $7E079B : db $02 : dw $A521 ; MDB dl $7E090F : db $02 : dw $9000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $4000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0004 ; Missiles dl $7E09CA : db $02 : dw $0005 ; Supers dl $7E0AF6 : db $02 : dw $009A ; Samus X dl $7E0AFA : db $02 : dw $00AB ; Samus Y dl $7ED8B8 : db $02 : dw $00EC ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_brinstar_kraid_etank: dw #preset_kpdr21_brinstar_kraid_kihunters_revisit ; Brinstar: Kraid Kihunters Revisit dl $7E078D : db $02 : dw $916E ; DDB dl $7E079B : db $02 : dw $A471 ; MDB dl $7E07F3 : db $02 : dw $0012 ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $D400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0051 ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED8B8 : db $02 : dw $00ED ; Events, Items, Doors dl $7ED91A : db $02 : dw $0013 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_business_center: dw #preset_kpdr21_brinstar_kraid_etank ; Brinstar: Kraid E-tank dl $7E078D : db $02 : dw $9246 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $A7DE ; MDB dl $7E079F : db $02 : dw $0002 ; Region dl $7E07C3 : db $02 : dw $C3F9 ; GFX Pointers dl $7E07C5 : db $02 : dw $BBBD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B6 ; GFX Pointers dl $7E07F3 : db $02 : dw $0015 ; Music Bank dl $7E090F : db $02 : dw $B000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0238 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0006 ; Missiles dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0080 ; Samus X dl $7E0AFA : db $02 : dw $02A8 ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_hi_jump_etank: dw #preset_kpdr21_upper_norfair_business_center ; Upper Norfair: Business Center dl $7E078F : db $02 : dw $0005 ; DoorOut Index dl $7E090F : db $02 : dw $EFFF ; Screen subpixel X position. dl $7E0915 : db $02 : dw $051B ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0003 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0041 ; Samus X dl $7E0AFA : db $02 : dw $058B ; Samus Y dl $7ED8B8 : db $02 : dw $20ED ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_leaving_hi_jump: dw #preset_kpdr21_upper_norfair_hi_jump_etank ; Upper Norfair: Hi Jump E-tank dl $7E078D : db $02 : dw $9426 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A9E5 ; MDB dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $1FFF ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09A2 : db $02 : dw $1105 ; Equipped Items dl $7E09A4 : db $02 : dw $1105 ; Collected Items dl $7E09C2 : db $02 : dw $012B ; Health dl $7E09C4 : db $02 : dw $012B ; Max health dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $00B5 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED876 : db $02 : dw $0121 ; Events, Items, Doors dl $7ED8BA : db $02 : dw $0001 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0016 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_business_center_2: dw #preset_kpdr21_upper_norfair_leaving_hi_jump ; Upper Norfair: Leaving Hi Jump dl $7E078D : db $02 : dw $93F6 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $AA41 ; MDB dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $E400 ; Screen subpixel Y position dl $7E09C6 : db $02 : dw $000B ; Missiles dl $7E09C8 : db $02 : dw $000F ; Max missiles dl $7E0AF6 : db $02 : dw $019C ; Samus X dl $7ED876 : db $02 : dw $01A1 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0018 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_precathedral: dw #preset_kpdr21_upper_norfair_business_center_2 ; Upper Norfair: Business Center 2 dl $7E078D : db $02 : dw $941A ; DDB dl $7E079B : db $02 : dw $A7DE ; MDB dl $7E090F : db $02 : dw $B000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $53FE ; Screen subpixel Y position dl $7E0915 : db $02 : dw $02F8 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $00A5 ; Samus X dl $7E0AFA : db $02 : dw $038B ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_cathedral: dw #preset_kpdr21_upper_norfair_precathedral ; Upper Norfair: Pre-Cathedral dl $7E078D : db $02 : dw $92CA ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A7B3 ; MDB dl $7E07C5 : db $02 : dw $E4BD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B5 ; GFX Pointers dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $F400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0009 ; Missiles dl $7E09CA : db $02 : dw $0002 ; Supers dl $7E0AF6 : db $02 : dw $02A6 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8B8 : db $02 : dw $24ED ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_rising_tide: dw #preset_kpdr21_upper_norfair_cathedral ; Upper Norfair: Cathedral dl $7E078D : db $02 : dw $92B2 ; DDB dl $7E079B : db $02 : dw $A788 ; MDB dl $7E090F : db $02 : dw $7FFF ; Screen subpixel X position. dl $7E0913 : db $02 : dw $2800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0001 ; Supers dl $7E0AF6 : db $02 : dw $02BB ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED8B8 : db $02 : dw $26ED ; Events, Items, Doors dl $7ED91A : db $02 : dw $0019 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_bubble_mountain: dw #preset_kpdr21_upper_norfair_rising_tide ; Upper Norfair: Rising Tide dl $7E078D : db $02 : dw $929A ; DDB dl $7E079B : db $02 : dw $AFA3 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0400 ; Screen X position in pixels dl $7E0913 : db $02 : dw $CC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0115 ; Health dl $7E0AF6 : db $02 : dw $04AD ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_bat_cave: dw #preset_kpdr21_upper_norfair_bubble_mountain ; Upper Norfair: Bubble Mountain dl $7E078D : db $02 : dw $973E ; DDB dl $7E079B : db $02 : dw $ACB3 ; MDB dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $2000 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $0110 ; Health dl $7E09C6 : db $02 : dw $0008 ; Missiles dl $7E0AF6 : db $02 : dw $01C2 ; Samus X dl $7ED8BA : db $02 : dw $0011 ; Events, Items, Doors dl $7ED91A : db $02 : dw $001A ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_single_chamber: dw #preset_kpdr21_upper_norfair_bat_cave ; Upper Norfair: Bat Cave dl $7E078D : db $02 : dw $97AA ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E090F : db $02 : dw $BFFF ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0104 ; Screen Y position in pixels dl $7E09A2 : db $02 : dw $3105 ; Equipped Items dl $7E09A4 : db $02 : dw $3105 ; Collected Items dl $7E09C2 : db $02 : dw $0126 ; Health dl $7E09C6 : db $02 : dw $000F ; Missiles dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0AF6 : db $02 : dw $01AD ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED822 : db $02 : dw $0020 ; Events, Items, Doors dl $7ED878 : db $02 : dw $0004 ; Events, Items, Doors dl $7ED8BA : db $02 : dw $0031 ; Events, Items, Doors dl $7ED91A : db $02 : dw $001E ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_double_chamber: dw #preset_kpdr21_upper_norfair_single_chamber ; Upper Norfair: Single Chamber dl $7E078D : db $02 : dw $9582 ; DDB dl $7E078F : db $02 : dw $0004 ; DoorOut Index dl $7E079B : db $02 : dw $AD5E ; MDB dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $A400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $011C ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0008 ; Missiles dl $7E0AF6 : db $02 : dw $00BE ; Samus X dl $7ED8BA : db $02 : dw $0071 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_double_chamber_revisit: dw #preset_kpdr21_upper_norfair_double_chamber ; Upper Norfair: Double Chamber dl $7E078D : db $02 : dw $961E ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $ADDE ; MDB dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $7800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09A6 : db $02 : dw $1001 ; Beams dl $7E09A8 : db $02 : dw $1001 ; Beams dl $7E09C6 : db $02 : dw $000D ; Missiles dl $7E09C8 : db $02 : dw $0014 ; Max missiles dl $7E09CA : db $02 : dw $0003 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0051 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED878 : db $02 : dw $001C ; Events, Items, Doors dl $7ED8BA : db $02 : dw $00F1 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0020 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_single_chamber_revisit: dw #preset_kpdr21_upper_norfair_double_chamber_revisit ; Upper Norfair: Double Chamber Revisit dl $7E078D : db $02 : dw $962A ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $ADAD ; MDB dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $6000 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $0050 ; Samus X dl $7ED91A : db $02 : dw $0021 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_bubble_mountain_revisit: dw #preset_kpdr21_upper_norfair_single_chamber_revisit ; Upper Norfair: Single Chamber Revisit dl $7E078D : db $02 : dw $9606 ; DDB dl $7E079B : db $02 : dw $AD5E ; MDB dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $EC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0002 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $008F ; Samus X dw #$FFFF .after preset_kpdr21_upper_norfair_frog_speedway: dw #preset_kpdr21_upper_norfair_bubble_mountain_revisit ; Upper Norfair: Bubble Mountain Revisit dl $7E078D : db $02 : dw $956A ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $AF72 ; MDB dl $7E090F : db $02 : dw $5000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $1400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $012B ; Health dl $7E09C6 : db $02 : dw $000E ; Missiles dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0AF6 : db $02 : dw $008E ; Samus X dl $7ED91A : db $02 : dw $0022 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_business_center_3: dw #preset_kpdr21_upper_norfair_frog_speedway ; Upper Norfair: Frog Speedway dl $7E078D : db $02 : dw $97DA ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $B167 ; MDB dl $7E07C3 : db $02 : dw $860B ; GFX Pointers dl $7E07C5 : db $02 : dw $21C0 ; GFX Pointers dl $7E07C7 : db $02 : dw $C2C0 ; GFX Pointers dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $A800 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $0029 ; Samus X dw #$FFFF .after preset_kpdr21_red_brinstar_alpha_spark: dw #preset_kpdr21_upper_norfair_business_center_3 ; Upper Norfair: Business Center 3 dl $7E078D : db $02 : dw $92EE ; DDB dl $7E078F : db $02 : dw $0004 ; DoorOut Index dl $7E079B : db $02 : dw $A6A1 ; MDB dl $7E079F : db $02 : dw $0001 ; Region dl $7E07C3 : db $02 : dw $A5AA ; GFX Pointers dl $7E07C5 : db $02 : dw $5FBC ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B3 ; GFX Pointers dl $7E07F3 : db $02 : dw $0012 ; Music Bank dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E09C6 : db $02 : dw $0014 ; Missiles dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0080 ; Samus X dl $7E0AFA : db $02 : dw $0086 ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_reverse_skree_boost: dw #preset_kpdr21_red_brinstar_alpha_spark ; Red Brinstar: Alpha Spark dl $7E078D : db $02 : dw $A36C ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A408 ; MDB dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $B400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0005 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $003F ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_red_tower_climb: dw #preset_kpdr21_red_brinstar_reverse_skree_boost ; Red Brinstar: Reverse Skree Boost dl $7E078D : db $02 : dw $910E ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $A3DD ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $EC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0129 ; Health dl $7E0AF6 : db $02 : dw $0024 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_hellway: dw #preset_kpdr21_red_brinstar_red_tower_climb ; Red Brinstar: Red Tower Climb dl $7E078D : db $02 : dw $90F6 ; DDB dl $7E079B : db $02 : dw $A253 ; MDB dl $7E090F : db $02 : dw $D000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $6800 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $008F ; Samus X dw #$FFFF .after preset_kpdr21_red_brinstar_caterpillars_down: dw #preset_kpdr21_red_brinstar_hellway ; Red Brinstar: Hellway dl $7E078D : db $02 : dw $901E ; DDB dl $7E079B : db $02 : dw $A2F7 ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $01FB ; Screen X position in pixels dl $7E0913 : db $02 : dw $4400 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $0119 ; Health dl $7E0AF6 : db $02 : dw $0291 ; Samus X dw #$FFFF .after preset_kpdr21_red_brinstar_alpha_power_bombs: dw #preset_kpdr21_red_brinstar_caterpillars_down ; Red Brinstar: Caterpillars Down dl $7E078D : db $02 : dw $908A ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A322 ; MDB dl $7E090F : db $02 : dw $D000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $071C ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0041 ; Samus X dl $7E0AFA : db $02 : dw $078B ; Samus Y dl $7ED8B6 : db $02 : dw $2008 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_red_brinstar_caterpillars_up: dw #preset_kpdr21_red_brinstar_alpha_power_bombs ; Red Brinstar: Alpha Power Bombs dl $7E078D : db $02 : dw $9096 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $A3AE ; MDB dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $FC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $010F ; Health dl $7E09CE : db $02 : dw $0005 ; Pbs dl $7E09D0 : db $02 : dw $0005 ; Max pbs dl $7E09D2 : db $02 : dw $0003 ; Currently selected item dl $7E09D2 : db $02 : dw $0003 ; Currently selected item dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $02AF ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED874 : db $02 : dw $0104 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0024 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_crateria_kihunters: dw #preset_kpdr21_red_brinstar_caterpillars_up ; Red Brinstar: Caterpillars Up dl $7E078D : db $02 : dw $90BA ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $962A ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $A400 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $0123 ; Health dl $7E09CA : db $02 : dw $0005 ; Supers dl $7E09CE : db $02 : dw $0003 ; Pbs dl $7E0A1C : db $02 : dw $0028 ; Samus position/state dl $7E0A1E : db $02 : dw $0504 ; More position/state dl $7E0AF6 : db $02 : dw $0068 ; Samus X dl $7E0AFA : db $02 : dw $0060 ; Samus Y dl $7ED8B2 : db $02 : dw $2C01 ; Events, Items, Doors dl $7ED8B6 : db $02 : dw $3008 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_oceanfly_setup: dw #preset_kpdr21_wrecked_ship_crateria_kihunters ; Wrecked Ship: Crateria Kihunters dl $7E078D : db $02 : dw $8AF6 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $948C ; MDB dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $8C00 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $3000 ; Screen subpixel Y position dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E09D2 : db $02 : dw $0000 ; Currently selected item dl $7E09D2 : db $02 : dw $0000 ; Currently selected item dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $002C ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8B0 : db $02 : dw $6000 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_ocean_spark: dw #preset_kpdr21_wrecked_ship_oceanfly_setup ; Wrecked Ship: Oceanfly Setup dl $7E078D : db $02 : dw $8A36 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $95FF ; MDB dl $7E090F : db $02 : dw $A3FF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $6C00 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $00EE ; Health dl $7E0AF6 : db $02 : dw $01C6 ; Samus X dl $7ED91A : db $02 : dw $0025 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_entering_wrecked_ship: dw #preset_kpdr21_wrecked_ship_ocean_spark ; Wrecked Ship: Ocean Spark dl $7E078D : db $02 : dw $8AEA ; DDB dl $7E079B : db $02 : dw $93FE ; MDB dl $7E07F3 : db $02 : dw $000C ; Music Bank dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0700 ; Screen X position in pixels dl $7E0913 : db $02 : dw $B000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0400 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0074 ; Health dl $7E09CA : db $02 : dw $0004 ; Supers dl $7E0AF6 : db $02 : dw $07DB ; Samus X dl $7E0AFA : db $02 : dw $048B ; Samus Y dl $7ED8B0 : db $02 : dw $7000 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0028 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_basement: dw #preset_kpdr21_wrecked_ship_entering_wrecked_ship ; Wrecked Ship: Entering Wrecked Ship dl $7E078D : db $02 : dw $A1BC ; DDB dl $7E079B : db $02 : dw $CAF6 ; MDB dl $7E079F : db $02 : dw $0003 ; Region dl $7E07C3 : db $02 : dw $AE9E ; GFX Pointers dl $7E07C5 : db $02 : dw $A6BB ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B1 ; GFX Pointers dl $7E07F3 : db $02 : dw $0030 ; Music Bank dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0400 ; Screen X position in pixels dl $7E0913 : db $02 : dw $F000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $071F ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0003 ; Supers dl $7E0AF6 : db $02 : dw $0455 ; Samus X dl $7E0AFA : db $02 : dw $07BB ; Samus Y dl $7ED8C0 : db $02 : dw $0010 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0029 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_phantoon: dw #preset_kpdr21_wrecked_ship_basement ; Wrecked Ship: Basement dl $7E078D : db $02 : dw $A21C ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $CC6F ; MDB dl $7E090F : db $02 : dw $F000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $7000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0002 ; Supers dl $7E0AF6 : db $02 : dw $04CC ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8C0 : db $02 : dw $0030 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_leaving_phantoon: dw #preset_kpdr21_wrecked_ship_phantoon ; Wrecked Ship: Phantoon dl $7E078D : db $02 : dw $A2C4 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E07C5 : db $02 : dw $E7BB ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B0 ; GFX Pointers dl $7E07F5 : db $02 : dw $0006 ; Music Track dl $7E090F : db $02 : dw $7000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $8000 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $00E2 ; Health dl $7E09CA : db $02 : dw $0005 ; Supers dl $7E09CE : db $02 : dw $0003 ; Pbs dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $04D6 ; Samus X dl $7ED82A : db $02 : dw $0100 ; Events, Items, Doors dl $7ED8C0 : db $02 : dw $0070 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_shaft_to_supers: dw #preset_kpdr21_wrecked_ship_leaving_phantoon ; Wrecked Ship: Leaving Phantoon dl $7E090F : db $02 : dw $6000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0226 ; Screen X position in pixels dl $7E0913 : db $02 : dw $FC00 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $02C4 ; Samus X dl $7E0AFA : db $02 : dw $006B ; Samus Y dw #$FFFF .after preset_kpdr21_wrecked_ship_wrecked_ship_shaft: dw #preset_kpdr21_wrecked_ship_shaft_to_supers ; Wrecked Ship: Shaft to Supers dl $7E078D : db $02 : dw $A210 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $CDA8 ; MDB dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $7800 ; Screen subpixel Y position dl $7E09CA : db $02 : dw $000A ; Supers dl $7E09CC : db $02 : dw $000A ; Max supers dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $00C4 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED880 : db $02 : dw $0020 ; Events, Items, Doors dl $7ED8C0 : db $02 : dw $0074 ; Events, Items, Doors dl $7ED91A : db $02 : dw $002B ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_attic: dw #preset_kpdr21_wrecked_ship_wrecked_ship_shaft ; Wrecked Ship: Wrecked Ship Shaft dl $7E078D : db $02 : dw $A2E8 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $CAF6 ; MDB dl $7E090F : db $02 : dw $AC00 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0400 ; Screen X position in pixels dl $7E0913 : db $02 : dw $B000 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $0445 ; Samus X dl $7E0AFA : db $02 : dw $006B ; Samus Y dl $7ED91A : db $02 : dw $002C ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_upper_west_ocean: dw #preset_kpdr21_wrecked_ship_attic ; Wrecked Ship: Attic dl $7E078D : db $02 : dw $A228 ; DDB dl $7E078F : db $02 : dw $0004 ; DoorOut Index dl $7E079B : db $02 : dw $CA52 ; MDB dl $7E090F : db $02 : dw $7000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $C7FD ; Screen subpixel Y position dl $7E0915 : db $02 : dw $001F ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00EE ; Health dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $003B ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8C0 : db $02 : dw $0174 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_pancakes_and_wavers: dw #preset_kpdr21_wrecked_ship_upper_west_ocean ; Wrecked Ship: Upper West Ocean dl $7E078D : db $02 : dw $A1E0 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $93FE ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E07F3 : db $02 : dw $000C ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $F800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $01FC ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0102 ; Health dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $02C2 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dl $7ED91A : db $02 : dw $002F ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_bowling_spark: dw #preset_kpdr21_wrecked_ship_pancakes_and_wavers ; Wrecked Ship: Pancakes and Wavers dl $7E078D : db $02 : dw $89E2 ; DDB dl $7E079B : db $02 : dw $9461 ; MDB dl $7E090F : db $02 : dw $6800 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $2400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $016E ; Samus X dl $7E0AFA : db $02 : dw $009D ; Samus Y dw #$FFFF .after preset_kpdr21_wrecked_ship_leaving_gravity: dw #preset_kpdr21_wrecked_ship_bowling_spark ; Wrecked Ship: Bowling Spark dl $7E078D : db $02 : dw $A1A4 ; DDB dl $7E079B : db $02 : dw $CE40 ; MDB dl $7E079F : db $02 : dw $0003 ; Region dl $7E07C3 : db $02 : dw $AE9E ; GFX Pointers dl $7E07C5 : db $02 : dw $E7BB ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B0 ; GFX Pointers dl $7E07F3 : db $02 : dw $0030 ; Music Bank dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $E400 ; Screen subpixel Y position dl $7E09A2 : db $02 : dw $3125 ; Equipped Items dl $7E09A4 : db $02 : dw $3125 ; Collected Items dl $7E09C2 : db $02 : dw $00A9 ; Health dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0078 ; Samus X dl $7E0AFA : db $02 : dw $0088 ; Samus Y dl $7ED880 : db $02 : dw $00A0 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0032 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_moat_ball: dw #preset_kpdr21_wrecked_ship_leaving_gravity ; Wrecked Ship: Leaving Gravity dl $7E078D : db $02 : dw $A300 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $93FE ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E07F3 : db $02 : dw $000C ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $00E4 ; Screen X position in pixels dl $7E0913 : db $02 : dw $2800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0445 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0184 ; Samus X dl $7E0AFA : db $02 : dw $04D0 ; Samus Y dl $7ED91A : db $02 : dw $0035 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_wrecked_ship_crateria_kihunters_return: dw #preset_kpdr21_wrecked_ship_moat_ball ; Wrecked Ship: Moat Ball dl $7E078D : db $02 : dw $89CA ; DDB dl $7E079B : db $02 : dw $95FF ; MDB dl $7E090F : db $02 : dw $8400 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0007 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $003B ; Samus X dl $7E0AFA : db $02 : dw $0097 ; Samus Y dl $7ED91A : db $02 : dw $0036 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_red_brinstar_final_red_tower_elevator: dw #preset_kpdr21_wrecked_ship_crateria_kihunters_return ; Wrecked Ship: Crateria Kihunters Return dl $7E078D : db $02 : dw $8B02 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A322 ; MDB dl $7E079F : db $02 : dw $0001 ; Region dl $7E07C3 : db $02 : dw $A5AA ; GFX Pointers dl $7E07C5 : db $02 : dw $5FBC ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B3 ; GFX Pointers dl $7E07F3 : db $02 : dw $0012 ; Music Bank dl $7E090F : db $02 : dw $F000 ; Screen subpixel X position. dl $7E0915 : db $02 : dw $0238 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00BD ; Health dl $7E09C6 : db $02 : dw $0012 ; Missiles dl $7E09CE : db $02 : dw $0003 ; Pbs dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0080 ; Samus X dl $7E0AFA : db $02 : dw $02A8 ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_final_hellway_revisit: dw #preset_kpdr21_red_brinstar_final_red_tower_elevator ; Red Brinstar Final: Red Tower Elevator dl $7E078F : db $02 : dw $0005 ; DoorOut Index dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $2800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0500 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0040 ; Samus X dl $7E0AFA : db $02 : dw $058B ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_final_red_tower_down: dw #preset_kpdr21_red_brinstar_final_hellway_revisit ; Red Brinstar Final: Hellway Revisit dl $7E078D : db $02 : dw $90AE ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $A2F7 ; MDB dl $7E0913 : db $02 : dw $9000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00B5 ; Health dl $7E0AF6 : db $02 : dw $003D ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_final_skree_boost_final: dw #preset_kpdr21_red_brinstar_final_red_tower_down ; Red Brinstar Final: Red Tower Down dl $7E078D : db $02 : dw $907E ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $A253 ; MDB dl $7E090F : db $02 : dw $A001 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $091A ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $0054 ; Samus X dl $7E0AFA : db $02 : dw $098B ; Samus Y dw #$FFFF .after preset_kpdr21_red_brinstar_final_below_spazer_final: dw #preset_kpdr21_red_brinstar_final_skree_boost_final ; Red Brinstar Final: Skree Boost Final dl $7E078D : db $02 : dw $9042 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $A3DD ; MDB dl $7E090F : db $02 : dw $5FFF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $4400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00B4 ; Health dl $7E0AF6 : db $02 : dw $01DC ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_breaking_tube: dw #preset_kpdr21_red_brinstar_final_below_spazer_final ; Red Brinstar Final: Below Spazer Final dl $7E078D : db $02 : dw $911A ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $CF54 ; MDB dl $7E079F : db $02 : dw $0004 ; Region dl $7E07C3 : db $02 : dw $B130 ; GFX Pointers dl $7E07C5 : db $02 : dw $3CBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B8 ; GFX Pointers dl $7E09D2 : db $02 : dw $0003 ; Currently selected item dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $7400 ; Screen subpixel Y position dl $7E09CA : db $02 : dw $000A ; Supers dl $7E0AF6 : db $02 : dw $002D ; Samus X dw #$FFFF .after preset_kpdr21_maridia_fish_tank: dw #preset_kpdr21_maridia_breaking_tube ; Maridia: Breaking Tube dl $7E078D : db $02 : dw $A330 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $CFC9 ; MDB dl $7E07F3 : db $02 : dw $001B ; Music Bank dl $7E07F5 : db $02 : dw $0006 ; Music Track dl $7E090F : db $02 : dw $4FFF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $00FE ; Screen X position in pixels dl $7E0913 : db $02 : dw $C000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $05F4 ; Screen Y position in pixels dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E09D2 : db $02 : dw $0000 ; Currently selected item dl $7E0AF6 : db $02 : dw $0167 ; Samus X dl $7E0AFA : db $02 : dw $068B ; Samus Y dl $7ED820 : db $02 : dw $0801 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0038 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_mt_everest: dw #preset_kpdr21_maridia_fish_tank ; Maridia: Fish Tank dl $7E078D : db $02 : dw $A3F0 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $D0B9 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $BC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $031F ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $017C ; Samus X dl $7E0AFA : db $02 : dw $03BB ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_crab_shaft: dw #preset_kpdr21_maridia_mt_everest ; Maridia: Mt Everest dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0500 ; Screen X position in pixels dl $7E0913 : db $02 : dw $9C01 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0079 ; Health dl $7E0AF6 : db $02 : dw $05C0 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_aqueduct: dw #preset_kpdr21_maridia_crab_shaft ; Maridia: Crab Shaft dl $7E078D : db $02 : dw $A468 ; DDB dl $7E078F : db $02 : dw $0005 ; DoorOut Index dl $7E079B : db $02 : dw $D1A3 ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $83FF ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0300 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E09D2 : db $02 : dw $0003 ; Currently selected item dl $7E0AF6 : db $02 : dw $01AD ; Samus X dl $7E0AFA : db $02 : dw $038B ; Samus Y dl $7ED8C0 : db $02 : dw $8174 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_botwoon_hallway: dw #preset_kpdr21_maridia_aqueduct ; Maridia: Aqueduct dl $7E078D : db $02 : dw $A4C8 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $D5A7 ; MDB dl $7E07C3 : db $02 : dw $E78D ; GFX Pointers dl $7E07C5 : db $02 : dw $2EBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B9 ; GFX Pointers dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $A000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $4000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09CE : db $02 : dw $0001 ; Pbs dl $7E09D2 : db $02 : dw $0000 ; Currently selected item dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $009D ; Samus X dl $7E0AFA : db $02 : dw $006B ; Samus Y dl $7ED91A : db $02 : dw $003A ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_botwoon: dw #preset_kpdr21_maridia_botwoon_hallway ; Maridia: Botwoon Hallway dl $7E078D : db $02 : dw $A72C ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $D617 ; MDB dl $7E090F : db $02 : dw $DFFF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0300 ; Screen X position in pixels dl $7E0913 : db $02 : dw $5800 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $03A4 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_botwoon_etank: dw #preset_kpdr21_maridia_botwoon ; Maridia: Botwoon dl $7E078D : db $02 : dw $A774 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $D95E ; MDB dl $7E07F3 : db $02 : dw $002A ; Music Bank dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $C000 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $00A1 ; Health dl $7E09C6 : db $02 : dw $0014 ; Missiles dl $7E09CA : db $02 : dw $0003 ; Supers dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E0AF6 : db $02 : dw $01C6 ; Samus X dl $7ED82C : db $02 : dw $0002 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_halfie_setup: dw #preset_kpdr21_maridia_botwoon_etank ; Maridia: Botwoon E-tank dl $7E078D : db $02 : dw $A918 ; DDB dl $7E079B : db $02 : dw $D7E4 ; MDB dl $7E07F3 : db $02 : dw $001B ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $4400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $001F ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $018F ; Health dl $7E09C4 : db $02 : dw $018F ; Max health dl $7E0AF6 : db $02 : dw $008D ; Samus X dl $7E0AFA : db $02 : dw $009B ; Samus Y dl $7ED882 : db $02 : dw $0100 ; Events, Items, Doors dl $7ED91A : db $02 : dw $003B ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_draygon: dw #preset_kpdr21_maridia_halfie_setup ; Maridia: Halfie Setup dl $7E078D : db $02 : dw $A7F8 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $D78F ; MDB dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $E400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0200 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0110 ; Health dl $7E09CA : db $02 : dw $0001 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0041 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dl $7ED8C2 : db $02 : dw $0C00 ; Events, Items, Doors dl $7ED91A : db $02 : dw $003C ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_reverse_halfie_spikesuit: dw #preset_kpdr21_maridia_draygon ; Maridia: Draygon dl $7E078D : db $02 : dw $A96C ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E090F : db $02 : dw $6000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09A2 : db $02 : dw $3325 ; Equipped Items dl $7E09A4 : db $02 : dw $3325 ; Collected Items dl $7E09C2 : db $02 : dw $00BA ; Health dl $7E09C6 : db $02 : dw $000D ; Missiles dl $7E09CA : db $02 : dw $0005 ; Supers dl $7E09CE : db $02 : dw $0003 ; Pbs dl $7E0A68 : db $02 : dw $0001 ; Flash suit dl $7E0AF6 : db $02 : dw $0044 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED82C : db $02 : dw $0003 ; Events, Items, Doors dl $7ED882 : db $02 : dw $0500 ; Events, Items, Doors dl $7ED8C2 : db $02 : dw $CC00 ; Events, Items, Doors dl $7ED91A : db $02 : dw $003E ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_womple_jump: dw #preset_kpdr21_maridia_reverse_halfie_spikesuit ; Maridia: Reverse Halfie (Spikesuit) dl $7E0A68 : db $02 : dw $0000 ; Flash suit dw #$FFFF .after preset_kpdr21_maridia_cac_alley_east: dw #preset_kpdr21_maridia_womple_jump ; Maridia: Womple Jump dl $7E078D : db $02 : dw $A7E0 ; DDB dl $7E079B : db $02 : dw $D913 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0915 : db $02 : dw $011A ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00BA ; Health dl $7E09C6 : db $02 : dw $000C ; Missiles dl $7E0A68 : db $02 : dw $0000 ; Flash suit dl $7E0AF6 : db $02 : dw $0030 ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED8C2 : db $02 : dw $DC00 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_cac_alley_west: dw #preset_kpdr21_maridia_cac_alley_east ; Maridia: Cac Alley East dl $7E078D : db $02 : dw $A900 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $DA2B ; MDB dl $7E090F : db $02 : dw $B000 ; Screen subpixel X position. dl $7E0915 : db $02 : dw $0002 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $000B ; Missiles dl $7E09CA : db $02 : dw $0007 ; Supers dl $7E0AF6 : db $02 : dw $005B ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_plasma_spark: dw #preset_kpdr21_maridia_cac_alley_west ; Maridia: Cac Alley West dl $7E078D : db $02 : dw $A93C ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $D5EC ; MDB dl $7E090F : db $02 : dw $2000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $7400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0008 ; Supers dl $7E0AF6 : db $02 : dw $0024 ; Samus X dw #$FFFF .after preset_kpdr21_maridia_plasma_climb: dw #preset_kpdr21_maridia_plasma_spark ; Maridia: Plasma Spark dl $7E078D : db $02 : dw $A750 ; DDB dl $7E079B : db $02 : dw $D340 ; MDB dl $7E07C3 : db $02 : dw $B130 ; GFX Pointers dl $7E07C5 : db $02 : dw $3CBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B8 ; GFX Pointers dl $7E090F : db $02 : dw $FFFF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $8C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $00F3 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $027F ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_plasma_beam: dw #preset_kpdr21_maridia_plasma_climb ; Maridia: Plasma Climb dl $7E078D : db $02 : dw $A5DC ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $D27E ; MDB dl $7E090F : db $02 : dw $9000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0095 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8C2 : db $02 : dw $DC08 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_plasma_spark_revisit: dw #preset_kpdr21_maridia_plasma_beam ; Maridia: Plasma Beam dl $7E078D : db $02 : dw $A540 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $D387 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $031A ; Screen Y position in pixels dl $7E09A6 : db $02 : dw $1009 ; Beams dl $7E09A8 : db $02 : dw $1009 ; Beams dl $7E09C2 : db $02 : dw $00A4 ; Health dl $7E09C6 : db $02 : dw $0011 ; Missiles dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0025 ; Samus X dl $7E0AFA : db $02 : dw $038B ; Samus Y dl $7ED880 : db $02 : dw $80A0 ; Events, Items, Doors dl $7ED8C2 : db $02 : dw $DC0A ; Events, Items, Doors dl $7ED91A : db $02 : dw $003F ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_toilet: dw #preset_kpdr21_maridia_plasma_spark_revisit ; Maridia: Plasma Spark Revisit dl $7E078D : db $02 : dw $A5D0 ; DDB dl $7E079B : db $02 : dw $D340 ; MDB dl $7E0911 : db $02 : dw $002E ; Screen X position in pixels dl $7E0913 : db $02 : dw $0800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $021F ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00A9 ; Health dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E0AF6 : db $02 : dw $00A3 ; Samus X dl $7E0AFA : db $02 : dw $02AB ; Samus Y dl $7ED8C2 : db $02 : dw $DC1A ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_maridia_sewers: dw #preset_kpdr21_maridia_toilet ; Maridia: Toilet dl $7E078D : db $02 : dw $A600 ; DDB dl $7E079B : db $02 : dw $D48E ; MDB dl $7E07C3 : db $02 : dw $E78D ; GFX Pointers dl $7E07C5 : db $02 : dw $2EBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B9 ; GFX Pointers dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $3000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $011C ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $00BB ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dw #$FFFF .after preset_kpdr21_maridia_lower_maridia_gate: dw #preset_kpdr21_maridia_sewers ; Maridia: Sewers dl $7E078D : db $02 : dw $A528 ; DDB dl $7E079B : db $02 : dw $D21C ; MDB dl $7E07C3 : db $02 : dw $B130 ; GFX Pointers dl $7E07C5 : db $02 : dw $3CBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B8 ; GFX Pointers dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $5C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00AE ; Health dl $7E09CE : db $02 : dw $0005 ; Pbs dl $7E0AF6 : db $02 : dw $002E ; Samus X dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_ice_beam_gates: dw #preset_kpdr21_maridia_lower_maridia_gate ; Maridia: Lower Maridia Gate dl $7E078D : db $02 : dw $9246 ; DDB dl $7E078F : db $02 : dw $0005 ; DoorOut Index dl $7E079B : db $02 : dw $A7DE ; MDB dl $7E079F : db $02 : dw $0002 ; Region dl $7E07C3 : db $02 : dw $C3F9 ; GFX Pointers dl $7E07C5 : db $02 : dw $BBBD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B6 ; GFX Pointers dl $7E07F3 : db $02 : dw $0015 ; Music Bank dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0326 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0007 ; Supers dl $7E0AF6 : db $02 : dw $0032 ; Samus X dl $7E0AFA : db $02 : dw $0395 ; Samus Y dl $7ED8B8 : db $02 : dw $2EED ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_ice_maze_up: dw #preset_kpdr21_upper_norfair_revisit_ice_beam_gates ; Upper Norfair Revisit: Ice Beam Gates dl $7E078D : db $02 : dw $931E ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $A75D ; MDB dl $7E07C5 : db $02 : dw $E4BD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B5 ; GFX Pointers dl $7E0913 : db $02 : dw $1800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0025 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_ice_maze_down: dw #preset_kpdr21_upper_norfair_revisit_ice_maze_up ; Upper Norfair Revisit: Ice Maze Up dl $7E078D : db $02 : dw $937E ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $A890 ; MDB dl $7E07C5 : db $02 : dw $BBBD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B6 ; GFX Pointers dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $5000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $7000 ; Screen subpixel Y position dl $7E09A6 : db $02 : dw $100B ; Beams dl $7E09A8 : db $02 : dw $100B ; Beams dl $7E09C2 : db $02 : dw $00BD ; Health dl $7E0AF6 : db $02 : dw $00BA ; Samus X dl $7ED876 : db $02 : dw $01A5 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0040 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_ice_escape: dw #preset_kpdr21_upper_norfair_revisit_ice_maze_down ; Upper Norfair Revisit: Ice Maze Down dl $7E078D : db $02 : dw $935A ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $A8B9 ; MDB dl $7E07C5 : db $02 : dw $E4BD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B5 ; GFX Pointers dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $9000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0200 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $00C5 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_purple_shaft_upper: dw #preset_kpdr21_upper_norfair_revisit_ice_escape ; Upper Norfair Revisit: Ice Escape dl $7E078D : db $02 : dw $971A ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $ACB3 ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $E800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0300 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0036 ; Samus X dl $7E0AFA : db $02 : dw $038B ; Samus Y dl $7ED91A : db $02 : dw $0041 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_magdollite_tunnel_upper: dw #preset_kpdr21_upper_norfair_revisit_purple_shaft_upper ; Upper Norfair Revisit: Purple Shaft (Upper) dl $7E078D : db $02 : dw $9576 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $AEDF ; MDB dl $7E090F : db $02 : dw $B001 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $01F4 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0059 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_kronic_boost_upper: dw #preset_kpdr21_upper_norfair_revisit_magdollite_tunnel_upper ; Upper Norfair Revisit: Magdollite Tunnel (Upper) dl $7E078D : db $02 : dw $96BA ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $AEB4 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $9000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $02B7 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_croc_speedway_lower: dw #preset_kpdr21_upper_norfair_revisit_ice_escape ; Upper Norfair Revisit: Ice Escape dl $7E078D : db $02 : dw $9336 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $A8F8 ; MDB dl $7E090F : db $02 : dw $6781 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0300 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $00DD ; Samus X dl $7E0AFA : db $02 : dw $038B ; Samus Y dl $7ED91A : db $02 : dw $0041 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_spiky_acid_snakes_lower: dw #preset_kpdr21_upper_norfair_revisit_croc_speedway_lower ; Upper Norfair Revisit: Croc Speedway (Lower) dl $7E078D : db $02 : dw $93C6 ; DDB dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E079B : db $02 : dw $AFCE ; MDB dl $7E090F : db $02 : dw $A000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $02A3 ; Screen X position in pixels dl $7E0913 : db $02 : dw $7400 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $030E ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7E0B3F : db $02 : dw $0000 ; Blue suit dw #$FFFF .after preset_kpdr21_upper_norfair_revisit_kronic_boost_lower: dw #preset_kpdr21_upper_norfair_revisit_spiky_acid_snakes_lower ; Upper Norfair Revisit: Spiky Acid Snakes (Lower) dl $7E078D : db $02 : dw $9792 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $AFFB ; MDB dl $7E090F : db $02 : dw $B000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0300 ; Screen X position in pixels dl $7E0913 : db $02 : dw $8C00 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $03BC ; Samus X dw #$FFFF .after preset_kpdr21_lower_norfair_ln_main_hall: dw #preset_kpdr21_upper_norfair_revisit_kronic_boost_upper ; Upper Norfair Revisit: Kronic Boost (Upper) dl $7E078D : db $02 : dw $96F6 ; DDB dl $7E079B : db $02 : dw $B236 ; MDB dl $7E07F3 : db $02 : dw $0018 ; Music Bank dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0400 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0200 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00BA ; Health dl $7E09CE : db $02 : dw $0004 ; Pbs dl $7E09D2 : db $02 : dw $0003 ; Currently selected item dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0480 ; Samus X dl $7E0AFA : db $02 : dw $0288 ; Samus Y dl $7ED8BA : db $02 : dw $01F1 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_prepillars: dw #preset_kpdr21_lower_norfair_ln_main_hall ; Lower Norfair: LN Main Hall dl $7E078F : db $02 : dw $0003 ; DoorOut Index dl $7E090F : db $02 : dw $9000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0700 ; Screen X position in pixels dl $7E0913 : db $02 : dw $E400 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $07A2 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dw #$FFFF .after preset_kpdr21_lower_norfair_worst_room_in_the_game: dw #preset_kpdr21_lower_norfair_prepillars ; Lower Norfair: Pre-Pillars dl $7E078D : db $02 : dw $9912 ; DDB dl $7E078F : db $02 : dw $0004 ; DoorOut Index dl $7E079B : db $02 : dw $B457 ; MDB dl $7E090F : db $02 : dw $64FF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0300 ; Screen X position in pixels dl $7E0913 : db $02 : dw $F800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0070 ; Health dl $7E09C6 : db $02 : dw $0013 ; Missiles dl $7E09CE : db $02 : dw $0005 ; Pbs dl $7E0AF6 : db $02 : dw $03DB ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_lower_norfair_amphitheatre: dw #preset_kpdr21_lower_norfair_worst_room_in_the_game ; Lower Norfair: Worst Room in the Game dl $7E078D : db $02 : dw $994E ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $B4AD ; MDB dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $A400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $011D ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0084 ; Health dl $7E09CE : db $02 : dw $0004 ; Pbs dl $7E09D2 : db $02 : dw $0000 ; Currently selected item dl $7E0AF6 : db $02 : dw $00A7 ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dw #$FFFF .after preset_kpdr21_lower_norfair_kihunter_stairs_down: dw #preset_kpdr21_lower_norfair_amphitheatre ; Lower Norfair: Amphitheatre dl $7E078D : db $02 : dw $997E ; DDB dl $7E079B : db $02 : dw $B4E5 ; MDB dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0282 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0043 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $02E2 ; Samus X dl $7E0AFA : db $02 : dw $00B3 ; Samus Y dw #$FFFF .after preset_kpdr21_lower_norfair_wasteland: dw #preset_kpdr21_lower_norfair_kihunter_stairs_down ; Lower Norfair: Kihunter Stairs Down dl $7E078D : db $02 : dw $99A2 ; DDB dl $7E079B : db $02 : dw $B585 ; MDB dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0915 : db $02 : dw $0419 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00AC ; Health dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E0A1C : db $02 : dw $001D ; Samus position/state dl $7E0A1E : db $02 : dw $0408 ; More position/state dl $7E0AF6 : db $02 : dw $0248 ; Samus X dl $7E0AFA : db $02 : dw $0489 ; Samus Y dl $7ED8BA : db $02 : dw $41F1 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_metal_ninja_pirates: dw #preset_kpdr21_lower_norfair_wasteland ; Lower Norfair: Wasteland dl $7E078D : db $02 : dw $99EA ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $B5D5 ; MDB dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0915 : db $02 : dw $021B ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0087 ; Health dl $7E09CA : db $02 : dw $0006 ; Supers dl $7E09CE : db $02 : dw $0001 ; Pbs dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0168 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dl $7ED8BA : db $02 : dw $C1F1 ; Events, Items, Doors dl $7ED91A : db $02 : dw $0042 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_plowerhouse: dw #preset_kpdr21_lower_norfair_metal_ninja_pirates ; Lower Norfair: Metal Ninja Pirates dl $7E078D : db $02 : dw $9A1A ; DDB dl $7E079B : db $02 : dw $B62B ; MDB dl $7E090F : db $02 : dw $7000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $CC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0122 ; Health dl $7E09C6 : db $02 : dw $0014 ; Missiles dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E0AF6 : db $02 : dw $006A ; Samus X dl $7E0AFA : db $02 : dw $00BB ; Samus Y dl $7ED8BC : db $02 : dw $0001 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_ridley: dw #preset_kpdr21_lower_norfair_plowerhouse ; Lower Norfair: Plowerhouse dl $7E078D : db $02 : dw $995A ; DDB dl $7E079B : db $02 : dw $B37A ; MDB dl $7E090F : db $02 : dw $2000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $5000 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $00E3 ; Health dl $7E09CA : db $02 : dw $0008 ; Supers dl $7E0AF6 : db $02 : dw $003D ; Samus X dl $7E0AFA : db $02 : dw $009B ; Samus Y dl $7ED8BA : db $02 : dw $D1F1 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_leaving_ridley: dw #preset_kpdr21_lower_norfair_ridley ; Lower Norfair: Ridley dl $7E078D : db $02 : dw $98CA ; DDB dl $7E079B : db $02 : dw $B32E ; MDB dl $7E07F3 : db $02 : dw $0024 ; Music Bank dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $3C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $011F ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00D9 ; Health dl $7E09CA : db $02 : dw $000A ; Supers dl $7E09CE : db $02 : dw $0003 ; Pbs dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $0057 ; Samus X dl $7E0AFA : db $02 : dw $019B ; Samus Y dl $7ED82A : db $02 : dw $0101 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_reverse_plowerhouse: dw #preset_kpdr21_lower_norfair_leaving_ridley ; Lower Norfair: Leaving Ridley dl $7E078D : db $02 : dw $98BE ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $B37A ; MDB dl $7E07F3 : db $02 : dw $0018 ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0200 ; Screen X position in pixels dl $7E0913 : db $02 : dw $AC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00D6 ; Health dl $7E0AF6 : db $02 : dw $02B8 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED8BA : db $02 : dw $D5F1 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_wasteland_revisit: dw #preset_kpdr21_lower_norfair_reverse_plowerhouse ; Lower Norfair: Reverse Plowerhouse dl $7E078D : db $02 : dw $9966 ; DDB dl $7E079B : db $02 : dw $B62B ; MDB dl $7E090F : db $02 : dw $9000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $7400 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $00B4 ; Health dl $7E0AF6 : db $02 : dw $02DC ; Samus X dw #$FFFF .after preset_kpdr21_lower_norfair_kihunter_stairs_up: dw #preset_kpdr21_lower_norfair_wasteland_revisit ; Lower Norfair: Wasteland Revisit dl $7E078D : db $02 : dw $9A3E ; DDB dl $7E079B : db $02 : dw $B5D5 ; MDB dl $7E090F : db $02 : dw $D5FF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0500 ; Screen X position in pixels dl $7E0913 : db $02 : dw $B000 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $00B2 ; Health dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E0AF6 : db $02 : dw $055B ; Samus X dl $7E0AFA : db $02 : dw $009B ; Samus Y dl $7ED91A : db $02 : dw $0043 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_fire_flea_room: dw #preset_kpdr21_lower_norfair_kihunter_stairs_up ; Lower Norfair: Kihunter Stairs Up dl $7E078D : db $02 : dw $9A26 ; DDB dl $7E079B : db $02 : dw $B585 ; MDB dl $7E090F : db $02 : dw $D000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $2800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $000D ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $00B7 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_lower_norfair_springball_maze: dw #preset_kpdr21_lower_norfair_fire_flea_room ; Lower Norfair: Fire Flea Room dl $7E078D : db $02 : dw $9A02 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $B6EE ; MDB dl $7E07C5 : db $02 : dw $BBBD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B6 ; GFX Pointers dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $016C ; Samus X dl $7ED91A : db $02 : dw $0044 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_three_musketeers: dw #preset_kpdr21_lower_norfair_springball_maze ; Lower Norfair: Springball Maze dl $7E078D : db $02 : dw $9A92 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $B510 ; MDB dl $7E07C5 : db $02 : dw $E4BD ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B5 ; GFX Pointers dl $7E090F : db $02 : dw $5A81 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $5000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0003 ; Screen Y position in pixels dl $7E0AF6 : db $02 : dw $0060 ; Samus X dl $7ED91A : db $02 : dw $0045 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_single_chamber_final: dw #preset_kpdr21_lower_norfair_three_musketeers ; Lower Norfair: Three Musketeers dl $7E078D : db $02 : dw $99AE ; DDB dl $7E079B : db $02 : dw $B656 ; MDB dl $7E090F : db $02 : dw $9000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $E000 ; Screen subpixel Y position dl $7E09C2 : db $02 : dw $0080 ; Health dl $7E0AF6 : db $02 : dw $016E ; Samus X dl $7ED91A : db $02 : dw $0046 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_lower_norfair_bubble_mountain_final: dw #preset_kpdr21_lower_norfair_single_chamber_final ; Lower Norfair: Single Chamber Final dl $7E078D : db $02 : dw $9A4A ; DDB dl $7E079B : db $02 : dw $AD5E ; MDB dl $7E07F3 : db $02 : dw $0015 ; Music Bank dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $A800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0016 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0074 ; Health dl $7E0AF6 : db $02 : dw $0075 ; Samus X dw #$FFFF .after preset_kpdr21_lower_norfair_business_center_final: dw #preset_kpdr21_lower_norfair_bubble_mountain_final ; Lower Norfair: Bubble Mountain Final dl $7E078D : db $02 : dw $97DA ; DDB dl $7E079B : db $02 : dw $B167 ; MDB dl $7E07C3 : db $02 : dw $860B ; GFX Pointers dl $7E07C5 : db $02 : dw $21C0 ; GFX Pointers dl $7E07C7 : db $02 : dw $C2C0 ; GFX Pointers dl $7E090F : db $02 : dw $6000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $5000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0088 ; Health dl $7E09C6 : db $02 : dw $0011 ; Missiles dl $7E09CE : db $02 : dw $0001 ; Pbs dl $7E0AF6 : db $02 : dw $0032 ; Samus X dl $7ED91A : db $02 : dw $0047 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_backtracking_maridia_tube_revisit: dw #preset_kpdr21_lower_norfair_business_center_final ; Lower Norfair: Business Center Final dl $7E078D : db $02 : dw $92EE ; DDB dl $7E078F : db $02 : dw $0004 ; DoorOut Index dl $7E079B : db $02 : dw $A6A1 ; MDB dl $7E079F : db $02 : dw $0001 ; Region dl $7E07C3 : db $02 : dw $A5AA ; GFX Pointers dl $7E07C5 : db $02 : dw $5FBC ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B3 ; GFX Pointers dl $7E07F3 : db $02 : dw $0012 ; Music Bank dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0080 ; Samus X dl $7E0AFA : db $02 : dw $0086 ; Samus Y dw #$FFFF .after preset_kpdr21_backtracking_fish_tank_revisit: dw #preset_kpdr21_backtracking_maridia_tube_revisit ; Backtracking: Maridia Tube Revisit dl $7E078D : db $02 : dw $A330 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $CFC9 ; MDB dl $7E079F : db $02 : dw $0004 ; Region dl $7E07C3 : db $02 : dw $B130 ; GFX Pointers dl $7E07C5 : db $02 : dw $3CBE ; GFX Pointers dl $7E07C7 : db $02 : dw $C2B8 ; GFX Pointers dl $7E07F3 : db $02 : dw $001B ; Music Bank dl $7E07F5 : db $02 : dw $0006 ; Music Track dl $7E0911 : db $02 : dw $00FA ; Screen X position in pixels dl $7E0913 : db $02 : dw $5000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $05F3 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $0168 ; Samus X dl $7E0AFA : db $02 : dw $068B ; Samus Y dl $7ED91A : db $02 : dw $0049 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_backtracking_mt_everest_revisit_revisit: dw #preset_kpdr21_backtracking_fish_tank_revisit ; Backtracking: Fish Tank Revisit dl $7E078D : db $02 : dw $A3B4 ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $D017 ; MDB dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0068 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $00C8 ; Samus X dl $7E0AFA : db $02 : dw $006B ; Samus Y dw #$FFFF .after preset_kpdr21_backtracking_red_brinstar_green_gate: dw #preset_kpdr21_backtracking_mt_everest_revisit_revisit ; Backtracking: Mt Everest Revisit Revisit dl $7E078D : db $02 : dw $A42C ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $D104 ; MDB dl $7E090F : db $02 : dw $3801 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $2000 ; Screen subpixel Y position dl $7E0AF6 : db $02 : dw $0079 ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dw #$FFFF .after preset_kpdr21_backtracking_crateria_kihunters_final: dw #preset_kpdr21_backtracking_red_brinstar_green_gate ; Backtracking: Red Brinstar Green Gate dl $7E078D : db $02 : dw $90BA ; DDB dl $7E078F : db $02 : dw $0002 ; DoorOut Index dl $7E079B : db $02 : dw $962A ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E07F3 : db $02 : dw $0012 ; Music Bank dl $7E07F5 : db $02 : dw $0003 ; Music Track dl $7E090F : db $02 : dw $A000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $2800 ; Screen subpixel Y position dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $0063 ; Samus X dl $7E0AFA : db $02 : dw $005B ; Samus Y dw #$FFFF .after preset_kpdr21_backtracking_parlor_spacejump: dw #preset_kpdr21_backtracking_crateria_kihunters_final ; Backtracking: Crateria Kihunters Final dl $7E078D : db $02 : dw $8AC6 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $91F8 ; MDB dl $7E07C3 : db $02 : dw $C629 ; GFX Pointers dl $7E07C5 : db $02 : dw $7CBA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AD ; GFX Pointers dl $7E07F3 : db $02 : dw $000C ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $05DC ; Screen X position in pixels dl $7E0913 : db $02 : dw $CC00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0400 ; Screen Y position in pixels dl $7E09C6 : db $02 : dw $0010 ; Missiles dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $067C ; Samus X dl $7E0AFA : db $02 : dw $04BB ; Samus Y dw #$FFFF .after preset_kpdr21_backtracking_terminator_revisit: dw #preset_kpdr21_backtracking_parlor_spacejump ; Backtracking: Parlor Spacejump dl $7E078D : db $02 : dw $8916 ; DDB dl $7E079B : db $02 : dw $92FD ; MDB dl $7E07F3 : db $02 : dw $0009 ; Music Bank dl $7E090F : db $02 : dw $4000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $B400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $001C ; Samus position/state dl $7E0A1E : db $02 : dw $0304 ; More position/state dl $7E0AF6 : db $02 : dw $0101 ; Samus X dl $7E0AFA : db $02 : dw $0086 ; Samus Y dl $7E0B3F : db $02 : dw $0104 ; Blue suit dw #$FFFF .after preset_kpdr21_backtracking_green_pirate_shaft_revisit: dw #preset_kpdr21_backtracking_terminator_revisit ; Backtracking: Terminator Revisit dl $7E078D : db $02 : dw $895E ; DDB dl $7E079B : db $02 : dw $990D ; MDB dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E090F : db $02 : dw $0000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0200 ; Screen Y position in pixels dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0073 ; Samus X dl $7E0AFA : db $02 : dw $029B ; Samus Y dl $7E0B3F : db $02 : dw $0000 ; Blue suit dl $7ED91A : db $02 : dw $004A ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_metroids_1: dw #preset_kpdr21_backtracking_green_pirate_shaft_revisit ; Backtracking: Green Pirate Shaft Revisit dl $7E078D : db $02 : dw $9222 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $DAAE ; MDB dl $7E079F : db $02 : dw $0005 ; Region dl $7E07C3 : db $02 : dw $D414 ; GFX Pointers dl $7E07C5 : db $02 : dw $EDBF ; GFX Pointers dl $7E07C7 : db $02 : dw $C2BA ; GFX Pointers dl $7E07F3 : db $02 : dw $001E ; Music Bank dl $7E090F : db $02 : dw $8000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0238 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00B0 ; Health dl $7E09C6 : db $02 : dw $0012 ; Missiles dl $7E09CA : db $02 : dw $0008 ; Supers dl $7E0A1C : db $02 : dw $009B ; Samus position/state dl $7E0A1E : db $02 : dw $0000 ; More position/state dl $7E0AF6 : db $02 : dw $0080 ; Samus X dl $7E0AFA : db $02 : dw $02A8 ; Samus Y dl $7ED820 : db $02 : dw $0FC1 ; Events, Items, Doors dl $7ED8B2 : db $02 : dw $6C01 ; Events, Items, Doors dl $7ED90C : db $02 : dw $0100 ; Events, Items, Doors dl $7ED91A : db $02 : dw $004C ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_metroids_2: dw #preset_kpdr21_tourian_metroids_1 ; Tourian: Metroids 1 dl $7E078D : db $02 : dw $A984 ; DDB dl $7E078F : db $02 : dw $0000 ; DoorOut Index dl $7E079B : db $02 : dw $DAE1 ; MDB dl $7E090F : db $02 : dw $7000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $5000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00EC ; Health dl $7E09C6 : db $02 : dw $0014 ; Missiles dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E09CE : db $02 : dw $0002 ; Pbs dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $003B ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED822 : db $02 : dw $0021 ; Events, Items, Doors dl $7ED8C4 : db $02 : dw $0001 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_metroids_3: dw #preset_kpdr21_tourian_metroids_2 ; Tourian: Metroids 2 dl $7E078D : db $02 : dw $A9B4 ; DDB dl $7E078F : db $02 : dw $0001 ; DoorOut Index dl $7E079B : db $02 : dw $DB31 ; MDB dl $7E090F : db $02 : dw $9000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $1000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0109 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0164 ; Health dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $00C2 ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED822 : db $02 : dw $0023 ; Events, Items, Doors dl $7ED8C4 : db $02 : dw $0003 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_metroids_4: dw #preset_kpdr21_tourian_metroids_3 ; Tourian: Metroids 3 dl $7E078D : db $02 : dw $A9CC ; DDB dl $7E079B : db $02 : dw $DB7D ; MDB dl $7E090F : db $02 : dw $C000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0500 ; Screen X position in pixels dl $7E0913 : db $02 : dw $0400 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $018F ; Health dl $7E0AF6 : db $02 : dw $059E ; Samus X dl $7E0AFA : db $02 : dw $008B ; Samus Y dl $7ED822 : db $02 : dw $0027 ; Events, Items, Doors dl $7ED8C4 : db $02 : dw $0007 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_giant_hoppers: dw #preset_kpdr21_tourian_metroids_4 ; Tourian: Metroids 4 dl $7E078D : db $02 : dw $A9E4 ; DDB dl $7E079B : db $02 : dw $DBCD ; MDB dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $4C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $011F ; Screen Y position in pixels dl $7E09CA : db $02 : dw $000A ; Supers dl $7E09CE : db $02 : dw $0005 ; Pbs dl $7E0AF6 : db $02 : dw $0058 ; Samus X dl $7E0AFA : db $02 : dw $01CB ; Samus Y dl $7ED822 : db $02 : dw $002F ; Events, Items, Doors dl $7ED8C4 : db $02 : dw $000F ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_baby_skip: dw #preset_kpdr21_tourian_giant_hoppers ; Tourian: Giant Hoppers dl $7E078D : db $02 : dw $AA14 ; DDB dl $7E079B : db $02 : dw $DC65 ; MDB dl $7E07F3 : db $02 : dw $0045 ; Music Bank dl $7E07F5 : db $02 : dw $0006 ; Music Track dl $7E090F : db $02 : dw $3000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $1800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0171 ; Health dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $01D8 ; Samus X dl $7E0AFA : db $02 : dw $00AB ; Samus Y dw #$FFFF .after preset_kpdr21_tourian_gadora_room: dw #preset_kpdr21_tourian_baby_skip ; Tourian: Baby Skip dl $7E078D : db $02 : dw $AA44 ; DDB dl $7E079B : db $02 : dw $DCFF ; MDB dl $7E07F3 : db $02 : dw $001E ; Music Bank dl $7E07F5 : db $02 : dw $0005 ; Music Track dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0000 ; Screen X position in pixels dl $7E0913 : db $02 : dw $B800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0117 ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0009 ; Supers dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0AF6 : db $02 : dw $00DC ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED8C4 : db $02 : dw $00AF ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_zeb_skip: dw #preset_kpdr21_tourian_gadora_room ; Tourian: Gadora Room dl $7E078D : db $02 : dw $AAA4 ; DDB dl $7E079B : db $02 : dw $DDF3 ; MDB dl $7E090F : db $02 : dw $E000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $0000 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $021A ; Screen Y position in pixels dl $7E09CA : db $02 : dw $0007 ; Supers dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $0038 ; Samus X dl $7E0AFA : db $02 : dw $028B ; Samus Y dl $7ED8C4 : db $02 : dw $03AF ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_escape_room_3: dw #preset_kpdr21_tourian_zeb_skip ; Tourian: Zeb Skip dl $7E078D : db $02 : dw $AAEC ; DDB dl $7E079B : db $02 : dw $DE7A ; MDB dl $7E07F3 : db $02 : dw $0024 ; Music Bank dl $7E07F5 : db $02 : dw $0007 ; Music Track dl $7E090F : db $02 : dw $1000 ; Screen subpixel X position. dl $7E0913 : db $02 : dw $2800 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0100 ; Screen Y position in pixels dl $7E09A6 : db $02 : dw $1009 ; Beams dl $7E09C2 : db $02 : dw $018F ; Health dl $7E09C6 : db $02 : dw $0000 ; Missiles dl $7E09CA : db $02 : dw $0000 ; Supers dl $7E09CE : db $02 : dw $0000 ; Pbs dl $7E0A1C : db $02 : dw $0001 ; Samus position/state dl $7E0A1E : db $02 : dw $0008 ; More position/state dl $7E0A76 : db $02 : dw $8000 ; Hyper beam dl $7E0AF6 : db $02 : dw $00DF ; Samus X dl $7E0AFA : db $02 : dw $018B ; Samus Y dl $7ED820 : db $02 : dw $4FC5 ; Events, Items, Doors dl $7ED82C : db $02 : dw $0203 ; Events, Items, Doors dw #$FFFF .after preset_kpdr21_tourian_climb_spark: dw #preset_kpdr21_tourian_escape_room_3 ; Tourian: Escape Room 3 dl $7E078D : db $02 : dw $AB1C ; DDB dl $7E079B : db $02 : dw $DEDE ; MDB dl $7E0911 : db $02 : dw $00F6 ; Screen X position in pixels dl $7E0913 : db $02 : dw $1C00 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $00EF ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $0171 ; Health dl $7E0AF6 : db $02 : dw $0156 ; Samus X dw #$FFFF .after preset_kpdr21_tourian_escape_parlor: dw #preset_kpdr21_tourian_climb_spark ; Tourian: Climb Spark dl $7E078D : db $02 : dw $AB34 ; DDB dl $7E079B : db $02 : dw $96BA ; MDB dl $7E079F : db $02 : dw $0000 ; Region dl $7E07C3 : db $02 : dw $F911 ; GFX Pointers dl $7E07C5 : db $02 : dw $43BA ; GFX Pointers dl $7E07C7 : db $02 : dw $C2AF ; GFX Pointers dl $7E090F : db $02 : dw $BFFF ; Screen subpixel X position. dl $7E0911 : db $02 : dw $0100 ; Screen X position in pixels dl $7E0913 : db $02 : dw $6801 ; Screen subpixel Y position dl $7E0915 : db $02 : dw $0000 ; Screen Y position in pixels dl $7E09C2 : db $02 : dw $00DE ; Health dl $7E0A1C : db $02 : dw $0002 ; Samus position/state dl $7E0A1E : db $02 : dw $0004 ; More position/state dl $7E0AF6 : db $02 : dw $01DA ; Samus X dl $7E0AFA : db $02 : dw $004B ; Samus Y dl $7ED90C : db $02 : dw $FF00 ; Events, Items, Doors dw #$FFFF .after
; A109398: a(n) = (1/n!)*Sum_{k=0..n} (n+k)!. ; 1,3,16,145,1926,33649,726328,18636561,553680370,18684924841,705833193924,29502690532393,1351724235304366,67359683340291105,3627011494019437936,209846445862386234529,12982402818188717219658 mov $2,$0 mov $3,15 lpb $0 sub $0,1 add $2,1 mul $3,$2 add $1,$3 lpe div $1,15 add $1,1 mov $0,$1
; ; Copyright (c) 2010 The WebM project authors. All Rights Reserved. ; ; Use of this source code is governed by a BSD-style license ; that can be found in the LICENSE file in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; %include "vpx_ports/x86_abi_support.asm" %macro PROCESS_16X2X8 1 %if %1 movdqa xmm0, XMMWORD PTR [rsi] movq xmm1, MMWORD PTR [rdi] movq xmm3, MMWORD PTR [rdi+8] movq xmm2, MMWORD PTR [rdi+16] punpcklqdq xmm1, xmm3 punpcklqdq xmm3, xmm2 movdqa xmm2, xmm1 mpsadbw xmm1, xmm0, 0x0 mpsadbw xmm2, xmm0, 0x5 psrldq xmm0, 8 movdqa xmm4, xmm3 mpsadbw xmm3, xmm0, 0x0 mpsadbw xmm4, xmm0, 0x5 paddw xmm1, xmm2 paddw xmm1, xmm3 paddw xmm1, xmm4 %else movdqa xmm0, XMMWORD PTR [rsi] movq xmm5, MMWORD PTR [rdi] movq xmm3, MMWORD PTR [rdi+8] movq xmm2, MMWORD PTR [rdi+16] punpcklqdq xmm5, xmm3 punpcklqdq xmm3, xmm2 movdqa xmm2, xmm5 mpsadbw xmm5, xmm0, 0x0 mpsadbw xmm2, xmm0, 0x5 psrldq xmm0, 8 movdqa xmm4, xmm3 mpsadbw xmm3, xmm0, 0x0 mpsadbw xmm4, xmm0, 0x5 paddw xmm5, xmm2 paddw xmm5, xmm3 paddw xmm5, xmm4 paddw xmm1, xmm5 %endif movdqa xmm0, XMMWORD PTR [rsi + rax] movq xmm5, MMWORD PTR [rdi+ rdx] movq xmm3, MMWORD PTR [rdi+ rdx+8] movq xmm2, MMWORD PTR [rdi+ rdx+16] punpcklqdq xmm5, xmm3 punpcklqdq xmm3, xmm2 lea rsi, [rsi+rax*2] lea rdi, [rdi+rdx*2] movdqa xmm2, xmm5 mpsadbw xmm5, xmm0, 0x0 mpsadbw xmm2, xmm0, 0x5 psrldq xmm0, 8 movdqa xmm4, xmm3 mpsadbw xmm3, xmm0, 0x0 mpsadbw xmm4, xmm0, 0x5 paddw xmm5, xmm2 paddw xmm5, xmm3 paddw xmm5, xmm4 paddw xmm1, xmm5 %endmacro %macro PROCESS_8X2X8 1 %if %1 movq xmm0, MMWORD PTR [rsi] movq xmm1, MMWORD PTR [rdi] movq xmm3, MMWORD PTR [rdi+8] punpcklqdq xmm1, xmm3 movdqa xmm2, xmm1 mpsadbw xmm1, xmm0, 0x0 mpsadbw xmm2, xmm0, 0x5 paddw xmm1, xmm2 %else movq xmm0, MMWORD PTR [rsi] movq xmm5, MMWORD PTR [rdi] movq xmm3, MMWORD PTR [rdi+8] punpcklqdq xmm5, xmm3 movdqa xmm2, xmm5 mpsadbw xmm5, xmm0, 0x0 mpsadbw xmm2, xmm0, 0x5 paddw xmm5, xmm2 paddw xmm1, xmm5 %endif movq xmm0, MMWORD PTR [rsi + rax] movq xmm5, MMWORD PTR [rdi+ rdx] movq xmm3, MMWORD PTR [rdi+ rdx+8] punpcklqdq xmm5, xmm3 lea rsi, [rsi+rax*2] lea rdi, [rdi+rdx*2] movdqa xmm2, xmm5 mpsadbw xmm5, xmm0, 0x0 mpsadbw xmm2, xmm0, 0x5 paddw xmm5, xmm2 paddw xmm1, xmm5 %endmacro %macro PROCESS_4X2X8 1 %if %1 movd xmm0, [rsi] movq xmm1, MMWORD PTR [rdi] movq xmm3, MMWORD PTR [rdi+8] punpcklqdq xmm1, xmm3 mpsadbw xmm1, xmm0, 0x0 %else movd xmm0, [rsi] movq xmm5, MMWORD PTR [rdi] movq xmm3, MMWORD PTR [rdi+8] punpcklqdq xmm5, xmm3 mpsadbw xmm5, xmm0, 0x0 paddw xmm1, xmm5 %endif movd xmm0, [rsi + rax] movq xmm5, MMWORD PTR [rdi+ rdx] movq xmm3, MMWORD PTR [rdi+ rdx+8] punpcklqdq xmm5, xmm3 lea rsi, [rsi+rax*2] lea rdi, [rdi+rdx*2] mpsadbw xmm5, xmm0, 0x0 paddw xmm1, xmm5 %endmacro ;void vp8_sad16x16x8_sse4( ; const unsigned char *src_ptr, ; int src_stride, ; const unsigned char *ref_ptr, ; int ref_stride, ; unsigned short *sad_array); global sym(vp8_sad16x16x8_sse4) sym(vp8_sad16x16x8_sse4): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 5 push rsi push rdi ; end prolog mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;ref_ptr movsxd rax, dword ptr arg(1) ;src_stride movsxd rdx, dword ptr arg(3) ;ref_stride PROCESS_16X2X8 1 PROCESS_16X2X8 0 PROCESS_16X2X8 0 PROCESS_16X2X8 0 PROCESS_16X2X8 0 PROCESS_16X2X8 0 PROCESS_16X2X8 0 PROCESS_16X2X8 0 mov rdi, arg(4) ;Results movdqa XMMWORD PTR [rdi], xmm1 ; begin epilog pop rdi pop rsi UNSHADOW_ARGS pop rbp ret ;void vp8_sad16x8x8_sse4( ; const unsigned char *src_ptr, ; int src_stride, ; const unsigned char *ref_ptr, ; int ref_stride, ; unsigned short *sad_array ;); global sym(vp8_sad16x8x8_sse4) sym(vp8_sad16x8x8_sse4): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 5 push rsi push rdi ; end prolog mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;ref_ptr movsxd rax, dword ptr arg(1) ;src_stride movsxd rdx, dword ptr arg(3) ;ref_stride PROCESS_16X2X8 1 PROCESS_16X2X8 0 PROCESS_16X2X8 0 PROCESS_16X2X8 0 mov rdi, arg(4) ;Results movdqa XMMWORD PTR [rdi], xmm1 ; begin epilog pop rdi pop rsi UNSHADOW_ARGS pop rbp ret ;void vp8_sad8x8x8_sse4( ; const unsigned char *src_ptr, ; int src_stride, ; const unsigned char *ref_ptr, ; int ref_stride, ; unsigned short *sad_array ;); global sym(vp8_sad8x8x8_sse4) sym(vp8_sad8x8x8_sse4): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 5 push rsi push rdi ; end prolog mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;ref_ptr movsxd rax, dword ptr arg(1) ;src_stride movsxd rdx, dword ptr arg(3) ;ref_stride PROCESS_8X2X8 1 PROCESS_8X2X8 0 PROCESS_8X2X8 0 PROCESS_8X2X8 0 mov rdi, arg(4) ;Results movdqa XMMWORD PTR [rdi], xmm1 ; begin epilog pop rdi pop rsi UNSHADOW_ARGS pop rbp ret ;void vp8_sad8x16x8_sse4( ; const unsigned char *src_ptr, ; int src_stride, ; const unsigned char *ref_ptr, ; int ref_stride, ; unsigned short *sad_array ;); global sym(vp8_sad8x16x8_sse4) sym(vp8_sad8x16x8_sse4): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 5 push rsi push rdi ; end prolog mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;ref_ptr movsxd rax, dword ptr arg(1) ;src_stride movsxd rdx, dword ptr arg(3) ;ref_stride PROCESS_8X2X8 1 PROCESS_8X2X8 0 PROCESS_8X2X8 0 PROCESS_8X2X8 0 PROCESS_8X2X8 0 PROCESS_8X2X8 0 PROCESS_8X2X8 0 PROCESS_8X2X8 0 mov rdi, arg(4) ;Results movdqa XMMWORD PTR [rdi], xmm1 ; begin epilog pop rdi pop rsi UNSHADOW_ARGS pop rbp ret ;void vp8_sad4x4x8_c( ; const unsigned char *src_ptr, ; int src_stride, ; const unsigned char *ref_ptr, ; int ref_stride, ; unsigned short *sad_array ;); global sym(vp8_sad4x4x8_sse4) sym(vp8_sad4x4x8_sse4): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 5 push rsi push rdi ; end prolog mov rsi, arg(0) ;src_ptr mov rdi, arg(2) ;ref_ptr movsxd rax, dword ptr arg(1) ;src_stride movsxd rdx, dword ptr arg(3) ;ref_stride PROCESS_4X2X8 1 PROCESS_4X2X8 0 mov rdi, arg(4) ;Results movdqa XMMWORD PTR [rdi], xmm1 ; begin epilog pop rdi pop rsi UNSHADOW_ARGS pop rbp ret
; Usage: uncircle(int x, int y, int radius, int skip); IF !__CPU_INTEL__ && !__CPU_GBZ80__ SECTION code_graphics PUBLIC uncircle PUBLIC _uncircle EXTERN asm_uncircle .uncircle ._uncircle push ix ld ix,2 add ix,sp ; de = x0, hl = y0, bc = radius, a = scale factor ld a,(ix+2) ;skip ld c,(ix+4) ;radius ld b,(ix+5) ld l,(ix+6) ;y ld h,(ix+7) ld e,(ix+8) ;x ld d,(ix+9) pop ix jp asm_uncircle ENDIF
ADDI R1 R1 8 ADDI R2 R2 5 ADD R1 R1 R2 ADD R2 R1 R2 ADD R1 R1 R2 ADD R2 R1 R2 SW R1 R2 0 LW R3 R2 0
.global s_prepare_buffers s_prepare_buffers: push %r15 push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x96ea, %rsi lea addresses_UC_ht+0x106aa, %rdi nop and %rbx, %rbx mov $31, %rcx rep movsw nop nop nop nop nop xor $35620, %r15 pop %rsi pop %rdi pop %rcx pop %rbx pop %r15 ret .global s_faulty_load s_faulty_load: push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi // Store lea addresses_WT+0x176f6, %rsi nop nop nop nop and $10459, %rdi movw $0x5152, (%rsi) nop sub %rax, %rax // Store lea addresses_normal+0x86aa, %r8 nop nop add %rcx, %rcx mov $0x5152535455565758, %rbp movq %rbp, %xmm7 vmovups %ymm7, (%r8) nop nop nop nop nop inc %rbp // Faulty Load lea addresses_normal+0x86aa, %rdi nop cmp %r15, %r15 movups (%rdi), %xmm2 vpextrq $0, %xmm2, %rax lea oracles, %r15 and $0xff, %rax shlq $12, %rax mov (%r15,%rax,1), %rax pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}} {'58': 172} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
; A293604: E.g.f.: exp(x * (1 - x)). ; 1,1,-1,-5,1,41,31,-461,-895,6481,22591,-107029,-604031,1964665,17669471,-37341149,-567425279,627491489,19919950975,-2669742629,-759627879679,-652838174519,31251532771999,59976412450835,-1377594095061119,-4256461892701199,64623242860354751,285959261280817099,-3203695853178339455,-19217414484904096999,166596944999439591391,1319641814093685411331,-9009368775871569254911,-93466444877867435580095,501151894329656135244031,6856870146024641754690491,-28223762457051287712391679,-521918412970825494050107031,1566640008850969796666877215,41232439394633707344475011571,-80965481295741936795541411199,-3379560632866438524353542336879,3259608833384400292880853381439,287142701994165236338578409679275,6816342323106811150825018875521,-25261741433163433986644075032900679,-25875212242243046990218326731697569 mul $0,2 mov $1,1 lpb $0 sub $0,2 sub $1,$2 add $2,$1 mul $2,$0 lpe mov $0,$1
cpu "8085.tbl" ; CPU Table monitor command hof "int8" ; HEX Format org 9000h ; Puts location pointer at prompt at 9000 ;Pneumonics GTHEX: EQU 030EH ; This routinue collects the hex digits entered from keyboard RDKBD: EQU 03BAH ; Reads keyboard. HXDSP: EQU 034FEH ; This routinue expands hex digits for display and stores in the specified buffer OUTPUT: EQU 0389H ; Outputs characters to display CLEAR: EQU 02BEH ; Clears the display UPDDT: EQU 044CH ; Update data field display using the current data at location FFF9H UPDAD: EQU 0440H ; Update the address field display using the current address stored at location FFF7H and FFF8H CURAD: EQU 8FEFH ; Displays the number stored in the address field of UPDAD CURDT: EQU 8FF1H ; Stores 8bit data and shows in the Data display. BEGIN: LXI H,0000H ; Begin funtion : loads 0000H into HL register MIN: ; Min Function ( Minutes function / Shows both Minutes and Hours hand ) SHLD CURAD ; Store data in HL at address of CURAD and display it.( minimum clock time is 00hr 00 min) MVI A,00H ; move 00H to register A ( Initializing A to be 00 ) SEC: ; SEC Function ( Seconds Function ) STA CURDT ; Show content of accumulator on Data Display ( Data Display represents Seconds Hand) CALL UPDAD ; Keep updating Address field all these time CALL UPDDT ; Show the data display CALL DELAY ; Call function DELAY LDA CURDT ; Load the value in address data display to accumulator ADI 01H ; Increment the value of data display by 1( next second increment ) DAA ; Binary decimal adder by 2's complement method CPI 60H ; Compare the value in accumulator with 60H JNZ SEC ; If the value in accumulator is not 60 then jump to SEC function ;If the value of seconds hand is 60 it must be put to 0 and update Minutes hand. LHLD CURAD ; Load the value in Address Display to HL register MOV A,L ; Move the value in register L to Accumulator ADI 01H ; Add 01H in accumulator DAA ; Binary Addition MOV L,A ; Move the value in Register L to accumulator CPI 60H ; Compare the value in accumulator to 60H JNZ MIN ; If the value in accumulator is not 60 them jump to MIN function ;If the value of seconds hand is 60 it must be put to 0 and update Hours hand. MVI L,00H ; Move value 00H into L register MOV A,H ; Move value of H into Accumulator ADI 01H ; Add 01H in accumulator DAA ; Binary Addition MOV H,A ; Move the value in accumulator to Regsiter H CPI 24H ; Compare the value in accumulator to 24 ( max hour hand is 24 ) JNZ MIN ; If the value in accumulator is not 24 jump to MIN function JMP BEGIN ; Unconditional jump to BEGIN function ; If hours hand exceeds 23 we need to change it to 0 DELAY: ; Delay function MVI C,03H ; Move the value 03H to register C OUTLOOP: ; OUTLOOP function LXI D,9FFFH ; Loads the value 9FFFH into DE register INLOOP: ; INLOOP function DCX D ; decrement the content of memory location DE by 1 MOV A,D ; Move value in register D to Accumulator ORA E ; OR with value in Register E JNZ INLOOP ; If the flag isn't 1 then go to INLOOP DCR C ; Contents of memory of C is decremented by 1 JNZ OUTLOOP ; As long as the memory of C is not 00H jump to OUTLOOP RET ; Return ; Delay of 1 second is brought by function DELAY by calling the required number of times. the frequency is 6.144MHz.
MCZ_2p_Header: smpsHeaderStartSong 2, 1 smpsHeaderVoice MCZ_2p_Voices smpsHeaderChan $06, $03 smpsHeaderTempo $01, $EC smpsHeaderDAC MCZ_2p_DAC smpsHeaderFM MCZ_2p_FM1, $00, $10 smpsHeaderFM MCZ_2p_FM2, $18, $0D smpsHeaderFM MCZ_2p_FM3, $00, $12 smpsHeaderFM MCZ_2p_FM4, $00, $18 smpsHeaderFM MCZ_2p_FM5, $00, $18 smpsHeaderPSG MCZ_2p_PSG1, $DC, $05, $00, fTone_0C smpsHeaderPSG MCZ_2p_PSG2, $E8, $04, $00, fTone_04 smpsHeaderPSG MCZ_2p_PSG3, $DC, $04, $00, fTone_0C MCZ_2p_Call01: dc.b nG4, $08, nA4, nB4 smpsReturn MCZ_2p_Call02: dc.b nF4, $30, smpsNoAttack, $30, smpsNoAttack, nF4, nRst, $18, nG4, $08, nA4, nB4 dc.b nF4, $30, smpsNoAttack, $30, smpsNoAttack, $30, smpsNoAttack, $24 smpsReturn MCZ_2p_Call00: dc.b nRst, $30, nRst, nB4, $06, nC5, nB4, nG4, nA4, nF4, $0C, nG4 dc.b nD4, nD4, $06, nF4, $0C, nG4 smpsReturn MCZ_2p_Call03: dc.b nB4, $30, smpsNoAttack, $30, nC5, $30, smpsNoAttack, $24, nB4, $06, nC5, nD5 dc.b $30, smpsNoAttack, $30, nB4, $30, smpsNoAttack, $30, nB4, $30, smpsNoAttack, $30, nC5 dc.b $30, smpsNoAttack, $24, nB4, $06, nC5, nD5, $30, smpsNoAttack, $30, nF5, $30 dc.b smpsNoAttack, $30, nG5, $24, nF5, nE5, $18, nF5, $24, nE5, nC5, $18 smpsReturn ; FM2 Data MCZ_2p_FM2: dc.b nRst, $18 smpsSetvoice $00 MCZ_2p_Jump05: dc.b nG1, $0C, nD1, nF1, nD1, $06, nG1, $05, nG1, $07, $06, nD1 dc.b $0C, nF1, nD1 smpsJump MCZ_2p_Jump05 ; FM1 Data MCZ_2p_FM1: smpsSetvoice $02 smpsAlterVol $12 smpsCall MCZ_2p_Call01 MCZ_2p_Jump04: smpsCall MCZ_2p_Call02 smpsModSet $24, $01, $03, $04 dc.b nRst, $0C smpsAlterVol $E6 smpsSetvoice $03 smpsCall MCZ_2p_Call03 dc.b $24, nB4, nD5, $18, smpsNoAttack, $30, smpsNoAttack, $30, nB5, $24, nA5, nG5 dc.b $18, nA5, $24, nG5, nE5, $18, nE5, nF5, $0C, nD5, $30, smpsNoAttack dc.b $0C, smpsNoAttack, $30, smpsNoAttack, $24, nRst, $0C, nRst, $30, nRst, nRst, nRst dc.b nC5, $24, nE5, nG5, $18, nF5, $24, nD5, nB4, $18, nB4, nC5 dc.b $0C, nB4, $30, smpsNoAttack, $0C, smpsNoAttack, $30, smpsNoAttack, $18, nRst, $18, nC5 dc.b $24, nE5, nG5, $18, nF5, $24, nD5, nB4, $18, nB5, $30, smpsNoAttack dc.b $30, smpsNoAttack, $30, smpsNoAttack, $0C, nRst, $0C smpsModOff smpsAlterVol $1A smpsSetvoice $02 dc.b nE4, $08, nF4, nG4 smpsJump MCZ_2p_Jump04 ; PSG1 Data MCZ_2p_PSG1: smpsAlterNote $02 dc.b nRst, $1B MCZ_2p_Jump08: dc.b nRst, $30, nRst, nRst, nRst, nRst, nRst, nRst, nRst smpsCall MCZ_2p_Call03 dc.b $24, nB4, nD5, $18, smpsNoAttack, $30, smpsNoAttack, $30, nB5, $24, nA5, nG5 dc.b $18, nA5, $24, nG5, nE5, $18, nE5, nF5, $0C, nD5, $30, smpsNoAttack dc.b $0C, smpsNoAttack, $30, smpsNoAttack, $24, nRst, $0C, nRst, $30, nRst, nRst, nRst dc.b nC5, $24, nE5, nG5, $18, nF5, $24, nD5, nB4, $18, nB4, nC5 dc.b $0C, nB4, $30, smpsNoAttack, $0C, smpsNoAttack, $30, smpsNoAttack, $18, nRst, $18, nC5 dc.b $24, nE5, nG5, $18, nF5, $24, nD5, nB4, $18, nB5, $30, smpsNoAttack dc.b $30, smpsNoAttack, $30, smpsNoAttack, $0C, nRst, $24 smpsJump MCZ_2p_Jump08 ; PSG3 Data MCZ_2p_PSG3: dc.b nRst, $18 MCZ_2p_Jump07: dc.b nRst, $30, nRst, nRst, nRst, nRst, nRst, nRst, nRst smpsCall MCZ_2p_Call03 dc.b $24, nB4, nD5, $18, smpsNoAttack, $30, smpsNoAttack, $30 smpsAlterVol $FE dc.b nG5, $24, nF5, nE5, $18, nF5, $24, nE5, nC5, $18, nC5, nD5 dc.b $0C, nB4, $30, smpsNoAttack, $0C, smpsNoAttack, $30, smpsNoAttack, $24, nRst, $0C, nRst dc.b $30, nRst, nRst, nRst, nA4, $24, nC5, nE5, $18, nD5, $24, nB4 dc.b nG4, $18, nF4, nD4, $0C, nG4, $30, smpsNoAttack, $0C, smpsNoAttack, $30, smpsNoAttack dc.b $18, nRst, $18, nA4, $24, nC5, nE5, $18, nD5, $24, nB4, nG4 dc.b $18, nG5, $30, smpsNoAttack, $30, smpsNoAttack, $30, smpsNoAttack, $0C, nRst, $24 smpsAlterVol $02 smpsJump MCZ_2p_Jump07 ; FM4 Data MCZ_2p_FM4: smpsSetvoice $02 smpsAlterNote $02 smpsPan panLeft, $00 smpsCall MCZ_2p_Call01 MCZ_2p_Jump03: smpsCall MCZ_2p_Call02 smpsAlterNote $00 smpsSetvoice $01 smpsAlterVol $F2 smpsAlterPitch $F4 dc.b nA3, $0C, nB3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, $24 dc.b nC4, $0C, nB3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, $24 dc.b nA3, $0C, nB3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, $24 dc.b nC4, $0C, nB3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, nRst dc.b nRst, nG4, $24, nF4, nE4, $18, nF4, $24, nE4, nC4, $18, $24 dc.b nB3, nD4, $18, smpsNoAttack, $30, smpsNoAttack, $30, nB4, $24, nA4, nG4, $18 dc.b nA4, $24, nG4, nE4, $18, nE4, nF4, $0C, nD4, $24 smpsAlterVol $0E smpsAlterPitch $0C smpsSetvoice $02 smpsCall MCZ_2p_Call01 dc.b nF4, $30, smpsNoAttack, $30, smpsNoAttack, $30, smpsNoAttack, $18, nRst, $18 smpsAlterVol $F2 smpsAlterPitch $F4 smpsSetvoice $01 dc.b nRst, $30, nRst, nRst, nRst, $24, nG4, $06, nF4, nG4, $0C, nG4 dc.b nF4, $06, nG4, $0C, $06, nRst, $24, $06, nF4, nG4, $0C dc.b nG4, nF4, $06, nG4, $0C, $06, nRst, $30, nRst, $30, nRst, nRst dc.b nRst, $24, $06, nF4, nG4, $0C, nG4, nF4, $06, nG4, $0C dc.b $06, nRst, $24, $06, nF4, nG4, $0C, nG4, nF4, $06, nG4 dc.b $0C, $06, nRst, $18 smpsAlterVol $0E smpsAlterPitch $0C smpsSetvoice $02 smpsCall MCZ_2p_Call01 smpsJump MCZ_2p_Jump03 ; FM5 Data MCZ_2p_FM5: dc.b nRst, $01 smpsSetvoice $02 smpsAlterNote $FE smpsPan panRight, $00 smpsCall MCZ_2p_Call01 MCZ_2p_Jump02: smpsCall MCZ_2p_Call02 smpsAlterNote $FA smpsAlterVol $F2 smpsAlterPitch $F4 smpsSetvoice $01 dc.b nF3, $0B, nG3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, $24 dc.b nA3, $0C, nG3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, $24 dc.b nF3, $0C, nG3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, $24 dc.b nA3, $0C, nG3, $06, nRst, $30, nRst, $2A, nRst, $30, nRst, nRst dc.b nRst, nG4, $24, nF4, nE4, $18, nF4, $24, nE4, nC4, $18, $24 dc.b nB3, nD4, $18, smpsNoAttack, $30, smpsNoAttack, $30, nG4, $24, nF4, nE4, $18 dc.b nF4, $24, nE4, nC4, $18, nC4, nD4, $0C, nB3, $24 smpsAlterVol $0E smpsAlterPitch $0C smpsSetvoice $02 smpsCall MCZ_2p_Call01 dc.b nF4, $30, smpsNoAttack, $30, smpsNoAttack, $30, smpsNoAttack, $18, nRst, $18 smpsAlterVol $F2 smpsAlterPitch $F4 smpsSetvoice $01 dc.b nRst, $30, nRst, $30, nRst, $30, nRst, $24, nD4, $06, nC4, nD4 dc.b $0C, nD4, nC4, $06, nD4, $0C, $06, nRst, $24, $06, nC4 dc.b nD4, $0C, nD4, nC4, $06, nD4, $0C, $06, nRst, $30, nRst, $30 dc.b nRst, nRst, nRst, $24, $06, nC4, nD4, $0C, nD4, nC4, $06 dc.b nD4, $0C, $06, nRst, $24, $06, nC4, nD4, $0C, nD4, nD4 dc.b $06, nC4, $0C, $06, nRst, $19 smpsAlterVol $0E smpsAlterPitch $0C smpsSetvoice $02 smpsCall MCZ_2p_Call01 smpsJump MCZ_2p_Jump02 ; FM3 Data MCZ_2p_FM3: smpsSetvoice $04 dc.b nRst, $18 MCZ_2p_Jump01: smpsAlterVol $FC smpsCall MCZ_2p_Call00 smpsCall MCZ_2p_Call00 smpsAlterVol $04 MCZ_2p_Loop00: dc.b nB4, $0C, nB4, nB4, $06, nRst, $12, nA4, $0C, nA4, nB4, $06 dc.b nRst, $12, $0C, $06, nB4, $0C, nB4, nB4, $06, nA4 dc.b $0C, nC5, nB4, $06, nRst, $12 smpsLoop $00, $09, MCZ_2p_Loop00 MCZ_2p_Loop01: dc.b nA4, $0C, nA4, nA4, $06, nRst, $12, nG4, $0C, nG4, nA4, $06 dc.b nRst, $12, nG4, $0C, $06, nG4, $0C, nG4, nG4, $06, nG4, $0C dc.b nE4, nG4, $06, nRst, $12, nB4, $0C, nB4, nB4, $06, nRst, $12 dc.b nA4, $0C, nA4, nB4, $06, nRst, $12, $0C, $06, nB4 dc.b $0C, nB4, nB4, $06, nA4, $0C, nC5, nB4, $06, nRst, $12 smpsLoop $00, $02, MCZ_2p_Loop01 smpsJump MCZ_2p_Jump01 ; PSG2 Data MCZ_2p_PSG2: smpsNoteFill $08 dc.b nRst, $18 MCZ_2p_Jump06: smpsCall MCZ_2p_Call00 smpsCall MCZ_2p_Call00 MCZ_2p_Loop02: dc.b nG4, $0C, nG4, nG4, $06, nRst, $12, nF4, $0C, nF4, nG4, $06 dc.b nRst, $12, $0C, $06, nG4, $0C, nG4, nG4, $06, nF4 dc.b $0C, nA4, nG4, $06, nRst, $12 smpsLoop $00, $09, MCZ_2p_Loop02 MCZ_2p_Loop03: dc.b nF4, $0C, nF4, nF4, $06, nRst, $12, nE4, $0C, nE4, nF4, $06 dc.b nRst, $12, nE4, $0C, $06, nE4, $0C, nE4, nE4, $06, nE4, $0C dc.b nC4, nE4, $06, nRst, $12, nG4, $0C, nG4, nG4, $06, nRst, $12 dc.b nF4, $0C, nF4, nG4, $06, nRst, $12, $0C, $06, nG4 dc.b $0C, nG4, nG4, $06, nF4, $0C, nA4, nG4, $06, nRst, $12 smpsLoop $00, $02, MCZ_2p_Loop03 smpsJump MCZ_2p_Jump06 ; DAC Data MCZ_2p_DAC: dc.b nRst, $18 MCZ_2p_Jump00: dc.b dKick, $0C, dHiClap, $06, dMidClap, dSnare, $0C, dMidClap, $06, dLowClap, dKick, $0C dc.b dHiClap, $06, dLowClap, dSnare, $0C, dHiClap, $06, dLowClap smpsJump MCZ_2p_Jump00 MCZ_2p_Voices: ; Voice $00 ; $3A ; $69, $70, $50, $60, $1C, $18, $1A, $18, $10, $0C, $02, $09 ; $08, $06, $06, $03, $F9, $56, $06, $06, $28, $15, $14, $00 smpsVcAlgorithm $02 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $06, $05, $07, $06 smpsVcCoarseFreq $00, $00, $00, $09 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $18, $1A, $18, $1C smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $09, $02, $0C, $10 smpsVcDecayRate2 $03, $06, $06, $08 smpsVcDecayLevel $00, $00, $05, $0F smpsVcReleaseRate $06, $06, $06, $09 smpsVcTotalLevel $00, $14, $15, $28 ; Voice $01 ; $3A ; $02, $04, $02, $02, $8E, $8E, $8D, $53, $0E, $0B, $0E, $0D ; $01, $00, $00, $00, $13, $FA, $13, $0A, $19, $19, $29, $00 smpsVcAlgorithm $02 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $00, $00, $00, $00 smpsVcCoarseFreq $02, $02, $04, $02 smpsVcRateScale $01, $02, $02, $02 smpsVcAttackRate $13, $0D, $0E, $0E smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $0D, $0E, $0B, $0E smpsVcDecayRate2 $00, $00, $00, $01 smpsVcDecayLevel $00, $01, $0F, $01 smpsVcReleaseRate $0A, $03, $0A, $03 smpsVcTotalLevel $00, $29, $19, $19 ; Voice $02 ; $3D ; $00, $01, $02, $01, $4C, $0F, $50, $12, $0C, $02, $00, $05 ; $01, $00, $00, $00, $28, $29, $2A, $19, $1A, $00, $06, $00 smpsVcAlgorithm $05 smpsVcFeedback $07 smpsVcUnusedBits $00 smpsVcDetune $00, $00, $00, $00 smpsVcCoarseFreq $01, $02, $01, $00 smpsVcRateScale $00, $01, $00, $01 smpsVcAttackRate $12, $10, $0F, $0C smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $05, $00, $02, $0C smpsVcDecayRate2 $00, $00, $00, $01 smpsVcDecayLevel $01, $02, $02, $02 smpsVcReleaseRate $09, $0A, $09, $08 smpsVcTotalLevel $00, $06, $00, $1A ; Voice $03 ; $06 ; $62, $23, $13, $71, $0D, $0D, $6D, $0E, $09, $06, $06, $06 ; $00, $00, $00, $00, $1F, $2F, $2F, $2F, $10, $94, $97, $80 smpsVcAlgorithm $06 smpsVcFeedback $00 smpsVcUnusedBits $00 smpsVcDetune $07, $01, $02, $06 smpsVcCoarseFreq $01, $03, $03, $02 smpsVcRateScale $00, $01, $00, $00 smpsVcAttackRate $0E, $2D, $0D, $0D smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $06, $06, $06, $09 smpsVcDecayRate2 $00, $00, $00, $00 smpsVcDecayLevel $02, $02, $02, $01 smpsVcReleaseRate $0F, $0F, $0F, $0F smpsVcTotalLevel $80, $97, $94, $10 ; Voice $04 ; $2C ; $71, $71, $31, $31, $1F, $16, $1F, $16, $00, $0F, $00, $0F ; $00, $0F, $00, $0F, $00, $FA, $00, $FA, $15, $00, $14, $00 smpsVcAlgorithm $04 smpsVcFeedback $05 smpsVcUnusedBits $00 smpsVcDetune $03, $03, $07, $07 smpsVcCoarseFreq $01, $01, $01, $01 smpsVcRateScale $00, $00, $00, $00 smpsVcAttackRate $16, $1F, $16, $1F smpsVcAmpMod $00, $00, $00, $00 smpsVcDecayRate1 $0F, $00, $0F, $00 smpsVcDecayRate2 $0F, $00, $0F, $00 smpsVcDecayLevel $0F, $00, $0F, $00 smpsVcReleaseRate $0A, $00, $0A, $00 smpsVcTotalLevel $00, $14, $00, $15
; Listing generated by Microsoft (R) Optimizing Compiler Version 17.00.50727.1 include listing.inc INCLUDELIB LIBCMT INCLUDELIB OLDNAMES PUBLIC ?mouse_x@@3HA ; mouse_x PUBLIC ?mouse_y@@3HA ; mouse_y PUBLIC ?mouse_x_difference@@3HA ; mouse_x_difference PUBLIC ?mouse_y_difference@@3HA ; mouse_y_difference PUBLIC ?prev_button@@3PAEA ; prev_button PUBLIC ?curr_button@@3PAEA ; curr_button PUBLIC ?mouse_button_state@@3IA ; mouse_button_state PUBLIC ?mouse_button@@3HC ; mouse_button PUBLIC ?old_message@@3U_dwm_message_@@A ; old_message _BSS SEGMENT mouse_cycle DB 01H DUP (?) ALIGN 4 ?mouse_x@@3HA DD 01H DUP (?) ; mouse_x ?mouse_y@@3HA DD 01H DUP (?) ; mouse_y ?mouse_x_difference@@3HA DD 01H DUP (?) ; mouse_x_difference ?mouse_y_difference@@3HA DD 01H DUP (?) ; mouse_y_difference ?prev_button@@3PAEA DB 03H DUP (?) ; prev_button ALIGN 4 ?curr_button@@3PAEA DB 03H DUP (?) ; curr_button ALIGN 4 ?mouse_button_state@@3IA DD 01H DUP (?) ; mouse_button_state ?mouse_button@@3HC DD 01H DUP (?) ; mouse_button ?old_message@@3U_dwm_message_@@A DB 01cH DUP (?) ; old_message _BSS ENDS CONST SEGMENT $SG6061 DB 'mouse', 00H ORG $+2 $SG6062 DB '/dev/mouse', 00H ORG $+5 $SG6066 DB 'mouse interrupt setupped', 0aH, 00H CONST ENDS PUBLIC ?initialize_mouse@@YAXXZ ; initialize_mouse PUBLIC ?mouse_wait@@YAXE@Z ; mouse_wait PUBLIC ?mouse_write@@YAXE@Z ; mouse_write PUBLIC ?mouse_read@@YAEXZ ; mouse_read PUBLIC ?left_button_up@@YAHXZ ; left_button_up PUBLIC ?mouse_handler@@YAX_KPEAX@Z ; mouse_handler PUBLIC ?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z ; mouse_ioquery PUBLIC ?mouse_register_device@@YAXXZ ; mouse_register_device EXTRN x64_cli:PROC EXTRN x64_sti:PROC EXTRN x64_inportb:PROC EXTRN ?inportb@@YAEG@Z:PROC ; inportb EXTRN ?outportb@@YAXGE@Z:PROC ; outportb EXTRN ?interrupt_end@@YAXI@Z:PROC ; interrupt_end EXTRN ?interrupt_set@@YAX_KP6AX0PEAX@ZE@Z:PROC ; interrupt_set EXTRN ?irq_mask@@YAXE_N@Z:PROC ; irq_mask EXTRN ?strcpy@@YAPEADPEADPEBD@Z:PROC ; strcpy EXTRN ?memset@@YAXPEAXEI@Z:PROC ; memset EXTRN memcpy:PROC EXTRN ?printf@@YAXPEBDZZ:PROC ; printf EXTRN ?vfs_mount@@YAXPEADPEAU_vfs_node_@@@Z:PROC ; vfs_mount EXTRN ?malloc@@YAPEAX_K@Z:PROC ; malloc EXTRN ?get_screen_width@@YAIXZ:PROC ; get_screen_width EXTRN ?get_screen_height@@YAIXZ:PROC ; get_screen_height EXTRN ?dwm_put_message@@YAXPEAU_dwm_message_@@@Z:PROC ; dwm_put_message EXTRN ?create_mutex@@YAPEAUmutex_t@@XZ:PROC ; create_mutex _BSS SEGMENT mouse_byte DB 04H DUP (?) ALIGN 8 mouse DQ 01H DUP (?) _BSS ENDS pdata SEGMENT $pdata$?initialize_mouse@@YAXXZ DD imagerel $LN3 DD imagerel $LN3+198 DD imagerel $unwind$?initialize_mouse@@YAXXZ pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$??__Emouse@@YAXXZ DD imagerel ??__Emouse@@YAXXZ DD imagerel ??__Emouse@@YAXXZ+21 DD imagerel $unwind$??__Emouse@@YAXXZ pdata ENDS pdata SEGMENT $pdata$?mouse_wait@@YAXE@Z DD imagerel $LN11 DD imagerel $LN11+131 DD imagerel $unwind$?mouse_wait@@YAXE@Z $pdata$?mouse_write@@YAXE@Z DD imagerel $LN3 DD imagerel $LN3+52 DD imagerel $unwind$?mouse_write@@YAXE@Z $pdata$?mouse_read@@YAEXZ DD imagerel $LN3 DD imagerel $LN3+25 DD imagerel $unwind$?mouse_read@@YAEXZ $pdata$?left_button_up@@YAHXZ DD imagerel $LN5 DD imagerel $LN5+76 DD imagerel $unwind$?left_button_up@@YAHXZ $pdata$?mouse_handler@@YAX_KPEAX@Z DD imagerel $LN26 DD imagerel $LN26+995 DD imagerel $unwind$?mouse_handler@@YAX_KPEAX@Z $pdata$?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z DD imagerel $LN9 DD imagerel $LN9+97 DD imagerel $unwind$?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z $pdata$?mouse_register_device@@YAXXZ DD imagerel $LN3 DD imagerel $LN3+201 DD imagerel $unwind$?mouse_register_device@@YAXXZ pdata ENDS CRT$XCU SEGMENT mouse$initializer$ DQ FLAT:??__Emouse@@YAXXZ CRT$XCU ENDS ; COMDAT xdata xdata SEGMENT $unwind$??__Emouse@@YAXXZ DD 010401H DD 04204H xdata ENDS xdata SEGMENT $unwind$?initialize_mouse@@YAXXZ DD 010401H DD 06204H $unwind$?mouse_wait@@YAXE@Z DD 010801H DD 06208H $unwind$?mouse_write@@YAXE@Z DD 010801H DD 04208H $unwind$?mouse_read@@YAEXZ DD 010401H DD 04204H $unwind$?left_button_up@@YAHXZ DD 010401H DD 02204H $unwind$?mouse_handler@@YAX_KPEAX@Z DD 010e01H DD 0c20eH $unwind$?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z DD 011201H DD 06212H $unwind$?mouse_register_device@@YAXXZ DD 010401H DD 06204H xdata ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT node$ = 32 ?mouse_register_device@@YAXXZ PROC ; mouse_register_device ; 211 : void mouse_register_device () { $LN3: sub rsp, 56 ; 00000038H ; 212 : vfs_node_t *node = (vfs_node_t*)malloc(sizeof(vfs_node_t)); mov ecx, 104 ; 00000068H call ?malloc@@YAPEAX_K@Z ; malloc mov QWORD PTR node$[rsp], rax ; 213 : strcpy (node->filename, "mouse"); mov rax, QWORD PTR node$[rsp] lea rdx, OFFSET FLAT:$SG6061 mov rcx, rax call ?strcpy@@YAPEADPEADPEBD@Z ; strcpy ; 214 : node->size = 0; mov rax, QWORD PTR node$[rsp] mov DWORD PTR [rax+32], 0 ; 215 : node->eof = 0; mov rax, QWORD PTR node$[rsp] mov DWORD PTR [rax+36], 0 ; 216 : node->pos = 0; mov rax, QWORD PTR node$[rsp] mov DWORD PTR [rax+40], 0 ; 217 : node->current = 0; mov rax, QWORD PTR node$[rsp] mov DWORD PTR [rax+44], 0 ; 218 : node->flags = FS_FLAG_GENERAL; mov rax, QWORD PTR node$[rsp] mov DWORD PTR [rax+48], 2 ; 219 : node->status = 0; mov rax, QWORD PTR node$[rsp] mov DWORD PTR [rax+52], 0 ; 220 : node->open = 0; mov rax, QWORD PTR node$[rsp] mov QWORD PTR [rax+64], 0 ; 221 : node->read = 0; mov rax, QWORD PTR node$[rsp] mov QWORD PTR [rax+72], 0 ; 222 : node->write = 0; mov rax, QWORD PTR node$[rsp] mov QWORD PTR [rax+80], 0 ; 223 : node->read_blk = 0; mov rax, QWORD PTR node$[rsp] mov QWORD PTR [rax+88], 0 ; 224 : node->ioquery = mouse_ioquery; mov rax, QWORD PTR node$[rsp] lea rcx, OFFSET FLAT:?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z ; mouse_ioquery mov QWORD PTR [rax+96], rcx ; 225 : vfs_mount ("/dev/mouse", node); mov rdx, QWORD PTR node$[rsp] lea rcx, OFFSET FLAT:$SG6062 call ?vfs_mount@@YAXPEADPEAU_vfs_node_@@@Z ; vfs_mount ; 226 : } add rsp, 56 ; 00000038H ret 0 ?mouse_register_device@@YAXXZ ENDP ; mouse_register_device _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT tv64 = 32 node$ = 64 code$ = 72 arg$ = 80 ?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z PROC ; mouse_ioquery ; 189 : int mouse_ioquery (vfs_node_t *node, int code, void* arg) { $LN9: mov QWORD PTR [rsp+24], r8 mov DWORD PTR [rsp+16], edx mov QWORD PTR [rsp+8], rcx sub rsp, 56 ; 00000038H ; 190 : switch (code) { mov eax, DWORD PTR code$[rsp] mov DWORD PTR tv64[rsp], eax cmp DWORD PTR tv64[rsp], 300 ; 0000012cH je SHORT $LN4@mouse_ioqu cmp DWORD PTR tv64[rsp], 301 ; 0000012dH je SHORT $LN3@mouse_ioqu cmp DWORD PTR tv64[rsp], 302 ; 0000012eH je SHORT $LN2@mouse_ioqu jmp SHORT $LN1@mouse_ioqu $LN4@mouse_ioqu: ; 191 : case MOUSE_IOCODE_DISABLE: ; 192 : irq_mask(12,true); mov dl, 1 mov cl, 12 call ?irq_mask@@YAXE_N@Z ; irq_mask ; 193 : break; jmp SHORT $LN5@mouse_ioqu $LN3@mouse_ioqu: ; 194 : case MOUSE_IOCODE_ENABLE: ; 195 : irq_mask(12, false); xor edx, edx mov cl, 12 call ?irq_mask@@YAXE_N@Z ; irq_mask ; 196 : break; jmp SHORT $LN5@mouse_ioqu $LN2@mouse_ioqu: ; 197 : case 302: ; 198 : return 10; mov eax, 10 jmp SHORT $LN7@mouse_ioqu $LN1@mouse_ioqu: $LN5@mouse_ioqu: ; 199 : break; ; 200 : default: ; 201 : break; ; 202 : } ; 203 : ; 204 : return 1; mov eax, 1 $LN7@mouse_ioqu: ; 205 : } add rsp, 56 ; 00000038H ret 0 ?mouse_ioquery@@YAHPEAU_vfs_node_@@HPEAX@Z ENDP ; mouse_ioquery _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT mouse_in$1 = 32 status$ = 33 x$2 = 36 tv75 = 40 y$3 = 44 tv151 = 48 tv156 = 52 msg$4 = 56 p$ = 112 param$ = 120 ?mouse_handler@@YAX_KPEAX@Z PROC ; mouse_handler ; 88 : void mouse_handler (size_t p, void* param) { $LN26: mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+8], rcx sub rsp, 104 ; 00000068H ; 89 : ; 90 : uint8_t status = inportb (MOUSE_STATUS); mov cx, 100 ; 00000064H call ?inportb@@YAEG@Z ; inportb mov BYTE PTR status$[rsp], al $LN23@mouse_hand: ; 91 : while ((status & MOUSE_BBIT) && (status & MOUSE_F_BIT)) { movzx eax, BYTE PTR status$[rsp] and eax, 1 test eax, eax je $LN22@mouse_hand movzx eax, BYTE PTR status$[rsp] and eax, 32 ; 00000020H test eax, eax je $LN22@mouse_hand ; 92 : int8_t mouse_in = inportb (MOUSE_PORT); mov cx, 96 ; 00000060H call ?inportb@@YAEG@Z ; inportb mov BYTE PTR mouse_in$1[rsp], al ; 93 : switch (mouse_cycle) { movzx eax, BYTE PTR mouse_cycle mov BYTE PTR tv75[rsp], al cmp BYTE PTR tv75[rsp], 0 je SHORT $LN19@mouse_hand cmp BYTE PTR tv75[rsp], 1 je SHORT $LN17@mouse_hand cmp BYTE PTR tv75[rsp], 2 je SHORT $LN16@mouse_hand cmp BYTE PTR tv75[rsp], 3 je $LN14@mouse_hand jmp $LN20@mouse_hand $LN19@mouse_hand: ; 94 : case 0: ; 95 : mouse_byte[0] = mouse_in; mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:mouse_byte movzx edx, BYTE PTR mouse_in$1[rsp] mov BYTE PTR [rcx+rax], dl ; 96 : if (!(mouse_in & MOUSE_V_BIT)) break; movsx eax, BYTE PTR mouse_in$1[rsp] and eax, 8 test eax, eax jne SHORT $LN18@mouse_hand jmp SHORT $LN20@mouse_hand $LN18@mouse_hand: ; 97 : ++mouse_cycle; movzx eax, BYTE PTR mouse_cycle inc al mov BYTE PTR mouse_cycle, al ; 98 : break; jmp SHORT $LN20@mouse_hand $LN17@mouse_hand: ; 99 : case 1: ; 100 : mouse_byte[1] = mouse_in; mov eax, 1 imul rax, 1 lea rcx, OFFSET FLAT:mouse_byte movzx edx, BYTE PTR mouse_in$1[rsp] mov BYTE PTR [rcx+rax], dl ; 101 : ++mouse_cycle; movzx eax, BYTE PTR mouse_cycle inc al mov BYTE PTR mouse_cycle, al ; 102 : break; jmp SHORT $LN20@mouse_hand $LN16@mouse_hand: ; 103 : case 2: ; 104 : mouse_byte[2] = mouse_in; mov eax, 1 imul rax, 2 lea rcx, OFFSET FLAT:mouse_byte movzx edx, BYTE PTR mouse_in$1[rsp] mov BYTE PTR [rcx+rax], dl ; 105 : goto finish_packet; jmp SHORT $LN15@mouse_hand jmp SHORT $finish_packet$27 $LN14@mouse_hand: ; 106 : case 3: ; 107 : mouse_byte[3] = mouse_in; mov eax, 1 imul rax, 3 lea rcx, OFFSET FLAT:mouse_byte movzx edx, BYTE PTR mouse_in$1[rsp] mov BYTE PTR [rcx+rax], dl ; 108 : goto finish_packet; jmp SHORT $LN13@mouse_hand jmp SHORT $finish_packet$27 $LN20@mouse_hand: ; 109 : } ; 110 : ; 111 : goto read_next; jmp $LN12@mouse_hand jmp $read_next$28 $LN13@mouse_hand: $LN15@mouse_hand: $finish_packet$27: ; 112 : ; 113 : finish_packet: ; 114 : mouse_cycle = 0; mov BYTE PTR mouse_cycle, 0 ; 115 : ; 116 : int x = mouse_byte[1]; mov eax, 1 imul rax, 1 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] mov DWORD PTR x$2[rsp], eax ; 117 : int y = mouse_byte[2]; mov eax, 1 imul rax, 2 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] mov DWORD PTR y$3[rsp], eax ; 118 : if (x && mouse_byte[0] & ( 1 << 4)) { cmp DWORD PTR x$2[rsp], 0 je SHORT $LN11@mouse_hand mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] and eax, 16 test eax, eax je SHORT $LN11@mouse_hand ; 119 : x = x - 0x100; mov eax, DWORD PTR x$2[rsp] sub eax, 256 ; 00000100H mov DWORD PTR x$2[rsp], eax $LN11@mouse_hand: ; 120 : } ; 121 : ; 122 : if (y && mouse_byte[0] & (1 << 5)) { cmp DWORD PTR y$3[rsp], 0 je SHORT $LN10@mouse_hand mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] and eax, 32 ; 00000020H test eax, eax je SHORT $LN10@mouse_hand ; 123 : y = y - 0x100; mov eax, DWORD PTR y$3[rsp] sub eax, 256 ; 00000100H mov DWORD PTR y$3[rsp], eax $LN10@mouse_hand: ; 124 : } ; 125 : ; 126 : mouse_x_difference = x; mov eax, DWORD PTR x$2[rsp] mov DWORD PTR ?mouse_x_difference@@3HA, eax ; mouse_x_difference ; 127 : mouse_y_difference = y; mov eax, DWORD PTR y$3[rsp] mov DWORD PTR ?mouse_y_difference@@3HA, eax ; mouse_y_difference ; 128 : mouse_x += mouse_x_difference; mov eax, DWORD PTR ?mouse_x_difference@@3HA ; mouse_x_difference mov ecx, DWORD PTR ?mouse_x@@3HA ; mouse_x add ecx, eax mov eax, ecx mov DWORD PTR ?mouse_x@@3HA, eax ; mouse_x ; 129 : mouse_y -= mouse_y_difference; mov eax, DWORD PTR ?mouse_y_difference@@3HA ; mouse_y_difference mov ecx, DWORD PTR ?mouse_y@@3HA ; mouse_y sub ecx, eax mov eax, ecx mov DWORD PTR ?mouse_y@@3HA, eax ; mouse_y ; 130 : ; 131 : if (mouse_x < 0) cmp DWORD PTR ?mouse_x@@3HA, 0 ; mouse_x jge SHORT $LN9@mouse_hand ; 132 : mouse_x = 0; mov DWORD PTR ?mouse_x@@3HA, 0 ; mouse_x $LN9@mouse_hand: ; 133 : ; 134 : if (mouse_y < 0) cmp DWORD PTR ?mouse_y@@3HA, 0 ; mouse_y jge SHORT $LN8@mouse_hand ; 135 : mouse_y = 0; mov DWORD PTR ?mouse_y@@3HA, 0 ; mouse_y $LN8@mouse_hand: ; 136 : ; 137 : if (mouse_x + 24 > get_screen_width()) mov eax, DWORD PTR ?mouse_x@@3HA ; mouse_x add eax, 24 mov DWORD PTR tv151[rsp], eax call ?get_screen_width@@YAIXZ ; get_screen_width mov ecx, DWORD PTR tv151[rsp] cmp ecx, eax jbe SHORT $LN7@mouse_hand ; 138 : mouse_x = get_screen_width() - 24; call ?get_screen_width@@YAIXZ ; get_screen_width sub eax, 24 mov DWORD PTR ?mouse_x@@3HA, eax ; mouse_x $LN7@mouse_hand: ; 139 : ; 140 : if (mouse_y + 24 > get_screen_height()) mov eax, DWORD PTR ?mouse_y@@3HA ; mouse_y add eax, 24 mov DWORD PTR tv156[rsp], eax call ?get_screen_height@@YAIXZ ; get_screen_height mov ecx, DWORD PTR tv156[rsp] cmp ecx, eax jbe SHORT $LN6@mouse_hand ; 141 : mouse_y = get_screen_height() - 24; call ?get_screen_height@@YAIXZ ; get_screen_height sub eax, 24 mov DWORD PTR ?mouse_y@@3HA, eax ; mouse_y $LN6@mouse_hand: ; 142 : ; 143 : mouse_button_state = 0; mov DWORD PTR ?mouse_button_state@@3IA, 0 ; mouse_button_state ; 144 : ; 145 : if (mouse_byte[0] & 0x01) { //0x01 for PS/2 mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] and eax, 1 test eax, eax je SHORT $LN5@mouse_hand ; 146 : curr_button[0] = 1; mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button mov BYTE PTR [rcx+rax], 1 ; 147 : mouse_button_state |= 1; mov eax, DWORD PTR ?mouse_button_state@@3IA ; mouse_button_state or eax, 1 mov DWORD PTR ?mouse_button_state@@3IA, eax ; mouse_button_state ; 148 : }else jmp SHORT $LN4@mouse_hand $LN5@mouse_hand: ; 149 : curr_button[0] = 0; mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button mov BYTE PTR [rcx+rax], 0 $LN4@mouse_hand: ; 150 : ; 151 : if (mouse_byte[0] & 0x02) { mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] and eax, 2 test eax, eax je SHORT $LN3@mouse_hand ; 152 : curr_button[2] = 1; mov eax, 1 imul rax, 2 lea rcx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button mov BYTE PTR [rcx+rax], 1 ; 153 : }else jmp SHORT $LN2@mouse_hand $LN3@mouse_hand: ; 154 : curr_button[2] = 0; mov eax, 1 imul rax, 2 lea rcx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button mov BYTE PTR [rcx+rax], 0 $LN2@mouse_hand: ; 155 : ; 156 : if (mouse_byte[0] & 0x04) mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] and eax, 4 test eax, eax je SHORT $LN1@mouse_hand ; 157 : mouse_button |= MOUSE_MIDDLE_CLICK; mov eax, DWORD PTR ?mouse_button@@3HC ; mouse_button or eax, 4 mov DWORD PTR ?mouse_button@@3HC, eax ; mouse_button $LN1@mouse_hand: ; 158 : ; 159 : //!Pass here the message stream to all waiting processes ; 160 : ; 161 : x64_cli(); call x64_cli ; 162 : //mutex_lock (mouse); ; 163 : dwm_message_t msg; // = (dwm_message_t*)pmmngr_alloc(); ; 164 : msg.type = 1; mov eax, 1 mov WORD PTR msg$4[rsp], ax ; 165 : msg.dword = mouse_x; mov eax, DWORD PTR ?mouse_x@@3HA ; mouse_x mov DWORD PTR msg$4[rsp+4], eax ; 166 : msg.dword2 = mouse_y; mov eax, DWORD PTR ?mouse_y@@3HA ; mouse_y mov DWORD PTR msg$4[rsp+8], eax ; 167 : msg.dword4 = mouse_button_state; mov eax, DWORD PTR ?mouse_button_state@@3IA ; mouse_button_state mov DWORD PTR msg$4[rsp+16], eax ; 168 : msg.dword5 = mouse_byte[1]; mov eax, 1 imul rax, 1 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] mov DWORD PTR msg$4[rsp+20], eax ; 169 : msg.dword6 = -mouse_byte[2]; mov eax, 1 imul rax, 2 lea rcx, OFFSET FLAT:mouse_byte movzx eax, BYTE PTR [rcx+rax] neg eax mov DWORD PTR msg$4[rsp+24], eax ; 170 : dwm_put_message (&msg); lea rcx, QWORD PTR msg$4[rsp] call ?dwm_put_message@@YAXPEAU_dwm_message_@@@Z ; dwm_put_message ; 171 : x64_sti(); call x64_sti ; 172 : //pmmngr_free (msg); ; 173 : //mutex_unlock (mouse); ; 174 : /* if (left_button_up()) { ; 175 : mouse_button_state |= 5; ; 176 : }*/ ; 177 : ; 178 : memcpy (prev_button, curr_button, 3); mov r8d, 3 lea rdx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button lea rcx, OFFSET FLAT:?prev_button@@3PAEA ; prev_button call memcpy ; 179 : memset (curr_button, 0x00, 3); mov r8d, 3 xor edx, edx lea rcx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button call ?memset@@YAXPEAXEI@Z ; memset $LN12@mouse_hand: $read_next$28: ; 180 : read_next: ; 181 : break; jmp SHORT $LN22@mouse_hand ; 182 : } jmp $LN23@mouse_hand $LN22@mouse_hand: ; 183 : ; 184 : interrupt_end(12); mov ecx, 12 call ?interrupt_end@@YAXI@Z ; interrupt_end ; 185 : } add rsp, 104 ; 00000068H ret 0 ?mouse_handler@@YAX_KPEAX@Z ENDP ; mouse_handler _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT tv72 = 0 ?left_button_up@@YAHXZ PROC ; left_button_up ; 76 : int left_button_up() { $LN5: sub rsp, 24 ; 77 : return prev_button[0] && !curr_button[0]; mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:?prev_button@@3PAEA ; prev_button movzx eax, BYTE PTR [rcx+rax] test eax, eax je SHORT $LN3@left_butto mov eax, 1 imul rax, 0 lea rcx, OFFSET FLAT:?curr_button@@3PAEA ; curr_button movzx eax, BYTE PTR [rcx+rax] test eax, eax jne SHORT $LN3@left_butto mov DWORD PTR tv72[rsp], 1 jmp SHORT $LN4@left_butto $LN3@left_butto: mov DWORD PTR tv72[rsp], 0 $LN4@left_butto: mov eax, DWORD PTR tv72[rsp] ; 78 : } add rsp, 24 ret 0 ?left_button_up@@YAHXZ ENDP ; left_button_up _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT ?mouse_read@@YAEXZ PROC ; mouse_read ; 70 : uint8_t mouse_read () { $LN3: sub rsp, 40 ; 00000028H ; 71 : mouse_wait (0); xor ecx, ecx call ?mouse_wait@@YAXE@Z ; mouse_wait ; 72 : return inportb (0x60); mov cx, 96 ; 00000060H call ?inportb@@YAEG@Z ; inportb ; 73 : } add rsp, 40 ; 00000028H ret 0 ?mouse_read@@YAEXZ ENDP ; mouse_read _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT write$ = 48 ?mouse_write@@YAXE@Z PROC ; mouse_write ; 60 : void mouse_write (uint8_t write) { $LN3: mov BYTE PTR [rsp+8], cl sub rsp, 40 ; 00000028H ; 61 : mouse_wait (1); mov cl, 1 call ?mouse_wait@@YAXE@Z ; mouse_wait ; 62 : outportb (0x64, 0xD4); mov dl, 212 ; 000000d4H mov cx, 100 ; 00000064H call ?outportb@@YAXGE@Z ; outportb ; 63 : mouse_wait (1); mov cl, 1 call ?mouse_wait@@YAXE@Z ; mouse_wait ; 64 : outportb (0x60, write); movzx edx, BYTE PTR write$[rsp] mov cx, 96 ; 00000060H call ?outportb@@YAXGE@Z ; outportb ; 65 : } add rsp, 40 ; 00000028H ret 0 ?mouse_write@@YAXE@Z ENDP ; mouse_write _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT _timer_out_$ = 32 tv68 = 36 tv76 = 40 a_type$ = 64 ?mouse_wait@@YAXE@Z PROC ; mouse_wait ; 38 : void mouse_wait (uint8_t a_type){ $LN11: mov BYTE PTR [rsp+8], cl sub rsp, 56 ; 00000038H ; 39 : uint32_t _timer_out_ = 100000; mov DWORD PTR _timer_out_$[rsp], 100000 ; 000186a0H ; 40 : if (a_type == 0) { movzx eax, BYTE PTR a_type$[rsp] test eax, eax jne SHORT $LN8@mouse_wait $LN7@mouse_wait: ; 41 : while (_timer_out_--){ mov eax, DWORD PTR _timer_out_$[rsp] mov DWORD PTR tv68[rsp], eax mov eax, DWORD PTR _timer_out_$[rsp] dec eax mov DWORD PTR _timer_out_$[rsp], eax cmp DWORD PTR tv68[rsp], 0 je SHORT $LN6@mouse_wait ; 42 : if ((x64_inportb(0x64) & 1) == 1){ mov cx, 100 ; 00000064H call x64_inportb movzx eax, al and eax, 1 cmp eax, 1 jne SHORT $LN5@mouse_wait ; 43 : return; jmp SHORT $LN9@mouse_wait $LN5@mouse_wait: ; 44 : } ; 45 : } jmp SHORT $LN7@mouse_wait $LN6@mouse_wait: ; 46 : return; jmp SHORT $LN9@mouse_wait ; 47 : }else { jmp SHORT $LN4@mouse_wait $LN8@mouse_wait: $LN3@mouse_wait: ; 48 : while (_timer_out_--){ mov eax, DWORD PTR _timer_out_$[rsp] mov DWORD PTR tv76[rsp], eax mov eax, DWORD PTR _timer_out_$[rsp] dec eax mov DWORD PTR _timer_out_$[rsp], eax cmp DWORD PTR tv76[rsp], 0 je SHORT $LN2@mouse_wait ; 49 : if ((x64_inportb(0x64) & 2) == 0){ mov cx, 100 ; 00000064H call x64_inportb movzx eax, al and eax, 2 test eax, eax jne SHORT $LN1@mouse_wait ; 50 : return; jmp SHORT $LN9@mouse_wait $LN1@mouse_wait: ; 51 : } ; 52 : } jmp SHORT $LN3@mouse_wait $LN2@mouse_wait: $LN4@mouse_wait: $LN9@mouse_wait: ; 53 : return; ; 54 : } ; 55 : } add rsp, 56 ; 00000038H ret 0 ?mouse_wait@@YAXE@Z ENDP ; mouse_wait _TEXT ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp ; COMDAT ??__Emouse@@YAXXZ text$yc SEGMENT ??__Emouse@@YAXXZ PROC ; `dynamic initializer for 'mouse'', COMDAT ; 32 : static mutex_t *mouse = create_mutex(); sub rsp, 40 ; 00000028H call ?create_mutex@@YAPEAUmutex_t@@XZ ; create_mutex mov QWORD PTR mouse, rax add rsp, 40 ; 00000028H ret 0 ??__Emouse@@YAXXZ ENDP ; `dynamic initializer for 'mouse'' text$yc ENDS ; Function compile flags: /Odtpy ; File e:\xeneva project\xeneva\aurora\aurora\drivers\mouse.cpp _TEXT SEGMENT status$ = 32 ?initialize_mouse@@YAXXZ PROC ; initialize_mouse ; 232 : void initialize_mouse () { $LN3: sub rsp, 56 ; 00000038H ; 233 : mouse_cycle = 0; mov BYTE PTR mouse_cycle, 0 ; 234 : mouse_x = 0; mov DWORD PTR ?mouse_x@@3HA, 0 ; mouse_x ; 235 : mouse_y = 0; mov DWORD PTR ?mouse_y@@3HA, 0 ; mouse_y ; 236 : ; 237 : uint8_t status; ; 238 : ; 239 : mouse_wait (1); mov cl, 1 call ?mouse_wait@@YAXE@Z ; mouse_wait ; 240 : outportb (0x64, 0xA8); mov dl, 168 ; 000000a8H mov cx, 100 ; 00000064H call ?outportb@@YAXGE@Z ; outportb ; 241 : ; 242 : mouse_wait(1); mov cl, 1 call ?mouse_wait@@YAXE@Z ; mouse_wait ; 243 : outportb (0x64, 0x20); mov dl, 32 ; 00000020H mov cx, 100 ; 00000064H call ?outportb@@YAXGE@Z ; outportb ; 244 : ; 245 : mouse_wait (0); xor ecx, ecx call ?mouse_wait@@YAXE@Z ; mouse_wait ; 246 : status = (inportb (0x60) | 2); mov cx, 96 ; 00000060H call ?inportb@@YAEG@Z ; inportb movzx eax, al or eax, 2 mov BYTE PTR status$[rsp], al ; 247 : ; 248 : mouse_wait (1); mov cl, 1 call ?mouse_wait@@YAXE@Z ; mouse_wait ; 249 : outportb (0x64, 0x60); mov dl, 96 ; 00000060H mov cx, 100 ; 00000064H call ?outportb@@YAXGE@Z ; outportb ; 250 : ; 251 : mouse_wait (1); mov cl, 1 call ?mouse_wait@@YAXE@Z ; mouse_wait ; 252 : outportb (0x60, status); movzx edx, BYTE PTR status$[rsp] mov cx, 96 ; 00000060H call ?outportb@@YAXGE@Z ; outportb ; 253 : ; 254 : mouse_write (0xF6); mov cl, 246 ; 000000f6H call ?mouse_write@@YAXE@Z ; mouse_write ; 255 : mouse_read (); call ?mouse_read@@YAEXZ ; mouse_read ; 256 : ; 257 : mouse_write (0xF4); mov cl, 244 ; 000000f4H call ?mouse_write@@YAXE@Z ; mouse_write ; 258 : mouse_read (); call ?mouse_read@@YAEXZ ; mouse_read ; 259 : ; 260 : interrupt_set (34, mouse_handler, 12); //34 mov r8b, 12 lea rdx, OFFSET FLAT:?mouse_handler@@YAX_KPEAX@Z ; mouse_handler mov ecx, 34 ; 00000022H call ?interrupt_set@@YAX_KP6AX0PEAX@ZE@Z ; interrupt_set ; 261 : printf ("mouse interrupt setupped\n"); lea rcx, OFFSET FLAT:$SG6066 call ?printf@@YAXPEBDZZ ; printf ; 262 : mouse_register_device (); call ?mouse_register_device@@YAXXZ ; mouse_register_device ; 263 : } add rsp, 56 ; 00000038H ret 0 ?initialize_mouse@@YAXXZ ENDP ; initialize_mouse _TEXT ENDS END
; A087385: a(n) = smallest prime == 1 (mod T(n)) where T(n) is the n-th triangular number (A000217). ; 2,7,7,11,31,43,29,37,181,331,67,79,547,211,241,137,307,2053,191,211,463,1013,277,601,1301,3511,379,2437,1741,1861,1489,2113,1123,2381,631,1999,4219,1483,2341,821,1723,3613,947,991,6211,12973,1129,3529,7351 seq $0,96 ; a(n) = n*(n+3)/2. seq $0,34694 ; Smallest prime == 1 (mod n).
; A100714: Number of runs in binary expansion of A000040(n) (the n-th prime number) for n>0. ; 2,1,3,1,3,3,3,3,3,3,1,5,5,5,3,5,3,3,3,3,5,3,5,5,3,5,3,5,5,3,1,3,5,5,7,5,5,5,5,7,5,7,3,3,5,3,5,3,3,5,5,3,3,3,3,3,5,3,7,5,5,7,5,5,5,5,7,7,7,7,5,5,5,7,5,3,5,5,5,5,5,7,5,5,5,5,3,5,5,3,5,3,3,5,3,3,3,5,5,5 seq $0,40 ; The prime numbers. seq $0,5811 ; Number of runs in binary expansion of n (n>0); number of 1's in Gray code for n.
;/*! ; @file ; ; @ingroup fapi ; ; @brief DosPFSVerifyFont DOS wrapper ; ; (c) osFree Project 2022, <http://www.osFree.org> ; for licence see licence.txt in root directory, or project website ; ; This is Family API implementation for DOS, used with BIND tools ; to link required API ; ; @author Yuri Prokushev (yuri.prokushev@gmail.com) ; ; ; ;*/ .8086 ; Helpers INCLUDE helpers.inc _TEXT SEGMENT BYTE PUBLIC 'CODE' USE16 @PROLOG DOSPFSVERIFYFONT @START DOSPFSVERIFYFONT XOR AX, AX EXIT: @EPILOG DOSPFSVERIFYFONT _TEXT ENDS END
;;; Copyright 2020 Tadashi G. Takaoka ;;; ;;; 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. cpu z86c40 org 0100h setrp -1 include "test_z8.inc" align 32 include "test_z86.inc" align 32 setrp 00h include "test_z86_rp00.inc" align 32 setrp 20h include "test_z86_rp20.inc" align 32 include "test_z86c.inc" end ;;; Local Variables: ;;; mode: asm ;;; End: ;;; vim: set ft=asm:
;-----------------------------------------------------------------------------; ; Author: Ege Balcı <ege.balci[at]invictuseurope[dot]com> ; Compatible: Windows 10/8.1/8/7/2008/Vista/2003/XP/2000/NT4 ; Version: 1.0 (25 January 2018) ; Size: 177 bytes ;-----------------------------------------------------------------------------; [BITS 32] pushad ; We preserve all the registers for the caller, bar EAX and ECX. mov eax,[fs:0x30] ; PEB mov eax,[eax + 0x0c] ; PEB_LDR_DATA mov eax,[eax + 0x0c] ; InOrderModuleList mov dword [eax + 0x20],0xFFFFFF ; SizeOfImage popad ; Pop back all the registers ret ; <-
; A298360: Numbers congruent to {3, 7, 13, 27} mod 30. ; 3,7,13,27,33,37,43,57,63,67,73,87,93,97,103,117,123,127,133,147,153,157,163,177,183,187,193,207,213,217,223,237,243,247,253,267,273,277,283,297,303,307,313,327,333,337,343,357,363,367,373,387,393,397,403 mov $2,$0 add $0,3 mov $3,$0 sub $3,1 mov $4,$0 mov $5,$0 mov $0,$3 add $5,$4 sub $5,5 lpb $0 sub $0,1 trn $0,1 mov $1,$5 mov $4,5 sub $4,$6 add $1,$4 add $5,3 mov $6,$4 lpe lpb $2 add $1,4 sub $2,1 lpe sub $1,3
.file "aes-aesni.asm" .text .macro AES128_EXPAND rcon, off vaeskeygenassist $\rcon, %xmm0, %xmm1 pshufd $0xFF, %xmm1 vpslldq $0x04, %xmm0, %xmm2 pxor %xmm2, %xmm0 pslldq $0x04, %xmm2 pxor %xmm2, %xmm0 pslldq $0x04, %xmm2 pxor %xmm2, %xmm0 pxor %xmm1, %xmm0 movdqa %xmm0, \off(%rdi) .endm .align 16 .globl _crypto_aes128_set_key_aesni .def _crypto_aes128_set_key_aesni; .scl 2; .type 32; .endef /* void _aes128_set_key_aesni(uint32_t* subkeys [%rdi], */ /* const uint8_t* key [%rsi]) */ _crypto_aes128_set_key_aesni: addq $0x30, %rdi /* Offset subkeys pointer */ /* Copy first 4 keys */ movdqu 0x00(%rsi), %xmm0 movdqa %xmm0, -0x30(%rdi) /* Key Set 1 */ AES128_EXPAND 0x01, -0x20 /* Key Set 2 */ AES128_EXPAND 0x02, -0x10 /* Key Set 3 */ AES128_EXPAND 0x04, 0x00 /* Key Set 4 */ AES128_EXPAND 0x08, 0x10 /* Key Set 5 */ AES128_EXPAND 0x10, 0x20 /* Key Set 6 */ AES128_EXPAND 0x20, 0x30 /* Key Set 7 */ AES128_EXPAND 0x40, 0x40 /* Key Set 8 */ AES128_EXPAND 0x80, 0x50 /* Key Set 9 */ AES128_EXPAND 0x1B, 0x60 /* Key Set 10 */ AES128_EXPAND 0x36, 0x70 /* Return */ ret .macro AES192_EXPAND_A rcon, off movdqa %xmm2, %xmm4 vaeskeygenassist $\rcon, %xmm2, %xmm1 pshufd $0x55, %xmm1 vpslldq $0x04, %xmm0, %xmm3 pxor %xmm3, %xmm0 pslldq $0x04, %xmm3 pxor %xmm3, %xmm0 pslldq $0x04, %xmm3 pxor %xmm3, %xmm0 pxor %xmm1, %xmm0 vpshufd $0xFF, %xmm0, %xmm1 vpslldq $0x04, %xmm2, %xmm3 pxor %xmm3, %xmm2 pxor %xmm1, %xmm2 shufpd $0x00, %xmm0, %xmm4 vshufpd $0x01, %xmm2, %xmm0, %xmm5 movdqa %xmm4, \off + 0x00(%rdi) movdqa %xmm5, \off + 0x10(%rdi) .endm .macro AES192_EXPAND_B rcon, off vaeskeygenassist $\rcon, %xmm2, %xmm1 pshufd $0x55, %xmm1 vpslldq $0x04, %xmm0, %xmm3 pxor %xmm3, %xmm0 pslldq $0x04, %xmm3 pxor %xmm3, %xmm0 pslldq $0x04, %xmm3 pxor %xmm3, %xmm0 pxor %xmm1, %xmm0 vpshufd $0xFF, %xmm0, %xmm1 vpslldq $0x04, %xmm2, %xmm3 pxor %xmm3, %xmm2 pxor %xmm1, %xmm2 movdqa %xmm0, \off(%rdi) .endm .align 16 .globl _crypto_aes192_set_key_aesni .def _crypto_aes192_set_key_aesni; .scl 2; .type 32; .endef /* void _aes192_set_key_aesni(uint32_t* subkeys [%rdi], */ /* const uint8_t* key [%rsi]) */ _crypto_aes192_set_key_aesni: addq $0x50, %rdi /* Offset subkeys pointer */ /* Copy first 6 keys */ movdqu 0x00(%rsi), %xmm0 movq 0x10(%rsi), %xmm2 movdqa %xmm0, -0x50(%rdi) /* Key Set 1 */ AES192_EXPAND_A 0x01, -0x40 /* Key Set 2 */ AES192_EXPAND_B 0x02, -0x20 /* Key Set 3 */ AES192_EXPAND_A 0x04, -0x10 /* Key Set 4 */ AES192_EXPAND_B 0x08, 0x10 /* Key Set 5 */ AES192_EXPAND_A 0x10, 0x20 /* Key Set 6 */ AES192_EXPAND_B 0x20, 0x40 /* Key Set 7 */ AES192_EXPAND_A 0x40, 0x50 /* Key Set 8 */ AES192_EXPAND_B 0x80, 0x70 /* Return */ ret .macro AES256_EXPAND_A rcon, off vaeskeygenassist $\rcon, %xmm2, %xmm1 pshufd $0xFF, %xmm1 vpslldq $0x04, %xmm0, %xmm3 pxor %xmm3, %xmm0 pslldq $0x04, %xmm3 pxor %xmm3, %xmm0 pslldq $0x04, %xmm3 pxor %xmm3, %xmm0 pxor %xmm1, %xmm0 movdqa %xmm0, \off(%rdi) .endm .macro AES256_EXPAND rcon, off AES256_EXPAND_A \rcon, \off vaeskeygenassist $0x00, %xmm0, %xmm1 pshufd $0xAA, %xmm1 vpslldq $0x04, %xmm2, %xmm3 pxor %xmm3, %xmm2 pslldq $0x04, %xmm3 pxor %xmm3, %xmm2 pslldq $0x04, %xmm3 pxor %xmm3, %xmm2 pxor %xmm1, %xmm2 movdqa %xmm2, \off + 0x10(%rdi) .endm .align 16 .globl _crypto_aes256_set_key_aesni .def _crypto_aes256_set_key_aesni; .scl 2; .type 32; .endef /* void _aes256_set_key_aesni(uint32_t* subkeys [%rdi], */ /* const uint8_t* key [%rsi]) */ _crypto_aes256_set_key_aesni: addq $0x70, %rdi /* Offset subkeys pointer */ /* Copy first 8 keys */ movdqu 0x00(%rsi), %xmm0 movq 0x10(%rsi), %xmm2 movdqa %xmm0, -0x70(%rdi) movdqa %xmm2, -0x60(%rdi) /* Key Set 1 */ AES256_EXPAND 0x01, -0x50 /* Key Set 2 */ AES256_EXPAND 0x02, -0x30 /* Key Set 3 */ AES256_EXPAND 0x04, -0x10 /* Key Set 4 */ AES256_EXPAND 0x08, 0x10 /* Key Set 5 */ AES256_EXPAND 0x10, 0x30 /* Key Set 6 */ AES256_EXPAND 0x20, 0x50 /* Key Set 7 */ AES256_EXPAND_A 0x40, 0x70 /* Return */ ret .align 16 .globl _crypto_aes128_invert_aesni .def _crypto_aes128_invert_aesni; .scl 2; .type 32; .endef /* void _aes128_invert_aesni(uint32_t* dst [%rdi], */ /* const uint32_t* src [%rsi]) */ _crypto_aes128_invert_aesni: addq $0x30, %rsi /* Offset src pointer */ addq $0x30, %rdi /* Offset dst pointer */ cmpq %rsi, %rdi jne 1f /* Copy first 4 and last 4 keys */ movdqa -0x30(%rsi), %xmm0 movdqa 0x70(%rsi), %xmm1 movdqa %xmm0, -0x30(%rdi) movdqa %xmm1, 0x70(%rdi) 1: aesimc -0x20(%rsi), %xmm0 aesimc -0x10(%rsi), %xmm1 aesimc 0x00(%rsi), %xmm2 aesimc 0x10(%rsi), %xmm3 aesimc 0x20(%rsi), %xmm4 movdqa %xmm0, -0x20(%rdi) movdqa %xmm1, -0x10(%rdi) movdqa %xmm2, 0x00(%rdi) movdqa %xmm3, 0x10(%rdi) movdqa %xmm4, 0x20(%rdi) aesimc 0x30(%rsi), %xmm0 aesimc 0x40(%rsi), %xmm1 aesimc 0x50(%rsi), %xmm2 aesimc 0x60(%rsi), %xmm3 movdqa %xmm0, 0x30(%rdi) movdqa %xmm1, 0x40(%rdi) movdqa %xmm2, 0x50(%rdi) movdqa %xmm3, 0x60(%rdi) ret .align 16 .globl _crypto_aes192_invert_aesni .def _crypto_aes192_invert_aesni; .scl 2; .type 32; .endef /* void _aes192_invert_aesni(uint32_t* dst [%rdi], */ /* const uint32_t* src [%rsi]) */ _crypto_aes192_invert_aesni: addq $0x50, %rsi /* Offset src pointer */ addq $0x50, %rdi /* Offset dst pointer */ cmpq %rsi, %rdi jne 1f /* Copy first 4 and last 4 keys */ movdqa -0x50(%rsi), %xmm0 movdqa 0x70(%rsi), %xmm1 movdqa %xmm0, -0x50(%rdi) movdqa %xmm1, 0x70(%rdi) 1: aesimc -0x40(%rsi), %xmm0 aesimc -0x30(%rsi), %xmm1 aesimc -0x20(%rsi), %xmm2 aesimc -0x10(%rsi), %xmm3 aesimc 0x00(%rsi), %xmm4 aesimc 0x10(%rsi), %xmm5 movdqa %xmm0, -0x40(%rdi) movdqa %xmm1, -0x30(%rdi) movdqa %xmm2, -0x20(%rdi) movdqa %xmm3, -0x10(%rdi) movdqa %xmm4, 0x00(%rdi) movdqa %xmm5, 0x10(%rdi) aesimc 0x20(%rsi), %xmm0 aesimc 0x30(%rsi), %xmm1 aesimc 0x40(%rsi), %xmm2 aesimc 0x50(%rsi), %xmm3 aesimc 0x60(%rsi), %xmm4 movdqa %xmm0, 0x20(%rdi) movdqa %xmm1, 0x30(%rdi) movdqa %xmm2, 0x40(%rdi) movdqa %xmm3, 0x50(%rdi) movdqa %xmm4, 0x60(%rdi) ret .align 16 .globl _crypto_aes256_invert_aesni .def _crypto_aes256_invert_aesni; .scl 2; .type 32; .endef /* void _aes256_invert_aesni(uint32_t* dst [%rdi], */ /* const uint32_t* src [%rsi]) */ _crypto_aes256_invert_aesni: addq $0x70, %rsi /* Offset src pointer */ addq $0x70, %rdi /* Offset dst pointer */ cmpq %rsi, %rdi jne 1f /* Copy first 4 and last 4 keys */ movdqa -0x70(%rsi), %xmm0 movdqa 0x70(%rsi), %xmm1 movdqa %xmm0, -0x70(%rdi) movdqa %xmm1, 0x70(%rdi) 1: aesimc -0x60(%rsi), %xmm0 aesimc -0x50(%rsi), %xmm1 aesimc -0x40(%rsi), %xmm2 aesimc -0x30(%rsi), %xmm3 aesimc -0x20(%rsi), %xmm4 movdqa %xmm0, -0x60(%rdi) movdqa %xmm1, -0x50(%rdi) movdqa %xmm2, -0x40(%rdi) movdqa %xmm3, -0x30(%rdi) movdqa %xmm4, -0x20(%rdi) aesimc -0x10(%rsi), %xmm0 aesimc 0x00(%rsi), %xmm1 aesimc 0x10(%rsi), %xmm2 aesimc 0x20(%rsi), %xmm3 aesimc 0x30(%rsi), %xmm4 movdqa %xmm0, -0x10(%rdi) movdqa %xmm1, 0x00(%rdi) movdqa %xmm2, 0x10(%rdi) movdqa %xmm3, 0x20(%rdi) movdqa %xmm4, 0x30(%rdi) aesimc 0x40(%rsi), %xmm0 aesimc 0x50(%rsi), %xmm1 aesimc 0x60(%rsi), %xmm2 movdqa %xmm0, 0x40(%rdi) movdqa %xmm1, 0x50(%rdi) movdqa %xmm2, 0x60(%rdi) ret .align 16 .globl _crypto_aes128_encrypt_aesni .def _crypto_aes128_encrypt_aesni; .scl 2; .type 32; .endef /* void _aes128_encrypt_aesni(const uint32_t* key [%rdi], */ /* uint8_t* dst [%rsi], */ /* const uint8_t* src [%rdx], */ /* size_t length [%rcx]) */ _crypto_aes128_encrypt_aesni: subq $0x28, %rsp movdqa %xmm6, 0x00(%rsp) movdqa %xmm7, 0x10(%rsp) cmpq $16, %rcx jb .Lencrypt128_end shrq $4, %rcx /* Divide length by 16 */ addq $0x30, %rdi /* Offset key pointer */ movq %rcx, %rax /* Check (length / 16) mod 4, and encrypt that many blocks outside of the loop */ andl $3, %eax jz .Lencrypt128_loop subq %rax, %rcx .Lencrypt128_pre: /* 1 block outside of loop */ movdqu (%rdx), %xmm0 pxor -0x30(%rdi), %xmm0, %xmm0 aesenc -0x20(%rdi), %xmm0, %xmm0 aesenc -0x10(%rdi), %xmm0, %xmm0 aesenc 0x00(%rdi), %xmm0, %xmm0 aesenc 0x10(%rdi), %xmm0, %xmm0 aesenc 0x20(%rdi), %xmm0, %xmm0 aesenc 0x30(%rdi), %xmm0, %xmm0 aesenc 0x40(%rdi), %xmm0, %xmm0 aesenc 0x50(%rdi), %xmm0, %xmm0 aesenc 0x60(%rdi), %xmm0, %xmm0 aesenclast 0x70(%rdi), %xmm0, %xmm0 movdqu %xmm0, (%rsi) addq $16, %rdx addq $16, %rsi decl %eax jnz .Lencrypt128_pre .align 16 .Lencrypt128_loop: movdqu 0x00(%rdx), %xmm0 movdqu 0x10(%rdx), %xmm1 movdqu 0x20(%rdx), %xmm2 movdqu 0x30(%rdx), %xmm3 movdqa -0x30(%rdi), %xmm5 movdqa -0x20(%rdi), %xmm6 movdqa -0x10(%rdi), %xmm7 pxor %xmm5, %xmm0, %xmm0 pxor %xmm5, %xmm1, %xmm1 pxor %xmm5, %xmm2, %xmm2 pxor %xmm5, %xmm3, %xmm3 aesenc %xmm6, %xmm0, %xmm0 aesenc %xmm6, %xmm1, %xmm1 aesenc %xmm6, %xmm2, %xmm2 aesenc %xmm6, %xmm3, %xmm3 aesenc %xmm7, %xmm0, %xmm0 aesenc %xmm7, %xmm1, %xmm1 aesenc %xmm7, %xmm2, %xmm2 aesenc %xmm7, %xmm3, %xmm3 movdqa 0x00(%rdi), %xmm4 movdqa 0x10(%rdi), %xmm5 movdqa 0x20(%rdi), %xmm6 movdqa 0x30(%rdi), %xmm7 aesenc %xmm4, %xmm0, %xmm0 aesenc %xmm4, %xmm1, %xmm1 aesenc %xmm4, %xmm2, %xmm2 aesenc %xmm4, %xmm3, %xmm3 aesenc %xmm5, %xmm0, %xmm0 aesenc %xmm5, %xmm1, %xmm1 aesenc %xmm5, %xmm2, %xmm2 aesenc %xmm5, %xmm3, %xmm3 aesenc %xmm6, %xmm0, %xmm0 aesenc %xmm6, %xmm1, %xmm1 aesenc %xmm6, %xmm2, %xmm2 aesenc %xmm6, %xmm3, %xmm3 aesenc %xmm7, %xmm0, %xmm0 aesenc %xmm7, %xmm1, %xmm1 aesenc %xmm7, %xmm2, %xmm2 aesenc %xmm7, %xmm3, %xmm3 movdqa 0x40(%rdi), %xmm4 movdqa 0x50(%rdi), %xmm5 movdqa 0x60(%rdi), %xmm6 movdqa 0x70(%rdi), %xmm7 aesenc %xmm4, %xmm0, %xmm0 aesenc %xmm4, %xmm1, %xmm1 aesenc %xmm4, %xmm2, %xmm2 aesenc %xmm4, %xmm3, %xmm3 aesenc %xmm5, %xmm0, %xmm0 aesenc %xmm5, %xmm1, %xmm1 aesenc %xmm5, %xmm2, %xmm2 aesenc %xmm5, %xmm3, %xmm3 aesenc %xmm6, %xmm0, %xmm0 aesenc %xmm6, %xmm1, %xmm1 aesenc %xmm6, %xmm2, %xmm2 aesenc %xmm6, %xmm3, %xmm3 aesenclast %xmm7, %xmm0, %xmm0 aesenclast %xmm7, %xmm1, %xmm1 aesenclast %xmm7, %xmm2, %xmm2 aesenclast %xmm7, %xmm3, %xmm3 movdqu %xmm0, 0x00(%rsi) movdqu %xmm1, 0x10(%rsi) movdqu %xmm2, 0x20(%rsi) movdqu %xmm3, 0x30(%rsi) addq $64, %rdx addq $64, %rsi subq $4, %rcx jnz .Lencrypt128_loop .align 16 .Lencrypt128_end: movdqa 0x10(%rsp), %xmm7 movdqa 0x00(%rsp), %xmm6 addq $0x28, %rsp ret .align 16 .globl _crypto_aes192_encrypt_aesni .def _crypto_aes192_encrypt_aesni; .scl 2; .type 32; .endef /* void _aes192_encrypt_aesni(const uint32_t* key [%rdi], */ /* uint8_t* dst [%rsi], */ /* const uint8_t* src [%rdx], */ /* size_t length [%rcx]) */ _crypto_aes192_encrypt_aesni: subq $0x28, %rsp vmovdqa %xmm6, 0x00(%rsp) vmovdqa %xmm7, 0x10(%rsp) cmpq $16, %rcx jb .Lencrypt192_end shrq $4, %rcx /* Divide length by 16 */ addq $0x50, %rdi /* Offset key pointer */ movq %rcx, %rax /* Check (length / 16) mod 4, and encrypt that many blocks outside of the loop */ andl $3, %eax jz .Lencrypt192_loop subq %rax, %rcx .Lencrypt192_pre: /* 1 block outside of loop */ vmovdqu (%rdx), %xmm0 vpxor -0x50(%rdi), %xmm0, %xmm0 vaesenc -0x40(%rdi), %xmm0, %xmm0 vaesenc -0x30(%rdi), %xmm0, %xmm0 vaesenc -0x20(%rdi), %xmm0, %xmm0 vaesenc -0x10(%rdi), %xmm0, %xmm0 vaesenc 0x00(%rdi), %xmm0, %xmm0 vaesenc 0x10(%rdi), %xmm0, %xmm0 vaesenc 0x20(%rdi), %xmm0, %xmm0 vaesenc 0x30(%rdi), %xmm0, %xmm0 vaesenc 0x40(%rdi), %xmm0, %xmm0 vaesenc 0x50(%rdi), %xmm0, %xmm0 vaesenc 0x60(%rdi), %xmm0, %xmm0 vaesenclast 0x70(%rdi), %xmm0, %xmm0 vmovdqu %xmm0, (%rsi) addq $16, %rdx addq $16, %rsi decl %eax jnz .Lencrypt192_pre .align 16 .Lencrypt192_loop: vmovdqu 0x00(%rdx), %xmm0 vmovdqu 0x10(%rdx), %xmm1 vmovdqu 0x20(%rdx), %xmm2 vmovdqu 0x30(%rdx), %xmm3 vmovdqa -0x50(%rdi), %xmm7 vpxor %xmm7, %xmm0, %xmm0 vpxor %xmm7, %xmm1, %xmm1 vpxor %xmm7, %xmm2, %xmm2 vpxor %xmm7, %xmm3, %xmm3 vmovdqa -0x40(%rdi), %xmm4 vmovdqa -0x30(%rdi), %xmm5 vmovdqa -0x20(%rdi), %xmm6 vmovdqa -0x10(%rdi), %xmm7 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 vaesenc %xmm5, %xmm0, %xmm0 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm7, %xmm0, %xmm0 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 vmovdqa 0x00(%rdi), %xmm4 vmovdqa 0x10(%rdi), %xmm5 vmovdqa 0x20(%rdi), %xmm6 vmovdqa 0x30(%rdi), %xmm7 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 vaesenc %xmm5, %xmm0, %xmm0 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm7, %xmm0, %xmm0 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 vmovdqa 0x40(%rdi), %xmm4 vmovdqa 0x50(%rdi), %xmm5 vmovdqa 0x60(%rdi), %xmm6 vmovdqa 0x70(%rdi), %xmm7 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 vaesenc %xmm5, %xmm0, %xmm0 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenclast %xmm7, %xmm0, %xmm0 vaesenclast %xmm7, %xmm1, %xmm1 vaesenclast %xmm7, %xmm2, %xmm2 vaesenclast %xmm7, %xmm3, %xmm3 vmovdqu %xmm0, 0x00(%rsi) vmovdqu %xmm1, 0x10(%rsi) vmovdqu %xmm2, 0x20(%rsi) vmovdqu %xmm3, 0x30(%rsi) addq $64, %rdx addq $64, %rsi subq $4, %rcx ja .Lencrypt192_loop .align 16 .Lencrypt192_end: vmovdqa 0x10(%rsp), %xmm7 vmovdqa 0x00(%rsp), %xmm6 addq $0x28, %rsp ret .align 16 .globl _crypto_aes256_encrypt_aesni .def _crypto_aes256_encrypt_aesni; .scl 2; .type 32; .endef /* void _aes256_encrypt_aesni(const uint32_t* key [%rdi], */ /* uint8_t* dst [%rsi], */ /* const uint8_t* src [%rdx], */ /* size_t length [%rcx]) */ _crypto_aes256_encrypt_aesni: subq $0x28, %rsp vmovdqa %xmm6, 0x00(%rsp) vmovdqa %xmm7, 0x10(%rsp) cmpq $16, %rcx jb .Lencrypt256_end shrq $4, %rcx /* Divide length by 16 */ addq $0x70, %rdi /* Offset key pointer */ movq %rcx, %rax /* Check (length / 16) mod 4, and encrypt that many blocks outside of the loop */ andl $3, %eax jz .Lencrypt256_loop subq %rax, %rcx .Lencrypt256_pre: /* 1 block outside of loop */ vmovdqu (%rdx), %xmm0 vpxor -0x70(%rdi), %xmm0, %xmm0 vaesenc -0x60(%rdi), %xmm0, %xmm0 vaesenc -0x50(%rdi), %xmm0, %xmm0 vaesenc -0x40(%rdi), %xmm0, %xmm0 vaesenc -0x30(%rdi), %xmm0, %xmm0 vaesenc -0x20(%rdi), %xmm0, %xmm0 vaesenc -0x10(%rdi), %xmm0, %xmm0 vaesenc 0x00(%rdi), %xmm0, %xmm0 vaesenc 0x10(%rdi), %xmm0, %xmm0 vaesenc 0x20(%rdi), %xmm0, %xmm0 vaesenc 0x30(%rdi), %xmm0, %xmm0 vaesenc 0x40(%rdi), %xmm0, %xmm0 vaesenc 0x50(%rdi), %xmm0, %xmm0 vaesenc 0x60(%rdi), %xmm0, %xmm0 vaesenclast 0x70(%rdi), %xmm0, %xmm0 vmovdqu %xmm0, (%rsi) addq $16, %rdx addq $16, %rsi decl %eax jnz .Lencrypt256_pre .align 16 .Lencrypt256_loop: vmovdqu 0x00(%rdx), %xmm0 vmovdqu 0x10(%rdx), %xmm1 vmovdqu 0x20(%rdx), %xmm2 vmovdqu 0x30(%rdx), %xmm3 vmovdqa -0x70(%rdi), %xmm5 vmovdqa -0x60(%rdi), %xmm6 vmovdqa -0x50(%rdi), %xmm7 vpxor %xmm5, %xmm0, %xmm0 vpxor %xmm5, %xmm1, %xmm1 vpxor %xmm5, %xmm2, %xmm2 vpxor %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm7, %xmm0, %xmm0 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 vmovdqa -0x40(%rdi), %xmm4 vmovdqa -0x30(%rdi), %xmm5 vmovdqa -0x20(%rdi), %xmm6 vmovdqa -0x10(%rdi), %xmm7 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 vaesenc %xmm5, %xmm0, %xmm0 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm7, %xmm0, %xmm0 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 vmovdqa 0x00(%rdi), %xmm4 vmovdqa 0x10(%rdi), %xmm5 vmovdqa 0x20(%rdi), %xmm6 vmovdqa 0x30(%rdi), %xmm7 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 vaesenc %xmm5, %xmm0, %xmm0 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenc %xmm7, %xmm0, %xmm0 vaesenc %xmm7, %xmm1, %xmm1 vaesenc %xmm7, %xmm2, %xmm2 vaesenc %xmm7, %xmm3, %xmm3 vmovdqa 0x40(%rdi), %xmm4 vmovdqa 0x50(%rdi), %xmm5 vmovdqa 0x60(%rdi), %xmm6 vmovdqa 0x70(%rdi), %xmm7 vaesenc %xmm4, %xmm0, %xmm0 vaesenc %xmm4, %xmm1, %xmm1 vaesenc %xmm4, %xmm2, %xmm2 vaesenc %xmm4, %xmm3, %xmm3 vaesenc %xmm5, %xmm0, %xmm0 vaesenc %xmm5, %xmm1, %xmm1 vaesenc %xmm5, %xmm2, %xmm2 vaesenc %xmm5, %xmm3, %xmm3 vaesenc %xmm6, %xmm0, %xmm0 vaesenc %xmm6, %xmm1, %xmm1 vaesenc %xmm6, %xmm2, %xmm2 vaesenc %xmm6, %xmm3, %xmm3 vaesenclast %xmm7, %xmm0, %xmm0 vaesenclast %xmm7, %xmm1, %xmm1 vaesenclast %xmm7, %xmm2, %xmm2 vaesenclast %xmm7, %xmm3, %xmm3 vmovdqu %xmm0, 0x00(%rsi) vmovdqu %xmm1, 0x10(%rsi) vmovdqu %xmm2, 0x20(%rsi) vmovdqu %xmm3, 0x30(%rsi) addq $64, %rdx addq $64, %rsi subq $4, %rcx ja .Lencrypt256_loop .align 16 .Lencrypt256_end: vmovdqa 0x10(%rsp), %xmm7 vmovdqa 0x00(%rsp), %xmm6 addq $0x28, %rsp ret .align 16 .globl _crypto_aes128_decrypt_aesni .def _crypto_aes128_decrypt_aesni; .scl 2; .type 32; .endef /* void _aes128_decrypt_aesni(const uint32_t* key [%rdi], */ /* uint8_t* dst [%rsi], */ /* const uint8_t* src [%rdx], */ /* size_t length [%rcx]) */ _crypto_aes128_decrypt_aesni: subq $0x28, %rsp vmovdqa %xmm6, 0x00(%rsp) vmovdqa %xmm7, 0x10(%rsp) cmpq $16, %rcx jb .Ldecrypt128_end shrq $4, %rcx /* Divide length by 16 */ addq $0x30, %rdi /* Offset key pointer */ movq %rcx, %rax /* Check (length / 16) mod 4, and encrypt that many blocks outside of the loop */ andl $3, %eax jz .Ldecrypt128_loop subq %rax, %rcx .Ldecrypt128_pre: /* 1 block outside of loop */ vmovdqu (%rdx), %xmm0 vpxor 0x70(%rdi), %xmm0, %xmm0 vaesdec 0x60(%rdi), %xmm0, %xmm0 vaesdec 0x50(%rdi), %xmm0, %xmm0 vaesdec 0x40(%rdi), %xmm0, %xmm0 vaesdec 0x30(%rdi), %xmm0, %xmm0 vaesdec 0x20(%rdi), %xmm0, %xmm0 vaesdec 0x10(%rdi), %xmm0, %xmm0 vaesdec 0x00(%rdi), %xmm0, %xmm0 vaesdec -0x10(%rdi), %xmm0, %xmm0 vaesdec -0x20(%rdi), %xmm0, %xmm0 vaesdeclast -0x30(%rdi), %xmm0, %xmm0 vmovdqu %xmm0, (%rsi) addq $16, %rdx addq $16, %rsi decl %eax jnz .Ldecrypt128_pre .align 16 .Ldecrypt128_loop: vmovdqu 0x00(%rdx), %xmm0 vmovdqu 0x10(%rdx), %xmm1 vmovdqu 0x20(%rdx), %xmm2 vmovdqu 0x30(%rdx), %xmm3 vmovdqa 0x70(%rdi), %xmm5 vmovdqa 0x60(%rdi), %xmm6 vmovdqa 0x50(%rdi), %xmm7 vpxor %xmm5, %xmm0, %xmm0 vpxor %xmm5, %xmm1, %xmm1 vpxor %xmm5, %xmm2, %xmm2 vpxor %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa 0x40(%rdi), %xmm4 vmovdqa 0x30(%rdi), %xmm5 vmovdqa 0x20(%rdi), %xmm6 vmovdqa 0x10(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa -0x00(%rdi), %xmm4 vmovdqa -0x10(%rdi), %xmm5 vmovdqa -0x20(%rdi), %xmm6 vmovdqa -0x30(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdeclast %xmm7, %xmm0, %xmm0 vaesdeclast %xmm7, %xmm1, %xmm1 vaesdeclast %xmm7, %xmm2, %xmm2 vaesdeclast %xmm7, %xmm3, %xmm3 vmovdqu %xmm0, 0x00(%rsi) vmovdqu %xmm1, 0x10(%rsi) vmovdqu %xmm2, 0x20(%rsi) vmovdqu %xmm3, 0x30(%rsi) addq $64, %rdx addq $64, %rsi subq $4, %rcx jnz .Ldecrypt128_loop .align 16 .Ldecrypt128_end: vmovdqa 0x10(%rsp), %xmm7 vmovdqa 0x00(%rsp), %xmm6 addq $0x28, %rsp ret .align 16 .globl _crypto_aes192_decrypt_aesni .def _crypto_aes192_decrypt_aesni; .scl 2; .type 32; .endef /* void _aes192_decrypt_aesni(const uint32_t* key [%rdi], */ /* uint8_t* dst [%rsi], */ /* const uint8_t* src [%rdx], */ /* size_t length [%rcx]) */ _crypto_aes192_decrypt_aesni: subq $0x28, %rsp vmovdqa %xmm6, 0x00(%rsp) vmovdqa %xmm7, 0x10(%rsp) cmpq $16, %rcx jb .Ldecrypt192_end shrq $4, %rcx /* Divide length by 16 */ addq $0x50, %rdi /* Offset key pointer */ movq %rcx, %rax /* Check (length / 16) mod 4, and decrypt that many blocks outside of the loop */ andl $3, %eax jz .Ldecrypt192_loop subq %rax, %rcx .Ldecrypt192_pre: /* 1 block outside of loop */ vmovdqu (%rdx), %xmm0 vpxor 0x70(%rdi), %xmm0, %xmm0 vaesdec 0x60(%rdi), %xmm0, %xmm0 vaesdec 0x50(%rdi), %xmm0, %xmm0 vaesdec 0x40(%rdi), %xmm0, %xmm0 vaesdec 0x30(%rdi), %xmm0, %xmm0 vaesdec 0x20(%rdi), %xmm0, %xmm0 vaesdec 0x10(%rdi), %xmm0, %xmm0 vaesdec 0x00(%rdi), %xmm0, %xmm0 vaesdec -0x10(%rdi), %xmm0, %xmm0 vaesdec -0x20(%rdi), %xmm0, %xmm0 vaesdec -0x30(%rdi), %xmm0, %xmm0 vaesdec -0x40(%rdi), %xmm0, %xmm0 vaesdeclast -0x50(%rdi), %xmm0, %xmm0 vmovdqu %xmm0, (%rsi) addq $16, %rdx addq $16, %rsi decl %eax jnz .Ldecrypt192_pre .align 16 .Ldecrypt192_loop: vmovdqu 0x00(%rdx), %xmm0 vmovdqu 0x10(%rdx), %xmm1 vmovdqu 0x20(%rdx), %xmm2 vmovdqu 0x30(%rdx), %xmm3 vmovdqa 0x70(%rdi), %xmm7 vpxor %xmm7, %xmm0, %xmm0 vpxor %xmm7, %xmm1, %xmm1 vpxor %xmm7, %xmm2, %xmm2 vpxor %xmm7, %xmm3, %xmm3 vmovdqa 0x60(%rdi), %xmm4 vmovdqa 0x50(%rdi), %xmm5 vmovdqa 0x40(%rdi), %xmm6 vmovdqa 0x30(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa 0x20(%rdi), %xmm4 vmovdqa 0x10(%rdi), %xmm5 vmovdqa 0x00(%rdi), %xmm6 vmovdqa -0x10(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa -0x20(%rdi), %xmm4 vmovdqa -0x30(%rdi), %xmm5 vmovdqa -0x40(%rdi), %xmm6 vmovdqa -0x50(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdeclast %xmm7, %xmm0, %xmm0 vaesdeclast %xmm7, %xmm1, %xmm1 vaesdeclast %xmm7, %xmm2, %xmm2 vaesdeclast %xmm7, %xmm3, %xmm3 vmovdqu %xmm0, 0x00(%rsi) vmovdqu %xmm1, 0x10(%rsi) vmovdqu %xmm2, 0x20(%rsi) vmovdqu %xmm3, 0x30(%rsi) addq $64, %rdx addq $64, %rsi subq $4, %rcx ja .Ldecrypt192_loop .align 16 .Ldecrypt192_end: vmovdqa 0x10(%rsp), %xmm7 vmovdqa 0x00(%rsp), %xmm6 addq $0x28, %rsp ret .align 16 .globl _crypto_aes256_decrypt_aesni .def _crypto_aes256_decrypt_aesni; .scl 2; .type 32; .endef /* void _aes256_decrypt_aesni(const uint32_t* key [%rdi], */ /* uint8_t* dst [%rsi], */ /* const uint8_t* src [%rdx], */ /* size_t length [%rcx]) */ _crypto_aes256_decrypt_aesni: subq $0x28, %rsp vmovdqa %xmm6, 0x00(%rsp) vmovdqa %xmm7, 0x10(%rsp) cmpq $16, %rcx jb .Ldecrypt256_end shrq $4, %rcx /* Divide length by 16 */ addq $0x70, %rdi /* Offset key pointer */ movq %rcx, %rax /* Check (length / 16) mod 4, and decrypt that many blocks outside of the loop */ andl $3, %eax jz .Ldecrypt256_loop subq %rax, %rcx .Ldecrypt256_pre: /* 1 block outside of loop */ vmovdqu (%rdx), %xmm0 vpxor 0x70(%rdi), %xmm0, %xmm0 vaesdec 0x60(%rdi), %xmm0, %xmm0 vaesdec 0x50(%rdi), %xmm0, %xmm0 vaesdec 0x40(%rdi), %xmm0, %xmm0 vaesdec 0x30(%rdi), %xmm0, %xmm0 vaesdec 0x20(%rdi), %xmm0, %xmm0 vaesdec 0x10(%rdi), %xmm0, %xmm0 vaesdec 0x00(%rdi), %xmm0, %xmm0 vaesdec -0x10(%rdi), %xmm0, %xmm0 vaesdec -0x20(%rdi), %xmm0, %xmm0 vaesdec -0x30(%rdi), %xmm0, %xmm0 vaesdec -0x40(%rdi), %xmm0, %xmm0 vaesdec -0x50(%rdi), %xmm0, %xmm0 vaesdec -0x60(%rdi), %xmm0, %xmm0 vaesdeclast -0x70(%rdi), %xmm0, %xmm0 vmovdqu %xmm0, (%rsi) addq $16, %rdx addq $16, %rsi decl %eax jnz .Ldecrypt256_pre .align 16 .Ldecrypt256_loop: vmovdqu 0x00(%rdx), %xmm0 vmovdqu 0x10(%rdx), %xmm1 vmovdqu 0x20(%rdx), %xmm2 vmovdqu 0x30(%rdx), %xmm3 vmovdqa 0x70(%rdi), %xmm5 vmovdqa 0x60(%rdi), %xmm6 vmovdqa 0x50(%rdi), %xmm7 vpxor %xmm5, %xmm0, %xmm0 vpxor %xmm5, %xmm1, %xmm1 vpxor %xmm5, %xmm2, %xmm2 vpxor %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa 0x40(%rdi), %xmm4 vmovdqa 0x30(%rdi), %xmm5 vmovdqa 0x20(%rdi), %xmm6 vmovdqa 0x10(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa -0x00(%rdi), %xmm4 vmovdqa -0x10(%rdi), %xmm5 vmovdqa -0x20(%rdi), %xmm6 vmovdqa -0x30(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdec %xmm7, %xmm0, %xmm0 vaesdec %xmm7, %xmm1, %xmm1 vaesdec %xmm7, %xmm2, %xmm2 vaesdec %xmm7, %xmm3, %xmm3 vmovdqa -0x40(%rdi), %xmm4 vmovdqa -0x50(%rdi), %xmm5 vmovdqa -0x60(%rdi), %xmm6 vmovdqa -0x70(%rdi), %xmm7 vaesdec %xmm4, %xmm0, %xmm0 vaesdec %xmm4, %xmm1, %xmm1 vaesdec %xmm4, %xmm2, %xmm2 vaesdec %xmm4, %xmm3, %xmm3 vaesdec %xmm5, %xmm0, %xmm0 vaesdec %xmm5, %xmm1, %xmm1 vaesdec %xmm5, %xmm2, %xmm2 vaesdec %xmm5, %xmm3, %xmm3 vaesdec %xmm6, %xmm0, %xmm0 vaesdec %xmm6, %xmm1, %xmm1 vaesdec %xmm6, %xmm2, %xmm2 vaesdec %xmm6, %xmm3, %xmm3 vaesdeclast %xmm7, %xmm0, %xmm0 vaesdeclast %xmm7, %xmm1, %xmm1 vaesdeclast %xmm7, %xmm2, %xmm2 vaesdeclast %xmm7, %xmm3, %xmm3 vmovdqu %xmm0, 0x00(%rsi) vmovdqu %xmm1, 0x10(%rsi) vmovdqu %xmm2, 0x20(%rsi) vmovdqu %xmm3, 0x30(%rsi) addq $64, %rdx addq $64, %rsi subq $4, %rcx ja .Ldecrypt256_loop .align 16 .Ldecrypt256_end: vmovdqa 0x10(%rsp), %xmm7 vmovdqa 0x00(%rsp), %xmm6 addq $0x28, %rsp ret
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/blockchain.h> #include <amount.h> #include <chain.h> #include <chainparams.h> #include <checkpoints.h> #include <coins.h> #include <consensus/validation.h> #include <validation.h> #include <core_io.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <rpc/server.h> #include <streams.h> #include <sync.h> #include <txdb.h> #include <txmempool.h> #include <util.h> #include <utilstrencodings.h> #include <hash.h> #include <validationinterface.h> #include <warnings.h> #include <stdint.h> #include <univalue.h> #include <miner.h> #include <kernel.h> #include <boost/thread/thread.hpp> // boost::thread::interrupt #include <memory> #include <mutex> #include <condition_variable> struct CUpdatedBlock { uint256 hash; int height; }; static std::mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry); /* Calculate the difficulty for a given block index, * or the block index of the given chain. */ double GetDifficulty(const CChain& chain, const CBlockIndex* blockindex) { if (blockindex == nullptr) { if (chain.Tip() == nullptr) return 1.0; else blockindex = GetLastBlockIndex(chain.Tip(), false); } return blockindex->GetBlockDifficulty(); } double GetDifficulty(const CBlockIndex* blockindex) { return GetDifficulty(chainActive, blockindex); } UniValue blockheaderToJSON(const CBlockIndex* blockindex) { AssertLockHeld(cs_main); UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", blockindex->nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion))); result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex())); result.push_back(Pair("time", (int64_t)blockindex->nTime)); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce)); result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainTrust.GetHex())); result.push_back(Pair("nTx", (uint64_t)blockindex->nTx)); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails) { AssertLockHeld(cs_main); UniValue result(UniValue::VOBJ); result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("strippedsize", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS))); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("weight", (int)::GetBlockWeight(block))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("npowblockheight", blockindex->nPOWBlockHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion))); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("time", (boost::uint64_t)block.GetBlockTime())); result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("chainwork", blockindex->nChainTrust.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work"))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake() ? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("modifier", blockindex->bnStakeModifier.GetHex())); result.push_back(Pair("blocksignature", HexStr(block.vchBlockSig))); UniValue txs(UniValue::VARR); for (const auto& tx : block.vtx) { if(txDetails) { UniValue objTx(UniValue::VOBJ); TxToJSON(*tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx->GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("nTx", (uint64_t)blockindex->nTx)); return result; } UniValue getblockcount(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest blockchain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } UniValue getbestblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest blockchain.\n" "\nResult:\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples:\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } void RPCNotifyBlockChange(bool ibd, const CBlockIndex * pindex) { if(pindex) { std::lock_guard<std::mutex> lock(cs_blockchange); latestblock.hash = pindex->GetBlockHash(); latestblock.height = pindex->nHeight; } cond_blockchange.notify_all(); } UniValue waitfornewblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "waitfornewblock (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitfornewblock", "1000") + HelpExampleRpc("waitfornewblock", "1000") ); int timeout = 0; if (!request.params[0].isNull()) timeout = request.params[0].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); block = latestblock; if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); else cond_blockchange.wait(lock, [&block]{return latestblock.height != block.height || latestblock.hash != block.hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "waitforblock <blockhash> (timeout)\n" "\nWaits for a specific new block and returns useful info about it.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. \"blockhash\" (required, string) Block hash to wait for.\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") + HelpExampleRpc("waitforblock", "\"0000000000079f8ef3d2c688c244eb7a4570b24c9ed7b4a8c619eb02596f8862\", 1000") ); int timeout = 0; uint256 hash = uint256S(request.params[0].get_str()); if (!request.params[1].isNull()) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&hash]{return latestblock.hash == hash || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&hash]{return latestblock.hash == hash || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue waitforblockheight(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "waitforblockheight <height> (timeout)\n" "\nWaits for (at least) block height and returns the height and hash\n" "of the current tip.\n" "\nReturns the current block on timeout or exit.\n" "\nArguments:\n" "1. height (required, int) Block height to wait for (int)\n" "2. timeout (int, optional, default=0) Time in milliseconds to wait for a response. 0 indicates no timeout.\n" "\nResult:\n" "{ (json object)\n" " \"hash\" : { (string) The blockhash\n" " \"height\" : { (int) Block height\n" "}\n" "\nExamples:\n" + HelpExampleCli("waitforblockheight", "\"100\", 1000") + HelpExampleRpc("waitforblockheight", "\"100\", 1000") ); int timeout = 0; int height = request.params[0].get_int(); if (!request.params[1].isNull()) timeout = request.params[1].get_int(); CUpdatedBlock block; { std::unique_lock<std::mutex> lock(cs_blockchange); if(timeout) cond_blockchange.wait_for(lock, std::chrono::milliseconds(timeout), [&height]{return latestblock.height >= height || !IsRPCRunning();}); else cond_blockchange.wait(lock, [&height]{return latestblock.height >= height || !IsRPCRunning(); }); block = latestblock; } UniValue ret(UniValue::VOBJ); ret.push_back(Pair("hash", block.hash.GetHex())); ret.push_back(Pair("height", block.height)); return ret; } UniValue syncwithvalidationinterfacequeue(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 0) { throw std::runtime_error( "syncwithvalidationinterfacequeue\n" "\nWaits for the validation interface queue to catch up on everything that was there when we entered this function.\n" "\nExamples:\n" + HelpExampleCli("syncwithvalidationinterfacequeue","") + HelpExampleRpc("syncwithvalidationinterfacequeue","") ); } SyncWithValidationInterfaceQueue(); return NullUniValue; } UniValue getdifficulty(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getdifficulty\n" "\nReturns the difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("proof-of-work", GetDifficulty(NULL))); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(chainActive.Tip(), true)))); return obj; } std::string EntryDescriptionString() { return " \"size\" : n, (numeric) virtual transaction size as defined in BIP 141. This is different from actual serialized size for witness transactions as witness data is discounted.\n" " \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n" " \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n" " \"descendantsize\" : n, (numeric) virtual transaction size of in-mempool descendants (including this one)\n" " \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n" " \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n" " \"ancestorsize\" : n, (numeric) virtual transaction size of in-mempool ancestors (including this one)\n" " \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n" " \"wtxid\" : hash, (string) hash of serialized transaction, including witness data\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n"; } void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) { AssertLockHeld(mempool.cs); info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("descendantcount", e.GetCountWithDescendants())); info.push_back(Pair("descendantsize", e.GetSizeWithDescendants())); info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants())); info.push_back(Pair("ancestorcount", e.GetCountWithAncestors())); info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors())); info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors())); info.push_back(Pair("wtxid", mempool.vTxHashes[e.vTxHashesIdx].first.ToString())); const CTransaction& tx = e.GetTx(); std::set<std::string> setDepends; for (const CTxIn& txin : tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } UniValue depends(UniValue::VARR); for (const std::string& dep : setDepends) { depends.push_back(dep); } info.push_back(Pair("depends", depends)); } UniValue mempoolToJSON(bool fVerbose) { if (fVerbose) { LOCK(mempool.cs); UniValue o(UniValue::VOBJ); for (const CTxMemPoolEntry& e : mempool.mapTx) { const uint256& hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(hash.ToString(), info)); } return o; } else { std::vector<uint256> vtxid; mempool.queryHashes(vtxid); UniValue a(UniValue::VARR); for (const uint256& hash : vtxid) a.push_back(hash.ToString()); return a; } } UniValue getrawmempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nHint: use getmempoolentry to fetch a specific transaction from the mempool.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); bool fVerbose = false; if (!request.params[0].isNull()) fVerbose = request.params[0].get_bool(); return mempoolToJSON(fVerbose); } UniValue getmempoolancestors(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "getmempoolancestors txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool ancestors.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolancestors", "\"mytxid\"") + HelpExampleRpc("getmempoolancestors", "\"mytxid\"") ); } bool fVerbose = false; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setAncestors; uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false); if (!fVerbose) { UniValue o(UniValue::VARR); for (CTxMemPool::txiter ancestorIt : setAncestors) { o.push_back(ancestorIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); for (CTxMemPool::txiter ancestorIt : setAncestors) { const CTxMemPoolEntry &e = *ancestorIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempooldescendants(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { throw std::runtime_error( "getmempooldescendants txid (verbose)\n" "\nIf txid is in the mempool, returns all in-mempool descendants.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "2. verbose (boolean, optional, default=false) True for a json object, false for array of transaction ids\n" "\nResult (for verbose=false):\n" "[ (json array of strings)\n" " \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n" " ,...\n" "]\n" "\nResult (for verbose=true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" + EntryDescriptionString() + " }, ...\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempooldescendants", "\"mytxid\"") + HelpExampleRpc("getmempooldescendants", "\"mytxid\"") ); } bool fVerbose = false; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } CTxMemPool::setEntries setDescendants; mempool.CalculateDescendants(it, setDescendants); // CTxMemPool::CalculateDescendants will include the given tx setDescendants.erase(it); if (!fVerbose) { UniValue o(UniValue::VARR); for (CTxMemPool::txiter descendantIt : setDescendants) { o.push_back(descendantIt->GetTx().GetHash().ToString()); } return o; } else { UniValue o(UniValue::VOBJ); for (CTxMemPool::txiter descendantIt : setDescendants) { const CTxMemPoolEntry &e = *descendantIt; const uint256& _hash = e.GetTx().GetHash(); UniValue info(UniValue::VOBJ); entryToJSON(info, e); o.push_back(Pair(_hash.ToString(), info)); } return o; } } UniValue getmempoolentry(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) { throw std::runtime_error( "getmempoolentry txid\n" "\nReturns mempool data for given transaction\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id (must be in mempool)\n" "\nResult:\n" "{ (json object)\n" + EntryDescriptionString() + "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolentry", "\"mytxid\"") + HelpExampleRpc("getmempoolentry", "\"mytxid\"") ); } uint256 hash = ParseHashV(request.params[0], "parameter 1"); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); if (it == mempool.mapTx.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool"); } const CTxMemPoolEntry &e = *it; UniValue info(UniValue::VOBJ); entryToJSON(info, e); return info; } UniValue getblockhash(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "getblockhash height\n" "\nReturns hash of block in best-block-chain at height provided.\n" "\nArguments:\n" "1. height (numeric, required) The height index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } UniValue getblockheader(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "getblockheader \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n" "If verbose is true, returns an Object with information about blockheader <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n" " \"nTx\" : n, (numeric) The number of transactions in the block.\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\", (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (!request.params[1].isNull()) fVerbose = request.params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockheaderToJSON(pblockindex); } UniValue getblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( "getblock \"blockhash\" ( verbosity ) \n" "\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbosity is 1, returns an Object with information about block <hash>.\n" "If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n" "\nArguments:\n" "1. \"blockhash\" (string, required) The block hash\n" "2. verbosity (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n" "\nResult (for verbosity = 0):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nResult (for verbosity = 1):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"strippedsize\" : n, (numeric) The block size excluding witness data\n" " \"weight\" : n (numeric) The block weight as defined in BIP 141\n" " \"height\" : n, (numeric) The block height or index\n" " \"npowblockheight\" : n, (numeric) The pow block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n" " \"nTx\" : n, (numeric) The number of transactions in the block.\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbosity = 2):\n" "{\n" " ..., Same output as verbosity = 1.\n" " \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n" " ,...\n" " ],\n" " ,... Same output as verbosity = 1.\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int verbosity = 1; if (!request.params[1].isNull()) { if(request.params[1].isNum()) verbosity = request.params[1].get_int(); else verbosity = request.params[1].get_bool() ? 1 : 0; } if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) // Block not found on disk. This could be because we have the block // header in our index but don't have the block (for example if a // non-whitelisted node sends us an unrequested long chain of valid // blocks, we add the headers to our index, but don't accept the // block). throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk"); if (verbosity <= 0) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags()); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex, verbosity >= 2); } struct CCoinsStats { int nHeight; uint256 hashBlock; uint64_t nTransactions; uint64_t nTransactionOutputs; uint64_t nBogoSize; uint256 hashSerialized; uint64_t nDiskSize; CAmount nTotalAmount; CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nBogoSize(0), nDiskSize(0), nTotalAmount(0) {} }; static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs) { assert(!outputs.empty()); ss << hash; ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase); stats.nTransactions++; for (const auto output : outputs) { ss << VARINT(output.first + 1); ss << output.second.out.scriptPubKey; ss << VARINT(output.second.out.nValue); stats.nTransactionOutputs++; stats.nTotalAmount += output.second.out.nValue; stats.nBogoSize += 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ + 8 /* amount */ + 2 /* scriptPubKey len */ + output.second.out.scriptPubKey.size() /* scriptPubKey */; } ss << VARINT(0); } //! Calculate statistics about the unspent transaction output set static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats) { std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor()); assert(pcursor); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = pcursor->GetBestBlock(); { LOCK(cs_main); stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight; } ss << stats.hashBlock; uint256 prevkey; std::map<uint32_t, Coin> outputs; while (pcursor->Valid()) { boost::this_thread::interruption_point(); COutPoint key; Coin coin; if (pcursor->GetKey(key) && pcursor->GetValue(coin)) { if (!outputs.empty() && key.hash != prevkey) { ApplyStats(stats, ss, prevkey, outputs); outputs.clear(); } prevkey = key.hash; outputs[key.n] = std::move(coin); } else { return error("%s: unable to read value", __func__); } pcursor->Next(); } if (!outputs.empty()) { ApplyStats(stats, ss, prevkey, outputs); } stats.hashSerialized = ss.GetHash(); stats.nDiskSize = view->EstimateSize(); return true; } UniValue gettxoutsetinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) The hash of the block at the tip of the chain\n" " \"transactions\": n, (numeric) The number of transactions with unspent outputs\n" " \"txouts\": n, (numeric) The number of unspent transaction outputs\n" " \"bogosize\": n, (numeric) A meaningless metric for UTXO set size\n" " \"hash_serialized_2\": \"hash\", (string) The serialized hash\n" " \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); UniValue ret(UniValue::VOBJ); CCoinsStats stats; FlushStateToDisk(); if (GetUTXOStats(pcoinsdbview.get(), stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bogosize", (int64_t)stats.nBogoSize)); ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex())); ret.push_back(Pair("disk_size", stats.nDiskSize)); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } else { throw JSONRPCError(RPC_INTERNAL_ERROR, "Unable to read UTXO set"); } return ret; } UniValue gettxout(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) throw std::runtime_error( "gettxout \"txid\" n ( include_mempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. \"n\" (numeric, required) vout number\n" "3. \"include_mempool\" (boolean, optional) Whether to include the mempool. Default: true." " Note that an unspent output that is spent in the mempool won't appear.\n" "\nResult:\n" "{\n" " \"bestblock\": \"hash\", (string) The hash of the block at the tip of the chain\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of violette addresses\n" " \"address\" (string) violette address\n" " ,...\n" " ]\n" " },\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); UniValue ret(UniValue::VOBJ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); int n = request.params[1].get_int(); COutPoint out(hash, n); bool fMempool = true; if (!request.params[2].isNull()) fMempool = request.params[2].get_bool(); Coin coin; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip.get(), mempool); if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { return NullUniValue; } } else { if (!pcoinsTip->GetCoin(out, coin)) { return NullUniValue; } } BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if (coin.nHeight == MEMPOOL_HEIGHT) { ret.push_back(Pair("confirmations", 0)); } else { ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1))); } ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue))); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(coin.out.scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("coinbase", (bool)coin.fCoinBase)); return ret; } UniValue verifychain(const JSONRPCRequest& request) { int nCheckLevel = gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL); int nCheckDepth = gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS); if (request.fHelp || request.params.size() > 2) throw std::runtime_error( "verifychain ( checklevel nblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n" "2. nblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); if (!request.params[0].isNull()) nCheckLevel = request.params[0].get_int(); if (!request.params[1].isNull()) nCheckDepth = request.params[1].get_int(); return CVerifyDB().VerifyDB(Params(), pcoinsTip.get(), nCheckLevel, nCheckDepth); } /** Implementation of IsSuperMajority with better feedback */ static UniValue SoftForkMajorityDesc(int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); bool activated = false; switch(version) { case 2: activated = pindex->nHeight >= consensusParams.BIP34Height; break; case 3: activated = true; break; case 4: activated = true; break; } rv.push_back(Pair("status", activated)); return rv; } static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams) { UniValue rv(UniValue::VOBJ); rv.push_back(Pair("id", name)); rv.push_back(Pair("version", version)); rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams))); return rv; } UniValue getblockchaininfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding blockchain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"mediantime\": xxxxxx, (numeric) median time for the current best block\n" " \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n" " \"initialblockdownload\": xxxx, (bool) (debug information) estimate of whether this node is in Initial Block Download mode.\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" " \"size_on_disk\": xxxxxx, (numeric) the estimated size of the block and undo files on disk\n" " \"softforks\": [ (array) status of softforks in progress\n" " {\n" " \"id\": \"xxxx\", (string) name of softfork\n" " \"version\": xx, (numeric) block version\n" " \"reject\": { (object) progress toward rejecting pre-softfork blocks\n" " \"status\": xx, (boolean) true if threshold reached\n" " },\n" " }, ...\n" " ],\n" " \"warnings\" : \"...\", (string) any network and blockchain warnings.\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast())); obj.push_back(Pair("verificationprogress", GuessVerificationProgress(Params().TxData(), chainActive.Tip()))); obj.push_back(Pair("initialblockdownload", IsInitialBlockDownload())); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainTrust.GetHex())); obj.push_back(Pair("size_on_disk", CalculateCurrentUsage())); const Consensus::Params& consensusParams = Params().GetConsensus(); CBlockIndex* tip = chainActive.Tip(); UniValue softforks(UniValue::VARR); softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams)); softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams)); obj.push_back(Pair("softforks", softforks)); obj.push_back(Pair("warnings", GetWarnings("statusbar"))); return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; UniValue getchaintips(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. * - add chainActive.Tip() */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; std::set<const CBlockIndex*> setOrphans; std::set<const CBlockIndex*> setPrevs; for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) { if (!chainActive.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } } for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it) { if (setPrevs.erase(*it) == 0) { setTips.insert(*it); } } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); for (const CBlockIndex* block : setTips) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); std::string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } UniValue mempoolInfoToJSON() { UniValue ret(UniValue::VOBJ); ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage())); size_t maxmempool = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; ret.push_back(Pair("maxmempool", (int64_t) maxmempool)); return ret; } UniValue getmempoolinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx, (numeric) Current tx count\n" " \"bytes\": xxxxx, (numeric) Sum of all virtual transaction sizes as defined in BIP 141. Differs from actual serialized size because witness data is discounted\n" " \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n" " \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n" " \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted. Is the maximum of minrelaytxfee and minimum mempool fee\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); return mempoolInfoToJSON(); } UniValue preciousblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "preciousblock \"blockhash\"\n" "\nTreats a block as if it were received before others with the same work.\n" "\nA later preciousblock call can override the effect of an earlier one.\n" "\nThe effects of preciousblock are not retained across restarts.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as precious\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("preciousblock", "\"blockhash\"") + HelpExampleRpc("preciousblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CBlockIndex* pblockindex; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hash]; } CValidationState state; PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue invalidateblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "invalidateblock \"blockhash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, Params(), pblockindex); } if (state.IsValid()) { ActivateBestChain(state, Params()); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue reconsiderblock(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 1) throw std::runtime_error( "reconsiderblock \"blockhash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. \"blockhash\" (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = request.params[0].get_str(); uint256 hash(uint256S(strHash)); { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ResetBlockFailureFlags(pblockindex); } CValidationState state; ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return NullUniValue; } UniValue getchaintxstats(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 2) throw std::runtime_error( "getchaintxstats ( nblocks blockhash )\n" "\nCompute statistics about the total number and rate of transactions in the chain.\n" "\nArguments:\n" "1. nblocks (numeric, optional) Size of the window in number of blocks (default: one month).\n" "2. \"blockhash\" (string, optional) The hash of the block that ends the window.\n" "\nResult:\n" "{\n" " \"time\": xxxxx, (numeric) The timestamp for the final block in the window in UNIX format.\n" " \"txcount\": xxxxx, (numeric) The total number of transactions in the chain up to that point.\n" " \"window_block_count\": xxxxx, (numeric) Size of the window in number of blocks.\n" " \"window_tx_count\": xxxxx, (numeric) The number of transactions in the window. Only returned if \"window_block_count\" is > 0.\n" " \"window_interval\": xxxxx, (numeric) The elapsed time in the window in seconds. Only returned if \"window_block_count\" is > 0.\n" " \"txrate\": x.xx, (numeric) The average rate of transactions per second in the window. Only returned if \"window_interval\" is > 0.\n" "}\n" "\nExamples:\n" + HelpExampleCli("getchaintxstats", "") + HelpExampleRpc("getchaintxstats", "2016") ); const CBlockIndex* pindex; int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month bool havehash = !request.params[1].isNull(); uint256 hash; if (havehash) { hash = uint256S(request.params[1].get_str()); } { LOCK(cs_main); if (havehash) { auto it = mapBlockIndex.find(hash); if (it == mapBlockIndex.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } pindex = it->second; if (!chainActive.Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain"); } } else { pindex = chainActive.Tip(); } } assert(pindex != nullptr); if (request.params[0].isNull()) { blockcount = std::max(0, std::min(blockcount, pindex->nHeight - 1)); } else { blockcount = request.params[0].get_int(); if (blockcount < 0 || (blockcount > 0 && blockcount >= pindex->nHeight)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 0 and the block's height - 1"); } } const CBlockIndex* pindexPast = pindex->GetAncestor(pindex->nHeight - blockcount); int nTimeDiff = pindex->GetMedianTimePast() - pindexPast->GetMedianTimePast(); int nTxDiff = pindex->nChainTx - pindexPast->nChainTx; UniValue ret(UniValue::VOBJ); ret.push_back(Pair("time", (int64_t)pindex->nTime)); ret.push_back(Pair("txcount", (int64_t)pindex->nChainTx)); ret.push_back(Pair("window_block_count", blockcount)); if (blockcount > 0) { ret.push_back(Pair("window_tx_count", nTxDiff)); ret.push_back(Pair("window_interval", nTimeDiff)); if (nTimeDiff > 0) { ret.push_back(Pair("txrate", ((double)nTxDiff) / nTimeDiff)); } } return ret; } UniValue savemempool(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) { throw std::runtime_error( "savemempool\n" "\nDumps the mempool to disk.\n" "\nExamples:\n" + HelpExampleCli("savemempool", "") + HelpExampleRpc("savemempool", "") ); } if (!DumpMempool()) { throw JSONRPCError(RPC_MISC_ERROR, "Unable to dump mempool to disk"); } return NullUniValue; } static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "blockchain", "getblockchaininfo", &getblockchaininfo, {} }, { "blockchain", "getchaintxstats", &getchaintxstats, {"nblocks", "blockhash"} }, { "blockchain", "getbestblockhash", &getbestblockhash, {} }, { "blockchain", "getblockcount", &getblockcount, {} }, { "blockchain", "getblock", &getblock, {"blockhash","verbosity|verbose"} }, { "blockchain", "getblockhash", &getblockhash, {"height"} }, { "blockchain", "getblockheader", &getblockheader, {"blockhash","verbose"} }, { "blockchain", "getchaintips", &getchaintips, {} }, { "blockchain", "getdifficulty", &getdifficulty, {} }, { "blockchain", "getmempoolancestors", &getmempoolancestors, {"txid","verbose"} }, { "blockchain", "getmempooldescendants", &getmempooldescendants, {"txid","verbose"} }, { "blockchain", "getmempoolentry", &getmempoolentry, {"txid"} }, { "blockchain", "getmempoolinfo", &getmempoolinfo, {} }, { "blockchain", "getrawmempool", &getrawmempool, {"verbose"} }, { "blockchain", "gettxout", &gettxout, {"txid","n","include_mempool"} }, { "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, {} }, { "blockchain", "savemempool", &savemempool, {} }, { "blockchain", "verifychain", &verifychain, {"checklevel","nblocks"} }, { "blockchain", "preciousblock", &preciousblock, {"blockhash"} }, /* Not shown in help */ { "hidden", "invalidateblock", &invalidateblock, {"blockhash"} }, { "hidden", "reconsiderblock", &reconsiderblock, {"blockhash"} }, { "hidden", "waitfornewblock", &waitfornewblock, {"timeout"} }, { "hidden", "waitforblock", &waitforblock, {"blockhash","timeout"} }, { "hidden", "waitforblockheight", &waitforblockheight, {"height","timeout"} }, { "hidden", "syncwithvalidationinterfacequeue", &syncwithvalidationinterfacequeue, {} }, }; void RegisterBlockchainRPCCommands(CRPCTable &t) { for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++) t.appendCommand(commands[vcidx].name, &commands[vcidx]); }
; unsigned char esx_f_chmod(unsigned char *filename, uint8_t attr_mask, uint8_t attr) SECTION code_esxdos PUBLIC esx_f_chmod EXTERN asm_esx_f_chmod esx_f_chmod: pop af pop de pop bc pop hl push hl push bc push de push af ld b,e jp asm_esx_f_chmod ; SDCC bridge for Classic IF __CLASSIC PUBLIC _esx_f_chmod defc _esx_f_chmod = esx_f_chmod ENDIF
;; -*- tab-width: 4 -*- bits 32 global _Import global _HashShiftPtr global _MaxNameLengthPtr extern __imp__LoadLibraryA@4 extern _DLLNames extern _ImportList extern _HashMultiplier ; Format of DLL names: ; For each DLL ; Zero-terminated DLL name (omitted for kernel32) ; byte: Number of hash-entries for this DLL (including dummies) ; For each entry ; byte: Number of ordinals imported from this hash, minus one ; byte: -1 section .text align=1 _Import: mov edi, _DLLNames pop eax mov eax, [eax+0ch] ; goto PEB_LDR_DATA mov eax, [eax+0ch] ; InLoadOrderModuleList mov eax, [byte eax+0h] ; forward to next LIST_ENTRY mov eax, [byte eax+0h] ; forward to next LIST_ENTRY mov eax, [eax+18h] ; Kernel32 base memory ;eax: misc ;ebx: exports ptr ;ecx: ordinal number ;edx: dllnames DLLLoop: xchg ebp, eax mov eax, [ebp + 3ch] ; eax = PE header offset add eax, ebp mov ebx, [eax + 78h] ; ebx = exports directory table offset add ebx, ebp ; ebx = exports directory table address xor ecx, ecx ; ecx = 0 ; Check all names of procedures for the right hash ScanProcedureNamesLoop: mov eax, [ebx + 20h] ; ebx = name pointers table offset add eax, ebp ; ebx = name pointers table address mov esi, [eax + ecx*4] ; esi = name pointer offset add esi, ebp ; esi = name pointer address ; Found, get the address from the table mov eax, [ebx + 24h] ; eax = ordinals table RNA offset add eax, ebp ; eax = ordinals table RNA address movzx edx, word [eax + ecx*2] ; edx = function ordinal mov eax, [ebx + 1ch] ; eax = address table RVA offset add eax, ebp ; eax = address table RVA address mov edx, [eax + edx*4] ; ebp = address of function RVA address add edx, ebp xor eax, eax CalculateHashLoop: lodsb imul eax, _HashMultiplier add al, al jne CalculateHashLoop shr eax, byte 0 ; filled out by crinkler _HashShiftPtrP: mov dword [_ImportList+eax*4], edx inc ecx cmp ecx, [ebx + 18h] jne ScanProcedureNamesLoop push edi call [__imp__LoadLibraryA@4] add edi, byte 0 _MaxNameLengthPtrP: test eax, eax jnz short DLLLoop _HashShiftPtr equ _HashShiftPtrP-1 _MaxNameLengthPtr equ _MaxNameLengthPtrP-1
; A247063: Dynamic Betting Game D(n,5,3). ; 1,2,3,4,5,6,8,9,10,11,12,13,16,17,18,19,20,21,22,24,25,26,27,28,29,32,33,34,35,36,37,38,40,41,42,43,44,45,48,49,50,51,52,53,54,56,57,58,59,60,61,64,65,66,67,68,69,70,72,73,74,75,76,77,80,81,82,83,84,85,86,88,89,90,91,92,93,96 mul $0,2 add $0,28 sub $2,$0 div $0,13 sub $2,$0 div $2,2 sub $0,$2 sub $0,16
; void p_forward_list_clear_fastcall(p_forward_list_t *list) SECTION code_adt_p_forward_list PUBLIC _p_forward_list_clear_fastcall defc _p_forward_list_clear_fastcall = asm_p_forward_list_clear INCLUDE "adt/p_forward_list/z80/asm_p_forward_list_clear.asm"
/* The smooth Class Library * Copyright (C) 1998-2020 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <smooth/graphics/backends/xlib/fontxlib.h> #include <smooth/graphics/surface.h> #include <smooth/files/file.h> #include <smooth/foreach.h> #include <smooth/init.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fribidi/fribidi.h> using namespace X11; #include <smooth/backends/xlib/backendxlib.h> S::GUI::FontBackend *CreateFontXLib(const S::String &iFontName, S::Short iFontSize, S::Short iFontWeight, S::Short iFontStyle, const S::GUI::Color &iFontColor) { return new S::GUI::FontXLib(iFontName, iFontSize, iFontWeight, iFontStyle, iFontColor); } S::Int fontXLibTmp = S::GUI::FontBackend::SetBackend(&CreateFontXLib); S::Int addFontXLibInitTmp = S::AddInitFunction(&S::GUI::FontXLib::Initialize); S::Int S::GUI::FontXLib::Initialize() { Font::Default = "Helvetica"; /* Search the path for gsettings. */ String path = getenv("PATH"); const Array<String> &paths = path.Explode(":"); foreach (const String &path, paths) { /* Check for gsettings in this path. */ if (File(String(path).Append("/").Append("gsettings")).Exists()) { /* If gsettings exists, use it to get the default font. */ FILE *pstdin = popen("gsettings get org.gnome.desktop.interface font-name", "r"); if (pstdin != NIL) { char fontName[256]; if (fgets(fontName, 256, pstdin) != NIL) { String font = fontName; Font::Default = font.SubString(1, font.FindLast(" ") - 1); Setup::FontSize = font.SubString(font.FindLast(" ") + 1, font.Length() - font.FindLast(" ") - 2).ToFloat() / Font::DefaultSize; } pclose(pstdin); } break; } } return Success(); } S::GUI::FontXLib::FontXLib(const String &iFontName, Short iFontSize, Short iFontWeight, Short iFontStyle, const Color &iFontColor) : FontBackend(iFontName, iFontSize, iFontWeight, iFontStyle, iFontColor) { type = FONT_XLIB; } S::GUI::FontXLib::~FontXLib() { } S::GUI::Size S::GUI::FontXLib::GetTextSize(const String &iText) const { if (iText == NIL) return Size(); Display *display = Backends::BackendXLib::GetDisplay(); if (display == NIL) return Size(); String text = iText; Int textLength = text.Length(); Float dpi = Surface().GetSurfaceDPI(); Bool rtlCharacters = False; for (Int i = 0; i < textLength; i++) if (text[i] >= 0x0590 && text[i] <= 0x08FF) { rtlCharacters = True; break; } if (rtlCharacters && Setup::useIconv) { /* Reorder the string with fribidi. */ FriBidiChar *visual = new FriBidiChar [textLength + 1]; FriBidiParType type = FRIBIDI_PAR_RTL; fribidi_log2vis((FriBidiChar *) text.ConvertTo("UCS-4LE"), textLength, &type, visual, NIL, NIL, NIL); visual[textLength] = 0; text.ImportFrom("UCS-4LE", (char *) visual); delete [] visual; } /* Get text extents. */ XftFont *font = XftFontOpenName(display, XDefaultScreen(display), String(fontName).Append("-").Append(String::FromInt(Math::Round(fontSize * dpi / 96.0))).Append(":").Append(fontWeight >= Font::Bold ? "bold" : "medium").Append(fontStyle & Font::Italic ? ":italic" : "")); XGlyphInfo extents = { 0 }; XftTextExtents16(display, font, (XftChar16 *) text.ConvertTo("UCS2"), textLength, &extents); XftFontClose(display, font); int lines = 1; for (Int i = 0; i < textLength; i++) if (text[i] == '\n') lines++; return Size(extents.width - 2, (font->ascent + 2) * lines); }
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld a, ff ldff(45), a ld b, 91 call lwaitly_b xor a, a ldff(40), a ld hl, fea0 lbegin_fill_oam: dec l ld(hl), a jrnz lbegin_fill_oam ld d, 10 ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l inc l inc l ld a, d ld(hl), a inc l ld a, a7 ld(hl), a inc l ld a, 40 ldff(41), a ld a, 02 ldff(ff), a xor a, a ldff(0f), a ei ld a, 01 ldff(45), a ld a, 93 ldff(40), a .text@1000 lstatint: ld a, 08 ldff(41), a xor a, a ldff(0f), a .text@1031 ldff a, (0f) and a, 03 jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles 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
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/merkle.h> #include <validation.h> #include <httpserver.h> #include <index/blockfilterindex.h> #include <index/txindex.h> #include <interfaces/chain.h> #include <key_io.h> #include <node/context.h> #include <outputtype.h> #include <pegins.h> #include <rpc/blockchain.h> #include <rpc/server.h> #include <rpc/util.h> #include <scheduler.h> #include <script/descriptor.h> #include <util/check.h> #include <util/message.h> // For MessageSign(), MessageVerify() #include <util/ref.h> #include <util/strencodings.h> #include <util/system.h> #include <stdint.h> #include <tuple> #ifdef HAVE_MALLOC_INFO #include <malloc.h> #endif #include <assetsdir.h> #include <univalue.h> static RPCHelpMan validateaddress() { return RPCHelpMan{"validateaddress", "\nReturn information about the given bitcoin address.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to validate"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "isvalid", "If the address is valid or not. If not, this is the only property returned."}, {RPCResult::Type::BOOL, "isvalid_parent", "If the address is valid or not for parent chain. Valid or not, no additional details will be appended unlike `isvalid`"}, {RPCResult::Type::STR, "address", "The address validated"}, {RPCResult::Type::STR_HEX, "scriptPubKey", "The hex-encoded scriptPubKey generated by the address"}, {RPCResult::Type::BOOL, "isscript", "If the key is a script"}, {RPCResult::Type::BOOL, "iswitness", "If the address is a witness address"}, {RPCResult::Type::NUM, "witness_version", /* optional */ true, "The version number of the witness program"}, {RPCResult::Type::STR_HEX, "witness_program", /* optional */ true, "The hex value of the witness program"}, {RPCResult::Type::STR_HEX, "confidential_key", "the raw blinding public key for that address, if any. \"\" if none"}, {RPCResult::Type::STR, "unconfidential", "The address without confidentiality key"}, {RPCResult::Type::OBJ, "parent_address_info", "If the address isvalid_parent, this object contains details about the parent address type", { {RPCResult::Type::STR, "address", ""}, {RPCResult::Type::STR_HEX, "scriptPubKey", ""}, }}, } }, RPCExamples{ HelpExampleCli("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") + HelpExampleRpc("validateaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { CTxDestination dest = DecodeDestination(request.params[0].get_str()); CTxDestination parent_dest = DecodeParentDestination(request.params[0].get_str()); bool isValid = IsValidDestination(dest); bool is_valid_parent = IsValidDestination(parent_dest); UniValue ret(UniValue::VOBJ); ret.pushKV("isvalid", isValid); ret.pushKV("isvalid_parent", is_valid_parent); if (isValid) { std::string currentAddress = EncodeDestination(dest); ret.pushKV("address", currentAddress); CScript scriptPubKey = GetScriptForDestination(dest); ret.pushKV("scriptPubKey", HexStr(scriptPubKey)); UniValue detail = DescribeAddress(dest); ret.pushKVs(detail); UniValue blind_detail = DescribeBlindAddress(dest); ret.pushKVs(blind_detail); } if (is_valid_parent) { UniValue parent_info(UniValue::VOBJ); std::string currentAddress = EncodeParentDestination(parent_dest); parent_info.pushKV("address", currentAddress); CScript scriptPubKey = GetScriptForDestination(parent_dest); parent_info.pushKV("scriptPubKey", HexStr(scriptPubKey)); UniValue detail = DescribeAddress(parent_dest); parent_info.pushKVs(detail); UniValue blind_detail = DescribeBlindAddress(parent_dest); parent_info.pushKVs(blind_detail); ret.pushKV("parent_address_info", parent_info); } return ret; }, }; } static RPCHelpMan createmultisig() { return RPCHelpMan{"createmultisig", "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n", { {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys."}, {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex-encoded public keys.", { {"key", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The hex-encoded public key"}, }}, {"address_type", RPCArg::Type::STR, /* default */ "legacy", "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "address", "The value of the new multisig address."}, {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script."}, {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"}, } }, RPCExamples{ "\nCreate a multisig address from 2 public keys\n" + HelpExampleCli("createmultisig", "2 \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"03789ed0bb717d88f7d321a368d905e7430207ebbd82bd342cf11ae157a7ace5fd\\\",\\\"03dbc6764b8884a92e871274b87583e6d5c2a58819473e17e107ef3f6aa5a61626\\\"]\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { int required = request.params[0].get_int(); // Get the public keys const UniValue& keys = request.params[1].get_array(); std::vector<CPubKey> pubkeys; for (unsigned int i = 0; i < keys.size(); ++i) { if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || keys[i].get_str().length() == 130)) { pubkeys.push_back(HexToPubKey(keys[i].get_str())); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid public key: %s\n.", keys[i].get_str())); } } // Get the output type OutputType output_type = OutputType::LEGACY; if (!request.params[2].isNull()) { if (!ParseOutputType(request.params[2].get_str(), output_type)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[2].get_str())); } } // Construct using pay-to-script-hash: FillableSigningProvider keystore; CScript inner; const CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, keystore, inner); // Make the descriptor std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), keystore); UniValue result(UniValue::VOBJ); result.pushKV("address", EncodeDestination(dest)); result.pushKV("redeemScript", HexStr(inner)); result.pushKV("descriptor", descriptor->ToString()); return result; }, }; } static RPCHelpMan getdescriptorinfo() { return RPCHelpMan{"getdescriptorinfo", {"\nAnalyses a descriptor.\n"}, { {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "descriptor", "The descriptor in canonical form, without private keys"}, {RPCResult::Type::STR, "checksum", "The checksum for the input descriptor"}, {RPCResult::Type::BOOL, "isrange", "Whether the descriptor is ranged"}, {RPCResult::Type::BOOL, "issolvable", "Whether the descriptor is solvable"}, {RPCResult::Type::BOOL, "hasprivatekeys", "Whether the input descriptor contained at least one private key"}, } }, RPCExamples{ "Analyse a descriptor\n" + HelpExampleCli("getdescriptorinfo", "\"wpkh([d34db33f/84h/0h/0h]0279be667ef9dcbbac55a06295Ce870b07029Bfcdb2dce28d959f2815b16f81798)\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { RPCTypeCheck(request.params, {UniValue::VSTR}); FlatSigningProvider provider; std::string error; auto desc = Parse(request.params[0].get_str(), provider, error); if (!desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } UniValue result(UniValue::VOBJ); result.pushKV("descriptor", desc->ToString()); result.pushKV("checksum", GetDescriptorChecksum(request.params[0].get_str())); result.pushKV("isrange", desc->IsRange()); result.pushKV("issolvable", desc->IsSolvable()); result.pushKV("hasprivatekeys", provider.keys.size() > 0); return result; }, }; } static RPCHelpMan deriveaddresses() { return RPCHelpMan{"deriveaddresses", {"\nDerives one or more addresses corresponding to an output descriptor.\n" "Examples of output descriptors are:\n" " pkh(<pubkey>) P2PKH outputs for the given pubkey\n" " wpkh(<pubkey>) Native segwit P2PKH outputs for the given pubkey\n" " sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n" " raw(<hex script>) Outputs whose scriptPubKey equals the specified hex scripts\n" "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n" "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n" "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"}, { {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."}, {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."}, }, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::STR, "address", "the derived addresses"}, } }, RPCExamples{ "First three native segwit receive addresses\n" + HelpExampleCli("deriveaddresses", "\"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu\" \"[0,2]\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later const std::string desc_str = request.params[0].get_str(); int64_t range_begin = 0; int64_t range_end = 0; if (request.params.size() >= 2 && !request.params[1].isNull()) { std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]); } FlatSigningProvider key_provider; std::string error; auto desc = Parse(desc_str, key_provider, error, /* require_checksum = */ true); if (!desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } if (!desc->IsRange() && request.params.size() > 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor"); } if (desc->IsRange() && request.params.size() == 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor"); } UniValue addresses(UniValue::VARR); for (int i = range_begin; i <= range_end; ++i) { FlatSigningProvider provider; std::vector<CScript> scripts; if (!desc->Expand(i, key_provider, scripts, provider)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys")); } for (const CScript &script : scripts) { CTxDestination dest; if (!ExtractDestination(script, dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Descriptor does not have a corresponding address")); } addresses.push_back(EncodeDestination(dest)); } } // This should not be possible, but an assert seems overkill: if (addresses.empty()) { throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result"); } return addresses; }, }; } static RPCHelpMan verifymessage() { return RPCHelpMan{"verifymessage", "\nVerify a signed message\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to use for the signature."}, {"signature", RPCArg::Type::STR, RPCArg::Optional::NO, "The signature provided by the signer in base 64 encoding (see signmessage)."}, {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message that was signed."}, }, RPCResult{ RPCResult::Type::BOOL, "", "If the signature is verified or not." }, RPCExamples{ "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"signature\", \"my message\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); std::string strAddress = request.params[0].get_str(); std::string strSign = request.params[1].get_str(); std::string strMessage = request.params[2].get_str(); switch (MessageVerify(strAddress, strSign, strMessage)) { case MessageVerificationResult::ERR_INVALID_ADDRESS: throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); case MessageVerificationResult::ERR_ADDRESS_NO_KEY: throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); case MessageVerificationResult::ERR_MALFORMED_SIGNATURE: throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); case MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED: case MessageVerificationResult::ERR_NOT_SIGNED: return false; case MessageVerificationResult::OK: return true; } return false; }, }; } static RPCHelpMan signmessagewithprivkey() { return RPCHelpMan{"signmessagewithprivkey", "\nSign a message with the private key of an address\n", { {"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key to sign the message with."}, {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."}, }, RPCResult{ RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64" }, RPCExamples{ "\nCreate the signature\n" + HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::string strPrivkey = request.params[0].get_str(); std::string strMessage = request.params[1].get_str(); CKey key = DecodeSecret(strPrivkey); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); } std::string signature; if (!MessageSign(key, strMessage, signature)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); } return signature; }, }; } static RPCHelpMan setmocktime() { return RPCHelpMan{"setmocktime", "\nSet the local time to given timestamp (-regtest only)\n", { {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, UNIX_EPOCH_TIME + "\n" " Pass 0 to go back to using the system time."}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { if (!Params().IsMockableChain()) { throw std::runtime_error("setmocktime is for regression testing (-regtest mode) only"); } // For now, don't change mocktime if we're in the middle of validation, as // this could have an effect on mempool time-based eviction, as well as // IsCurrentForFeeEstimation() and IsInitialBlockDownload(). // TODO: figure out the right way to synchronize around mocktime, and // ensure all call sites of GetTime() are accessing this safely. LOCK(cs_main); RPCTypeCheck(request.params, {UniValue::VNUM}); int64_t time = request.params[0].get_int64(); SetMockTime(time); if (request.context.Has<NodeContext>()) { for (const auto& chain_client : request.context.Get<NodeContext>().chain_clients) { chain_client->setMockTime(time); } } return NullUniValue; }, }; } static RPCHelpMan mockscheduler() { return RPCHelpMan{"mockscheduler", "\nBump the scheduler into the future (-regtest only)\n", { {"delta_time", RPCArg::Type::NUM, RPCArg::Optional::NO, "Number of seconds to forward the scheduler into the future." }, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { if (!Params().IsMockableChain()) { throw std::runtime_error("mockscheduler is for regression testing (-regtest mode) only"); } // check params are valid values RPCTypeCheck(request.params, {UniValue::VNUM}); int64_t delta_seconds = request.params[0].get_int64(); if ((delta_seconds <= 0) || (delta_seconds > 3600)) { throw std::runtime_error("delta_time must be between 1 and 3600 seconds (1 hr)"); } // protect against null pointer dereference CHECK_NONFATAL(request.context.Has<NodeContext>()); NodeContext& node = request.context.Get<NodeContext>(); CHECK_NONFATAL(node.scheduler); node.scheduler->MockForward(std::chrono::seconds(delta_seconds)); return NullUniValue; }, }; } static UniValue RPCLockedMemoryInfo() { LockedPool::Stats stats = LockedPoolManager::Instance().stats(); UniValue obj(UniValue::VOBJ); obj.pushKV("used", uint64_t(stats.used)); obj.pushKV("free", uint64_t(stats.free)); obj.pushKV("total", uint64_t(stats.total)); obj.pushKV("locked", uint64_t(stats.locked)); obj.pushKV("chunks_used", uint64_t(stats.chunks_used)); obj.pushKV("chunks_free", uint64_t(stats.chunks_free)); return obj; } #ifdef HAVE_MALLOC_INFO static std::string RPCMallocInfo() { char *ptr = nullptr; size_t size = 0; FILE *f = open_memstream(&ptr, &size); if (f) { malloc_info(0, f); fclose(f); if (ptr) { std::string rv(ptr, size); free(ptr); return rv; } } return ""; } #endif static RPCHelpMan getmemoryinfo() { /* Please, avoid using the word "pool" here in the RPC interface or help, * as users will undoubtedly confuse it with the other "memory pool" */ return RPCHelpMan{"getmemoryinfo", "Returns an object containing information about memory usage.\n", { {"mode", RPCArg::Type::STR, /* default */ "\"stats\"", "determines what kind of information is returned.\n" " - \"stats\" returns general statistics about memory usage in the daemon.\n" " - \"mallocinfo\" returns an XML string describing low-level heap state (only available if compiled with glibc 2.10+)."}, }, { RPCResult{"mode \"stats\"", RPCResult::Type::OBJ, "", "", { {RPCResult::Type::OBJ, "locked", "Information about locked memory manager", { {RPCResult::Type::NUM, "used", "Number of bytes used"}, {RPCResult::Type::NUM, "free", "Number of bytes available in current arenas"}, {RPCResult::Type::NUM, "total", "Total number of bytes managed"}, {RPCResult::Type::NUM, "locked", "Amount of bytes that succeeded locking. If this number is smaller than total, locking pages failed at some point and key data could be swapped to disk."}, {RPCResult::Type::NUM, "chunks_used", "Number allocated chunks"}, {RPCResult::Type::NUM, "chunks_free", "Number unused chunks"}, }}, } }, RPCResult{"mode \"mallocinfo\"", RPCResult::Type::STR, "", "\"<malloc version=\"1\">...\"" }, }, RPCExamples{ HelpExampleCli("getmemoryinfo", "") + HelpExampleRpc("getmemoryinfo", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::string mode = request.params[0].isNull() ? "stats" : request.params[0].get_str(); if (mode == "stats") { UniValue obj(UniValue::VOBJ); obj.pushKV("locked", RPCLockedMemoryInfo()); return obj; } else if (mode == "mallocinfo") { #ifdef HAVE_MALLOC_INFO return RPCMallocInfo(); #else throw JSONRPCError(RPC_INVALID_PARAMETER, "mallocinfo is only available when compiled with glibc 2.10+"); #endif } else { throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown mode " + mode); } }, }; } static void EnableOrDisableLogCategories(UniValue cats, bool enable) { cats = cats.get_array(); for (unsigned int i = 0; i < cats.size(); ++i) { std::string cat = cats[i].get_str(); bool success; if (enable) { success = LogInstance().EnableCategory(cat); } else { success = LogInstance().DisableCategory(cat); } if (!success) { throw JSONRPCError(RPC_INVALID_PARAMETER, "unknown logging category " + cat); } } } static RPCHelpMan logging() { return RPCHelpMan{"logging", "Gets and sets the logging configuration.\n" "When called without an argument, returns the list of categories with status that are currently being debug logged or not.\n" "When called with arguments, adds or removes categories from debug logging and return the lists above.\n" "The arguments are evaluated in order \"include\", \"exclude\".\n" "If an item is both included and excluded, it will thus end up being excluded.\n" "The valid logging categories are: " + LogInstance().LogCategoriesString() + "\n" "In addition, the following are available as category names with special meanings:\n" " - \"all\", \"1\" : represent all logging categories.\n" " - \"none\", \"0\" : even if other logging categories are specified, ignore all of them.\n" , { {"include", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to add to debug logging", { {"include_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"}, }}, {"exclude", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The categories to remove from debug logging", { {"exclude_category", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "the valid logging category"}, }}, }, RPCResult{ RPCResult::Type::OBJ_DYN, "", "keys are the logging categories, and values indicates its status", { {RPCResult::Type::BOOL, "category", "if being debug logged or not. false:inactive, true:active"}, } }, RPCExamples{ HelpExampleCli("logging", "\"[\\\"all\\\"]\" \"[\\\"http\\\"]\"") + HelpExampleRpc("logging", "[\"all\"], [\"libevent\"]") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { uint32_t original_log_categories = LogInstance().GetCategoryMask(); if (request.params[0].isArray()) { EnableOrDisableLogCategories(request.params[0], true); } if (request.params[1].isArray()) { EnableOrDisableLogCategories(request.params[1], false); } uint32_t updated_log_categories = LogInstance().GetCategoryMask(); uint32_t changed_log_categories = original_log_categories ^ updated_log_categories; // Update libevent logging if BCLog::LIBEVENT has changed. // If the library version doesn't allow it, UpdateHTTPServerLogging() returns false, // in which case we should clear the BCLog::LIBEVENT flag. // Throw an error if the user has explicitly asked to change only the libevent // flag and it failed. if (changed_log_categories & BCLog::LIBEVENT) { if (!UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT))) { LogInstance().DisableCategory(BCLog::LIBEVENT); if (changed_log_categories == BCLog::LIBEVENT) { throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1."); } } } UniValue result(UniValue::VOBJ); for (const auto& logCatActive : LogInstance().LogCategoriesList()) { result.pushKV(logCatActive.category, logCatActive.active); } return result; }, }; } static RPCHelpMan echo(const std::string& name) { return RPCHelpMan{name, "\nSimply echo back the input arguments. This command is for testing.\n" "\nIt will return an internal bug report when arg9='trigger_internal_bug' is passed.\n" "\nThe difference between echo and echojson is that echojson has argument conversion enabled in the client-side table in " "elements-cli and the GUI. There is no server-side difference.", { {"arg0", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg1", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg2", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg3", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg4", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg5", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg6", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg7", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg8", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, {"arg9", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, ""}, }, RPCResult{RPCResult::Type::NONE, "", "Returns whatever was passed in"}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { if (request.fHelp) throw std::runtime_error(self.ToString()); if (request.params[9].isStr()) { CHECK_NONFATAL(request.params[9].get_str() != "trigger_internal_bug"); } return request.params; }, }; } static RPCHelpMan echo() { return echo("echo"); } static RPCHelpMan echojson() { return echo("echojson"); } static UniValue SummaryToJSON(const IndexSummary&& summary, std::string index_name) { UniValue ret_summary(UniValue::VOBJ); if (!index_name.empty() && index_name != summary.name) return ret_summary; UniValue entry(UniValue::VOBJ); entry.pushKV("synced", summary.synced); entry.pushKV("best_block_height", summary.best_block_height); ret_summary.pushKV(summary.name, entry); return ret_summary; } static RPCHelpMan getindexinfo() { return RPCHelpMan{"getindexinfo", "\nReturns the status of one or all available indices currently running in the node.\n", { {"index_name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Filter results for an index with a specific name."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { { RPCResult::Type::OBJ, "name", "The name of the index", { {RPCResult::Type::BOOL, "synced", "Whether the index is synced or not"}, {RPCResult::Type::NUM, "best_block_height", "The block height to which the index is synced"}, } }, }, }, RPCExamples{ HelpExampleCli("getindexinfo", "") + HelpExampleRpc("getindexinfo", "") + HelpExampleCli("getindexinfo", "txindex") + HelpExampleRpc("getindexinfo", "txindex") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { UniValue result(UniValue::VOBJ); const std::string index_name = request.params[0].isNull() ? "" : request.params[0].get_str(); if (g_txindex) { result.pushKVs(SummaryToJSON(g_txindex->GetSummary(), index_name)); } ForEachBlockFilterIndex([&result, &index_name](const BlockFilterIndex& index) { result.pushKVs(SummaryToJSON(index.GetSummary(), index_name)); }); return result; }, }; } // // ELEMENTS CALLS UniValue tweakfedpegscript(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) throw std::runtime_error( RPCHelpMan{"tweakfedpegscript", "\nReturns a tweaked fedpegscript.\n", { {"claim_script", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Script to tweak the fedpegscript with. For example obtained as a result of getpeginaddress."}, {"fedpegscript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED_NAMED_ARG, "Fedpegscript to be used with the claim_script. By default this is the current fedpegscript."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "script", "The fedpegscript tweaked with claim_script"}, {RPCResult::Type::STR, "address", "The address corresponding to the tweaked fedpegscript"}, } }, RPCExamples{""}, }.ToString()); if (!IsHex(request.params[0].get_str())) { throw JSONRPCError(RPC_TYPE_ERROR, "the first argument must be a hex string"); } CScript fedpegscript = GetValidFedpegScripts(::ChainActive().Tip(), Params().GetConsensus(), true /* nextblock_validation */).front().second; if (!request.params[1].isNull()) { if (IsHex(request.params[1].get_str())) { std::vector<unsigned char> fedpeg_byte = ParseHex(request.params[1].get_str()); fedpegscript = CScript(fedpeg_byte.begin(), fedpeg_byte.end()); } else { throw JSONRPCError(RPC_TYPE_ERROR, "fedpegscript must be a hex string"); } } std::vector<unsigned char> scriptData = ParseHex(request.params[0].get_str()); CScript claim_script = CScript(scriptData.begin(), scriptData.end()); CScript tweaked_script = calculate_contract(fedpegscript, claim_script); CScript redeem_script = GetScriptForDestination(WitnessV0ScriptHash(tweaked_script)); CTxDestination parent_addr{ScriptHash(redeem_script)}; UniValue ret(UniValue::VOBJ); ret.pushKV("script", HexStr(tweaked_script)); ret.pushKV("address", EncodeParentDestination(parent_addr)); return ret; } UniValue FormatPAKList(CPAKList &paklist) { UniValue paklist_value(UniValue::VOBJ); std::vector<std::vector<unsigned char> > offline_keys; std::vector<std::vector<unsigned char> > online_keys; paklist.ToBytes(offline_keys, online_keys); UniValue retOnline(UniValue::VARR); UniValue retOffline(UniValue::VARR); for (unsigned int i = 0; i < offline_keys.size(); i++) { retOffline.push_back(HexStr(offline_keys[i])); retOnline.push_back(HexStr(online_keys[i])); } paklist_value.pushKV("online", retOnline); paklist_value.pushKV("offline", retOffline); paklist_value.pushKV("reject", retOffline.empty()); return paklist_value; } UniValue getpakinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( RPCHelpMan{"getpakinfo", "\nReturns relevant pegout authorization key (PAK) information about this node, both from blockchain data.\n", {}, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::ARR, "block_paklist", "The PAK list loaded from latest epoch", { {RPCResult::Type::ELISION, "", ""} }}, } }, RPCExamples{""}, }.ToString()); LOCK(cs_main); UniValue ret(UniValue::VOBJ); CPAKList paklist = GetActivePAKList(::ChainActive().Tip(), Params().GetConsensus()); ret.pushKV("block_paklist", FormatPAKList(paklist)); return ret; } UniValue calcfastmerkleroot(const JSONRPCRequest& request) { std::vector<uint256> leaves; for (const UniValue& leaf : request.params[0].get_array().getValues()) { uint256 l; l.SetHex(leaf.get_str()); leaves.push_back(l); } uint256 root = ComputeFastMerkleRoot(leaves); UniValue ret(UniValue::VOBJ); ret.setStr(root.GetHex()); return ret; } UniValue dumpassetlabels(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( RPCHelpMan{"dumpassetlabels", "\nLists all known asset id/label pairs in this wallet. This list can be modified with `-assetdir` configuration argument.\n", {}, RPCResults{}, RPCExamples{ HelpExampleCli("dumpassetlabels", "" ) + HelpExampleRpc("dumpassetlabels", "" ) }, }.ToString()); UniValue obj(UniValue::VOBJ); for (const auto& as : gAssetsDir.GetKnownAssets()) { obj.pushKV(gAssetsDir.GetLabel(as), as.GetHex()); } return obj; } class BlindingPubkeyAdderVisitor : public boost::static_visitor<> { public: CPubKey blind_key; explicit BlindingPubkeyAdderVisitor(const CPubKey& blind_key_in) : blind_key(blind_key_in) {} void operator()(const CNoDestination& dest) const {} void operator()(PKHash& keyID) const { keyID.blinding_pubkey = blind_key; } void operator()(ScriptHash& scriptID) const { scriptID.blinding_pubkey = blind_key; } void operator()(WitnessV0KeyHash& id) const { id.blinding_pubkey = blind_key; } void operator()(WitnessV0ScriptHash& id) const { id.blinding_pubkey = blind_key; } void operator()(WitnessUnknown& id) const { id.blinding_pubkey = blind_key; } void operator()(const NullData& id) const {} }; UniValue createblindedaddress(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 2) throw std::runtime_error( RPCHelpMan{"createblindedaddress", "\nCreates a blinded address using the provided blinding key.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The unblinded address to be blinded."}, {"blinding_key", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The blinding public key. This can be obtained for a given address using `validateaddress`."}, }, RPCResult{ RPCResult::Type::STR, "blinded_address", "The blinded address" }, RPCExamples{ "\nCreate a multisig address from 2 addresses\n" + HelpExampleCli("createblindedaddress", "HEZk3iQi1jC49bxUriTtynnXgWWWdAYx16 ec09811118b6febfa5ebe68642e5091c418fbace07e655da26b4a845a691fc2d") + "\nAs a json rpc call\n" + HelpExampleRpc("createblindedaddress", "HEZk3iQi1jC49bxUriTtynnXgWWWdAYx16, ec09811118b6febfa5ebe68642e5091c418fbace07e655da26b4a845a691fc2d") }, }.ToString()); CTxDestination address = DecodeDestination(request.params[0].get_str()); if (!IsValidDestination(address)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address or script"); } if (IsBlindDestination(address)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not an unblinded address"); } if (!IsHex(request.params[1].get_str())) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid hexadecimal for key"); } std::vector<unsigned char> keydata = ParseHex(request.params[1].get_str()); if (keydata.size() != 33) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid hexadecimal key length, must be length 66."); } CPubKey key; key.Set(keydata.begin(), keydata.end()); // Append blinding key and return boost::apply_visitor(BlindingPubkeyAdderVisitor(key), address); return EncodeDestination(address); } // END ELEMENTS CALLS // void RegisterMiscRPCCommands(CRPCTable &t) { // clang-format off static const CRPCCommand commands[] = { // category name actor (function) argNames // --------------------- ------------------------ ----------------------- ---------- { "control", "getmemoryinfo", &getmemoryinfo, {"mode"} }, { "control", "logging", &logging, {"include", "exclude"}}, { "util", "validateaddress", &validateaddress, {"address"} }, { "util", "createmultisig", &createmultisig, {"nrequired","keys","address_type"} }, { "util", "deriveaddresses", &deriveaddresses, {"descriptor", "range"} }, { "util", "getdescriptorinfo", &getdescriptorinfo, {"descriptor"} }, { "util", "verifymessage", &verifymessage, {"address","signature","message"} }, { "util", "signmessagewithprivkey", &signmessagewithprivkey, {"privkey","message"} }, { "util", "getindexinfo", &getindexinfo, {"index_name"} }, // ELEMENTS: { "util", "getpakinfo", &getpakinfo, {}}, { "util", "tweakfedpegscript", &tweakfedpegscript, {"claim_script", "fedpegscript"} }, { "util", "createblindedaddress", &createblindedaddress, {"address", "blinding_key"}}, { "util", "dumpassetlabels", &dumpassetlabels, {}}, { "hidden", "calcfastmerkleroot", &calcfastmerkleroot, {"leaves"} }, /* Not shown in help */ { "hidden", "setmocktime", &setmocktime, {"timestamp"}}, { "hidden", "mockscheduler", &mockscheduler, {"delta_time"}}, { "hidden", "echo", &echo, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, { "hidden", "echojson", &echojson, {"arg0","arg1","arg2","arg3","arg4","arg5","arg6","arg7","arg8","arg9"}}, }; // clang-format on for (const auto& c : commands) { t.appendCommand(c.name, &c); } }
/* * Copyright (C) 2008-2020 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ExecutableAllocator.h" #if ENABLE(JIT) #include "ExecutableAllocationFuzz.h" #include "IterationStatus.h" #include "LinkBuffer.h" #include <wtf/FastBitVector.h> #include <wtf/FileSystem.h> #include <wtf/MetaAllocator.h> #include <wtf/PageReservation.h> #include <wtf/ProcessID.h> #include <wtf/SystemTracing.h> #include <wtf/WorkQueue.h> #if HAVE(IOS_JIT_RESTRICTIONS) #include <wtf/cocoa/Entitlements.h> #endif #if OS(DARWIN) #include <fcntl.h> #include <mach/mach.h> #include <mach/mach_time.h> extern "C" { /* Routine mach_vm_remap */ #ifdef mig_external mig_external #else extern #endif /* mig_external */ kern_return_t mach_vm_remap ( vm_map_t target_task, mach_vm_address_t *target_address, mach_vm_size_t size, mach_vm_offset_t mask, int flags, vm_map_t src_task, mach_vm_address_t src_address, boolean_t copy, vm_prot_t *cur_protection, vm_prot_t *max_protection, vm_inherit_t inheritance ); } #endif namespace JSC { using namespace WTF; #if defined(FIXED_EXECUTABLE_MEMORY_POOL_SIZE_IN_MB) && FIXED_EXECUTABLE_MEMORY_POOL_SIZE_IN_MB > 0 static constexpr size_t fixedExecutableMemoryPoolSize = FIXED_EXECUTABLE_MEMORY_POOL_SIZE_IN_MB * MB; #elif CPU(ARM) static constexpr size_t fixedExecutableMemoryPoolSize = 16 * MB; #elif CPU(ARM64) #if USE(JUMP_ISLANDS) static constexpr size_t fixedExecutableMemoryPoolSize = 1 * GB; // These sizes guarantee that any jump within an island can jump forwards or backwards // to the adjacent island in a single instruction. static constexpr size_t regionSize = 112 * MB; static constexpr size_t islandRegionSize = 16 * MB; static constexpr size_t numberOfRegions = fixedExecutableMemoryPoolSize / regionSize; static constexpr size_t islandSizeInBytes = 4; static constexpr size_t maxIslandsPerRegion = islandRegionSize / islandSizeInBytes; #else static constexpr size_t fixedExecutableMemoryPoolSize = 128 * MB; #endif #elif CPU(X86_64) static constexpr size_t fixedExecutableMemoryPoolSize = 1 * GB; #else static constexpr size_t fixedExecutableMemoryPoolSize = 32 * MB; #endif #if CPU(ARM) static constexpr double executablePoolReservationFraction = 0.15; #else static constexpr double executablePoolReservationFraction = 0.25; #endif static bool isJITEnabled() { bool jitEnabled = !g_jscConfig.jitDisabled; #if HAVE(IOS_JIT_RESTRICTIONS) return processHasEntitlement("dynamic-codesigning") && jitEnabled; #else return jitEnabled; #endif } void ExecutableAllocator::setJITEnabled(bool enabled) { bool jitEnabled = !g_jscConfig.jitDisabled; ASSERT(!g_jscConfig.fixedVMPoolExecutableAllocator); if (jitEnabled == enabled) return; g_jscConfig.jitDisabled = !enabled; #if HAVE(IOS_JIT_RESTRICTIONS) if (!enabled) { // Because of an OS quirk, even after the JIT region has been unmapped, // the OS thinks that region is reserved, and as such, can cause Gigacage // allocation to fail. We work around this by initializing the Gigacage // first. // Note: when called, setJITEnabled() is always called extra early in the // process bootstrap. Under normal operation (when setJITEnabled() isn't // called at all), we will naturally initialize the Gigacage before we // allocate the JIT region. Hence, this workaround is merely ensuring the // same behavior of allocation ordering. Gigacage::ensureGigacage(); constexpr size_t size = 1; constexpr int protection = PROT_READ | PROT_WRITE | PROT_EXEC; constexpr int flags = MAP_PRIVATE | MAP_ANON | MAP_JIT; constexpr int fd = OSAllocator::JSJITCodePages; void* allocation = mmap(nullptr, size, protection, flags, fd, 0); const void* executableMemoryAllocationFailure = reinterpret_cast<void*>(-1); RELEASE_ASSERT_WITH_MESSAGE(allocation && allocation != executableMemoryAllocationFailure, "We should not have allocated executable memory before disabling the JIT."); RELEASE_ASSERT_WITH_MESSAGE(!munmap(allocation, size), "Unmapping executable memory should succeed so we do not have any executable memory in the address space"); RELEASE_ASSERT_WITH_MESSAGE(mmap(nullptr, size, protection, flags, fd, 0) == executableMemoryAllocationFailure, "Allocating executable memory should fail after setJITEnabled(false) is called."); } #endif } #if OS(DARWIN) && HAVE(REMAP_JIT) #if USE(EXECUTE_ONLY_JIT_WRITE_FUNCTION) static ALWAYS_INLINE MacroAssemblerCodeRef<JITThunkPtrTag> jitWriteThunkGenerator(void* writableAddr, void* stubBase, size_t stubSize) { using namespace ARM64Registers; using TrustedImm32 = MacroAssembler::TrustedImm32; MacroAssembler jit; jit.tagReturnAddress(); jit.move(MacroAssembler::TrustedImmPtr(writableAddr), x7); jit.addPtr(x7, x0); jit.move(x0, x3); MacroAssembler::Jump smallCopy = jit.branch64(MacroAssembler::Below, x2, MacroAssembler::TrustedImm64(64)); jit.add64(TrustedImm32(32), x3); jit.and64(TrustedImm32(-32), x3); jit.loadPair64(x1, x12, x13); jit.loadPair64(x1, TrustedImm32(16), x14, x15); jit.sub64(x3, x0, x5); jit.addPtr(x5, x1); jit.loadPair64(x1, x8, x9); jit.loadPair64(x1, TrustedImm32(16), x10, x11); jit.add64(TrustedImm32(32), x1); jit.sub64(x5, x2); jit.storePair64(x12, x13, x0); jit.storePair64(x14, x15, x0, TrustedImm32(16)); MacroAssembler::Jump cleanup = jit.branchSub64(MacroAssembler::BelowOrEqual, TrustedImm32(64), x2); MacroAssembler::Label copyLoop = jit.label(); jit.storePair64WithNonTemporalAccess(x8, x9, x3); jit.storePair64WithNonTemporalAccess(x10, x11, x3, TrustedImm32(16)); jit.add64(TrustedImm32(32), x3); jit.loadPair64WithNonTemporalAccess(x1, x8, x9); jit.loadPair64WithNonTemporalAccess(x1, TrustedImm32(16), x10, x11); jit.add64(TrustedImm32(32), x1); jit.branchSub64(MacroAssembler::Above, TrustedImm32(32), x2).linkTo(copyLoop, &jit); cleanup.link(&jit); jit.add64(x2, x1); jit.loadPair64(x1, x12, x13); jit.loadPair64(x1, TrustedImm32(16), x14, x15); jit.storePair64(x8, x9, x3); jit.storePair64(x10, x11, x3, TrustedImm32(16)); jit.addPtr(x2, x3); jit.storePair64(x12, x13, x3, TrustedImm32(32)); jit.storePair64(x14, x15, x3, TrustedImm32(48)); jit.ret(); MacroAssembler::Label local0 = jit.label(); jit.load64(x1, PostIndex(8), x6); jit.store64(x6, x3, PostIndex(8)); smallCopy.link(&jit); jit.branchSub64(MacroAssembler::AboveOrEqual, TrustedImm32(8), x2).linkTo(local0, &jit); MacroAssembler::Jump local2 = jit.branchAdd64(MacroAssembler::Equal, TrustedImm32(8), x2); MacroAssembler::Label local1 = jit.label(); jit.load8(x1, PostIndex(1), x6); jit.store8(x6, x3, PostIndex(1)); jit.branchSub64(MacroAssembler::NotEqual, TrustedImm32(1), x2).linkTo(local1, &jit); local2.link(&jit); jit.ret(); auto stubBaseCodePtr = MacroAssemblerCodePtr<LinkBufferPtrTag>(tagCodePtr<LinkBufferPtrTag>(stubBase)); LinkBuffer linkBuffer(jit, stubBaseCodePtr, stubSize); // We don't use FINALIZE_CODE() for two reasons. // The first is that we don't want the writeable address, as disassembled instructions, // to appear in the console or anywhere in memory, via the PrintStream buffer. // The second is we can't guarantee that the code is readable when using the // asyncDisassembly option as our caller will set our pages execute only. return linkBuffer.finalizeCodeWithoutDisassembly<JITThunkPtrTag>(); } #else // not USE(EXECUTE_ONLY_JIT_WRITE_FUNCTION) static void genericWriteToJITRegion(off_t offset, const void* data, size_t dataSize) { memcpy((void*)(g_jscConfig.startOfFixedWritableMemoryPool + offset), data, dataSize); } static MacroAssemblerCodeRef<JITThunkPtrTag> ALWAYS_INLINE jitWriteThunkGenerator(void* address, void*, size_t) { g_jscConfig.startOfFixedWritableMemoryPool = reinterpret_cast<uintptr_t>(address); void* function = reinterpret_cast<void*>(&genericWriteToJITRegion); #if CPU(ARM_THUMB2) // Handle thumb offset uintptr_t functionAsInt = reinterpret_cast<uintptr_t>(function); functionAsInt -= 1; function = reinterpret_cast<void*>(functionAsInt); #endif auto codePtr = MacroAssemblerCodePtr<JITThunkPtrTag>(tagCFunctionPtr<JITThunkPtrTag>(function)); return MacroAssemblerCodeRef<JITThunkPtrTag>::createSelfManagedCodeRef(codePtr); } #endif // USE(EXECUTE_ONLY_JIT_WRITE_FUNCTION) static ALWAYS_INLINE void initializeSeparatedWXHeaps(void* stubBase, size_t stubSize, void* jitBase, size_t jitSize) { mach_vm_address_t writableAddr = 0; // Create a second mapping of the JIT region at a random address. vm_prot_t cur, max; int remapFlags = VM_FLAGS_ANYWHERE; #if defined(VM_FLAGS_RANDOM_ADDR) remapFlags |= VM_FLAGS_RANDOM_ADDR; #endif kern_return_t ret = mach_vm_remap(mach_task_self(), &writableAddr, jitSize, 0, remapFlags, mach_task_self(), (mach_vm_address_t)jitBase, FALSE, &cur, &max, VM_INHERIT_DEFAULT); bool remapSucceeded = (ret == KERN_SUCCESS); if (!remapSucceeded) return; // Assemble a thunk that will serve as the means for writing into the JIT region. MacroAssemblerCodeRef<JITThunkPtrTag> writeThunk = jitWriteThunkGenerator(reinterpret_cast<void*>(writableAddr), stubBase, stubSize); int result = 0; #if USE(EXECUTE_ONLY_JIT_WRITE_FUNCTION) // Prevent reading the write thunk code. result = vm_protect(mach_task_self(), reinterpret_cast<vm_address_t>(stubBase), stubSize, true, VM_PROT_EXECUTE); RELEASE_ASSERT(!result); #endif // Prevent writing into the executable JIT mapping. result = vm_protect(mach_task_self(), reinterpret_cast<vm_address_t>(jitBase), jitSize, true, VM_PROT_READ | VM_PROT_EXECUTE); RELEASE_ASSERT(!result); // Prevent execution in the writable JIT mapping. result = vm_protect(mach_task_self(), static_cast<vm_address_t>(writableAddr), jitSize, true, VM_PROT_READ | VM_PROT_WRITE); RELEASE_ASSERT(!result); // Zero out writableAddr to avoid leaking the address of the writable mapping. memset_s(&writableAddr, sizeof(writableAddr), 0, sizeof(writableAddr)); #if ENABLE(SEPARATED_WX_HEAP) g_jscConfig.jitWriteSeparateHeaps = reinterpret_cast<JITWriteSeparateHeapsFunction>(writeThunk.code().executableAddress()); #endif } #else // OS(DARWIN) && HAVE(REMAP_JIT) static ALWAYS_INLINE void initializeSeparatedWXHeaps(void*, size_t, void*, size_t) { } #endif struct JITReservation { PageReservation pageReservation; void* base { nullptr }; size_t size { 0 }; }; static ALWAYS_INLINE JITReservation initializeJITPageReservation() { JITReservation reservation; if (!isJITEnabled()) return reservation; reservation.size = fixedExecutableMemoryPoolSize; #if !USE(JUMP_ISLANDS) // FIXME: Consider making jump islands work with Options::jitMemoryReservationSize // https://bugs.webkit.org/show_bug.cgi?id=209037 if (Options::jitMemoryReservationSize()) reservation.size = Options::jitMemoryReservationSize(); #endif reservation.size = std::max(roundUpToMultipleOf(pageSize(), reservation.size), pageSize() * 2); auto tryCreatePageReservation = [] (size_t reservationSize) { #if OS(LINUX) // If we use uncommitted reservation, mmap operation is recorded with small page size in perf command's output. // This makes the following JIT code logging broken and some of JIT code is not recorded correctly. // To avoid this problem, we use committed reservation if we need perf JITDump logging. if (Options::logJITCodeForPerf()) return PageReservation::reserveAndCommitWithGuardPages(reservationSize, OSAllocator::JSJITCodePages, EXECUTABLE_POOL_WRITABLE, true); #endif return PageReservation::reserveWithGuardPages(reservationSize, OSAllocator::JSJITCodePages, EXECUTABLE_POOL_WRITABLE, true); }; reservation.pageReservation = tryCreatePageReservation(reservation.size); if (reservation.pageReservation) { ASSERT(reservation.pageReservation.size() == reservation.size); reservation.base = reservation.pageReservation.base(); bool fastJITPermissionsIsSupported = useFastJITPermissions(); if (fastJITPermissionsIsSupported) threadSelfRestrictRWXToRX(); #if ENABLE(SEPARATED_WX_HEAP) if (!fastJITPermissionsIsSupported) { // First page of our JIT allocation is reserved. ASSERT(reservation.size >= pageSize() * 2); reservation.base = (void*)((uintptr_t)(reservation.base) + pageSize()); reservation.size -= pageSize(); initializeSeparatedWXHeaps(reservation.pageReservation.base(), pageSize(), reservation.base, reservation.size); } #endif void* reservationEnd = reinterpret_cast<uint8_t*>(reservation.base) + reservation.size; g_jscConfig.startExecutableMemory = tagCodePtr<ExecutableMemoryPtrTag>(reservation.base); g_jscConfig.endExecutableMemory = tagCodePtr<ExecutableMemoryPtrTag>(reservationEnd); } return reservation; } class FixedVMPoolExecutableAllocator final { WTF_MAKE_FAST_ALLOCATED; #if USE(JUMP_ISLANDS) class Islands; class RegionAllocator; #endif public: FixedVMPoolExecutableAllocator() #if USE(JUMP_ISLANDS) : m_allocators(constructFixedSizeArrayWithArguments<RegionAllocator, numberOfRegions>(*this)) #else : m_allocator(*this) #endif { JITReservation reservation = initializeJITPageReservation(); m_reservation = WTFMove(reservation.pageReservation); if (m_reservation) { #if USE(JUMP_ISLANDS) uintptr_t start = bitwise_cast<uintptr_t>(memoryStart()); uintptr_t reservationEnd = bitwise_cast<uintptr_t>(memoryEnd()); for (size_t i = 0; i < numberOfRegions; ++i) { RELEASE_ASSERT(start < reservationEnd); m_allocators[i].m_start = tagCodePtr<ExecutableMemoryPtrTag>(bitwise_cast<void*>(start)); m_allocators[i].m_end = tagCodePtr<ExecutableMemoryPtrTag>(bitwise_cast<void*>(start + regionSize)); if (m_allocators[i].end() > reservationEnd) { // We may have taken a page for the executable only copy thunk. RELEASE_ASSERT(i == numberOfRegions - 1); m_allocators[i].m_end = tagCodePtr<ExecutableMemoryPtrTag>(bitwise_cast<void*>(reservationEnd)); } m_allocators[i].addFreshFreeSpace(bitwise_cast<void*>(m_allocators[i].start()), m_allocators[i].allocatorSize()); RELEASE_ASSERT(m_allocators[i].allocatorSize() < regionSize); RELEASE_ASSERT(m_allocators[i].islandBegin() > m_allocators[i].start()); RELEASE_ASSERT(m_allocators[i].islandBegin() < m_allocators[i].end()); start += regionSize; } #else m_allocator.addFreshFreeSpace(reservation.base, reservation.size); ASSERT(bytesReserved() == reservation.size); // Since our executable memory is fixed-sized, bytesReserved is never changed after initialization. #endif } } ~FixedVMPoolExecutableAllocator() { m_reservation.deallocate(); } void* memoryStart() { return untagCodePtr<ExecutableMemoryPtrTag>(g_jscConfig.startExecutableMemory); } void* memoryEnd() { return untagCodePtr<ExecutableMemoryPtrTag>(g_jscConfig.endExecutableMemory); } bool isJITPC(void* pc) { return memoryStart() <= pc && pc < memoryEnd(); } bool isValid() { return !!m_reservation; } RefPtr<ExecutableMemoryHandle> allocate(size_t sizeInBytes) { #if USE(JUMP_ISLANDS) auto locker = holdLock(getLock()); unsigned start = 0; if (Options::useRandomizingExecutableIslandAllocation()) start = cryptographicallyRandomNumber() % m_allocators.size(); unsigned i = start; while (true) { RegionAllocator& allocator = m_allocators[i]; if (RefPtr<ExecutableMemoryHandle> result = allocator.allocate(locker, sizeInBytes)) return result; i = (i + 1) % m_allocators.size(); if (i == start) break; } return nullptr; #else return m_allocator.allocate(sizeInBytes); #endif // USE(JUMP_ISLANDS) } Lock& getLock() { return m_lock; } // Non atomic size_t bytesAllocated() { size_t result = 0; forEachAllocator([&] (Allocator& allocator) { result += allocator.bytesAllocated(); }); return result; } size_t bytesReserved() { size_t result = 0; forEachAllocator([&] (Allocator& allocator) { result += allocator.bytesReserved(); }); return result; } size_t bytesCommitted() { size_t result = 0; forEachAllocator([&] (Allocator& allocator) { result += allocator.bytesCommitted(); }); return result; } bool isInAllocatedMemory(const AbstractLocker& locker, void* address) { #if USE(JUMP_ISLANDS) if (RegionAllocator* allocator = findRegion(bitwise_cast<uintptr_t>(address))) return allocator->isInAllocatedMemory(locker, address); return false; #else return m_allocator.isInAllocatedMemory(locker, address); #endif } #if ENABLE(META_ALLOCATOR_PROFILE) void dumpProfile() { forEachAllocator([&] (Allocator& allocator) { allocator.dumpProfile(); }); } #endif MetaAllocator::Statistics currentStatistics() { auto locker = holdLock(getLock()); MetaAllocator::Statistics result { 0, 0, 0 }; forEachAllocator([&] (Allocator& allocator) { auto allocatorStats = allocator.currentStatistics(locker); result.bytesAllocated += allocatorStats.bytesAllocated; result.bytesReserved += allocatorStats.bytesReserved; result.bytesCommitted += allocatorStats.bytesCommitted; }); return result; } #if USE(JUMP_ISLANDS) void handleWillBeReleased(const LockHolder& locker, MetaAllocatorHandle& handle) { if (m_islandsForJumpSourceLocation.isEmpty()) return; Vector<Islands*, 16> toRemove; void* start = handle.start().untaggedPtr(); void* end = handle.end().untaggedPtr(); m_islandsForJumpSourceLocation.iterate([&] (Islands& islands, bool& visitLeft, bool& visitRight) { if (start <= islands.key() && islands.key() < end) toRemove.append(&islands); if (islands.key() > start) visitLeft = true; if (islands.key() < end) visitRight = true; }); for (Islands* islands : toRemove) freeIslands(locker, islands); if (ASSERT_ENABLED) { m_islandsForJumpSourceLocation.iterate([&] (Islands& islands, bool& visitLeft, bool& visitRight) { if (start <= islands.key() && islands.key() < end) { dataLogLn("did not remove everything!"); RELEASE_ASSERT_NOT_REACHED(); } visitLeft = true; visitRight = true; }); } } void* makeIsland(uintptr_t jumpLocation, uintptr_t newTarget, bool concurrently) { auto locker = holdLock(getLock()); return islandForJumpLocation(locker, jumpLocation, newTarget, concurrently); } private: RegionAllocator* findRegion(uintptr_t ptr) { RegionAllocator* result = nullptr; forEachAllocator([&] (RegionAllocator& allocator) { if (allocator.start() <= ptr && ptr < allocator.end()) { result = &allocator; return IterationStatus::Done; } return IterationStatus::Continue; }); return result; } void freeJumpIslands(const LockHolder&, Islands* islands) { for (CodeLocationLabel<ExecutableMemoryPtrTag> jumpIsland : islands->jumpIslands) { uintptr_t untaggedJumpIsland = bitwise_cast<uintptr_t>(jumpIsland.dataLocation()); RegionAllocator* allocator = findRegion(untaggedJumpIsland); RELEASE_ASSERT(allocator); allocator->freeIsland(untaggedJumpIsland); } islands->jumpIslands.clear(); } void freeIslands(const LockHolder& locker, Islands* islands) { freeJumpIslands(locker, islands); m_islandsForJumpSourceLocation.remove(islands); delete islands; } void* islandForJumpLocation(const LockHolder& locker, uintptr_t jumpLocation, uintptr_t target, bool concurrently) { Islands* islands = m_islandsForJumpSourceLocation.findExact(bitwise_cast<void*>(jumpLocation)); if (islands) { // FIXME: We could create some method of reusing already allocated islands here, but it's // unlikely to matter in practice. if (!concurrently) freeJumpIslands(locker, islands); } else { islands = new Islands; islands->jumpSourceLocation = CodeLocationLabel<ExecutableMemoryPtrTag>(tagCodePtr<ExecutableMemoryPtrTag>(bitwise_cast<void*>(jumpLocation))); m_islandsForJumpSourceLocation.insert(islands); } RegionAllocator* allocator = findRegion(jumpLocation > target ? jumpLocation - regionSize : jumpLocation); RELEASE_ASSERT(allocator); void* result = allocator->allocateIsland(); void* currentIsland = result; jumpLocation = bitwise_cast<uintptr_t>(currentIsland); while (true) { islands->jumpIslands.append(CodeLocationLabel<ExecutableMemoryPtrTag>(tagCodePtr<ExecutableMemoryPtrTag>(currentIsland))); auto emitJumpTo = [&] (void* target) { RELEASE_ASSERT(ARM64Assembler::canEmitJump(bitwise_cast<void*>(jumpLocation), target)); MacroAssembler jit; auto jump = jit.jump(); LinkBuffer linkBuffer(jit, MacroAssemblerCodePtr<NoPtrTag>(currentIsland), islandSizeInBytes, JITCompilationMustSucceed, false); RELEASE_ASSERT(linkBuffer.isValid()); // We use this to appease the assertion that we're not finalizing on a compiler thread. In this situation, it's // ok to do this on a compiler thread, since the compiler thread is linking a jump to this code (and no other live // code can jump to these islands). It's ok because the CPU protocol for exposing code to other CPUs is: // - Self modifying code fence (what FINALIZE_CODE does below). This does various memory flushes + instruction sync barrier (isb). // - Any CPU that will run the code must run a crossModifyingCodeFence (isb) before running it. Since the code that // has a jump linked to this island hasn't finalized yet, they're guaranteed to finalize there code and run an isb. linkBuffer.setIsJumpIsland(); linkBuffer.link(jump, CodeLocationLabel<NoPtrTag>(target)); FINALIZE_CODE(linkBuffer, NoPtrTag, "Jump Island: %lu", jumpLocation); }; if (ARM64Assembler::canEmitJump(bitwise_cast<void*>(jumpLocation), bitwise_cast<void*>(target))) { emitJumpTo(bitwise_cast<void*>(target)); break; } uintptr_t nextIslandRegion; if (jumpLocation > target) nextIslandRegion = jumpLocation - regionSize; else nextIslandRegion = jumpLocation + regionSize; RegionAllocator* allocator = findRegion(nextIslandRegion); RELEASE_ASSERT(allocator); void* nextIsland = allocator->allocateIsland(); emitJumpTo(nextIsland); jumpLocation = bitwise_cast<uintptr_t>(nextIsland); currentIsland = nextIsland; } return result; } #endif // USE(JUMP_ISLANDS) private: class Allocator : public MetaAllocator { using Base = MetaAllocator; public: Allocator(FixedVMPoolExecutableAllocator& allocator) : Base(allocator.getLock(), jitAllocationGranule, pageSize()) // round up all allocations to 32 bytes , m_fixedAllocator(allocator) { } FreeSpacePtr allocateNewSpace(size_t&) override { // We're operating in a fixed pool, so new allocation is always prohibited. return nullptr; } void notifyNeedPage(void* page, size_t count) override { m_fixedAllocator.m_reservation.commit(page, pageSize() * count); } void notifyPageIsFree(void* page, size_t count) override { m_fixedAllocator.m_reservation.decommit(page, pageSize() * count); } FixedVMPoolExecutableAllocator& m_fixedAllocator; }; #if USE(JUMP_ISLANDS) class RegionAllocator final : public Allocator { using Base = Allocator; public: RegionAllocator(FixedVMPoolExecutableAllocator& allocator) : Base(allocator) { } // ------------------------------------ // | jit allocations --> <-- islands | // ------------------------------------- uintptr_t start() { return bitwise_cast<uintptr_t>(untagCodePtr<ExecutableMemoryPtrTag>(m_start)); } uintptr_t end() { return bitwise_cast<uintptr_t>(untagCodePtr<ExecutableMemoryPtrTag>(m_end)); } uintptr_t islandBegin() { // [start, allocatorEnd) return end() - islandRegionSize; } uintptr_t allocatorSize() { return islandBegin() - start(); } size_t islandsPerPage() { size_t islandsPerPage = pageSize() / islandSizeInBytes; ASSERT(islandsPerPage * islandSizeInBytes == pageSize()); ASSERT(isPowerOfTwo(islandsPerPage)); return islandsPerPage; } void release(const LockHolder& locker, MetaAllocatorHandle& handle) final { m_fixedAllocator.handleWillBeReleased(locker, handle); Base::release(locker, handle); } void* allocateIsland() { uintptr_t end = this->end(); auto findResult = [&] () -> void* { size_t resultBit = islandBits.findClearBit(0); if (resultBit == islandBits.size()) return nullptr; islandBits[resultBit] = true; uintptr_t result = end - ((resultBit + 1) * islandSizeInBytes); return bitwise_cast<void*>(result); }; if (void* result = findResult()) return result; islandBits.resize(islandBits.size() + islandsPerPage()); if (UNLIKELY(islandBits.size() > maxIslandsPerRegion)) crashOnJumpIslandExhaustion(); uintptr_t pageBegin = end - (islandBits.size() * islandSizeInBytes); // [islandBegin, end) m_fixedAllocator.m_reservation.commit(bitwise_cast<void*>(pageBegin), pageSize()); void* result = findResult(); RELEASE_ASSERT(result); return result; } NEVER_INLINE NO_RETURN_DUE_TO_CRASH void crashOnJumpIslandExhaustion() { CRASH(); } Optional<size_t> islandBit(uintptr_t island) { uintptr_t end = this->end(); if (islandBegin() <= island && island < end) return ((end - island) / islandSizeInBytes) - 1; return WTF::nullopt; } void freeIsland(uintptr_t island) { RELEASE_ASSERT(islandBegin() <= island && island < end()); size_t bit = islandBit(island).value(); RELEASE_ASSERT(!!islandBits[bit]); islandBits[bit] = false; } bool isInAllocatedMemory(const AbstractLocker& locker, void* address) { if (Base::isInAllocatedMemory(locker, address)) return true; if (Optional<size_t> bit = islandBit(bitwise_cast<uintptr_t>(address))) { if (bit.value() < islandBits.size()) return !!islandBits[bit.value()]; } return false; } // Range: [start, end) void* m_start; void* m_end; FastBitVector islandBits; }; #endif // USE(JUMP_ISLANDS) template <typename Function> void forEachAllocator(Function function) { #if USE(JUMP_ISLANDS) for (RegionAllocator& allocator : m_allocators) { using FunctionResultType = decltype(function(allocator)); if constexpr (std::is_same<IterationStatus, FunctionResultType>::value) { if (function(allocator) == IterationStatus::Done) break; } else { static_assert(std::is_same<void, FunctionResultType>::value); function(allocator); } } #else function(m_allocator); #endif // USE(JUMP_ISLANDS) } #if USE(JUMP_ISLANDS) class Islands : public RedBlackTree<Islands, void*>::Node { WTF_MAKE_FAST_ALLOCATED; public: void* key() { return jumpSourceLocation.dataLocation(); } CodeLocationLabel<ExecutableMemoryPtrTag> jumpSourceLocation; Vector<CodeLocationLabel<ExecutableMemoryPtrTag>> jumpIslands; }; #endif // USE(JUMP_ISLANDS) Lock m_lock; PageReservation m_reservation; #if USE(JUMP_ISLANDS) std::array<RegionAllocator, numberOfRegions> m_allocators; RedBlackTree<Islands, void*> m_islandsForJumpSourceLocation; #else Allocator m_allocator; #endif // USE(JUMP_ISLANDS) }; // Keep this pointer in a mutable global variable to help Leaks find it. // But we do not use this pointer. static FixedVMPoolExecutableAllocator* globalFixedVMPoolExecutableAllocatorToWorkAroundLeaks = nullptr; void ExecutableAllocator::initializeUnderlyingAllocator() { RELEASE_ASSERT(!g_jscConfig.fixedVMPoolExecutableAllocator); g_jscConfig.fixedVMPoolExecutableAllocator = new FixedVMPoolExecutableAllocator(); globalFixedVMPoolExecutableAllocatorToWorkAroundLeaks = g_jscConfig.fixedVMPoolExecutableAllocator; } bool ExecutableAllocator::isValid() const { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::isValid(); return allocator->isValid(); } bool ExecutableAllocator::underMemoryPressure() { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::underMemoryPressure(); return allocator->bytesAllocated() > allocator->bytesReserved() / 2; } double ExecutableAllocator::memoryPressureMultiplier(size_t addedMemoryUsage) { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::memoryPressureMultiplier(addedMemoryUsage); ASSERT(allocator->bytesAllocated() <= allocator->bytesReserved()); size_t bytesAllocated = allocator->bytesAllocated() + addedMemoryUsage; size_t bytesAvailable = static_cast<size_t>( allocator->bytesReserved() * (1 - executablePoolReservationFraction)); if (bytesAllocated >= bytesAvailable) bytesAllocated = bytesAvailable; double result = 1.0; size_t divisor = bytesAvailable - bytesAllocated; if (divisor) result = static_cast<double>(bytesAvailable) / divisor; if (result < 1.0) result = 1.0; return result; } RefPtr<ExecutableMemoryHandle> ExecutableAllocator::allocate(size_t sizeInBytes, JITCompilationEffort effort) { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::allocate(sizeInBytes, effort); if (Options::logExecutableAllocation()) { MetaAllocator::Statistics stats = allocator->currentStatistics(); dataLog("Allocating ", sizeInBytes, " bytes of executable memory with ", stats.bytesAllocated, " bytes allocated, ", stats.bytesReserved, " bytes reserved, and ", stats.bytesCommitted, " committed.\n"); } if (effort != JITCompilationCanFail && Options::reportMustSucceedExecutableAllocations()) { dataLog("Allocating ", sizeInBytes, " bytes of executable memory with JITCompilationMustSucceed.\n"); WTFReportBacktrace(); } if (effort == JITCompilationCanFail && doExecutableAllocationFuzzingIfEnabled() == PretendToFailExecutableAllocation) return nullptr; if (effort == JITCompilationCanFail) { // Don't allow allocations if we are down to reserve. size_t bytesAllocated = allocator->bytesAllocated() + sizeInBytes; size_t bytesAvailable = static_cast<size_t>( allocator->bytesReserved() * (1 - executablePoolReservationFraction)); if (bytesAllocated > bytesAvailable) { if (Options::logExecutableAllocation()) dataLog("Allocation failed because bytes allocated ", bytesAllocated, " > ", bytesAvailable, " bytes available.\n"); return nullptr; } } RefPtr<ExecutableMemoryHandle> result = allocator->allocate(sizeInBytes); if (!result) { if (effort != JITCompilationCanFail) { dataLog("Ran out of executable memory while allocating ", sizeInBytes, " bytes.\n"); CRASH(); } return nullptr; } void* start = allocator->memoryStart(); void* end = allocator->memoryEnd(); void* resultStart = result->start().untaggedPtr(); void* resultEnd = result->end().untaggedPtr(); RELEASE_ASSERT(start <= resultStart && resultStart < end); RELEASE_ASSERT(start < resultEnd && resultEnd <= end); return result; } bool ExecutableAllocator::isValidExecutableMemory(const AbstractLocker& locker, void* address) { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::isValidExecutableMemory(locker, address); return allocator->isInAllocatedMemory(locker, address); } Lock& ExecutableAllocator::getLock() const { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::getLock(); return allocator->getLock(); } size_t ExecutableAllocator::committedByteCount() { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return Base::committedByteCount(); return allocator->bytesCommitted(); } #if ENABLE(META_ALLOCATOR_PROFILE) void ExecutableAllocator::dumpProfile() { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return; allocator->dumpProfile(); } #endif #if USE(JUMP_ISLANDS) void* ExecutableAllocator::getJumpIslandTo(void* from, void* newDestination) { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) RELEASE_ASSERT_NOT_REACHED(); return allocator->makeIsland(bitwise_cast<uintptr_t>(from), bitwise_cast<uintptr_t>(newDestination), false); } void* ExecutableAllocator::getJumpIslandToConcurrently(void* from, void* newDestination) { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) RELEASE_ASSERT_NOT_REACHED(); return allocator->makeIsland(bitwise_cast<uintptr_t>(from), bitwise_cast<uintptr_t>(newDestination), true); } #endif void* startOfFixedExecutableMemoryPoolImpl() { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return nullptr; return allocator->memoryStart(); } void* endOfFixedExecutableMemoryPoolImpl() { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; if (!allocator) return nullptr; return allocator->memoryEnd(); } bool isJITPC(void* pc) { FixedVMPoolExecutableAllocator* allocator = g_jscConfig.fixedVMPoolExecutableAllocator; return allocator && allocator->isJITPC(pc); } void dumpJITMemory(const void* dst, const void* src, size_t size) { RELEASE_ASSERT(Options::dumpJITMemoryPath()); #if OS(DARWIN) static int fd = -1; static uint8_t* buffer; static constexpr size_t bufferSize = fixedExecutableMemoryPoolSize; static size_t offset = 0; static Lock dumpJITMemoryLock; static bool needsToFlush = false; static auto flush = [](const AbstractLocker&) { if (fd == -1) { String path = Options::dumpJITMemoryPath(); path = path.replace("%pid", String::number(getCurrentProcessID())); fd = open(FileSystem::fileSystemRepresentation(path).data(), O_CREAT | O_TRUNC | O_APPEND | O_WRONLY | O_EXLOCK | O_NONBLOCK, 0666); RELEASE_ASSERT(fd != -1); } write(fd, buffer, offset); offset = 0; needsToFlush = false; }; static std::once_flag once; static LazyNeverDestroyed<Ref<WorkQueue>> flushQueue; std::call_once(once, [] { buffer = bitwise_cast<uint8_t*>(malloc(bufferSize)); flushQueue.construct(WorkQueue::create("jsc.dumpJITMemory.queue", WorkQueue::Type::Serial, WorkQueue::QOS::Background)); std::atexit([] { LockHolder locker(dumpJITMemoryLock); flush(locker); close(fd); fd = -1; }); }); static auto enqueueFlush = [](const AbstractLocker&) { if (needsToFlush) return; needsToFlush = true; flushQueue.get()->dispatchAfter(Seconds(Options::dumpJITMemoryFlushInterval()), [] { LockHolder locker(dumpJITMemoryLock); if (!needsToFlush) return; flush(locker); }); }; static auto write = [](const AbstractLocker& locker, const void* src, size_t size) { if (UNLIKELY(offset + size > bufferSize)) flush(locker); memcpy(buffer + offset, src, size); offset += size; enqueueFlush(locker); }; LockHolder locker(dumpJITMemoryLock); uint64_t time = mach_absolute_time(); uint64_t dst64 = bitwise_cast<uintptr_t>(dst); uint64_t size64 = size; TraceScope(DumpJITMemoryStart, DumpJITMemoryStop, time, dst64, size64); write(locker, &time, sizeof(time)); write(locker, &dst64, sizeof(dst64)); write(locker, &size64, sizeof(size64)); write(locker, src, size); #else UNUSED_PARAM(dst); UNUSED_PARAM(src); UNUSED_PARAM(size); RELEASE_ASSERT_NOT_REACHED(); #endif } } // namespace JSC #endif // ENABLE(JIT) namespace JSC { // Keep this pointer in a mutable global variable to help Leaks find it. // But we do not use this pointer. static ExecutableAllocator* globalExecutableAllocatorToWorkAroundLeaks = nullptr; void ExecutableAllocator::initialize() { g_jscConfig.executableAllocator = new ExecutableAllocator; globalExecutableAllocatorToWorkAroundLeaks = g_jscConfig.executableAllocator; } ExecutableAllocator& ExecutableAllocator::singleton() { ASSERT(g_jscConfig.executableAllocator); return *g_jscConfig.executableAllocator; } } // namespace JSC
; A030130: Binary expansion contains a single 0. ; 0,2,5,6,11,13,14,23,27,29,30,47,55,59,61,62,95,111,119,123,125,126,191,223,239,247,251,253,254,383,447,479,495,503,507,509,510,767,895,959,991,1007,1015,1019,1021,1022,1535,1791,1919,1983,2015,2031,2039,2043,2045,2046,3071,3583,3839,3967,4031,4063,4079,4087,4091,4093,4094,6143,7167,7679,7935,8063,8127,8159,8175,8183,8187,8189,8190,12287,14335,15359,15871,16127,16255,16319,16351,16367,16375,16379,16381,16382,24575,28671,30719,31743,32255,32511,32639,32703,32735,32751,32759,32763,32765,32766,49151,57343,61439,63487,64511,65023,65279,65407,65471,65503,65519,65527,65531,65533,65534,98303,114687,122879,126975,129023,130047,130559,130815,130943,131007,131039,131055,131063,131067,131069,131070,196607,229375,245759,253951,258047,260095,261119,261631,261887,262015,262079,262111,262127,262135,262139,262141,262142,393215,458751,491519,507903,516095,520191,522239,523263,523775,524031,524159,524223,524255,524271,524279,524283,524285,524286,786431,917503,983039,1015807,1032191,1040383,1044479,1046527,1047551,1048063,1048319,1048447,1048511,1048543,1048559,1048567,1048571,1048573,1048574,1572863,1835007,1966079,2031615,2064383,2080767,2088959,2093055,2095103,2096127,2096639,2096895,2097023,2097087,2097119,2097135,2097143,2097147,2097149,2097150,3145727,3670015,3932159,4063231,4128767,4161535,4177919,4186111,4190207,4192255,4193279,4193791,4194047,4194175,4194239,4194271,4194287,4194295,4194299,4194301,4194302,6291455,7340031,7864319,8126463,8257535,8323071,8355839,8372223,8380415,8384511,8386559,8387583,8388095,8388351,8388479,8388543,8388575,8388591 lpb $0 sub $0,1 cal $0,175332 ; Numbers whose binary expansion is of the form 11+0* mov $1,$0 mov $0,$2 sub $1,1 lpe
############################################################################### # Copyright 2019 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. ############################################################################### .text .p2align 5, 0x90 .globl _l9_PurgeBlock _l9_PurgeBlock: movslq %esi, %rcx xor %rax, %rax sub $(8), %rcx jl .Ltest_purgegas_1 .Lpurge8gas_1: movq %rax, (%rdi) add $(8), %rdi sub $(8), %rcx jge .Lpurge8gas_1 .Ltest_purgegas_1: add $(8), %rcx jz .Lquitgas_1 .Lpurge1gas_1: movb %al, (%rdi) add $(1), %rdi sub $(1), %rcx jg .Lpurge1gas_1 .Lquitgas_1: vzeroupper ret
#pragma once #include "elx_deconv_direct.hpp" namespace euler { Template_elx_deconv_direct_t void Instance_elx_deconv_direct_t::bind_execute_functions() { #define BIND_CONV_KERNEL(S, F, K) \ if (K == 3) { \ conv_kernel_binder::bind<S, F, 3>(O, T, func); \ } else if (K == 5) { \ conv_kernel_binder::bind<S, F, 5>(O, T, func); \ } else if (K == 7) { \ conv_kernel_binder::bind<S, F, 7>(O, T, func); \ } auto bind_conv_kernel = [&](int O, int T, conv_kernel_binder::kconv<TarrayTypes> **func, int K) { switch (xopt_) { case (0xa060): if (ep.input_fmt == nchw) { if (ep.ws == 1) { BIND_CONV_KERNEL(1, GKF_EBD, K); } else if (ep.ws == 2) { BIND_CONV_KERNEL(2, GKF_EBD, K); } else { el_error("Stride > 2 not yet bounded"); } } else if (ep.input_fmt == nhwc) { if (ep.ws == 1) { BIND_CONV_KERNEL(1, GKF_FCF, K); } else if (ep.ws == 2) { BIND_CONV_KERNEL(2, GKF_FCF, K); } else { el_error("Stride > 2 not yet bounded"); } } else { if (ep.ws == 1) { BIND_CONV_KERNEL(1, GKF_DCD, K); } else if (ep.ws == 2) { BIND_CONV_KERNEL(2, GKF_DCD, K); } else { el_error("Stride > 2 not yet bounded"); } } break; default: el_error("Unknown xopt"); break; } }; bind_conv_kernel(ep.O, ep.T, &ker_conv_, ep.kw); bind_conv_kernel(ep.O, ep.Tr, &ker_conv_Tr_, ep.kw); #define EXECUTE_CASE(n) \ case 0x##n: \ execute_opt_ = &Instance_elx_deconv_direct_t::__execute_##n; \ break switch (xopt_) { EXECUTE_CASE(a060); default: el_error("Unimplemented xopt"); break; } } } // namespace euler
USE32 ALIGN 4096 section .diskdata incbin "testdisk"
//Copyright [2020] [Indian Institute of Science, Bangalore & Tata Institute of Fundamental Research, Mumbai] //SPDX-License-Identifier: Apache-2.0 #include <rapidjson/document.h> #include <rapidjson/istreamwrapper.h> #include <rapidjson/prettywriter.h> #include <rapidjson/stringbuffer.h> #include <algorithm> #include <iostream> #include <fstream> #include <vector> #include <random> #include <string> #include <cmath> #include <set> #include "models.h" #include "initializers.h" #ifdef DEBUG #include <cassert> #endif using std::string; using std::vector; using std::set; using std::to_string; auto readJSONFile(string filename){ std::ifstream ifs(filename, std::ifstream::in); rapidjson::IStreamWrapper isw(ifs); rapidjson::Document d; d.ParseStream(isw); return d; } auto prettyJSON(const rapidjson::Document& d){ rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } vector<house> init_homes(){ auto houseJSON = readJSONFile(GLOBAL.input_base + "houses.json"); auto size = houseJSON.GetArray().Size(); vector<house> homes(size); GLOBAL.num_homes = size; double temp_non_compliance_metric = 0; count_type index = 0; bool compliance; for (auto &elem: houseJSON.GetArray()){ temp_non_compliance_metric = get_non_compliance_metric(); if(elem.HasMember("slum") && elem["slum"].GetInt()){ compliance = (temp_non_compliance_metric<=GLOBAL.HD_COMPLIANCE_PROBABILITY); } else { compliance = (temp_non_compliance_metric<=GLOBAL.COMPLIANCE_PROBABILITY); } homes[index].set(elem["lat"].GetDouble(), elem["lon"].GetDouble(), compliance, temp_non_compliance_metric); //Cyclic strategy class if(GLOBAL.CYCLIC_POLICY_ENABLED && GLOBAL.CYCLIC_POLICY_TYPE == Cycle_Type::home){ homes[index].cyclic_strategy_class = uniform_count_type(0, GLOBAL.NUMBER_OF_CYCLIC_CLASSES - 1); } homes[index].age_independent_mixing = 0; if(GLOBAL.USE_AGE_DEPENDENT_MIXING){ homes[index].age_dependent_mixing.resize(GLOBAL.NUM_AGE_GROUPS, 0); } ++index; } return homes; } vector<workplace> init_workplaces() { auto schoolJSON = readJSONFile(GLOBAL.input_base + "schools.json"); auto wpJSON = readJSONFile(GLOBAL.input_base + "workplaces.json"); auto school_size = schoolJSON.GetArray().Size(); GLOBAL.num_schools = school_size; auto wp_size = wpJSON.GetArray().Size(); GLOBAL.num_workplaces = wp_size; auto size = wp_size + school_size; vector<workplace> wps(size); count_type index = 0; // schools come first followed by workspaces, as in the JSON version for (auto &elem: schoolJSON.GetArray()){ wps[index].set(elem["lat"].GetDouble(), elem["lon"].GetDouble(), WorkplaceType::school); wps[index].age_independent_mixing = 0; if(GLOBAL.USE_AGE_DEPENDENT_MIXING){ wps[index].age_dependent_mixing.resize(GLOBAL.NUM_AGE_GROUPS, 0); } ++index; } assert(index == GLOBAL.num_schools); for (auto &elem: wpJSON.GetArray()){ wps[index].set(elem["lat"].GetDouble(), elem["lon"].GetDouble(), WorkplaceType::office); wps[index].office_type = static_cast<OfficeType>(elem["officeType"].GetInt()); wps[index].age_independent_mixing = 0; if(GLOBAL.USE_AGE_DEPENDENT_MIXING){ wps[index].age_dependent_mixing.resize(GLOBAL.NUM_AGE_GROUPS, 0); } ++index; } assert(index == GLOBAL.num_schools + GLOBAL.num_workplaces); return wps; } vector<community> init_community() { auto comJSON = readJSONFile(GLOBAL.input_base + "commonArea.json"); auto size = comJSON.GetArray().Size(); GLOBAL.num_communities = size; vector<community> communities(size); count_type index = 0; for (auto &elem: comJSON.GetArray()){ communities[index].set(elem["lat"].GetDouble(), elem["lon"].GetDouble(), elem["wardNo"].GetInt()); ++index; } assert(index == GLOBAL.num_communities); sort(communities.begin(), communities.end(), [](const auto& a, const auto& b){ return a.wardNo < b.wardNo; }); return communities; } matrix<nbr_cell> init_nbr_cells() { matrix<nbr_cell> nbr_cells; if(GLOBAL.ENABLE_NBR_CELLS){ location loc_temp; loc_temp.lat = GLOBAL.city_SW.lat; loc_temp.lon = GLOBAL.city_NE.lon; count_type num_x_grids = ceil(earth_distance(GLOBAL.city_SW,loc_temp)/GLOBAL.NBR_CELL_SIZE); nbr_cells.resize(num_x_grids); loc_temp.lon = GLOBAL.city_SW.lon; loc_temp.lat = GLOBAL.city_NE.lat; count_type num_y_grids = ceil(earth_distance(GLOBAL.city_SW,loc_temp)/GLOBAL.NBR_CELL_SIZE); for(count_type count_x_grid = 0; count_x_grid < num_x_grids; ++count_x_grid){ nbr_cells[count_x_grid].resize(num_y_grids); for(count_type count_y_grid = 0; count_y_grid < num_y_grids; ++count_y_grid){ nbr_cells[count_x_grid][count_y_grid].neighbourhood.cell_x = count_x_grid; nbr_cells[count_x_grid][count_y_grid].neighbourhood.cell_y = count_y_grid; } } } return nbr_cells; } void print_intervention_params(const int index, const intervention_params intv_params){ std::cout<<std::endl<<"Index : "<<index<<". num_days = "<< intv_params.num_days; std::cout<<". Case Isolation : " << intv_params.case_isolation; std::cout<<". Home Quarantine : " << intv_params.home_quarantine; std::cout<<". Lockdown : " << intv_params.lockdown; std::cout<<". SDO : " << intv_params.social_dist_elderly; std::cout<<". School Closed : " << intv_params.school_closed; std::cout<<". workplace_odd_even : " << intv_params.workplace_odd_even; std::cout<<". SC_factor : " << intv_params.SC_factor; std::cout<<". community_factor : " << intv_params.community_factor; std::cout<<". neighbourhood_containment : " << intv_params.neighbourhood_containment; std::cout<<". ward_containment : " << intv_params.ward_containment; std::cout<<". compliance : " << intv_params.compliance; std::cout<<". compliance_hd : " << intv_params.compliance_hd; std::cout<<". trains_active : " << intv_params.trains_active; std::cout<<". fraction_forced_to_take_train : " << intv_params.fraction_forced_to_take_train; } vector<intervention_params> init_intervention_params(){ vector<intervention_params> intv_params; if(GLOBAL.INTERVENTION==Intervention::intv_file_read){ std::cout<<std::endl<<"Inside init_intervention_params"; auto intvJSON = readJSONFile(GLOBAL.input_base + GLOBAL.intervention_filename); intv_params.reserve(intvJSON.GetArray().Size()); int index = 0; for (auto &elem: intvJSON.GetArray()){ intervention_params temp; if((elem.HasMember("num_days")) && (elem["num_days"].GetInt() > 0)){ temp.num_days = elem["num_days"].GetInt(); if(elem.HasMember("compliance")){ temp.compliance = elem["compliance"].GetDouble(); temp.compliance_hd = elem["compliance"].GetDouble(); //By default, compliance = compliance_hd. Can be reset below } else{ temp.compliance = GLOBAL.COMPLIANCE_PROBABILITY; temp.compliance_hd = GLOBAL.COMPLIANCE_PROBABILITY; //By default, compliance = compliance_hd. Can be reset below } if(elem.HasMember("compliance_hd")){ temp.compliance_hd = elem["compliance_hd"].GetDouble(); } else{ temp.compliance_hd = GLOBAL.COMPLIANCE_PROBABILITY; } if(elem.HasMember("case_isolation")){ temp.case_isolation = elem["case_isolation"]["active"].GetBool(); } if(elem.HasMember("home_quarantine")){ temp.home_quarantine = elem["home_quarantine"]["active"].GetBool(); } if(elem.HasMember("locked_community_leakage")){ temp.locked_community_leakage = elem["locked_community_leakage"].GetDouble(); } else { temp.locked_community_leakage = GLOBAL.LOCKED_COMMUNITY_LEAKAGE; //Keeps last state if not specified explicitly. } if(elem.HasMember("lockdown")){ //TODO: collect all these statements in a function. temp.lockdown = elem["lockdown"]["active"].GetBool(); if(elem["lockdown"].HasMember("kappa_values_compliant")){ if(elem["lockdown"]["kappa_values_compliant"].HasMember("kappa_H")){ temp.lockdown_kappas_compliant.kappa_H = elem["lockdown"]["kappa_values_compliant"]["kappa_H"].GetDouble(); } if(elem["lockdown"]["kappa_values_compliant"].HasMember("kappa_H_incoming")){ temp.lockdown_kappas_compliant.kappa_H_incoming = elem["lockdown"]["kappa_values_compliant"]["kappa_H_incoming"].GetDouble(); } if(elem["lockdown"]["kappa_values_compliant"].HasMember("kappa_W")){ temp.lockdown_kappas_compliant.kappa_W = elem["lockdown"]["kappa_values_compliant"]["kappa_W"].GetDouble(); } if(elem["lockdown"]["kappa_values_compliant"].HasMember("kappa_W_incoming")){ temp.lockdown_kappas_compliant.kappa_W_incoming = elem["lockdown"]["kappa_values_compliant"]["kappa_W_incoming"].GetDouble(); } if(elem["lockdown"]["kappa_values_compliant"].HasMember("kappa_C")){ temp.lockdown_kappas_compliant.kappa_C = elem["lockdown"]["kappa_values_compliant"]["kappa_C"].GetDouble(); } if(elem["lockdown"]["kappa_values_compliant"].HasMember("kappa_C_incoming")){ temp.lockdown_kappas_compliant.kappa_C_incoming = elem["lockdown"]["kappa_values_compliant"]["kappa_C_incoming"].GetDouble(); } } if(elem["lockdown"].HasMember("kappa_values_non_compliant")){ if(elem["lockdown"]["kappa_values_non_compliant"].HasMember("kappa_H")){ temp.lockdown_kappas_non_compliant.kappa_H = elem["lockdown"]["kappa_values_non_compliant"]["kappa_H"].GetDouble(); } if(elem["lockdown"]["kappa_values_non_compliant"].HasMember("kappa_H_incoming")){ temp.lockdown_kappas_non_compliant.kappa_H_incoming = elem["lockdown"]["kappa_values_non_compliant"]["kappa_H_incoming"].GetDouble(); } if(elem["lockdown"]["kappa_values_non_compliant"].HasMember("kappa_W")){ temp.lockdown_kappas_non_compliant.kappa_W = elem["lockdown"]["kappa_values_non_compliant"]["kappa_W"].GetDouble(); } if(elem["lockdown"]["kappa_values_non_compliant"].HasMember("kappa_W_incoming")){ temp.lockdown_kappas_non_compliant.kappa_W_incoming = elem["lockdown"]["kappa_values_non_compliant"]["kappa_W_incoming"].GetDouble(); } if(elem["lockdown"]["kappa_values_non_compliant"].HasMember("kappa_C")){ temp.lockdown_kappas_non_compliant.kappa_C = elem["lockdown"]["kappa_values_non_compliant"]["kappa_C"].GetDouble(); } if(elem["lockdown"]["kappa_values_non_compliant"].HasMember("kappa_C_incoming")){ temp.lockdown_kappas_non_compliant.kappa_C_incoming = elem["lockdown"]["kappa_values_non_compliant"]["kappa_C_incoming"].GetDouble(); } } } if(elem.HasMember("social_dist_elderly")){ temp.social_dist_elderly = elem["social_dist_elderly"]["active"].GetBool(); } if(elem.HasMember("school_closed")){ temp.school_closed = elem["school_closed"]["active"].GetBool(); if(elem["school_closed"].HasMember("SC_factor")){ temp.SC_factor = elem["school_closed"]["SC_factor"].GetDouble(); } } if(elem.HasMember("workplace_odd_even")){ temp.workplace_odd_even = elem["workplace_odd_even"]["active"].GetBool(); } if(elem.HasMember("community_factor")){ temp.community_factor = elem["community_factor"].GetDouble(); } if(elem.HasMember("trains")){ temp.trains_active = elem["trains"]["active"].GetBool(); if(elem["trains"].HasMember("fraction_forced_to_take_train")){ temp.fraction_forced_to_take_train = elem["trains"]["fraction_forced_to_take_train"].GetDouble(); } } if(elem.HasMember("neighbourhood_containment")){ temp.neighbourhood_containment = elem["neighbourhood_containment"]["active"].GetBool() && GLOBAL.ENABLE_NEIGHBORHOOD_SOFT_CONTAINMENT && GLOBAL.ENABLE_NBR_CELLS; if(!(GLOBAL.ENABLE_NEIGHBORHOOD_SOFT_CONTAINMENT && GLOBAL.ENABLE_NBR_CELLS)){ std::cout<<std::endl<<"To enable containment strategies, add --ENABLE_NEIGHBORHOOD_SOFT_CONTAINMENT and --ENABLE_NBR_CELLS to argument list. Ignoring neighbourhood containment."; }else{ if(elem["neighbourhood_containment"].HasMember("leakage")){ temp.neighbourhood_containment_leakage = elem["neighbourhood_containment"]["leakage"].GetDouble(); }else{ temp.neighbourhood_containment_leakage = GLOBAL.LOCKED_NEIGHBORHOOD_LEAKAGE; } if(elem["neighbourhood_containment"].HasMember("threshold")){ temp.neighbourhood_containment_threshold = elem["neighbourhood_containment"]["threshold"].GetDouble(); }else{ temp.neighbourhood_containment_threshold = GLOBAL.NEIGHBORHOOD_LOCK_THRESHOLD; } } } if(elem.HasMember("ward_containment")){ temp.ward_containment = elem["ward_containment"]["active"].GetBool() && GLOBAL.ENABLE_CONTAINMENT; if(!GLOBAL.ENABLE_CONTAINMENT){ std::cout<<std::endl<<"To enable containment strategies, add --ENABLE_CONTAINMENT to argument list. Ignoring ward containment."; }else{ if(elem["ward_containment"].HasMember("leakage")){ temp.ward_containment_leakage = elem["ward_containment"]["leakage"].GetDouble(); }else{ temp.ward_containment_leakage = GLOBAL.LOCKED_COMMUNITY_LEAKAGE; } if(elem["ward_containment"].HasMember("threshold")){ temp.ward_containment_threshold = elem["ward_containment"]["threshold"].GetDouble(); }else{ temp.ward_containment_threshold = GLOBAL.COMMUNITY_LOCK_THRESHOLD; } } } print_intervention_params(index, temp); intv_params.push_back(temp); ++index; }else{ std::cout<<std::endl<<"num_days not specified or less than 1. Skipping current index."; assert(false); } } } std::cout<<std::endl<<"Intervention params size = "<<intv_params.size(); return intv_params; } void print_testing_protocol(const int index, const testing_probability probabilities){ std::cout<<std::endl<<"Index : "<<index<<". num_days = "<<probabilities.num_days; std::cout<<". prob_test_index_symptomatic: "<<probabilities.prob_test_index_symptomatic; std::cout<<". prob_test_index_hospitalised: "<<probabilities.prob_test_index_hospitalised; std::cout<<". prob_test_household_positive_symptomatic: "<<probabilities.prob_test_household_positive_symptomatic; std::cout<<". prob_test_household_hospitalised_symptomatic: "<<probabilities.prob_test_household_hospitalised_symptomatic; std::cout<<". prob_test_household_symptomatic_symptomatic: "<<probabilities.prob_test_household_symptomatic_symptomatic; std::cout<<". prob_test_household_positive_asymptomatic: "<<probabilities.prob_test_household_positive_asymptomatic; std::cout<<". prob_test_household_hospitalised_asymptomatic: "<<probabilities.prob_test_household_hospitalised_asymptomatic; std::cout<<". prob_test_household_symptomatic_asymptomatic: "<<probabilities.prob_test_household_symptomatic_asymptomatic; std::cout<<". prob_test_workplace_positive_symptomatic: "<<probabilities.prob_test_workplace_positive_symptomatic; std::cout<<". prob_test_workplace_hospitalised_symptomatic: "<<probabilities.prob_test_workplace_hospitalised_symptomatic; std::cout<<". prob_test_workplace_symptomatic_symptomatic: "<<probabilities.prob_test_workplace_symptomatic_symptomatic; std::cout<<". prob_test_workplace_positive_asymptomatic: "<<probabilities.prob_test_workplace_positive_asymptomatic; std::cout<<". prob_test_workplace_hospitalised_asymptomatic: "<<probabilities.prob_test_workplace_hospitalised_asymptomatic; std::cout<<". prob_test_workplace_symptomatic_asymptomatic: "<<probabilities.prob_test_workplace_symptomatic_asymptomatic; std::cout<<". prob_test_random_community_positive_symptomatic: "<<probabilities.prob_test_random_community_positive_symptomatic; std::cout<<". prob_test_random_community_hospitalised_symptomatic: "<<probabilities.prob_test_random_community_hospitalised_symptomatic; std::cout<<". prob_test_random_community_symptomatic_symptomatic: "<<probabilities.prob_test_random_community_symptomatic_symptomatic; std::cout<<". prob_test_random_community_positive_asymptomatic: "<<probabilities.prob_test_random_community_positive_asymptomatic; std::cout<<". prob_test_random_community_hospitalised_asymptomatic: "<<probabilities.prob_test_random_community_hospitalised_asymptomatic; std::cout<<". prob_test_random_community_symptomatic_asymptomatic: "<<probabilities.prob_test_random_community_symptomatic_asymptomatic; std::cout<<". prob_test_neighbourhood_positive_symptomatic: "<<probabilities.prob_test_neighbourhood_positive_symptomatic; std::cout<<". prob_test_neighbourhood_hospitalised_symptomatic: "<<probabilities.prob_test_neighbourhood_hospitalised_symptomatic; std::cout<<". prob_test_neighbourhood_symptomatic_symptomatic: "<<probabilities.prob_test_neighbourhood_symptomatic_symptomatic; std::cout<<". prob_test_neighbourhood_positive_asymptomatic: "<<probabilities.prob_test_neighbourhood_positive_asymptomatic; std::cout<<". prob_test_neighbourhood_hospitalised_asymptomatic: "<<probabilities.prob_test_neighbourhood_hospitalised_asymptomatic; std::cout<<". prob_test_neighbourhood_symptomatic_asymptomatic: "<<probabilities.prob_test_neighbourhood_symptomatic_asymptomatic; std::cout<<". prob_test_school_positive_symptomatic: "<<probabilities.prob_test_school_positive_symptomatic; std::cout<<". prob_test_school_hospitalised_symptomatic: "<<probabilities.prob_test_school_hospitalised_symptomatic; std::cout<<". prob_test_school_symptomatic_symptomatic: "<<probabilities.prob_test_school_symptomatic_symptomatic; std::cout<<". prob_test_school_positive_asymptomatic: "<<probabilities.prob_test_school_positive_asymptomatic; std::cout<<". prob_test_school_hospitalised_asymptomatic: "<<probabilities.prob_test_school_hospitalised_asymptomatic; std::cout<<". prob_test_school_symptomatic_asymptomatic: "<<probabilities.prob_test_school_symptomatic_asymptomatic; std::cout<<". prob_retest_recovered: "<<probabilities.prob_retest_recovered; std::cout<<". prob_contact_trace_household_symptomatic: "<<probabilities.prob_contact_trace_household_symptomatic; std::cout<<". prob_contact_trace_project_symptomatic: "<<probabilities.prob_contact_trace_project_symptomatic; std::cout<<". prob_contact_trace_random_community_symptomatic: "<<probabilities.prob_contact_trace_random_community_symptomatic; std::cout<<". prob_contact_trace_neighbourhood_symptomatic: "<<probabilities.prob_contact_trace_neighbourhood_symptomatic; std::cout<<". prob_contact_trace_class_symptomatic: "<<probabilities.prob_contact_trace_class_symptomatic; std::cout<<". prob_contact_trace_household_hospitalised: "<<probabilities.prob_contact_trace_household_hospitalised; std::cout<<". prob_contact_trace_project_hospitalised: "<<probabilities.prob_contact_trace_project_hospitalised; std::cout<<". prob_contact_trace_random_community_hospitalised: "<<probabilities.prob_contact_trace_random_community_hospitalised; std::cout<<". prob_contact_trace_neighbourhood_hospitalised: "<<probabilities.prob_contact_trace_neighbourhood_hospitalised; std::cout<<". prob_contact_trace_class_hospitalised: "<<probabilities.prob_contact_trace_class_hospitalised; std::cout<<". prob_contact_trace_household_positive: "<<probabilities.prob_contact_trace_household_positive; std::cout<<". prob_contact_trace_project_positive: "<<probabilities.prob_contact_trace_project_positive; std::cout<<". prob_contact_trace_random_community_positive: "<<probabilities.prob_contact_trace_random_community_positive; std::cout<<". prob_contact_trace_neighbourhood_positive: "<<probabilities.prob_contact_trace_neighbourhood_positive; std::cout<<". prob_contact_trace_class_positive: "<<probabilities.prob_contact_trace_class_positive; } vector<testing_probability> init_testing_protocol(){ vector<testing_probability> testing_protocol; if(GLOBAL.TESTING_PROTOCOL==Testing_Protocol::testing_protocol_file_read){ std::cout<<std::endl<<"Inside init_testing_protocol"; auto testProtJSON = readJSONFile(GLOBAL.input_base + GLOBAL.testing_protocol_filename); testing_protocol.reserve(testProtJSON.GetArray().Size()); count_type index = 0; for (auto &elem: testProtJSON.GetArray()){ testing_probability temp; if((elem.HasMember("num_days")) && (elem["num_days"].GetInt() > 0)){ temp.num_days = elem["num_days"].GetInt(); if(elem.HasMember("test_false_positive")){ GLOBAL.TEST_FALSE_POSITIVE = elem["test_false_positive"].GetDouble(); } if(elem.HasMember("test_false_negative")){ GLOBAL.TEST_FALSE_NEGATIVE = elem["test_false_negative"].GetDouble(); } if(elem.HasMember("prob_test_index_symptomatic")){ temp.prob_test_index_symptomatic = elem["prob_test_index_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_index_hospitalised")){ temp.prob_test_index_hospitalised = elem["prob_test_index_hospitalised"].GetDouble(); } //Testing probabilities for household networks if(elem.HasMember("prob_test_household_positive_symptomatic")){ temp.prob_test_household_positive_symptomatic = elem["prob_test_household_positive_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_household_hospitalised_symptomatic")){ temp.prob_test_household_hospitalised_symptomatic = elem["prob_test_household_hospitalised_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_household_symptomatic_symptomatic")){ temp.prob_test_household_symptomatic_symptomatic = elem["prob_test_household_symptomatic_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_household_positive_asymptomatic")){ temp.prob_test_household_positive_asymptomatic = elem["prob_test_household_positive_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_household_hospitalised_asymptomatic")){ temp.prob_test_household_hospitalised_asymptomatic = elem["prob_test_household_hospitalised_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_household_symptomatic_asymptomatic")){ temp.prob_test_household_symptomatic_asymptomatic = elem["prob_test_household_symptomatic_asymptomatic"].GetDouble(); } //Testing probabilities for workplace networks if(elem.HasMember("prob_test_workplace_positive_symptomatic")){ temp.prob_test_workplace_positive_symptomatic = elem["prob_test_workplace_positive_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_workplace_hospitalised_symptomatic")){ temp.prob_test_workplace_hospitalised_symptomatic = elem["prob_test_workplace_hospitalised_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_workplace_symptomatic_symptomatic")){ temp.prob_test_workplace_symptomatic_symptomatic = elem["prob_test_workplace_symptomatic_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_workplace_positive_asymptomatic")){ temp.prob_test_workplace_positive_asymptomatic = elem["prob_test_workplace_positive_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_workplace_hospitalised_asymptomatic")){ temp.prob_test_workplace_hospitalised_asymptomatic = elem["prob_test_workplace_hospitalised_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_workplace_symptomatic_asymptomatic")){ temp.prob_test_workplace_symptomatic_asymptomatic = elem["prob_test_workplace_symptomatic_asymptomatic"].GetDouble(); } //Testing probabilities for school networks if(elem.HasMember("prob_test_school_positive_symptomatic")){ temp.prob_test_school_positive_symptomatic = elem["prob_test_school_positive_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_school_hospitalised_symptomatic")){ temp.prob_test_school_hospitalised_symptomatic = elem["prob_test_school_hospitalised_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_school_symptomatic_symptomatic")){ temp.prob_test_school_symptomatic_symptomatic = elem["prob_test_school_symptomatic_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_school_positive_asymptomatic")){ temp.prob_test_school_positive_asymptomatic = elem["prob_test_school_positive_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_school_hospitalised_asymptomatic")){ temp.prob_test_school_hospitalised_asymptomatic = elem["prob_test_school_hospitalised_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_school_symptomatic_asymptomatic")){ temp.prob_test_school_symptomatic_asymptomatic = elem["prob_test_school_symptomatic_asymptomatic"].GetDouble(); } //Testing probabilities for random community networks if(elem.HasMember("prob_test_random_community_positive_symptomatic")){ temp.prob_test_random_community_positive_symptomatic = elem["prob_test_random_community_positive_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_random_community_hospitalised_symptomatic")){ temp.prob_test_random_community_hospitalised_symptomatic = elem["prob_test_random_community_hospitalised_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_random_community_symptomatic_symptomatic")){ temp.prob_test_random_community_symptomatic_symptomatic = elem["prob_test_random_community_symptomatic_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_random_community_positive_asymptomatic")){ temp.prob_test_random_community_positive_asymptomatic = elem["prob_test_random_community_positive_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_random_community_hospitalised_asymptomatic")){ temp.prob_test_random_community_hospitalised_asymptomatic = elem["prob_test_random_community_hospitalised_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_random_community_symptomatic_asymptomatic")){ temp.prob_test_random_community_symptomatic_asymptomatic = elem["prob_test_random_community_symptomatic_asymptomatic"].GetDouble(); } //Testing probabilities for random community networks if(elem.HasMember("prob_test_neighbourhood_positive_symptomatic")){ temp.prob_test_neighbourhood_positive_symptomatic = elem["prob_test_neighbourhood_positive_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_neighbourhood_hospitalised_symptomatic")){ temp.prob_test_neighbourhood_hospitalised_symptomatic = elem["prob_test_neighbourhood_hospitalised_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_neighbourhood_symptomatic_symptomatic")){ temp.prob_test_neighbourhood_symptomatic_symptomatic = elem["prob_test_neighbourhood_symptomatic_symptomatic"].GetDouble(); } if(elem.HasMember("prob_test_neighbourhood_positive_asymptomatic")){ temp.prob_test_neighbourhood_positive_asymptomatic = elem["prob_test_neighbourhood_positive_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_neighbourhood_hospitalised_asymptomatic")){ temp.prob_test_neighbourhood_hospitalised_asymptomatic = elem["prob_test_neighbourhood_hospitalised_asymptomatic"].GetDouble(); } if(elem.HasMember("prob_test_neighbourhood_symptomatic_asymptomatic")){ temp.prob_test_neighbourhood_symptomatic_asymptomatic = elem["prob_test_neighbourhood_symptomatic_asymptomatic"].GetDouble(); } //Contact trace probabilities for in networks for symptomatic index patient. if(elem.HasMember("prob_contact_trace_household_symptomatic")){ temp.prob_contact_trace_household_symptomatic = elem["prob_contact_trace_household_symptomatic"].GetDouble(); } if(elem.HasMember("prob_contact_trace_project_symptomatic")){ temp.prob_contact_trace_project_symptomatic = elem["prob_contact_trace_project_symptomatic"].GetDouble(); } if(elem.HasMember("prob_contact_trace_random_community_symptomatic")){ temp.prob_contact_trace_random_community_symptomatic = elem["prob_contact_trace_random_community_symptomatic"].GetDouble(); } if(elem.HasMember("prob_contact_trace_neighbourhood_symptomatic")){ temp.prob_contact_trace_neighbourhood_symptomatic = elem["prob_contact_trace_neighbourhood_symptomatic"].GetDouble(); } if(elem.HasMember("prob_contact_trace_class_symptomatic")){ temp.prob_contact_trace_class_symptomatic = elem["prob_contact_trace_class_symptomatic"].GetDouble(); } //Contact trace probabilities for in networks for hospitalised index patient. if(elem.HasMember("prob_contact_trace_household_hospitalised")){ temp.prob_contact_trace_household_hospitalised = elem["prob_contact_trace_household_hospitalised"].GetDouble(); } if(elem.HasMember("prob_contact_trace_project_hospitalised")){ temp.prob_contact_trace_project_hospitalised = elem["prob_contact_trace_project_hospitalised"].GetDouble(); } if(elem.HasMember("prob_contact_trace_random_community_hospitalised")){ temp.prob_contact_trace_random_community_hospitalised = elem["prob_contact_trace_random_community_hospitalised"].GetDouble(); } if(elem.HasMember("prob_contact_trace_neighbourhood_hospitalised")){ temp.prob_contact_trace_neighbourhood_hospitalised = elem["prob_contact_trace_neighbourhood_hospitalised"].GetDouble(); } if(elem.HasMember("prob_contact_trace_class_hospitalised")){ temp.prob_contact_trace_class_hospitalised = elem["prob_contact_trace_class_hospitalised"].GetDouble(); } //Contact trace probabilities for in networks for positive index patient. if(elem.HasMember("prob_contact_trace_household_positive")){ temp.prob_contact_trace_household_positive = elem["prob_contact_trace_household_positive"].GetDouble(); } if(elem.HasMember("prob_contact_trace_project_positive")){ temp.prob_contact_trace_project_positive = elem["prob_contact_trace_project_positive"].GetDouble(); } if(elem.HasMember("prob_contact_trace_random_community_positive")){ temp.prob_contact_trace_random_community_positive = elem["prob_contact_trace_random_community_positive"].GetDouble(); } if(elem.HasMember("prob_contact_trace_neighbourhood_positive")){ temp.prob_contact_trace_neighbourhood_positive = elem["prob_contact_trace_neighbourhood_positive"].GetDouble(); } if(elem.HasMember("prob_contact_trace_class_positive")){ temp.prob_contact_trace_class_positive = elem["prob_contact_trace_class_positive"].GetDouble(); } if(elem.HasMember("prob_retest_recovered")){ temp.prob_retest_recovered = elem["prob_retest_recovered"].GetDouble(); } testing_protocol.push_back(temp); print_testing_protocol(index, temp); ++index; }else{ std::cout<<std::endl<<"num_days not specified or less than 1. Skipping current index."; assert(false); } } } std::cout<<std::endl<<"Testing Protocal size = "<<testing_protocol.size(); return testing_protocol; } vector<double> compute_prob_infection_given_community(double infection_probability, bool set_uniform){ auto fracPopJSON = readJSONFile(GLOBAL.input_base + "fractionPopulation.json"); auto num_communities = fracPopJSON.GetArray().Size(); if(set_uniform){ return vector<double>(num_communities, infection_probability); } else { auto fracQuarantinesJSON = readJSONFile(GLOBAL.input_base + "quarantinedPopulation.json"); const rapidjson::Value& quar_array = fracQuarantinesJSON.GetArray(); const rapidjson::Value& frac_array = fracPopJSON.GetArray(); vector<double> prob_infec_given_community(num_communities); for(count_type index = 0; index < num_communities; ++index){ prob_infec_given_community[index] = infection_probability * quar_array[index]["fracQuarantined"].GetDouble() / frac_array[index]["fracPopulation"].GetDouble(); } return prob_infec_given_community; } } void seed_initial_infection_at_node(agent& node, double time_of_infection){ node.infection_status = Progression::exposed; node.time_of_infection = time_of_infection; ++GLOBAL.INIT_ACTUALLY_INFECTED; } template <class T> void set_node_initial_infection(agent& node, double community_infection_probability, int node_index, const T& elem, vector<count_type>& seed_candidates ){ if(SEED_INFECTION_FROM_FILE){ #ifdef DEBUG assert(elem["infection_status"].IsInt()); #endif if(elem["infection_status"].GetInt()){ seed_initial_infection_at_node(node, -elem["time_since_infected"].GetDouble()); } } else { //Infections not being seeded from file bool seed_candidate = (GLOBAL.SEED_HD_AREA_POPULATION || !node.hd_area_resident) && !(GLOBAL.SEED_ONLY_NON_COMMUTER && node.has_to_travel); if(GLOBAL.SEED_FIXED_NUMBER){ if(seed_candidate){ seed_candidates.push_back(node_index); } } else { if(seed_candidate && bernoulli(community_infection_probability)){ // Always seed non-high-density-ares residents // High-density-area residents seeded based on global flag. seed_initial_infection_at_node(node, -uniform_real(0, node.incubation_period)); } } } // node.infective = (node.infection_status == Progression::infective); } vector<agent> init_nodes(){ auto indivJSON = readJSONFile(GLOBAL.input_base + "individuals.json"); auto size = indivJSON.GetArray().Size(); GLOBAL.num_people = size; vector<agent> nodes(size); auto community_infection_prob = compute_prob_infection_given_community(GLOBAL.INIT_FRAC_INFECTED, GLOBAL.USE_SAME_INFECTION_PROB_FOR_ALL_WARDS); count_type i = 0; vector<count_type> seed_candidates; seed_candidates.reserve(size); for (auto &elem: indivJSON.GetArray()){ nodes[i].loc = location{elem["lat"].GetDouble(), elem["lon"].GetDouble()}; #ifdef DEBUG assert(elem["age"].IsInt()); #endif int age = elem["age"].GetInt(); nodes[i].age = age; nodes[i].age_group = get_age_group(age); nodes[i].age_index = get_age_index(age); nodes[i].zeta_a = zeta(age); nodes[i].infectiousness = gamma(GLOBAL.INFECTIOUSNESS_SHAPE, GLOBAL.INFECTIOUSNESS_SCALE); nodes[i].severity_index = uniform_real(0,1); nodes[i].severity = (nodes[i].severity_index<=GLOBAL.SEVERITY_RATE)?1:0; #ifdef DEBUG assert(elem["household"].IsInt()); #endif nodes[i].home = elem["household"].GetInt(); nodes[i].workplace = WORKPLACE_HOME; //null workplace, by default nodes[i].workplace_type = WorkplaceType::home; //home, by default nodes[i].workplace_subnetwork = 0; if(elem["workplaceType"].IsInt()){ switch(elem["workplaceType"].GetInt()){ case 1: if(elem["workplace"].IsNumber()){ nodes[i].workplace_type = WorkplaceType::office; nodes[i].workplace = int(elem["workplace"].GetDouble()); //Travel nodes[i].has_to_travel = bernoulli(GLOBAL.P_TRAIN); } break; case 2: if(elem["school"].IsNumber()){ nodes[i].workplace_type = WorkplaceType::school; nodes[i].workplace = int(elem["school"].GetDouble()); //Travel nodes[i].has_to_travel = bernoulli(GLOBAL.P_TRAIN); nodes[i].workplace_subnetwork = age; } break; default: break; } } //Initialize cohorts - other definitions are in cohorts.cc if (GLOBAL.ENABLE_COHORTS && !elem["startStation"].IsNull() && !elem["endStation"].IsNull()){ nodes[i].my_cohort.takes_train = true; nodes[i].my_cohort.source_station = (int)(elem["startStation"].GetDouble()); nodes[i].my_cohort.destination_station = (int)(elem["endStation"].GetDouble()); nodes[i].my_cohort.edge_weight = 1.0; nodes[i].my_cohort.one_off_traveler = (uniform_real(0.0, 1.0) < GLOBAL.ONE_OFF_TRAVELERS_RATIO); } #ifdef DEBUG assert(elem["wardNo"].IsInt()); #endif count_type community = elem["wardNo"].GetInt() - 1; //minus 1 for 0-based indexing. PB: Might need to use //"wardIndex" instead, because that is the one actually sent by //the generator scripts. // Does the individual live in a slum? In that case we need to // scale the contribution to their infection rates by a factor. // // Only use this feature if the field is present in the // "individuals" input files. if(elem.HasMember("slum")){ #ifdef DEBUG assert(elem["slum"].IsInt()); #endif if(elem["slum"].GetInt()){ nodes[i].hd_area_resident = true; nodes[i].hd_area_factor = GLOBAL.HD_AREA_FACTOR; nodes[i].hd_area_exponent = GLOBAL.HD_AREA_EXPONENT; } } nodes[i].community = community; nodes[i].funct_d_ck = f_kernel(elem["CommunityCentreDistance"].GetDouble()); nodes[i].incubation_period = gamma(GLOBAL.INCUBATION_PERIOD_SHAPE, GLOBAL.INCUBATION_PERIOD_SCALE); nodes[i].asymptomatic_period = gamma(1.0, GLOBAL.ASYMPTOMATIC_PERIOD); nodes[i].symptomatic_period = gamma(1.0, GLOBAL.SYMPTOMATIC_PERIOD); nodes[i].hospital_regular_period = GLOBAL.HOSPITAL_REGULAR_PERIOD; nodes[i].hospital_critical_period = GLOBAL.HOSPITAL_CRITICAL_PERIOD; //Now procees node to check if it could be an initial seed given //all its other data set_node_initial_infection(nodes[i], community_infection_prob[community], i, elem, seed_candidates); nodes[i].test_status.tested_epoch = -1*GLOBAL.MINIMUM_TEST_INTERVAL*GLOBAL.SIM_STEPS_PER_DAY; ++i; } assert(i == GLOBAL.num_people); // If seeding a fixed number, go through the list of seed candidates // and seed a randomly chosen fixed number of them if(GLOBAL.SEED_FIXED_NUMBER){ count_type candidate_list_size = seed_candidates.size(); if (candidate_list_size > GLOBAL.INIT_FIXED_NUMBER_INFECTED){ //Randomly permute the list of candidates std::shuffle(seed_candidates.begin(), seed_candidates.end(), GENERATOR); } count_type num = std::min(candidate_list_size, GLOBAL.INIT_FIXED_NUMBER_INFECTED); for(count_type j = 0; j < num; ++j){ seed_initial_infection_at_node(nodes[seed_candidates[j]], -uniform_real(0, nodes[seed_candidates[j]].incubation_period)); } } return nodes; } vector<double> read_JSON_convert_array(const string& file_name){ vector<double> return_object; auto file_JSON = readJSONFile(GLOBAL.input_base + "age_tx/" + file_name); auto size = file_JSON.GetArray().Size(); return_object.resize(size); int i = 0; for (auto &elem: file_JSON.GetArray()){ return_object[i] = elem[to_string(i).c_str()].GetDouble(); i += 1; } return return_object; } matrix<double> read_JSON_convert_matrix(const string& file_name){ matrix<double> return_object; auto file_JSON = readJSONFile(GLOBAL.input_base + "age_tx/" + file_name); auto size = file_JSON.GetArray().Size(); return_object.resize(size, vector<double>(size)); int i = 0; for (auto &elem: file_JSON.GetArray()){ for (count_type j = 0; j < size; ++j){ return_object[i][j] = elem[to_string(j).c_str()].GetDouble(); } i += 1; } return return_object; } void init_age_interaction_matrix(const string& directory_base, svd& svd){ string u_file = directory_base + "/U_" + directory_base + ".json"; string sigma_file = directory_base + "/Sigma_" + directory_base + ".json"; string vT_file = directory_base + "/Vtranspose_" + directory_base + ".json"; svd.u = read_JSON_convert_matrix(u_file); svd.sigma = read_JSON_convert_array(sigma_file); svd.vT = read_JSON_convert_matrix(vT_file); } svd init_home_age_interaction_matrix(){ svd svd; init_age_interaction_matrix("home", svd); return svd; } svd init_school_age_interaction_matrix(){ svd svd; init_age_interaction_matrix("school", svd); return svd; } svd init_workplace_age_interaction_matrix(){ svd svd; init_age_interaction_matrix("workplace", svd); return svd; } svd init_community_age_interaction_matrix(){ svd svd; init_age_interaction_matrix("other", svd); return svd; } matrix<double> compute_community_distances(const vector<community>& communities){ auto wardDistJSON = readJSONFile(GLOBAL.input_base + "wardCentreDistance.json"); const rapidjson::Value& mat = wardDistJSON.GetArray(); auto size = mat.Size(); matrix<double> dist_matrix(size, vector<double>(size)); for(count_type i = 0; i < size; ++i){ dist_matrix[i][i] = 0; for(count_type j = i + 1; j < size; ++j){ dist_matrix[i][j] = mat[i][to_string(j + 1).c_str()].GetDouble(); dist_matrix[j][i] = dist_matrix[i][j]; } } return dist_matrix; } matrix<double> compute_community_distances_fkernel(const matrix<double>& community_distances){ auto size = community_distances.size(); matrix<double> fk_matrix(size, vector<double>(size)); for(count_type i = 0; i < size; ++i){ fk_matrix[i][i] = f_kernel(community_distances[i][i]); for(count_type j = i + 1; j < size; ++j){ fk_matrix[i][j] = f_kernel(community_distances[i][j]); fk_matrix[j][i] = fk_matrix[i][j]; } } return fk_matrix; } void assign_individual_home_community(vector<agent>& nodes, vector<house>& homes, vector<workplace>& workplaces, vector<community>& communities){ //Assign individuals to homes, workplace, community for(count_type i = 0; i < nodes.size(); ++i){ int home = nodes[i].home; homes[home].individuals.push_back(i); //No checking for null as all individuals have a home nodes[i].compliant = homes[home].compliant; //All members of the household are set the same compliance value //Assign cyclic strategy class for this node if(GLOBAL.CYCLIC_POLICY_ENABLED){ switch(GLOBAL.CYCLIC_POLICY_TYPE){ case Cycle_Type::home: nodes[i].cyclic_strategy_class = homes[home].cyclic_strategy_class; break; case Cycle_Type::individual: nodes[i].cyclic_strategy_class = uniform_count_type(0, GLOBAL.NUMBER_OF_CYCLIC_CLASSES - 1); break; default: assert(false); break; } assert(0 <= nodes[i].cyclic_strategy_class && nodes[i].cyclic_strategy_class < GLOBAL.NUMBER_OF_CYCLIC_CLASSES); } int workplace = nodes[i].workplace; if(nodes[i].workplace_type == WorkplaceType::office){ nodes[i].office_type = workplaces[workplace].office_type; } if(workplace != WORKPLACE_HOME){ workplaces[workplace].individuals.push_back(i); //Since the individual is not home_bound, compute their //commute_distance nodes[i].commute_distance = earth_distance(workplaces[workplace].loc, homes[home].loc); } //No checking for null as all individuals have a community/ward communities[nodes[i].community].individuals.push_back(i); } } void assign_individual_projects(vector<workplace>& workplaces, vector<agent>& nodes){ for(count_type i=0; i<workplaces.size(); ++i){ if(workplaces[i].workplace_type==WorkplaceType::office){ randomly_shuffle(workplaces[i].individuals); count_type shuffle_index = 0, project_index = 0; count_type individuals_to_be_assigned = workplaces[i].individuals.size(); while(individuals_to_be_assigned > 0){ project temp; workplaces[i].projects.push_back(temp); workplaces[i].projects[project_index].workplace = i; count_type project_size = uniform_count_type_network(GLOBAL.MIN_PROJECT_SIZE, GLOBAL.MAX_PROJECT_SIZE); project_size = std::min(project_size, individuals_to_be_assigned); for(count_type j=0; j<project_size; ++j){ auto individual = workplaces[i].individuals[shuffle_index]; workplaces[i].projects[project_index].individuals.push_back(individual); nodes[individual].workplace_subnetwork = project_index; ++shuffle_index; } ++project_index; individuals_to_be_assigned -= project_size; } } if(workplaces[i].workplace_type==WorkplaceType::school){ workplaces[i].projects.resize(GLOBAL.MAX_CLASS_AGE+1); //for(count_type j=0; j < workplaces[i].individuals.size(); ++j){ for(const auto& individual: workplaces[i].individuals){ auto age_index = nodes[individual].workplace_subnetwork; //For agents whose workplace is school, workplace_subnetwork is already //initialized in init_nodes(), and is equal to the age of the individual workplaces[i].projects[age_index].individuals.push_back(individual); } } } } void assign_household_community(vector<community>& communities, const vector<agent>& nodes, vector<house>& homes){ for(count_type i=0; i<homes.size(); ++i){ if(homes[i].individuals.size()>0){ homes[i].community = nodes[homes[i].individuals[0]].community; //All individuals in the same home have the same community, so we can take //any one. communities[homes[i].community].households.push_back(i); } } } void assign_household_random_community(vector<house>& homes, const vector<community>& communities){ for(count_type i = 0; i < communities.size(); ++i){ auto NUM_HOUSEHOLDS = communities[i].households.size(); for(count_type j = 0; j < NUM_HOUSEHOLDS; ++j){ count_type current_household = communities[i].households[j]; count_type degree = uniform_count_type_network(GLOBAL.MIN_RANDOM_COMMUNITY_SIZE/2, GLOBAL.MAX_RANDOM_COMMUNITY_SIZE/2); degree = (degree > NUM_HOUSEHOLDS-1)?NUM_HOUSEHOLDS-1:degree; count_type candidate; while(homes[current_household].random_households.households.size() < degree){ do{ candidate = communities[i].households[uniform_count_type_network(0, NUM_HOUSEHOLDS - 1)]; }while(candidate == current_household || (std::find( homes[current_household].random_households.households.begin(), homes[current_household].random_households.households.end(), candidate ) != homes[current_household].random_households.households.end())); homes[current_household].random_households.households.push_back(candidate); //homes[candidate].random_households.households.push_back(current_household); } } } //symmetrize random network interaction graph. for(count_type current_house = 0; current_house < homes.size(); ++current_house){ for (count_type j = 0; j < homes[current_house].random_households.households.size(); ++j){ count_type random_contact = homes[current_house].random_households.households[j]; if(std::find(homes[random_contact].random_households.households.begin(), homes[random_contact].random_households.households.end(), current_house) == homes[random_contact].random_households.households.end()){ homes[random_contact].random_households.households.push_back(current_house); } } } } void assign_homes_nbr_cell(const vector<house>& homes, matrix<nbr_cell>& neighbourhood_cells){ if(!GLOBAL.ENABLE_NBR_CELLS){ return; } for (count_type home_count = 0; home_count < homes.size(); ++home_count){ grid_cell my_nbr_cell = homes[home_count].neighbourhood; neighbourhood_cells[my_nbr_cell.cell_x][my_nbr_cell.cell_y].houses_list.push_back(home_count); neighbourhood_cells[my_nbr_cell.cell_x][my_nbr_cell.cell_y].population += homes[home_count].individuals.size(); } } // Compute scale factors for each home, workplace and community. Done once at the beginning. void compute_scale_homes(vector<house>& homes){ for (count_type w = 0; w < homes.size(); ++w){ if(homes[w].individuals.size()==0){ homes[w].scale = 0; } else { homes[w].scale = GLOBAL.BETA_H * homes[w].Q_h /(pow(homes[w].individuals.size(), GLOBAL.ALPHA)); } } } void compute_scale_workplaces(vector<workplace>& workplaces){ for (count_type w=0; w < workplaces.size(); ++w) { if(workplaces[w].individuals.size()==0){ workplaces[w].scale = 0; } else { double beta_workplace = 0; if(workplaces[w].workplace_type == WorkplaceType::office){ beta_workplace = GLOBAL.BETA_W; //workplace } else if (workplaces[w].workplace_type == WorkplaceType::school){ beta_workplace = GLOBAL.BETA_S; //school } workplaces[w].scale = beta_workplace * workplaces[w].Q_w / workplaces[w].individuals.size(); } for(count_type j=0; j<workplaces[w].projects.size(); ++j){ if(workplaces[w].projects[j].individuals.size() ==0){ workplaces[w].projects[j].scale = 0; } else{ double beta_project = 0; if(workplaces[w].workplace_type == WorkplaceType::office){ beta_project = GLOBAL.BETA_PROJECT; //project } else if (workplaces[w].workplace_type == WorkplaceType::school){ beta_project = GLOBAL.BETA_CLASS; // class } workplaces[w].projects[j].scale = beta_project/workplaces[w].projects[j].individuals.size(); } } } } void compute_scale_communities(const vector<agent>& nodes, vector<community>& communities){ for (count_type w=0; w < communities.size(); ++w) { double sum_value = 0; for (auto indiv: communities[w].individuals){ sum_value += nodes[indiv].funct_d_ck; } if(sum_value==0){ communities[w].scale = 0; } else communities[w].scale = GLOBAL.BETA_C * communities[w].Q_c / sum_value; } } void compute_scale_random_community(vector<house>& houses, vector<agent>& nodes){ for(count_type i=0; i<houses.size(); ++i){ double sum_value = 0; for(count_type j=0; j < houses[i].random_households.households.size(); ++j){ auto neighbor = houses[i].random_households.households[j]; if(houses[neighbor].individuals.size()>0){ sum_value += houses[neighbor].individuals.size()*nodes[houses[neighbor].individuals[0]].funct_d_ck; } } if(sum_value==0){ houses[i].random_households.scale = 0; } else{ houses[i].random_households.scale = GLOBAL.BETA_RANDOM_COMMUNITY/sum_value; } } } void compute_scale_nbr_cells(vector<agent>& nodes, vector<vector<nbr_cell>>& nbr_cells, const vector<house>& homes){ for(count_type i=0; i<nbr_cells.size(); ++i){ for(count_type j=0; j<nbr_cells[i].size(); ++j){ double sum_values = 0; for(count_type h=0; h<nbr_cells[i][j].houses_list.size(); ++h){ sum_values += homes[nbr_cells[i][j].houses_list[h]].individuals.size(); } if(sum_values>0){ nbr_cells[i][j].scale = GLOBAL.BETA_NBR_CELLS/sum_values; } else{ nbr_cells[i][j].scale = 0; } } } } //Initialize the office attendance void initialize_office_attendance(){ //No need to read the attendance file if we are specifically asked to ignore //it if(GLOBAL.IGNORE_ATTENDANCE_FILE) return; //constexpr count_type NUMBER_OF_OFFICE_TYPES = 6; auto attendanceJSON = readJSONFile(GLOBAL.input_base + GLOBAL.attendance_filename); ATTENDANCE.number_of_entries = attendanceJSON.GetArray().Size(); //will change for new file type ATTENDANCE.probabilities.reserve(ATTENDANCE.number_of_entries); //will change for new file type count_type index = 0; for(auto& elem: attendanceJSON.GetArray()){ count_type num_days = 1; if(elem.HasMember("num_days")){ num_days = elem["num_days"].GetInt(); ATTENDANCE.attendance_new_file_type = true; } for (count_type day = 0; day < num_days; ++day){ ATTENDANCE.probabilities.push_back(vector<double>(GLOBAL.NUMBER_OF_OFFICE_TYPES)); count_type val; std::string val_s; val = static_cast<count_type>(OfficeType::other); val_s = std::to_string(val); ATTENDANCE.probabilities[index].at(val) = elem[val_s.c_str()].GetDouble(); val = static_cast<count_type>(OfficeType::sez); val_s = std::to_string(val); ATTENDANCE.probabilities[index].at(val) = elem[val_s.c_str()].GetDouble(); val = static_cast<count_type>(OfficeType::government); val_s = std::to_string(val); ATTENDANCE.probabilities[index].at(val) = elem[val_s.c_str()].GetDouble(); val = static_cast<count_type>(OfficeType::it); val_s = std::to_string(val); ATTENDANCE.probabilities[index].at(val) = elem[val_s.c_str()].GetDouble(); val = static_cast<count_type>(OfficeType::construction); val_s = std::to_string(val); ATTENDANCE.probabilities[index].at(val) = elem[val_s.c_str()].GetDouble(); val = static_cast<count_type>(OfficeType::hospital); val_s = std::to_string(val); ATTENDANCE.probabilities[index].at(val) = elem[val_s.c_str()].GetDouble(); ++index; } } ATTENDANCE.number_of_entries = index; //assert(index == ATTENDANCE.number_of_entries); }
<% from pwnlib.shellcraft.i386.linux import syscall %> <%page args="addr, length, advice"/> <%docstring> Invokes the syscall madvise. See 'man 2 madvise' for more information. Arguments: addr(void): addr len(size_t): len advice(int): advice </%docstring> ${syscall('SYS_madvise', addr, length, advice)}
NewBarkTown_MapScripts: db 0 ; scene scripts db 1 ; callbacks callback MAPCALLBACK_NEWMAP, .FlyPoint .FlyPoint: setflag ENGINE_FLYPOINT_NEW_BARK clearevent EVENT_FIRST_TIME_BANKING_WITH_MOM return NewBarkTown_MapEvents: db 0, 0 ; filler db 0 ; warp events db 0 ; coord events db 0 ; bg events db 0 ; object events
; ; z88dk library: Generic VDP support code ; ; int msx_color(int foreground, int background, int border ); ; ; Change the color attributes (MSX style) ; ; $Id: gen_color.asm,v 1.1 2010/06/30 13:21:38 stefano Exp $ ; XLIB msx_color LIB SETWRT LIB set_vdp_reg ;XREF SCRMOD INCLUDE "msx/vdp.inc" msx_color: ld ix,0 add ix,sp ;ld a,(SCRMOD) ;SCRMOD dec a push af ld a,(ix+6) ;foreground rlca rlca rlca rlca and $F0 ld l,a ld a,(ix+2) ;border or l ld b,a ld c,7 call set_vdp_reg pop af ;ret nz ret ; SCREEN1 ; ld a,(ix+6) ;foreground ; rlca ; rlca ; rlca ; rlca ; and $F0 ; ld a,(ix+4) ;background ; or (hl) ; ld hl,$2000 ; VDP table for 32 columns text mode ; ld bc,$0020 ; push af ; call SETWRT ;cclr_lp: ; pop af ; out (VDP_DATA),a ; push af ; dec bc ; ld a,b ; or c ; jr nz,cclr_lp ; pop af ; ret
#ifndef BOOST_NETWORK_MESSAGE_WRAPPERS_BODY_HPP_20110930 #define BOOST_NETWORK_MESSAGE_WRAPPERS_BODY_HPP_20110930 // Copyright 2011 Dean Michael Berris <dberris@google.com>. // Copyright 2011 Google, Inc. // Distributed under 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) #include <boost/range/iterator.hpp> #include <boost/optional.hpp> #include <boost/network/message/message_base.hpp> namespace boost { namespace network { struct body_wrapper { explicit body_wrapper(message_base const & message); operator std::string () const; std::size_t size() const; operator iterator_range<std::string::const_iterator> () const; std::string::const_iterator begin() const; std::string::const_iterator end() const; private: message_base const & message_; mutable optional<std::string> cache_; }; inline std::ostream & operator<<(std::ostream & os, body_wrapper const & body) { os << static_cast<std::string>(body); return os; } inline body_wrapper const body(message_base const & message_) { return body_wrapper(message_); } } // namespace network } // namespace boost #ifdef BOOST_NETWORK_NO_LIB #include <boost/network/message/wrappers/body.ipp> #endif #endif // __NETWORK_MESSAGE_WRAPPERS_BODY_HPP__
DEVICE ZXSPECTRUM48 OPT --syntax=F app_begin: ; Startup handler ORG #0000 jp startup_handler DB 0,"Sizif Magic ROM",0 ; NMI handler ORG #0066 jp nmi_handler ; INT IM1 handler ORG #0038 push bc ld bc, #0038 ld (var_int_vector), bc pop bc ret ; INT IM2 handler ORG #0101 ret ; INT IM2 vector table ORG #0600 .257 db #01 ; by Z80 user manual int vector is I * 256 + (D & 0xFE) ; but by other references and by T80/A-Z80 implementation int vector is I * 256 + D ; so we just play safe and use symmetric int handler address and vector table with one extra byte startup_handler: ld sp, Stack_top ld ix, #5800 ; draw 4 rygb boxes on left top corner to indicate boot ld (ix+0), #D2 ; r ld (ix+1), #F6 ; y call init_config call init_cpld ld (ix+2), #E4 ; g ld (ix+3), #C9 ; b ld hl, 0 jp exit_with_jp nmi_handler: ld (var_sp_reg), sp ld sp, Stack_top push af push hl push bc ld a, #01 ; show magic border out (#ff), a ; ... xor a ld (var_magic_enter_cnt), a ld (var_magic_leave_cnt), a .loop: call check_magic_delay call check_magic_hold ; A == 1 if we are entering menu, A == 2 if we are leaving to... bit 0, a ; ...default nmi handler, A == 0 otherwise jp nz, main ; ... bit 1, a ; ... jr z, .loop ; ... .leave: xor a ; disable border ld bc, #01ff ; ... out (c), a ; ... ld hl, #0066 ; jump to default nmi handler jp exit_with_jp ; ... ; IN - HL - jump address exit_with_jp: ld (Exit_vector-1), hl ld a, #c3 ; c3 - jp ld (Exit_vector-2), a pop bc pop hl pop af ld sp, (var_sp_reg) jp Exit_vector-2 exit_with_ret: ld hl, #45ed ; ed45 - retn; reverse bytes order ld (Exit_vector-1), hl pop bc pop hl pop af ld sp, (var_sp_reg) jp Exit_vector-1 init_config: ld hl, cfg_initialized ; if (cfg_initialized == "magic word") {restore cfg} else {default cfg} ld a, #B1 ; ... cpi ; ... hl++ jr nz, .init_default ; ... ld a, #5B ; ... cpi ; ... hl++ jr nz, .init_default ; ... ld a, #00 ; ... cpi ; ... hl++ jr nz, .init_default ; ... ld a, #B5 ; ... cpi ; ... hl++ jr nz, .init_default ; ... jr .restore ; ... .init_default: ld bc, CFG_T+CFGEXT_T ; cfg_saved = cfg_default ld de, cfg_saved ; ... ld hl, CFG_DEFAULT ; ... ldir ; ... call detect_ext_board ; read ext board jumpres if any .restore: ld bc, CFG_T+CFGEXT_T ; cfg = cfg_saved ld de, cfg ; ... ld hl, cfg_saved ; ... ldir ; ... .save_magic: ld hl, #5BB1 ; cfg_initialized = "magic word" ld (cfg_initialized+0), hl ; ... ld hl, #B500 ; ... ld (cfg_initialized+2), hl ; ... ret save_config: ld bc, CFG_T+CFGEXT_T ; cfg_saved = cfg ld de, cfg_saved ; ... ld hl, cfg ; ... ldir ; ... ret init_cpld: .check_ram48k: ld a, (cfg.ram) ; if ram == 48K - run basic48 cp 1 ; ... jr nz, .check_plus3_disabled ; ... ld a, #10 ; ... ld bc, #7ffd ; ... out (c), a ; ... ld a, #4 ; ... ld bc, #1ffd ; ... out (c), a ; ... jr .do_load .check_plus3_disabled: ld a, (cfg.plus3) ; if plus3 disabled - set 1ffd rom to basic48 or a ; ... this is required for case when plus3 will be jr nz, .do_load ; ... activated later by magic menu - this prevents ld a, #4 ; ... hang if user activating plus3 while basic48 active ld bc, #1ffd ; ... out (c), a ; ... .do_load: ld b, CFG_T ; B = registers count ld c, #ff ; ld hl, cfg+CFG_T-1 ; HL = &cfg[registers count-1] otdr ; do { b--; out(bc, *hl); hl--; } while(b) .do_load_ext: ; same for extension board ld d, CFGEXT_T ; ... ld b, #e1 ; ... ld c, #ff ; ... ld hl, cfgext ; ... .do_load_ext_loop: ; ... ld a, (hl) ; ... out (c), a ; ... inc hl ; ... inc b ; ... dec d ; ... jr nz, .do_load_ext_loop ; ... ret ; OUT - A = 1 if ext board present, 0 otherwise ; OUT - F - garbage ; OUT - BC - garbage detect_ext_board: ld b, #e0 ; read port #e0ff ld c, #ff ; ... in a, (c) ; ... ld b, a ; if (result & 0xF0 != 0) - return and #f0 ; ... jr z, .detected ; ... .not_detected: xor a ld (var_ext_presence), a ret .detected ld a, 1 ld (var_ext_presence), a xor a bit 0, b ; check TSFM jumper jr z, .cfg_tsfm ld a, 1 .cfg_tsfm: ld (cfgext_saved.tsfm), a xor a bit 1, b ; check SAA jumper jr z, .cfg_saa ld a, 1 .cfg_saa: ld (cfgext_saved.saa), a xor a bit 2, b ; check GS jumper jr z, .cfg_gs ld a, 1 .cfg_gs: ld (cfgext_saved.gs), a ret ; OUT - A = 1 if we are entering menu, A = 2 if we are leaving menu, A = 0 otherwise ; OUT - F - garbage check_magic_hold: ld a, #ff ; read magic key state in bit 7 of #FE port in a, (#fe) ; ... bit 7, a ; check key is hold jr z, .is_hold ; yes? .not_hold: ld a, (var_magic_leave_cnt) ; leave_counter++ inc a ; ... ld (var_magic_leave_cnt), a ; ... cp MENU_LEAVE_DELAY ; if (counter == MENU_LEAVE_DELAY) - return 2 jr nz, .return0 ; ... ld a, 2 ret .is_hold: ld a, (var_magic_enter_cnt) ; enter_counter++ inc a ; ... ld (var_magic_enter_cnt), a ; ... cp MENU_ENTER_DELAY ; if (counter == MENU_ENTER_DELAY) - return 1 jr nz, .return0 ; ... ld a, 1 ret .return0: xor a ret ; OUT - AF - garbage ; OUT - BC - garbage check_magic_delay: ld c, MENU_HOLDCHECK_DELAY ld a, (cfg.clock) or a jr z, .loop ld c, MENU_HOLDCHECK_DELAY*2 dec a jr z, .loop ld c, MENU_HOLDCHECK_DELAY*4 .loop: ld a, c .loop_outer: ld b, 255 ; ~1ms cycle at 3.5MHz .loop_inner: ; ... djnz .loop_inner ; 13 T-states dec a jr nz, .loop_outer ret ; read non-magic im2 table and returns im2 handler address ; IN - A - im2 table address hight byte ; OUT - HL - handler address ; OUT - AF - garbage get_im2_handler: ld h, a ; HL = im2 table address ld l, #ff ; HL = im2 table address ld a, #2a ; 2a - ld hl, (nn) ld (Readout_vector-2), a ; ... ld (Readout_vector-1), hl ; HL was set earlier by im2 table address ld a, #c9 ; c9 - ret ld (Readout_vector+1), a ; ... call Readout_vector-2 ; HL = default im2 handler address ret save: .mute_gs: ld a, (var_ext_presence) ; if (no_ext_pcb || gs_is_disabled) - skip gs or a ; ...this is required to be compatible with DivIDE jr z, .mute_saa1099 ; ...which uses same port #bb ld a, (cfgext.gs) ; ... or a ; ... jr z, .mute_saa1099 ; ... ld a, #fa ; send command Out zero_to_zero out (#bb), a ; ... .mute_saa1099: ld bc, #ffff ; select saa register ld a, #1c ; ... out (c), a ; ... ld b, #fe ; mute xor a ; ... out (c), a ; ... .save_ay: ld hl, var_save_ay ; select first AY chip in TurboSound ld a, #ff ; ... call .save_ay_sub ld a, #fe ; select second AY chip in TurboSound call .save_ay_sub .save_screen: ld bc, 6912 ld de, var_save_screen ld hl, #4000 ldir .save_ulaplus: ld bc, #bf3b ; set ulaplus address = mode register ld a, #40 ; ... out (c), a ; ... ld bc, #ff3b ; save mode register value in a, (c) ; ... ld (var_save_ulaplus), a ; ... xor a ; disable ulaplus out (c), a ; ... ret .save_ay_sub: ld bc, #fffd ; ... out (c), a ; ... ld d, 16 ; register_number=16 .save_ay_sub_loop: dec d ; register_number-- ld b, #ff ; select register number out (c), d ; ... in a, (c) ; read register ld (hl), a ; save to ram xor a ; set register to 0 ld b, #bf ; ... out (c), a ; ... inc hl ; ram++ or d ; register_number == 0? jr nz, .save_ay_sub_loop ret restore: .restore_ulaplus: ld bc, #bf3b ; set ulaplus address = mode register ld a, #40 ; ... out (c), a ; ... ld bc, #ff3b ; restore mode register value ld a, (var_save_ulaplus) ; ... out (c), a ; ... .restore_screen: ld bc, 6912 ld de, #4000 ld hl, var_save_screen ldir .restore_ay: ld hl, var_save_ay+16 ; select second AY chip in TurboSound ld a, #fe ; ... call .restore_ay_sub ld hl, var_save_ay ; select first AY chip in TurboSound ld a, #ff ; ... call .restore_ay_sub .restore_gs: ld a, (var_ext_presence) ; if (no_ext_pcb || gs_is_disabled) - skip gs or a ; ...this is required to be compatible with DivIDE jr z, .restore_ret ; ...which uses same port #bb ld a, (cfgext.gs) ; ... or a ; ... jr z, .restore_ret ; ... ld a, #60 ; send command Get Song Position out (#bb), a ; ... .restore_ret: ret .restore_ay_sub: ld bc, #fffd ; ... out (c), a ; ... ld d, 16 ; register_number=16 .restore_ay_sub_loop: dec d ; register_number-- ld b, #ff ; select register number out (c), d ; ... ld b, #bf ; restore register ld a, (hl) ; ... out (c), a ; ... inc hl ; ram++ xor a ; register_number == 0? or d ; ... jr nz, .restore_ay_sub_loop ; ret ; Main program main: push de push ix push iy ld a, i ; save I reg and IFF2 push af ; ... ld a, #06 ; set our interrupt table address (#06xx) ld i, a ; ... xor a ld (var_exit_flag), a ld (var_exit_reboot), a ld (var_input_key), a ld (var_input_key_last), a ld (var_input_key_hold_timer), a ld (var_menu_current_item), a ld (var_menu_animate_cnt), a call save call menu_init .loop: ei halt call input_process ; B = 32 if exit key pressed bit 5, b jr nz, .wait_for_keys_release call menu_process ld a, (var_exit_flag) or a jr z, .loop .wait_for_keys_release: ei halt call input_process ; B = 0 if no keys pressed xor a or b jr nz, .wait_for_keys_release .leave: call save_config call restore ld a, (var_exit_reboot) ; should we reboot? or a ; ... jr z, .leave_without_reboot ; ... ld a, 1 ; reboot ld bc, #00ff ; ... out (c), a ; ... .leave_without_reboot: pop af ; A = I push af ; call get_im2_handler ; HL = default im2 handler address ld (var_int_vector), hl xor a ; disable border ld bc, #01ff ; ... out (c), a ; ... pop af pop iy pop ix pop de ei ; wait for int just for safety halt ; ... ld i, a ; restore default interrupt table address jp po, exit_with_ret ; check int was enabled by default. no? just do retn ld hl, (var_int_vector) ; ... jp exit_with_jp ; yes? goto default int handler ; Includes include config.asm include draw.asm include input.asm include menu.asm include menu_structure.asm include font.asm include strings.asm app_end: ORG #3FE8 DB 0,"End of Sizif Magic ROM",0 ; Magic vectors Exit_vector EQU #F000 Readout_vector EQU #F008 ; Variables ORG #D500 var_save_screen: .6912 DB 0 ORG #F020 var_save_ay: .32 DB 0 var_save_ulaplus: DB 0 var_sp_reg: DW 0 var_int_vector: DW 0 var_magic_enter_cnt: DB 0 var_magic_leave_cnt: DB 0 var_exit_flag: DB 0 var_exit_reboot: DB 0 var_input_key: DB 0 var_input_key_last: DB 0 var_input_key_hold_timer: DB 0 var_menu_current_item: DB 0 var_menu_animate_cnt: DB 0 var_menu: MENU_T var_ext_presence: DB 0 cfg CFG_T cfgext CFGEXT_T cfg_saved CFG_T cfgext_saved CFGEXT_T cfg_initialized: DB #B1, #5B, #00, #B5 ORG #FFBE Stack_top: ORG #FFC0 Ulaplus_pallete: .64 DB 0 DISPLAY "Application size: ",/D,app_end-app_begin CSPECTMAP "main.map" SAVEBIN "main.bin",0,16384
;; ;; Copyright (c) 2012-2018, Intel Corporation ;; ;; 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. ;; %include "os.asm" %include "mb_mgr_datastruct.asm" section .data default rel align 16 PSHUFFLE_BYTE_FLIP_MASK: ;ddq 0x0c0d0e0f08090a0b0405060700010203 dq 0x0405060700010203, 0x0c0d0e0f08090a0b K00_19: ;ddq 0x5A8279995A8279995A8279995A827999 dq 0x5A8279995A827999, 0x5A8279995A827999 K20_39: ;ddq 0x6ED9EBA16ED9EBA16ED9EBA16ED9EBA1 dq 0x6ED9EBA16ED9EBA1, 0x6ED9EBA16ED9EBA1 K40_59: ;ddq 0x8F1BBCDC8F1BBCDC8F1BBCDC8F1BBCDC dq 0x8F1BBCDC8F1BBCDC, 0x8F1BBCDC8F1BBCDC K60_79: ;ddq 0xCA62C1D6CA62C1D6CA62C1D6CA62C1D6 dq 0xCA62C1D6CA62C1D6, 0xCA62C1D6CA62C1D6 section .text ;; code to compute quad SHA1 using AVX ;; derived from ...\sha1_multiple\sha1_quad4.asm ;; variation of sha1_mult2.asm : clobbers all xmm regs, rcx left intact ;; rbx, rsi, rdi, rbp, r12-r15 left intact ;; This version is not safe to call from C/C++ ;; Stack must be aligned to 16 bytes before call ;; Windows clobbers: rax rdx r8 r9 r10 r11 ;; Windows preserves: rbx rcx rsi rdi rbp r12 r13 r14 r15 ;; ;; Linux clobbers: rax rsi r8 r9 r10 r11 ;; Linux preserves: rbx rcx rdx rdi rbp r12 r13 r14 r15 ;; ;; clobbers xmm0-15 ; transpose r0, r1, r2, r3, t0, t1 ; "transpose" data in {r0..r3} using temps {t0..t3} ; Input looks like: {r0 r1 r2 r3} ; r0 = {a3 a2 a1 a0} ; r1 = {b3 b2 b1 b0} ; r2 = {c3 c2 c1 c0} ; r3 = {d3 d2 d1 d0} ; ; output looks like: {t0 r1 r0 r3} ; t0 = {d0 c0 b0 a0} ; r1 = {d1 c1 b1 a1} ; r0 = {d2 c2 b2 a2} ; r3 = {d3 c3 b3 a3} ; %macro TRANSPOSE 6 %define %%r0 %1 %define %%r1 %2 %define %%r2 %3 %define %%r3 %4 %define %%t0 %5 %define %%t1 %6 vshufps %%t0, %%r0, %%r1, 0x44 ; t0 = {b1 b0 a1 a0} vshufps %%r0, %%r0, %%r1, 0xEE ; r0 = {b3 b2 a3 a2} vshufps %%t1, %%r2, %%r3, 0x44 ; t1 = {d1 d0 c1 c0} vshufps %%r2, %%r2, %%r3, 0xEE ; r2 = {d3 d2 c3 c2} vshufps %%r1, %%t0, %%t1, 0xDD ; r1 = {d1 c1 b1 a1} vshufps %%r3, %%r0, %%r2, 0xDD ; r3 = {d3 c3 b3 a3} vshufps %%r0, %%r0, %%r2, 0x88 ; r0 = {d2 c2 b2 a2} vshufps %%t0, %%t0, %%t1, 0x88 ; t0 = {d0 c0 b0 a0} %endmacro ;; ;; Magic functions defined in FIPS 180-1 ;; ; macro MAGIC_F0 F,B,C,D,T ;; F = (D ^ (B & (C ^ D))) %macro MAGIC_F0 5 %define %%regF %1 %define %%regB %2 %define %%regC %3 %define %%regD %4 %define %%regT %5 vpxor %%regF, %%regC,%%regD vpand %%regF, %%regF,%%regB vpxor %%regF, %%regF,%%regD %endmacro ; macro MAGIC_F1 F,B,C,D,T ;; F = (B ^ C ^ D) %macro MAGIC_F1 5 %define %%regF %1 %define %%regB %2 %define %%regC %3 %define %%regD %4 %define %%regT %5 vpxor %%regF,%%regD,%%regC vpxor %%regF,%%regF,%%regB %endmacro ; macro MAGIC_F2 F,B,C,D,T ;; F = ((B & C) | (B & D) | (C & D)) %macro MAGIC_F2 5 %define %%regF %1 %define %%regB %2 %define %%regC %3 %define %%regD %4 %define %%regT %5 vpor %%regF,%%regB,%%regC vpand %%regT,%%regB,%%regC vpand %%regF,%%regF,%%regD vpor %%regF,%%regF,%%regT %endmacro ; macro MAGIC_F3 F,B,C,D,T ;; F = (B ^ C ^ D) %macro MAGIC_F3 5 %define %%regF %1 %define %%regB %2 %define %%regC %3 %define %%regD %4 %define %%regT %5 MAGIC_F1 %%regF,%%regB,%%regC,%%regD,%%regT %endmacro ; PROLD reg, imm, tmp %macro PROLD 3 %define %%reg %1 %define %%imm %2 %define %%tmp %3 vpsrld %%tmp, %%reg, (32-(%%imm)) vpslld %%reg, %%reg, %%imm vpor %%reg, %%reg, %%tmp %endmacro ; non-destructive ; PROLD_nd reg, imm, tmp, src %macro PROLD_nd 4 %define %%reg %1 %define %%imm %2 %define %%tmp %3 %define %%src %4 vpsrld %%tmp, %%src, (32-(%%imm)) vpslld %%reg, %%src, %%imm vpor %%reg, %%reg, %%tmp %endmacro %macro SHA1_STEP_00_15 10 %define %%regA %1 %define %%regB %2 %define %%regC %3 %define %%regD %4 %define %%regE %5 %define %%regT %6 %define %%regF %7 %define %%memW %8 %define %%immCNT %9 %define %%MAGIC %10 vpaddd %%regE, %%regE,%%immCNT vpaddd %%regE, %%regE,[rsp + (%%memW * 16)] PROLD_nd %%regT,5, %%regF,%%regA vpaddd %%regE, %%regE,%%regT %%MAGIC %%regF,%%regB,%%regC,%%regD,%%regT ;; FUN = MAGIC_Fi(B,C,D) PROLD %%regB,30, %%regT vpaddd %%regE, %%regE,%%regF %endmacro %macro SHA1_STEP_16_79 10 %define %%regA %1 %define %%regB %2 %define %%regC %3 %define %%regD %4 %define %%regE %5 %define %%regT %6 %define %%regF %7 %define %%memW %8 %define %%immCNT %9 %define %%MAGIC %10 vpaddd %%regE, %%regE,%%immCNT vmovdqa W14, [rsp + ((%%memW - 14) & 15) * 16] vpxor W16, W16, W14 vpxor W16, W16, [rsp + ((%%memW - 8) & 15) * 16] vpxor W16, W16, [rsp + ((%%memW - 3) & 15) * 16] vpsrld %%regF, W16, (32-1) vpslld W16, W16, 1 vpor %%regF, %%regF, W16 ROTATE_W vmovdqa [rsp + ((%%memW - 0) & 15) * 16],%%regF vpaddd %%regE, %%regE,%%regF PROLD_nd %%regT,5, %%regF, %%regA vpaddd %%regE, %%regE,%%regT %%MAGIC %%regF,%%regB,%%regC,%%regD,%%regT ;; FUN = MAGIC_Fi(B,C,D) PROLD %%regB,30, %%regT vpaddd %%regE,%%regE,%%regF %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; FRAMESZ must be an odd multiple of 8 %define FRAMESZ 16*16 + 8 %define VMOVPS vmovdqu %ifdef LINUX %define arg1 rdi %define arg2 rsi %else %define arg1 rcx %define arg2 rdx %endif %define inp0 r8 %define inp1 r9 %define inp2 r10 %define inp3 r11 %define IDX rax %define A xmm0 %define B xmm1 %define C xmm2 %define D xmm3 %define E xmm4 %define F xmm5 ; tmp %define G xmm6 ; tmp %define TMP G %define FUN F %define K xmm7 %define AA xmm8 %define BB xmm9 %define CC xmm10 %define DD xmm11 %define EE xmm12 %define T0 xmm6 %define T1 xmm7 %define T2 xmm8 %define T3 xmm9 %define T4 xmm10 %define T5 xmm11 %define W14 xmm13 %define W15 xmm14 %define W16 xmm15 %macro ROTATE_ARGS 0 %xdefine TMP_ E %xdefine E D %xdefine D C %xdefine C B %xdefine B A %xdefine A TMP_ %endm %macro ROTATE_W 0 %xdefine TMP_ W16 %xdefine W16 W15 %xdefine W15 W14 %xdefine W14 TMP_ %endm align 32 ; XMM registers are clobbered. Saving/restoring must be done at a higher level ; void sha1_mult_avx(SHA1_ARGS *args, UINT32 size_in_blocks); ; arg 1 : rcx : pointer to args ; arg 2 : rdx : size (in blocks) ;; assumed to be >= 1 MKGLOBAL(sha1_mult_avx,function,internal) sha1_mult_avx: sub rsp, FRAMESZ ;; Initialize digests vmovdqa A, [arg1 + 0*SHA1_DIGEST_ROW_SIZE] vmovdqa B, [arg1 + 1*SHA1_DIGEST_ROW_SIZE] vmovdqa C, [arg1 + 2*SHA1_DIGEST_ROW_SIZE] vmovdqa D, [arg1 + 3*SHA1_DIGEST_ROW_SIZE] vmovdqa E, [arg1 + 4*SHA1_DIGEST_ROW_SIZE] ;; transpose input onto stack mov inp0,[arg1 + _data_ptr_sha1 + 0*PTR_SZ] mov inp1,[arg1 + _data_ptr_sha1 + 1*PTR_SZ] mov inp2,[arg1 + _data_ptr_sha1 + 2*PTR_SZ] mov inp3,[arg1 + _data_ptr_sha1 + 3*PTR_SZ] xor IDX, IDX lloop: vmovdqa F, [rel PSHUFFLE_BYTE_FLIP_MASK] %assign I 0 %rep 4 VMOVPS T2,[inp0+IDX] VMOVPS T1,[inp1+IDX] VMOVPS T4,[inp2+IDX] VMOVPS T3,[inp3+IDX] TRANSPOSE T2, T1, T4, T3, T0, T5 vpshufb T0, T0, F vmovdqa [rsp+(I*4+0)*16],T0 vpshufb T1, T1, F vmovdqa [rsp+(I*4+1)*16],T1 vpshufb T2, T2, F vmovdqa [rsp+(I*4+2)*16],T2 vpshufb T3, T3, F vmovdqa [rsp+(I*4+3)*16],T3 add IDX, 4*4 %assign I (I+1) %endrep ; save old digests vmovdqa AA, A vmovdqa BB, B vmovdqa CC, C vmovdqa DD, D vmovdqa EE, E ;; ;; perform 0-79 steps ;; vmovdqa K, [rel K00_19] ;; do rounds 0...15 %assign I 0 %rep 16 SHA1_STEP_00_15 A,B,C,D,E, TMP,FUN, I, K, MAGIC_F0 ROTATE_ARGS %assign I (I+1) %endrep ;; do rounds 16...19 vmovdqa W16, [rsp + ((16 - 16) & 15) * 16] vmovdqa W15, [rsp + ((16 - 15) & 15) * 16] %rep 4 SHA1_STEP_16_79 A,B,C,D,E, TMP,FUN, I, K, MAGIC_F0 ROTATE_ARGS %assign I (I+1) %endrep ;; do rounds 20...39 vmovdqa K, [rel K20_39] %rep 20 SHA1_STEP_16_79 A,B,C,D,E, TMP,FUN, I, K, MAGIC_F1 ROTATE_ARGS %assign I (I+1) %endrep ;; do rounds 40...59 vmovdqa K, [rel K40_59] %rep 20 SHA1_STEP_16_79 A,B,C,D,E, TMP,FUN, I, K, MAGIC_F2 ROTATE_ARGS %assign I (I+1) %endrep ;; do rounds 60...79 vmovdqa K, [rel K60_79] %rep 20 SHA1_STEP_16_79 A,B,C,D,E, TMP,FUN, I, K, MAGIC_F3 ROTATE_ARGS %assign I (I+1) %endrep vpaddd A,A,AA vpaddd B,B,BB vpaddd C,C,CC vpaddd D,D,DD vpaddd E,E,EE sub arg2, 1 jne lloop ; write out digests vmovdqa [arg1 + 0*SHA1_DIGEST_ROW_SIZE], A vmovdqa [arg1 + 1*SHA1_DIGEST_ROW_SIZE], B vmovdqa [arg1 + 2*SHA1_DIGEST_ROW_SIZE], C vmovdqa [arg1 + 3*SHA1_DIGEST_ROW_SIZE], D vmovdqa [arg1 + 4*SHA1_DIGEST_ROW_SIZE], E ; update input pointers add inp0, IDX mov [arg1 + _data_ptr_sha1 + 0*PTR_SZ], inp0 add inp1, IDX mov [arg1 + _data_ptr_sha1 + 1*PTR_SZ], inp1 add inp2, IDX mov [arg1 + _data_ptr_sha1 + 2*PTR_SZ], inp2 add inp3, IDX mov [arg1 + _data_ptr_sha1 + 3*PTR_SZ], inp3 ;;;;;;;;;;;;;;;; ;; Postamble add rsp, FRAMESZ ret %ifdef LINUX section .note.GNU-stack noalloc noexec nowrite progbits %endif
#include "const.hpp" #include <cerrno> #include <cstdio> #include <cstdlib> #include <fcntl.h> #include <sys/epoll.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> struct ChildState { int pid; int readPipe; }; static struct ChildState g_States[ChildCount]; bool SpawnChild(struct ChildState* state, int index) { int pipefd[2]; if (pipe2(pipefd, O_CLOEXEC) == -1) { perror("pipe2"); return false; } char arg1[3]; std::sprintf(arg1, "%d", index); char appName[] = "app1"; char* args[] = {appName, arg1, NULL}; int childPid = fork(); if (childPid == -1) { perror("fork"); return false; } else if (childPid == 0) { // child if (pipefd[1] == MyPipeFd) { if (fcntl(MyPipeFd, F_SETFD, 0) == -1) { perror("fcntl"); _exit(1); } } else { if (dup2(pipefd[1], MyPipeFd) == -1) { perror("dup2"); _exit(1); } } execvpe(MyProgramName, args, environ); perror("execve"); _exit(1); } else { // parent close(pipefd[1]); state->readPipe = pipefd[0]; state->pid = childPid; std::printf("spawned pid %d\n", state->pid); return true; } } int appmain(int argc, const char** argv) { // fork children, then epoll pipes for (int i = 0; i < ChildCount; i++) { if (!SpawnChild(&g_States[i], i)) { std::printf("failed\n"); return 1; } } int epfd = epoll_create1(EPOLL_CLOEXEC); if (epfd == -1) { perror("epoll_create"); return 1; } for (int i = 0; i < ChildCount; i++) { struct ChildState* pState = &g_States[i]; struct epoll_event event; event.events = EPOLLIN; event.data.ptr = pState; epoll_ctl(epfd, EPOLL_CTL_ADD, pState->readPipe, &event); std::printf("registered State %p (readPipe) %d\n", pState, pState->readPipe); } int remainingProcs = ChildCount; while (remainingProcs > 0) { struct epoll_event event; int ret; while ((ret = epoll_wait(epfd, &event, 1, -1)) == -1 && errno == EINTR) ; if (ret == -1) { perror("epoll_wait"); return 1; } std::printf("event %x, data %p\n", event.events, event.data.ptr); if (event.events == EPOLLIN || event.events == EPOLLHUP) { struct ChildState* pState = static_cast<ChildState*>(event.data.ptr); int value; ssize_t readSize = read(pState->readPipe, &value, sizeof(int)); if (readSize == -1) { perror("read"); } else if (readSize != 4) { std::printf("%p: premature end of data.\n", pState); } else { int wstatus = 0; waitpid(pState->pid, &wstatus, 0); std::printf("%d finished with %d\n", value, wstatus); } remainingProcs--; epoll_ctl(epfd, EPOLL_CTL_DEL, pState->readPipe, &event); } } close(epfd); return 0; }
/** * @file rcDataObjCopy.cpp * */ /*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ /* This is script-generated code. */ /* See dataObjCopy.h for a description of this API call.*/ #include "dataObjCopy.h" #include "procApiRequest.h" #include "apiNumber.h" /** * \fn rcDataObjCopy (rcComm_t *conn, dataObjCopyInp_t *dataObjCopyInp) * * \brief Copy a data object from a iRODS path to another a iRODS path. * * \user client * * \ingroup data_object * * \since 1.0 * * * \remark none * * \note none * * \usage * Copy a data object /myZone/home/john/myfileA to /myZone/home/john/myfileB * and store in myRescource: * \n dataObjCopyInp_t dataObjCopyInp; * \n bzero (&dataObjCopyInp, sizeof (dataObjCopyInp)); * \n rstrcpy (dataObjCopyInp.destDataObjInp.objPath, * "/myZone/home/john/myfileB", MAX_NAME_LEN); * \n rstrcpy (dataObjCopyInp.srcDataObjInp.objPath, * "/myZone/home/john/myfileA", MAX_NAME_LEN); * \n addKeyVal (&dataObjCopyInp.destDataObjInp.condInput, DEST_RESC_NAME_KW, * "myRescource"); * \n status = rcDataObjCopy (conn, &dataObjCopyInp); * \n if (status < 0) { * \n .... handle the error * \n } * * \param[in] conn - A rcComm_t connection handle to the server. * \param[in] dataObjCopyInp - Elements of dataObjCopyInp_t used : * \li char \b srcDataObjInp.objPath[MAX_NAME_LEN] - full path of the * source data object. * \li char \b destDataObjInp.objPath[MAX_NAME_LEN] - full path of the * target data object. * \li int \b destDataObjInp.numThreads - the number of threads to use. * Valid values are: * \n NO_THREADING (-1) - no multi-thread * \n 0 - the server will decide the number of threads. * (recommanded setting). * \n A positive integer - specifies the number of threads. * \li keyValPair_t \b destDataObjInp.condInput - keyword/value pair input. * Valid keywords: * \n DATA_TYPE_KW - the data type of the data object. * \n FORCE_FLAG_KW - overwrite existing target. This keyWd has no value * \n REG_CHKSUM_KW - register the target checksum value after the copy. * This keyWd has no value. * \n VERIFY_CHKSUM_KW - verify and register the target checksum value * after the copy. This keyWd has no value. * \n DEST_RESC_NAME_KW - The resource to store this data object * \n FILE_PATH_KW - The physical file path for this data object if the * normal resource vault is not used. * \n RBUDP_TRANSFER_KW - use RBUDP for data transfer. This keyWd has no * value * \n RBUDP_SEND_RATE_KW - the number of RBUDP packet to send per second * The default is 600000 * \n RBUDP_PACK_SIZE_KW - the size of RBUDP packet. The default is 8192 * * \return integer * \retval 0 on success * \sideeffect none * \pre none * \post none * \sa none **/ int rcDataObjCopy( rcComm_t *conn, dataObjCopyInp_t *dataObjCopyInp ) { int status; transferStat_t *transferStat = NULL; memset( &conn->transStat, 0, sizeof( transferStat_t ) ); dataObjCopyInp->srcDataObjInp.oprType = COPY_SRC; dataObjCopyInp->destDataObjInp.oprType = COPY_DEST; status = _rcDataObjCopy( conn, dataObjCopyInp, &transferStat ); if ( status >= 0 && transferStat != NULL ) { conn->transStat = *( transferStat ); } if ( transferStat != NULL ) { free( transferStat ); } return status; } int _rcDataObjCopy( rcComm_t *conn, dataObjCopyInp_t *dataObjCopyInp, transferStat_t **transferStat ) { int status; status = procApiRequest( conn, DATA_OBJ_COPY_AN, dataObjCopyInp, NULL, ( void ** ) transferStat, NULL ); return status; }
; DRAW LOAD SPRITE 2 BYTE DEFINITION ROTATED ; 01.2006 aralbrec, Sprite Pack v3.0 ; sinclair spectrum version INCLUDE "clib_target_cfg.asm" SECTION code_temp_sp1 PUBLIC _SP1_DRAW_LOAD2 EXTERN _SP1_DRAW_LOAD2NR EXTERN SP1RETSPRDRAW ; following data segment copied into struct sp1_cs ld hl,0 ld ix,0 call _SP1_DRAW_LOAD2 ; following draw code called by way of SP1UpdateNow ; ; a = hor rot table ; bc = graphic disp ; hl = graphic def ptr (mask,graph) pairs ; ix = left graphic def ptr ; ; 51 + 150*4 - 6 + 10 = 655 cycles _SP1_DRAW_LOAD2: cp SP1V_ROTTBL/256 jp z, _SP1_DRAW_LOAD2NR add hl,bc add ix,bc ex de,hl ld h,a ; h = shift table ; de = sprite def (mask,graph) pairs ; ix = left sprite def _SP1Load2Rotate: ; 0 inc de ld a,(de) inc de ld l,a ld a,(hl) inc h ld l,(ix+1) or (hl) ld (SP1V_PIXELBUFFER+0),a ld l,(ix+3) ld b,(hl) dec h inc de ld a,(de) inc de ld l,a ld a,b or (hl) ld (SP1V_PIXELBUFFER+1),a ; 1 inc de ld a,(de) inc de ld l,a ld a,(hl) inc h ld l,(ix+5) or (hl) ld (SP1V_PIXELBUFFER+2),a ld l,(ix+7) ld b,(hl) dec h inc de ld a,(de) inc de ld l,a ld a,b or (hl) ld (SP1V_PIXELBUFFER+3),a ; 2 inc de ld a,(de) inc de ld l,a ld a,(hl) inc h ld l,(ix+9) or (hl) ld (SP1V_PIXELBUFFER+4),a ld l,(ix+11) ld b,(hl) dec h inc de ld a,(de) inc de ld l,a ld a,b or (hl) ld (SP1V_PIXELBUFFER+5),a ; 3 inc de ld a,(de) inc de ld l,a ld a,(hl) inc h ld l,(ix+13) or (hl) ld (SP1V_PIXELBUFFER+6),a ld l,(ix+15) ld b,(hl) dec h inc de ld a,(de) ld l,a ld a,b or (hl) ld (SP1V_PIXELBUFFER+7),a jp SP1RETSPRDRAW
5 ;the program starts at address 5 100 ;ISR address ;data segment 10 20 30 40 50 60 70 LDD R1,3 ;R1=20 LDD R2,4 ;R2=30 ADD R2,R1 ;R1=50 STD R1,4 ;M[4]=50 Push R2 ;M[1023]=30 Sp=1022 assume von Neumann arch Push R1 ;M[1022]=50 Sp=1021 LDD R1,0 ;R1=5 LDD R2,1 ;R2=100 ADD R2,R1 ;R1=105 Pop R1 ;R1=50 pop R2 ;R2=30 .100 SETC LDM R1,5 LDM R2,5 sub R1,R2 RTI
; int fseek_callee(FILE *stream, long offset, int whence) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _fseek_callee EXTERN asm_fseek _fseek_callee: pop af pop ix pop hl pop de pop bc push af jp asm_fseek ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC _fseek_callee EXTERN _fseek_unlocked_callee defc _fseek_callee = _fseek_unlocked_callee ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX AssertionProp XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif /***************************************************************************** * * Helper passed to Compiler::fgWalkTreePre() to find the Asgn node for optAddCopies() */ /* static */ Compiler::fgWalkResult Compiler::optAddCopiesCallback(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->OperIs(GT_ASG)) { GenTree* op1 = tree->AsOp()->gtOp1; Compiler* comp = data->compiler; if ((op1->gtOper == GT_LCL_VAR) && (op1->AsLclVarCommon()->GetLclNum() == comp->optAddCopyLclNum)) { comp->optAddCopyAsgnNode = tree; return WALK_ABORT; } } return WALK_CONTINUE; } /***************************************************************************** * * Add new copies before Assertion Prop. */ void Compiler::optAddCopies() { unsigned lclNum; LclVarDsc* varDsc; #ifdef DEBUG if (verbose) { printf("\n*************** In optAddCopies()\n\n"); } if (verboseTrees) { printf("Blocks/Trees at start of phase\n"); fgDispBasicBlocks(true); } #endif // Don't add any copies if we have reached the tracking limit. if (lvaHaveManyLocals()) { return; } for (lclNum = 0, varDsc = lvaTable; lclNum < lvaCount; lclNum++, varDsc++) { var_types typ = varDsc->TypeGet(); // We only add copies for non temp local variables // that have a single def and that can possibly be enregistered if (varDsc->lvIsTemp || !varDsc->lvSingleDef || !varTypeIsEnregisterable(typ)) { continue; } /* For lvNormalizeOnLoad(), we need to add a cast to the copy-assignment like "copyLclNum = int(varDsc)" and optAssertionGen() only tracks simple assignments. The same goes for lvNormalizedOnStore as the cast is generated in fgMorphSmpOpAsg. This boils down to not having a copy until optAssertionGen handles this*/ if (varDsc->lvNormalizeOnLoad() || varDsc->lvNormalizeOnStore()) { continue; } if (varTypeIsSmall(varDsc->TypeGet()) || typ == TYP_BOOL) { continue; } // If locals must be initialized to zero, that initialization counts as a second definition. // VB in particular allows usage of variables not explicitly initialized. // Note that this effectively disables this optimization for all local variables // as C# sets InitLocals all the time starting in Whidbey. if (!varDsc->lvIsParam && info.compInitMem) { continue; } // On x86 we may want to add a copy for an incoming double parameter // because we can ensure that the copy we make is double aligned // where as we can never ensure the alignment of an incoming double parameter // // On all other platforms we will never need to make a copy // for an incoming double parameter bool isFloatParam = false; #ifdef TARGET_X86 isFloatParam = varDsc->lvIsParam && varTypeIsFloating(typ); #endif if (!isFloatParam && !varDsc->lvVolatileHint) { continue; } // We don't want to add a copy for a variable that is part of a struct if (varDsc->lvIsStructField) { continue; } // We require that the weighted ref count be significant. if (varDsc->lvRefCntWtd() <= (BB_LOOP_WEIGHT_SCALE * BB_UNITY_WEIGHT / 2)) { continue; } // For parameters, we only want to add a copy for the heavier-than-average // uses instead of adding a copy to cover every single use. // 'paramImportantUseDom' is the set of blocks that dominate the // heavier-than-average uses of a parameter. // Initial value is all blocks. BlockSet paramImportantUseDom(BlockSetOps::MakeFull(this)); // This will be threshold for determining heavier-than-average uses BasicBlock::weight_t paramAvgWtdRefDiv2 = (varDsc->lvRefCntWtd() + varDsc->lvRefCnt() / 2) / (varDsc->lvRefCnt() * 2); bool paramFoundImportantUse = false; #ifdef DEBUG if (verbose) { printf("Trying to add a copy for V%02u %s, avg_wtd = %s\n", lclNum, varDsc->lvIsParam ? "an arg" : "a local", refCntWtd2str(paramAvgWtdRefDiv2)); } #endif // // We must have a ref in a block that is dominated only by the entry block // if (BlockSetOps::MayBeUninit(varDsc->lvRefBlks)) { // No references continue; } bool isDominatedByFirstBB = false; BlockSetOps::Iter iter(this, varDsc->lvRefBlks); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { /* Find the block 'bbNum' */ BasicBlock* block = fgFirstBB; while (block && (block->bbNum != bbNum)) { block = block->bbNext; } noway_assert(block && (block->bbNum == bbNum)); bool importantUseInBlock = (varDsc->lvIsParam) && (block->getBBWeight(this) > paramAvgWtdRefDiv2); bool isPreHeaderBlock = ((block->bbFlags & BBF_LOOP_PREHEADER) != 0); BlockSet blockDom(BlockSetOps::UninitVal()); BlockSet blockDomSub0(BlockSetOps::UninitVal()); if (block->bbIDom == nullptr && isPreHeaderBlock) { // Loop Preheader blocks that we insert will have a bbDom set that is nullptr // but we can instead use the bNext successor block's dominator information noway_assert(block->bbNext != nullptr); BlockSetOps::AssignNoCopy(this, blockDom, fgGetDominatorSet(block->bbNext)); } else { BlockSetOps::AssignNoCopy(this, blockDom, fgGetDominatorSet(block)); } if (!BlockSetOps::IsEmpty(this, blockDom)) { BlockSetOps::Assign(this, blockDomSub0, blockDom); if (isPreHeaderBlock) { // We must clear bbNext block number from the dominator set BlockSetOps::RemoveElemD(this, blockDomSub0, block->bbNext->bbNum); } /* Is this block dominated by fgFirstBB? */ if (BlockSetOps::IsMember(this, blockDomSub0, fgFirstBB->bbNum)) { isDominatedByFirstBB = true; } } #ifdef DEBUG if (verbose) { printf(" Referenced in " FMT_BB ", bbWeight is %s", bbNum, refCntWtd2str(block->getBBWeight(this))); if (isDominatedByFirstBB) { printf(", which is dominated by BB01"); } if (importantUseInBlock) { printf(", ImportantUse"); } printf("\n"); } #endif /* If this is a heavier-than-average block, then track which blocks dominate this use of the parameter. */ if (importantUseInBlock) { paramFoundImportantUse = true; BlockSetOps::IntersectionD(this, paramImportantUseDom, blockDomSub0); // Clear blocks that do not dominate } } // We should have found at least one heavier-than-averageDiv2 block. if (varDsc->lvIsParam) { if (!paramFoundImportantUse) { continue; } } // For us to add a new copy: // we require that we have a floating point parameter // or a lvVolatile variable that is always reached from the first BB // and we have at least one block available in paramImportantUseDom // bool doCopy = (isFloatParam || (isDominatedByFirstBB && varDsc->lvVolatileHint)) && !BlockSetOps::IsEmpty(this, paramImportantUseDom); // Under stress mode we expand the number of candidates // to include parameters of any type // or any variable that is always reached from the first BB // if (compStressCompile(STRESS_GENERIC_VARN, 30)) { // Ensure that we preserve the invariants required by the subsequent code. if (varDsc->lvIsParam || isDominatedByFirstBB) { doCopy = true; } } if (!doCopy) { continue; } Statement* stmt; unsigned copyLclNum = lvaGrabTemp(false DEBUGARG("optAddCopies")); // Because lvaGrabTemp may have reallocated the lvaTable, ensure varDsc // is still in sync with lvaTable[lclNum]; varDsc = &lvaTable[lclNum]; // Set lvType on the new Temp Lcl Var lvaTable[copyLclNum].lvType = typ; #ifdef DEBUG if (verbose) { printf("\n Finding the best place to insert the assignment V%02i=V%02i\n", copyLclNum, lclNum); } #endif if (varDsc->lvIsParam) { noway_assert(varDsc->lvDefStmt == nullptr || varDsc->lvIsStructField); // Create a new copy assignment tree GenTree* copyAsgn = gtNewTempAssign(copyLclNum, gtNewLclvNode(lclNum, typ)); /* Find the best block to insert the new assignment */ /* We will choose the lowest weighted block, and within */ /* those block, the highest numbered block which */ /* dominates all the uses of the local variable */ /* Our default is to use the first block */ BasicBlock* bestBlock = fgFirstBB; BasicBlock::weight_t bestWeight = bestBlock->getBBWeight(this); BasicBlock* block = bestBlock; #ifdef DEBUG if (verbose) { printf(" Starting at " FMT_BB ", bbWeight is %s", block->bbNum, refCntWtd2str(block->getBBWeight(this))); printf(", bestWeight is %s\n", refCntWtd2str(bestWeight)); } #endif /* We have already calculated paramImportantUseDom above. */ BlockSetOps::Iter iter(this, paramImportantUseDom); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { /* Advance block to point to 'bbNum' */ /* This assumes that the iterator returns block number is increasing lexical order. */ while (block && (block->bbNum != bbNum)) { block = block->bbNext; } noway_assert(block && (block->bbNum == bbNum)); #ifdef DEBUG if (verbose) { printf(" Considering " FMT_BB ", bbWeight is %s", block->bbNum, refCntWtd2str(block->getBBWeight(this))); printf(", bestWeight is %s\n", refCntWtd2str(bestWeight)); } #endif // Does this block have a smaller bbWeight value? if (block->getBBWeight(this) > bestWeight) { #ifdef DEBUG if (verbose) { printf("bbWeight too high\n"); } #endif continue; } // Don't use blocks that are exception handlers because // inserting a new first statement will interface with // the CATCHARG if (handlerGetsXcptnObj(block->bbCatchTyp)) { #ifdef DEBUG if (verbose) { printf("Catch block\n"); } #endif continue; } // Don't use the BBJ_ALWAYS block marked with BBF_KEEP_BBJ_ALWAYS. These // are used by EH code. The JIT can not generate code for such a block. if (block->bbFlags & BBF_KEEP_BBJ_ALWAYS) { #if defined(FEATURE_EH_FUNCLETS) // With funclets, this is only used for BBJ_CALLFINALLY/BBJ_ALWAYS pairs. For x86, it is also used // as the "final step" block for leaving finallys. assert(block->isBBCallAlwaysPairTail()); #endif // FEATURE_EH_FUNCLETS #ifdef DEBUG if (verbose) { printf("Internal EH BBJ_ALWAYS block\n"); } #endif continue; } // This block will be the new candidate for the insert point // for the new assignment CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf("new bestBlock\n"); } #endif bestBlock = block; bestWeight = block->getBBWeight(this); } // If there is a use of the variable in this block // then we insert the assignment at the beginning // otherwise we insert the statement at the end CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf(" Insert copy at the %s of " FMT_BB "\n", (BlockSetOps::IsEmpty(this, paramImportantUseDom) || BlockSetOps::IsMember(this, varDsc->lvRefBlks, bestBlock->bbNum)) ? "start" : "end", bestBlock->bbNum); } #endif if (BlockSetOps::IsEmpty(this, paramImportantUseDom) || BlockSetOps::IsMember(this, varDsc->lvRefBlks, bestBlock->bbNum)) { stmt = fgNewStmtAtBeg(bestBlock, copyAsgn); } else { stmt = fgNewStmtNearEnd(bestBlock, copyAsgn); } } else { noway_assert(varDsc->lvDefStmt != nullptr); /* Locate the assignment to varDsc in the lvDefStmt */ stmt = varDsc->lvDefStmt; optAddCopyLclNum = lclNum; // in optAddCopyAsgnNode = nullptr; // out fgWalkTreePre(stmt->GetRootNodePointer(), Compiler::optAddCopiesCallback, (void*)this, false); noway_assert(optAddCopyAsgnNode); GenTree* tree = optAddCopyAsgnNode; GenTree* op1 = tree->AsOp()->gtOp1; noway_assert(tree && op1 && tree->OperIs(GT_ASG) && (op1->gtOper == GT_LCL_VAR) && (op1->AsLclVarCommon()->GetLclNum() == lclNum)); /* Assign the old expression into the new temp */ GenTree* newAsgn = gtNewTempAssign(copyLclNum, tree->AsOp()->gtOp2); /* Copy the new temp to op1 */ GenTree* copyAsgn = gtNewAssignNode(op1, gtNewLclvNode(copyLclNum, typ)); /* Change the tree to a GT_COMMA with the two assignments as child nodes */ tree->gtBashToNOP(); tree->ChangeOper(GT_COMMA); tree->AsOp()->gtOp1 = newAsgn; tree->AsOp()->gtOp2 = copyAsgn; tree->gtFlags |= (newAsgn->gtFlags & GTF_ALL_EFFECT); tree->gtFlags |= (copyAsgn->gtFlags & GTF_ALL_EFFECT); } #ifdef DEBUG if (verbose) { printf("\nIntroducing a new copy for V%02u\n", lclNum); gtDispTree(stmt->GetRootNode()); printf("\n"); } #endif } } //------------------------------------------------------------------------------ // GetAssertionDep: Retrieve the assertions on this local variable // // Arguments: // lclNum - The local var id. // // Return Value: // The dependent assertions (assertions using the value of the local var) // of the local var. // ASSERT_TP& Compiler::GetAssertionDep(unsigned lclNum) { JitExpandArray<ASSERT_TP>& dep = *optAssertionDep; if (dep[lclNum] == nullptr) { dep[lclNum] = BitVecOps::MakeEmpty(apTraits); } return dep[lclNum]; } /***************************************************************************** * * Initialize the assertion prop bitset traits and the default bitsets. */ void Compiler::optAssertionTraitsInit(AssertionIndex assertionCount) { apTraits = new (this, CMK_AssertionProp) BitVecTraits(assertionCount, this); apFull = BitVecOps::MakeFull(apTraits); } /***************************************************************************** * * Initialize the assertion prop tracking logic. */ void Compiler::optAssertionInit(bool isLocalProp) { // Use a function countFunc to determine a proper maximum assertion count for the // method being compiled. The function is linear to the IL size for small and // moderate methods. For large methods, considering throughput impact, we track no // more than 64 assertions. // Note this tracks at most only 256 assertions. static const AssertionIndex countFunc[] = {64, 128, 256, 64}; static const unsigned lowerBound = 0; static const unsigned upperBound = _countof(countFunc) - 1; const unsigned codeSize = info.compILCodeSize / 512; optMaxAssertionCount = countFunc[isLocalProp ? lowerBound : min(upperBound, codeSize)]; optLocalAssertionProp = isLocalProp; optAssertionTabPrivate = new (this, CMK_AssertionProp) AssertionDsc[optMaxAssertionCount]; optComplementaryAssertionMap = new (this, CMK_AssertionProp) AssertionIndex[optMaxAssertionCount + 1](); // zero-inited (NO_ASSERTION_INDEX) assert(NO_ASSERTION_INDEX == 0); if (!isLocalProp) { optValueNumToAsserts = new (getAllocator(CMK_AssertionProp)) ValueNumToAssertsMap(getAllocator(CMK_AssertionProp)); } if (optAssertionDep == nullptr) { optAssertionDep = new (this, CMK_AssertionProp) JitExpandArray<ASSERT_TP>(getAllocator(CMK_AssertionProp), max(1, lvaCount)); } optAssertionTraitsInit(optMaxAssertionCount); optAssertionCount = 0; optAssertionPropagated = false; bbJtrueAssertionOut = nullptr; } #ifdef DEBUG void Compiler::optPrintAssertion(AssertionDsc* curAssertion, AssertionIndex assertionIndex /* = 0 */) { if (curAssertion->op1.kind == O1K_EXACT_TYPE) { printf("Type "); } else if (curAssertion->op1.kind == O1K_ARR_BND) { printf("ArrBnds "); } else if (curAssertion->op1.kind == O1K_SUBTYPE) { printf("Subtype "); } else if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { printf("Copy "); } else if ((curAssertion->op2.kind == O2K_CONST_INT) || (curAssertion->op2.kind == O2K_CONST_LONG) || (curAssertion->op2.kind == O2K_CONST_DOUBLE)) { printf("Constant "); } else if (curAssertion->op2.kind == O2K_SUBRANGE) { printf("Subrange "); } else { printf("?assertion classification? "); } printf("Assertion: "); if (!optLocalAssertionProp) { printf("(" FMT_VN "," FMT_VN ") ", curAssertion->op1.vn, curAssertion->op2.vn); } if ((curAssertion->op1.kind == O1K_LCLVAR) || (curAssertion->op1.kind == O1K_EXACT_TYPE) || (curAssertion->op1.kind == O1K_SUBTYPE)) { printf("V%02u", curAssertion->op1.lcl.lclNum); if (curAssertion->op1.lcl.ssaNum != SsaConfig::RESERVED_SSA_NUM) { printf(".%02u", curAssertion->op1.lcl.ssaNum); } } else if (curAssertion->op1.kind == O1K_ARR_BND) { printf("[idx:"); vnStore->vnDump(this, curAssertion->op1.bnd.vnIdx); printf(";len:"); vnStore->vnDump(this, curAssertion->op1.bnd.vnLen); printf("]"); } else if (curAssertion->op1.kind == O1K_BOUND_OPER_BND) { printf("Oper_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_BOUND_LOOP_BND) { printf("Loop_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND) { printf("Const_Loop_Bnd"); vnStore->vnDump(this, curAssertion->op1.vn); } else if (curAssertion->op1.kind == O1K_VALUE_NUMBER) { printf("Value_Number"); vnStore->vnDump(this, curAssertion->op1.vn); } else { printf("?op1.kind?"); } if (curAssertion->assertionKind == OAK_SUBRANGE) { printf(" in "); } else if (curAssertion->assertionKind == OAK_EQUAL) { if (curAssertion->op1.kind == O1K_LCLVAR) { printf(" == "); } else { printf(" is "); } } else if (curAssertion->assertionKind == OAK_NO_THROW) { printf(" in range "); } else if (curAssertion->assertionKind == OAK_NOT_EQUAL) { if (curAssertion->op1.kind == O1K_LCLVAR) { printf(" != "); } else { printf(" is not "); } } else { printf(" ?assertionKind? "); } if (curAssertion->op1.kind != O1K_ARR_BND) { switch (curAssertion->op2.kind) { case O2K_LCLVAR_COPY: printf("V%02u", curAssertion->op2.lcl.lclNum); if (curAssertion->op1.lcl.ssaNum != SsaConfig::RESERVED_SSA_NUM) { printf(".%02u", curAssertion->op1.lcl.ssaNum); } break; case O2K_CONST_INT: case O2K_IND_CNS_INT: if (curAssertion->op1.kind == O1K_EXACT_TYPE) { printf("Exact Type MT(%08X)", dspPtr(curAssertion->op2.u1.iconVal)); assert(curAssertion->op2.u1.iconFlags != GTF_EMPTY); } else if (curAssertion->op1.kind == O1K_SUBTYPE) { printf("MT(%08X)", dspPtr(curAssertion->op2.u1.iconVal)); assert(curAssertion->op2.u1.iconFlags != GTF_EMPTY); } else if (curAssertion->op1.kind == O1K_BOUND_OPER_BND) { assert(!optLocalAssertionProp); vnStore->vnDump(this, curAssertion->op2.vn); } else if (curAssertion->op1.kind == O1K_BOUND_LOOP_BND) { assert(!optLocalAssertionProp); vnStore->vnDump(this, curAssertion->op2.vn); } else if (curAssertion->op1.kind == O1K_CONSTANT_LOOP_BND) { assert(!optLocalAssertionProp); vnStore->vnDump(this, curAssertion->op2.vn); } else { var_types op1Type; if (curAssertion->op1.kind == O1K_VALUE_NUMBER) { op1Type = vnStore->TypeOfVN(curAssertion->op1.vn); } else { unsigned lclNum = curAssertion->op1.lcl.lclNum; assert(lclNum < lvaCount); LclVarDsc* varDsc = lvaTable + lclNum; op1Type = varDsc->lvType; } if (op1Type == TYP_REF) { assert(curAssertion->op2.u1.iconVal == 0); printf("null"); } else { if ((curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) != 0) { printf("[%08p]", dspPtr(curAssertion->op2.u1.iconVal)); } else { printf("%d", curAssertion->op2.u1.iconVal); } } } break; case O2K_CONST_LONG: printf("0x%016llx", curAssertion->op2.lconVal); break; case O2K_CONST_DOUBLE: if (*((__int64*)&curAssertion->op2.dconVal) == (__int64)I64(0x8000000000000000)) { printf("-0.00000"); } else { printf("%#lg", curAssertion->op2.dconVal); } break; case O2K_SUBRANGE: printf("[%d..%d]", curAssertion->op2.u2.loBound, curAssertion->op2.u2.hiBound); break; default: printf("?op2.kind?"); break; } } if (assertionIndex > 0) { printf(", index = "); optPrintAssertionIndex(assertionIndex); } printf("\n"); } void Compiler::optPrintAssertionIndex(AssertionIndex index) { if (index == NO_ASSERTION_INDEX) { printf("#NA"); return; } printf("#%02u", index); } void Compiler::optPrintAssertionIndices(ASSERT_TP assertions) { if (BitVecOps::IsEmpty(apTraits, assertions)) { optPrintAssertionIndex(NO_ASSERTION_INDEX); return; } BitVecOps::Iter iter(apTraits, assertions); unsigned bitIndex = 0; if (iter.NextElem(&bitIndex)) { optPrintAssertionIndex(static_cast<AssertionIndex>(bitIndex + 1)); while (iter.NextElem(&bitIndex)) { printf(" "); optPrintAssertionIndex(static_cast<AssertionIndex>(bitIndex + 1)); } } } #endif // DEBUG /* static */ void Compiler::optDumpAssertionIndices(const char* header, ASSERT_TP assertions, const char* footer /* = nullptr */) { #ifdef DEBUG Compiler* compiler = JitTls::GetCompiler(); if (compiler->verbose) { printf(header); compiler->optPrintAssertionIndices(assertions); if (footer != nullptr) { printf(footer); } } #endif // DEBUG } /* static */ void Compiler::optDumpAssertionIndices(ASSERT_TP assertions, const char* footer /* = nullptr */) { optDumpAssertionIndices("", assertions, footer); } /****************************************************************************** * * Helper to retrieve the "assertIndex" assertion. Note that assertIndex 0 * is NO_ASSERTION_INDEX and "optAssertionCount" is the last valid index. * */ Compiler::AssertionDsc* Compiler::optGetAssertion(AssertionIndex assertIndex) { assert(NO_ASSERTION_INDEX == 0); assert(assertIndex != NO_ASSERTION_INDEX); assert(assertIndex <= optAssertionCount); AssertionDsc* assertion = &optAssertionTabPrivate[assertIndex - 1]; #ifdef DEBUG optDebugCheckAssertion(assertion); #endif return assertion; } //------------------------------------------------------------------------ // optCreateAssertion: Create an (op1 assertionKind op2) assertion. // // Arguments: // op1 - the first assertion operand // op2 - the second assertion operand // assertionKind - the assertion kind // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // Return Value: // The new assertion index or NO_ASSERTION_INDEX if a new assertion // was not created. // // Notes: // Assertion creation may fail either because the provided assertion // operands aren't supported or because the assertion table is full. // AssertionIndex Compiler::optCreateAssertion(GenTree* op1, GenTree* op2, optAssertionKind assertionKind, bool helperCallArgs) { assert((op1 != nullptr) && !op1->OperIs(GT_LIST)); assert((op2 == nullptr) || !op2->OperIs(GT_LIST)); assert(!helperCallArgs || (op2 != nullptr)); AssertionDsc assertion; memset(&assertion, 0, sizeof(AssertionDsc)); assert(assertion.assertionKind == OAK_INVALID); var_types toType; if (op1->gtOper == GT_ARR_BOUNDS_CHECK) { if (assertionKind == OAK_NO_THROW) { GenTreeBoundsChk* arrBndsChk = op1->AsBoundsChk(); assertion.assertionKind = assertionKind; assertion.op1.kind = O1K_ARR_BND; assertion.op1.bnd.vnIdx = vnStore->VNConservativeNormalValue(arrBndsChk->gtIndex->gtVNPair); assertion.op1.bnd.vnLen = vnStore->VNConservativeNormalValue(arrBndsChk->gtArrLen->gtVNPair); goto DONE_ASSERTION; } } // // Are we trying to make a non-null assertion? // if (op2 == nullptr) { // // Must be an OAK_NOT_EQUAL assertion // noway_assert(assertionKind == OAK_NOT_EQUAL); // // Set op1 to the instance pointer of the indirection // ssize_t offset = 0; while ((op1->gtOper == GT_ADD) && (op1->gtType == TYP_BYREF)) { if (op1->gtGetOp2()->IsCnsIntOrI()) { offset += op1->gtGetOp2()->AsIntCon()->gtIconVal; op1 = op1->gtGetOp1(); } else if (op1->gtGetOp1()->IsCnsIntOrI()) { offset += op1->gtGetOp1()->AsIntCon()->gtIconVal; op1 = op1->gtGetOp2(); } else { break; } } if (fgIsBigOffset(offset) || op1->gtOper != GT_LCL_VAR) { goto DONE_ASSERTION; // Don't make an assertion } unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum < lvaCount); LclVarDsc* lclVar = &lvaTable[lclNum]; ValueNum vn; // // We only perform null-checks on GC refs // so only make non-null assertions about GC refs or byrefs if we can't determine // the corresponding ref. // if (lclVar->TypeGet() != TYP_REF) { if (optLocalAssertionProp || (lclVar->TypeGet() != TYP_BYREF)) { goto DONE_ASSERTION; // Don't make an assertion } vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); VNFuncApp funcAttr; // Try to get value number corresponding to the GC ref of the indirection while (vnStore->GetVNFunc(vn, &funcAttr) && (funcAttr.m_func == (VNFunc)GT_ADD) && (vnStore->TypeOfVN(vn) == TYP_BYREF)) { if (vnStore->IsVNConstant(funcAttr.m_args[1]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[1]))) { offset += vnStore->CoercedConstantValue<ssize_t>(funcAttr.m_args[1]); vn = funcAttr.m_args[0]; } else if (vnStore->IsVNConstant(funcAttr.m_args[0]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[0]))) { offset += vnStore->CoercedConstantValue<ssize_t>(funcAttr.m_args[0]); vn = funcAttr.m_args[1]; } else { break; } } if (fgIsBigOffset(offset)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_VALUE_NUMBER; } else { // If the local variable has its address exposed then bail if (lclVar->lvAddrExposed) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_LCLVAR; assertion.op1.lcl.lclNum = lclNum; assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); } assertion.op1.vn = vn; assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_CONST_INT; assertion.op2.vn = ValueNumStore::VNForNull(); assertion.op2.u1.iconVal = 0; assertion.op2.u1.iconFlags = GTF_EMPTY; #ifdef TARGET_64BIT assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG #endif // TARGET_64BIT } // // Are we making an assertion about a local variable? // else if (op1->gtOper == GT_LCL_VAR) { unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum < lvaCount); LclVarDsc* lclVar = &lvaTable[lclNum]; // If the local variable has its address exposed then bail if (lclVar->lvAddrExposed) { goto DONE_ASSERTION; // Don't make an assertion } if (helperCallArgs) { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } if (op2->gtOper == GT_IND) { op2 = op2->AsOp()->gtOp1; assertion.op2.kind = O2K_IND_CNS_INT; } else { assertion.op2.kind = O2K_CONST_INT; } if (op2->gtOper != GT_CNS_INT) { goto DONE_ASSERTION; // Don't make an assertion } // // TODO-CQ: Check for Sealed class and change kind to O1K_EXACT_TYPE // And consider the special cases, like CORINFO_FLG_SHAREDINST or CORINFO_FLG_VARIANCE // where a class can be sealed, but they don't behave as exact types because casts to // non-base types sometimes still succeed. // assertion.op1.kind = O1K_SUBTYPE; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); assertion.op2.u1.iconVal = op2->AsIntCon()->gtIconVal; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); assertion.op2.u1.iconFlags = op2->GetIconHandleFlag(); // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; } else // !helperCallArgs { /* Skip over a GT_COMMA node(s), if necessary */ while (op2->gtOper == GT_COMMA) { op2 = op2->AsOp()->gtOp2; } assertion.op1.kind = O1K_LCLVAR; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); switch (op2->gtOper) { optOp2Kind op2Kind; // // No Assertion // default: goto DONE_ASSERTION; // Don't make an assertion // // Constant Assertions // case GT_CNS_INT: op2Kind = O2K_CONST_INT; goto CNS_COMMON; case GT_CNS_LNG: op2Kind = O2K_CONST_LONG; goto CNS_COMMON; case GT_CNS_DBL: op2Kind = O2K_CONST_DOUBLE; goto CNS_COMMON; CNS_COMMON: { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } // If the LclVar is a TYP_LONG then we only make // assertions where op2 is also TYP_LONG // if ((lclVar->TypeGet() == TYP_LONG) && (op2->TypeGet() != TYP_LONG)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.kind = op2Kind; assertion.op2.lconVal = 0; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); if (op2->gtOper == GT_CNS_INT) { #ifdef TARGET_ARM // Do not Constant-Prop large constants for ARM // TODO-CrossBitness: we wouldn't need the cast below if GenTreeIntCon::gtIconVal had // target_ssize_t type. if (!codeGen->validImmForMov((target_ssize_t)op2->AsIntCon()->gtIconVal)) { goto DONE_ASSERTION; // Don't make an assertion } #endif // TARGET_ARM assertion.op2.u1.iconVal = op2->AsIntCon()->gtIconVal; assertion.op2.u1.iconFlags = op2->GetIconHandleFlag(); #ifdef TARGET_64BIT if (op2->TypeGet() == TYP_LONG || op2->TypeGet() == TYP_BYREF) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } else if (op2->gtOper == GT_CNS_LNG) { assertion.op2.lconVal = op2->AsLngCon()->gtLconVal; } else { noway_assert(op2->gtOper == GT_CNS_DBL); /* If we have an NaN value then don't record it */ if (_isnan(op2->AsDblCon()->gtDconVal)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.dconVal = op2->AsDblCon()->gtDconVal; } // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; } break; // // Copy Assertions // case GT_LCL_VAR: { // // Must either be an OAK_EQUAL or an OAK_NOT_EQUAL assertion // if ((assertionKind != OAK_EQUAL) && (assertionKind != OAK_NOT_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } unsigned lclNum2 = op2->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum2 < lvaCount); LclVarDsc* lclVar2 = &lvaTable[lclNum2]; // If the two locals are the same then bail if (lclNum == lclNum2) { goto DONE_ASSERTION; // Don't make an assertion } // If the types are different then bail */ if (lclVar->lvType != lclVar2->lvType) { goto DONE_ASSERTION; // Don't make an assertion } // If we're making a copy of a "normalize on load" lclvar then the destination // has to be "normalize on load" as well, otherwise we risk skipping normalization. if (lclVar2->lvNormalizeOnLoad() && !lclVar->lvNormalizeOnLoad()) { goto DONE_ASSERTION; // Don't make an assertion } // If the local variable has its address exposed then bail if (lclVar2->lvAddrExposed) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.kind = O2K_LCLVAR_COPY; assertion.op2.lcl.lclNum = lclNum2; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); assertion.op2.lcl.ssaNum = op2->AsLclVarCommon()->GetSsaNum(); // // Ok everything has been set and the assertion looks good // assertion.assertionKind = assertionKind; } break; // Subrange Assertions case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GT: case GT_GE: /* Assigning the result of a RELOP, we can add a boolean subrange assertion */ toType = TYP_BOOL; goto SUBRANGE_COMMON; case GT_CLS_VAR: /* Assigning the result of an indirection into a LCL_VAR, see if we can add a subrange assertion */ toType = op2->gtType; goto SUBRANGE_COMMON; case GT_LCL_FLD: /* Assigning the result of an indirection into a LCL_VAR, see if we can add a subrange assertion */ toType = op2->gtType; goto SUBRANGE_COMMON; case GT_IND: /* Assigning the result of an indirection into a LCL_VAR, see if we can add a subrange assertion */ toType = op2->gtType; goto SUBRANGE_COMMON; case GT_CAST: { if (lvaTable[lclNum].lvIsStructField && lvaTable[lclNum].lvNormalizeOnLoad()) { // Keep the cast on small struct fields. goto DONE_ASSERTION; // Don't make an assertion } toType = op2->CastToType(); SUBRANGE_COMMON: if ((assertionKind != OAK_SUBRANGE) && (assertionKind != OAK_EQUAL)) { goto DONE_ASSERTION; // Don't make an assertion } if (varTypeIsFloating(op1->TypeGet())) { // We don't make assertions on a cast from floating point goto DONE_ASSERTION; } switch (toType) { case TYP_BOOL: case TYP_BYTE: case TYP_UBYTE: case TYP_SHORT: case TYP_USHORT: #ifdef TARGET_64BIT case TYP_UINT: case TYP_INT: #endif // TARGET_64BIT assertion.op2.u2.loBound = AssertionDsc::GetLowerBoundForIntegralType(toType); assertion.op2.u2.hiBound = AssertionDsc::GetUpperBoundForIntegralType(toType); break; default: goto DONE_ASSERTION; // Don't make an assertion } assertion.op2.kind = O2K_SUBRANGE; assertion.assertionKind = OAK_SUBRANGE; } break; } } // else // !helperCallArgs } // if (op1->gtOper == GT_LCL_VAR) // // Are we making an IsType assertion? // else if (op1->gtOper == GT_IND) { op1 = op1->AsOp()->gtOp1; // // Is this an indirection of a local variable? // if (op1->gtOper == GT_LCL_VAR) { unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum < lvaCount); // If the local variable is not in SSA then bail if (!lvaInSsa(lclNum)) { goto DONE_ASSERTION; } // If we have an typeHnd indirection then op1 must be a TYP_REF // and the indirection must produce a TYP_I // if (op1->gtType != TYP_REF) { goto DONE_ASSERTION; // Don't make an assertion } assertion.op1.kind = O1K_EXACT_TYPE; assertion.op1.lcl.lclNum = lclNum; assertion.op1.vn = vnStore->VNConservativeNormalValue(op1->gtVNPair); assertion.op1.lcl.ssaNum = op1->AsLclVarCommon()->GetSsaNum(); assert((assertion.op1.lcl.ssaNum == SsaConfig::RESERVED_SSA_NUM) || (assertion.op1.vn == vnStore->VNConservativeNormalValue( lvaTable[lclNum].GetPerSsaData(assertion.op1.lcl.ssaNum)->m_vnPair))); ssize_t cnsValue = 0; GenTreeFlags iconFlags = GTF_EMPTY; // Ngen case if (op2->gtOper == GT_IND) { if (!optIsTreeKnownIntValue(!optLocalAssertionProp, op2->AsOp()->gtOp1, &cnsValue, &iconFlags)) { goto DONE_ASSERTION; // Don't make an assertion } assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_IND_CNS_INT; assertion.op2.u1.iconVal = cnsValue; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->AsOp()->gtOp1->gtVNPair); /* iconFlags should only contain bits in GTF_ICON_HDL_MASK */ assert((iconFlags & ~GTF_ICON_HDL_MASK) == 0); assertion.op2.u1.iconFlags = iconFlags; #ifdef TARGET_64BIT if (op2->AsOp()->gtOp1->TypeGet() == TYP_LONG) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } // JIT case else if (optIsTreeKnownIntValue(!optLocalAssertionProp, op2, &cnsValue, &iconFlags)) { assertion.assertionKind = assertionKind; assertion.op2.kind = O2K_CONST_INT; assertion.op2.u1.iconVal = cnsValue; assertion.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); /* iconFlags should only contain bits in GTF_ICON_HDL_MASK */ assert((iconFlags & ~GTF_ICON_HDL_MASK) == 0); assertion.op2.u1.iconFlags = iconFlags; #ifdef TARGET_64BIT if (op2->TypeGet() == TYP_LONG) { assertion.op2.u1.iconFlags |= GTF_ASSERTION_PROP_LONG; // Signify that this is really TYP_LONG } #endif // TARGET_64BIT } else { goto DONE_ASSERTION; // Don't make an assertion } } } DONE_ASSERTION: if (assertion.assertionKind == OAK_INVALID) { return NO_ASSERTION_INDEX; } if (!optLocalAssertionProp) { if ((assertion.op1.vn == ValueNumStore::NoVN) || (assertion.op2.vn == ValueNumStore::NoVN) || (assertion.op1.vn == ValueNumStore::VNForVoid()) || (assertion.op2.vn == ValueNumStore::VNForVoid())) { return NO_ASSERTION_INDEX; } // TODO: only copy assertions rely on valid SSA number so we could generate more assertions here if ((assertion.op1.kind != O1K_VALUE_NUMBER) && (assertion.op1.lcl.ssaNum == SsaConfig::RESERVED_SSA_NUM)) { return NO_ASSERTION_INDEX; } } // Now add the assertion to our assertion table noway_assert(assertion.op1.kind != O1K_INVALID); noway_assert((assertion.op1.kind == O1K_ARR_BND) || (assertion.op2.kind != O2K_INVALID)); return optAddAssertion(&assertion); } /***************************************************************************** * * If tree is a constant node holding an integral value, retrieve the value in * pConstant. If the method returns true, pConstant holds the appropriate * constant. Set "vnBased" to true to indicate local or global assertion prop. * "pFlags" indicates if the constant is a handle marked by GTF_ICON_HDL_MASK. */ bool Compiler::optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, GenTreeFlags* pFlags) { // Is Local assertion prop? if (!vnBased) { if (tree->OperGet() == GT_CNS_INT) { *pConstant = tree->AsIntCon()->IconValue(); *pFlags = tree->GetIconHandleFlag(); return true; } #ifdef TARGET_64BIT // Just to be clear, get it from gtLconVal rather than // overlapping gtIconVal. else if (tree->OperGet() == GT_CNS_LNG) { *pConstant = tree->AsLngCon()->gtLconVal; *pFlags = tree->GetIconHandleFlag(); return true; } #endif return false; } // Global assertion prop ValueNum vn = vnStore->VNConservativeNormalValue(tree->gtVNPair); if (!vnStore->IsVNConstant(vn)) { return false; } // ValueNumber 'vn' indicates that this node evaluates to a constant var_types vnType = vnStore->TypeOfVN(vn); if (vnType == TYP_INT) { *pConstant = vnStore->ConstantValue<int>(vn); *pFlags = vnStore->IsVNHandle(vn) ? vnStore->GetHandleFlags(vn) : GTF_EMPTY; return true; } #ifdef TARGET_64BIT else if (vnType == TYP_LONG) { *pConstant = vnStore->ConstantValue<INT64>(vn); *pFlags = vnStore->IsVNHandle(vn) ? vnStore->GetHandleFlags(vn) : GTF_EMPTY; return true; } #endif return false; } #ifdef DEBUG /***************************************************************************** * * Print the assertions related to a VN for all VNs. * */ void Compiler::optPrintVnAssertionMapping() { printf("\nVN Assertion Mapping\n"); printf("---------------------\n"); for (ValueNumToAssertsMap::KeyIterator ki = optValueNumToAsserts->Begin(); !ki.Equal(optValueNumToAsserts->End()); ++ki) { printf("(%d => ", ki.Get()); printf("%s)\n", BitVecOps::ToString(apTraits, ki.GetValue())); } } #endif /***************************************************************************** * * Maintain a map "optValueNumToAsserts" i.e., vn -> to set of assertions * about that VN. Given "assertions" about a "vn" add it to the previously * mapped assertions about that "vn." */ void Compiler::optAddVnAssertionMapping(ValueNum vn, AssertionIndex index) { ASSERT_TP* cur = optValueNumToAsserts->LookupPointer(vn); if (cur == nullptr) { optValueNumToAsserts->Set(vn, BitVecOps::MakeSingleton(apTraits, index - 1)); } else { BitVecOps::AddElemD(apTraits, *cur, index - 1); } } /***************************************************************************** * Statically if we know that this assertion's VN involves a NaN don't bother * wasting an assertion table slot. */ bool Compiler::optAssertionVnInvolvesNan(AssertionDsc* assertion) { if (optLocalAssertionProp) { return false; } static const int SZ = 2; ValueNum vns[SZ] = {assertion->op1.vn, assertion->op2.vn}; for (int i = 0; i < SZ; ++i) { if (vnStore->IsVNConstant(vns[i])) { var_types type = vnStore->TypeOfVN(vns[i]); if ((type == TYP_FLOAT && _isnan(vnStore->ConstantValue<float>(vns[i])) != 0) || (type == TYP_DOUBLE && _isnan(vnStore->ConstantValue<double>(vns[i])) != 0)) { return true; } } } return false; } /***************************************************************************** * * Given an assertion add it to the assertion table * * If it is already in the assertion table return the assertionIndex that * we use to refer to this element. * Otherwise add it to the assertion table ad return the assertionIndex that * we use to refer to this element. * If we need to add to the table and the table is full return the value zero */ AssertionIndex Compiler::optAddAssertion(AssertionDsc* newAssertion) { noway_assert(newAssertion->assertionKind != OAK_INVALID); // Even though the propagation step takes care of NaN, just a check // to make sure there is no slot involving a NaN. if (optAssertionVnInvolvesNan(newAssertion)) { JITDUMP("Assertion involved Nan not adding\n"); return NO_ASSERTION_INDEX; } // Check if exists already, so we can skip adding new one. Search backwards. for (AssertionIndex index = optAssertionCount; index >= 1; index--) { AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->Equals(newAssertion, !optLocalAssertionProp)) { return index; } } // Check if we are within max count. if (optAssertionCount >= optMaxAssertionCount) { return NO_ASSERTION_INDEX; } optAssertionTabPrivate[optAssertionCount] = *newAssertion; optAssertionCount++; #ifdef DEBUG if (verbose) { printf("GenTreeNode creates assertion:\n"); gtDispTree(optAssertionPropCurrentTree, nullptr, nullptr, true); printf(optLocalAssertionProp ? "In " FMT_BB " New Local " : "In " FMT_BB " New Global ", compCurBB->bbNum); optPrintAssertion(newAssertion, optAssertionCount); } #endif // DEBUG // Assertion mask bits are [index + 1]. if (optLocalAssertionProp) { assert(newAssertion->op1.kind == O1K_LCLVAR); // Mark the variables this index depends on unsigned lclNum = newAssertion->op1.lcl.lclNum; BitVecOps::AddElemD(apTraits, GetAssertionDep(lclNum), optAssertionCount - 1); if (newAssertion->op2.kind == O2K_LCLVAR_COPY) { lclNum = newAssertion->op2.lcl.lclNum; BitVecOps::AddElemD(apTraits, GetAssertionDep(lclNum), optAssertionCount - 1); } } else // If global assertion prop, then add it to the dependents map. { optAddVnAssertionMapping(newAssertion->op1.vn, optAssertionCount); if (newAssertion->op2.kind == O2K_LCLVAR_COPY) { optAddVnAssertionMapping(newAssertion->op2.vn, optAssertionCount); } } #ifdef DEBUG optDebugCheckAssertions(optAssertionCount); #endif return optAssertionCount; } #ifdef DEBUG void Compiler::optDebugCheckAssertion(AssertionDsc* assertion) { assert(assertion->assertionKind < OAK_COUNT); assert(assertion->op1.kind < O1K_COUNT); assert(assertion->op2.kind < O2K_COUNT); // It would be good to check that op1.vn and op2.vn are valid value numbers. switch (assertion->op1.kind) { case O1K_LCLVAR: case O1K_EXACT_TYPE: case O1K_SUBTYPE: assert(assertion->op1.lcl.lclNum < lvaCount); assert(optLocalAssertionProp || lvaTable[assertion->op1.lcl.lclNum].lvPerSsaData.IsValidSsaNum(assertion->op1.lcl.ssaNum)); break; case O1K_ARR_BND: // It would be good to check that bnd.vnIdx and bnd.vnLen are valid value numbers. break; case O1K_BOUND_OPER_BND: case O1K_BOUND_LOOP_BND: case O1K_CONSTANT_LOOP_BND: case O1K_VALUE_NUMBER: assert(!optLocalAssertionProp); break; default: break; } switch (assertion->op2.kind) { case O2K_IND_CNS_INT: case O2K_CONST_INT: { // The only flags that can be set are those in the GTF_ICON_HDL_MASK, or GTF_ASSERTION_PROP_LONG, which is // used to indicate a long constant. #ifdef TARGET_64BIT assert((assertion->op2.u1.iconFlags & ~(GTF_ICON_HDL_MASK | GTF_ASSERTION_PROP_LONG)) == 0); #else assert((assertion->op2.u1.iconFlags & ~GTF_ICON_HDL_MASK) == 0); #endif switch (assertion->op1.kind) { case O1K_EXACT_TYPE: case O1K_SUBTYPE: assert(assertion->op2.u1.iconFlags != GTF_EMPTY); break; case O1K_LCLVAR: assert((lvaTable[assertion->op1.lcl.lclNum].lvType != TYP_REF) || (assertion->op2.u1.iconVal == 0) || doesMethodHaveFrozenString()); break; case O1K_VALUE_NUMBER: assert((vnStore->TypeOfVN(assertion->op1.vn) != TYP_REF) || (assertion->op2.u1.iconVal == 0)); break; default: break; } } break; case O2K_CONST_LONG: { // All handles should be represented by O2K_CONST_INT, // so no handle bits should be set here. assert((assertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) == 0); } break; default: // for all other 'assertion->op2.kind' values we don't check anything break; } } /***************************************************************************** * * Verify that assertion prop related assumptions are valid. If "index" * is 0 (i.e., NO_ASSERTION_INDEX) then verify all assertions in the table. * If "index" is between 1 and optAssertionCount, then verify the assertion * desc corresponding to "index." */ void Compiler::optDebugCheckAssertions(AssertionIndex index) { AssertionIndex start = (index == NO_ASSERTION_INDEX) ? 1 : index; AssertionIndex end = (index == NO_ASSERTION_INDEX) ? optAssertionCount : index; for (AssertionIndex ind = start; ind <= end; ++ind) { AssertionDsc* assertion = optGetAssertion(ind); optDebugCheckAssertion(assertion); } } #endif //------------------------------------------------------------------------ // optCreateComplementaryAssertion: Create an assertion that is the complementary // of the specified assertion. // // Arguments: // assertionIndex - the index of the assertion // op1 - the first assertion operand // op2 - the second assertion operand // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // // Notes: // The created complementary assertion is associated with the original // assertion such that it can be found by optFindComplementary. // void Compiler::optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTree* op1, GenTree* op2, bool helperCallArgs) { if (assertionIndex == NO_ASSERTION_INDEX) { return; } AssertionDsc& candidateAssertion = *optGetAssertion(assertionIndex); if (candidateAssertion.op1.kind == O1K_BOUND_OPER_BND || candidateAssertion.op1.kind == O1K_BOUND_LOOP_BND || candidateAssertion.op1.kind == O1K_CONSTANT_LOOP_BND) { AssertionDsc dsc = candidateAssertion; dsc.assertionKind = dsc.assertionKind == OAK_EQUAL ? OAK_NOT_EQUAL : OAK_EQUAL; optAddAssertion(&dsc); return; } if (candidateAssertion.assertionKind == OAK_EQUAL) { AssertionIndex index = optCreateAssertion(op1, op2, OAK_NOT_EQUAL, helperCallArgs); optMapComplementary(index, assertionIndex); } else if (candidateAssertion.assertionKind == OAK_NOT_EQUAL) { AssertionIndex index = optCreateAssertion(op1, op2, OAK_EQUAL, helperCallArgs); optMapComplementary(index, assertionIndex); } // Are we making a subtype or exact type assertion? if ((candidateAssertion.op1.kind == O1K_SUBTYPE) || (candidateAssertion.op1.kind == O1K_EXACT_TYPE)) { optCreateAssertion(op1, nullptr, OAK_NOT_EQUAL); } } //------------------------------------------------------------------------ // optCreateJtrueAssertions: Create assertions about a JTRUE's relop operands. // // Arguments: // op1 - the first assertion operand // op2 - the second assertion operand // assertionKind - the assertion kind // helperCallArgs - when true this indicates that the assertion operands // are the arguments of a type cast helper call such as // CORINFO_HELP_ISINSTANCEOFCLASS // Return Value: // The new assertion index or NO_ASSERTION_INDEX if a new assertion // was not created. // // Notes: // Assertion creation may fail either because the provided assertion // operands aren't supported or because the assertion table is full. // If an assertion is created succesfully then an attempt is made to also // create a second, complementary assertion. This may too fail, for the // same reasons as the first one. // AssertionIndex Compiler::optCreateJtrueAssertions(GenTree* op1, GenTree* op2, Compiler::optAssertionKind assertionKind, bool helperCallArgs) { AssertionIndex assertionIndex = optCreateAssertion(op1, op2, assertionKind, helperCallArgs); // Don't bother if we don't have an assertion on the JTrue False path. Current implementation // allows for a complementary only if there is an assertion on the False path (tree->HasAssertion()). if (assertionIndex != NO_ASSERTION_INDEX) { optCreateComplementaryAssertion(assertionIndex, op1, op2, helperCallArgs); } return assertionIndex; } AssertionInfo Compiler::optCreateJTrueBoundsAssertion(GenTree* tree) { GenTree* relop = tree->gtGetOp1(); if ((relop->OperKind() & GTK_RELOP) == 0) { return NO_ASSERTION_INDEX; } GenTree* op1 = relop->gtGetOp1(); GenTree* op2 = relop->gtGetOp2(); ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); ValueNum relopVN = vnStore->VNConservativeNormalValue(relop->gtVNPair); bool hasTestAgainstZero = (relop->gtOper == GT_EQ || relop->gtOper == GT_NE) && (op2VN == vnStore->VNZeroForType(op2->TypeGet())); ValueNumStore::UnsignedCompareCheckedBoundInfo unsignedCompareBnd; // Cases where op1 holds the upper bound arithmetic and op2 is 0. // Loop condition like: "i < bnd +/-k == 0" // Assertion: "i < bnd +/- k == 0" if (hasTestAgainstZero && vnStore->IsVNCompareCheckedBoundArith(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_OPER_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition and op2 holds the bound arithmetic. // Loop condition like: "i < bnd +/-k" // Assertion: "i < bnd +/- k != 0" else if (vnStore->IsVNCompareCheckedBoundArith(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_OPER_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the upper bound and op2 is 0. // Loop condition like: "i < bnd == 0" // Assertion: "i < bnd == false" else if (hasTestAgainstZero && vnStore->IsVNCompareCheckedBound(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_LOOP_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition op2 holds the bound. // Loop condition like "i < bnd" // Assertion: "i < bnd != 0" else if (vnStore->IsVNCompareCheckedBound(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_BOUND_LOOP_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Loop condition like "(uint)i < (uint)bnd" or equivalent // Assertion: "no throw" since this condition guarantees that i is both >= 0 and < bnd (on the appropiate edge) else if (vnStore->IsVNUnsignedCompareCheckedBound(relopVN, &unsignedCompareBnd)) { assert(unsignedCompareBnd.vnIdx != ValueNumStore::NoVN); assert((unsignedCompareBnd.cmpOper == VNF_LT_UN) || (unsignedCompareBnd.cmpOper == VNF_GE_UN)); assert(vnStore->IsVNCheckedBound(unsignedCompareBnd.vnBound)); AssertionDsc dsc; dsc.assertionKind = OAK_NO_THROW; dsc.op1.kind = O1K_ARR_BND; dsc.op1.vn = relopVN; dsc.op1.bnd.vnIdx = unsignedCompareBnd.vnIdx; dsc.op1.bnd.vnLen = vnStore->VNNormalValue(unsignedCompareBnd.vnBound); dsc.op2.kind = O2K_INVALID; dsc.op2.vn = ValueNumStore::NoVN; AssertionIndex index = optAddAssertion(&dsc); if (unsignedCompareBnd.cmpOper == VNF_GE_UN) { // By default JTRUE generated assertions hold on the "jump" edge. We have i >= bnd but we're really // after i < bnd so we need to change the assertion edge to "next". return AssertionInfo::ForNextEdge(index); } return index; } // Cases where op1 holds the condition bound check and op2 is 0. // Loop condition like: "i < 100 == 0" // Assertion: "i < 100 == false" else if (hasTestAgainstZero && vnStore->IsVNConstantBound(op1VN)) { AssertionDsc dsc; dsc.assertionKind = relop->gtOper == GT_EQ ? OAK_EQUAL : OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND; dsc.op1.vn = op1VN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(op2->TypeGet()); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } // Cases where op1 holds the lhs of the condition op2 holds rhs. // Loop condition like "i < 100" // Assertion: "i < 100 != 0" else if (vnStore->IsVNConstantBound(relopVN)) { AssertionDsc dsc; dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.kind = O1K_CONSTANT_LOOP_BND; dsc.op1.vn = relopVN; dsc.op2.kind = O2K_CONST_INT; dsc.op2.vn = vnStore->VNZeroForType(TYP_INT); dsc.op2.u1.iconVal = 0; dsc.op2.u1.iconFlags = GTF_EMPTY; AssertionIndex index = optAddAssertion(&dsc); optCreateComplementaryAssertion(index, nullptr, nullptr); return index; } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Compute assertions for the JTrue node. */ AssertionInfo Compiler::optAssertionGenJtrue(GenTree* tree) { // Only create assertions for JTRUE when we are in the global phase if (optLocalAssertionProp) { return NO_ASSERTION_INDEX; } GenTree* relop = tree->AsOp()->gtOp1; if ((relop->OperKind() & GTK_RELOP) == 0) { return NO_ASSERTION_INDEX; } Compiler::optAssertionKind assertionKind = OAK_INVALID; AssertionInfo info = optCreateJTrueBoundsAssertion(tree); if (info.HasAssertion()) { return info; } // Find assertion kind. switch (relop->gtOper) { case GT_EQ: assertionKind = OAK_EQUAL; break; case GT_NE: assertionKind = OAK_NOT_EQUAL; break; default: // TODO-CQ: add other relop operands. Disabled for now to measure perf // and not occupy assertion table slots. We'll add them when used. return NO_ASSERTION_INDEX; } // Look through any CSEs so we see the actual trees providing values, if possible. // This is important for exact type assertions, which need to see the GT_IND. // GenTree* op1 = relop->AsOp()->gtOp1->gtCommaAssignVal(); GenTree* op2 = relop->AsOp()->gtOp2->gtCommaAssignVal(); // Check for op1 or op2 to be lcl var and if so, keep it in op1. if ((op1->gtOper != GT_LCL_VAR) && (op2->gtOper == GT_LCL_VAR)) { std::swap(op1, op2); } ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); // If op1 is lcl and op2 is const or lcl, create assertion. if ((op1->gtOper == GT_LCL_VAR) && ((op2->OperKind() & GTK_CONST) || (op2->gtOper == GT_LCL_VAR))) // Fix for Dev10 851483 { return optCreateJtrueAssertions(op1, op2, assertionKind); } else if (vnStore->IsVNCheckedBound(op1VN) && vnStore->IsVNInt32Constant(op2VN)) { assert(relop->OperIs(GT_EQ, GT_NE)); int con = vnStore->ConstantValue<int>(op2VN); if (con >= 0) { AssertionDsc dsc; // For arr.Length != 0, we know that 0 is a valid index // For arr.Length == con, we know that con - 1 is the greatest valid index if (con == 0) { dsc.assertionKind = OAK_NOT_EQUAL; dsc.op1.bnd.vnIdx = vnStore->VNForIntCon(0); } else { dsc.assertionKind = OAK_EQUAL; dsc.op1.bnd.vnIdx = vnStore->VNForIntCon(con - 1); } dsc.op1.vn = op1VN; dsc.op1.kind = O1K_ARR_BND; dsc.op1.bnd.vnLen = op1VN; dsc.op2.vn = vnStore->VNConservativeNormalValue(op2->gtVNPair); dsc.op2.kind = O2K_CONST_INT; dsc.op2.u1.iconFlags = GTF_EMPTY; dsc.op2.u1.iconVal = 0; // when con is not zero, create an assertion on the arr.Length == con edge // when con is zero, create an assertion on the arr.Length != 0 edge AssertionIndex index = optAddAssertion(&dsc); if (relop->OperIs(GT_NE) != (con == 0)) { return AssertionInfo::ForNextEdge(index); } else { return index; } } } // Check op1 and op2 for an indirection of a GT_LCL_VAR and keep it in op1. if (((op1->gtOper != GT_IND) || (op1->AsOp()->gtOp1->gtOper != GT_LCL_VAR)) && ((op2->gtOper == GT_IND) && (op2->AsOp()->gtOp1->gtOper == GT_LCL_VAR))) { std::swap(op1, op2); } // If op1 is ind, then extract op1's oper. if ((op1->gtOper == GT_IND) && (op1->AsOp()->gtOp1->gtOper == GT_LCL_VAR)) { return optCreateJtrueAssertions(op1, op2, assertionKind); } // Look for a call to an IsInstanceOf helper compared to a nullptr if ((op2->gtOper != GT_CNS_INT) && (op1->gtOper == GT_CNS_INT)) { std::swap(op1, op2); } // Validate op1 and op2 if ((op1->gtOper != GT_CALL) || (op1->AsCall()->gtCallType != CT_HELPER) || (op1->TypeGet() != TYP_REF) || // op1 (op2->gtOper != GT_CNS_INT) || (op2->AsIntCon()->gtIconVal != 0)) // op2 { return NO_ASSERTION_INDEX; } GenTreeCall* call = op1->AsCall(); // Note CORINFO_HELP_READYTORUN_ISINSTANCEOF does not have the same argument pattern. // In particular, it is not possible to deduce what class is being tested from its args. // // Also note The CASTCLASS helpers won't appear in predicates as they throw on failure. // So the helper list here is smaller than the one in optAssertionProp_Call. if ((call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFINTERFACE)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFARRAY)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFCLASS)) || (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFANY))) { fgArgInfo* const argInfo = call->fgArgInfo; GenTree* objectNode = argInfo->GetArgNode(1); GenTree* methodTableNode = argInfo->GetArgNode(0); assert(objectNode->TypeGet() == TYP_REF); assert(methodTableNode->TypeGet() == TYP_I_IMPL); // Reverse the assertion assert((assertionKind == OAK_EQUAL) || (assertionKind == OAK_NOT_EQUAL)); assertionKind = (assertionKind == OAK_EQUAL) ? OAK_NOT_EQUAL : OAK_EQUAL; if (objectNode->OperIs(GT_LCL_VAR)) { return optCreateJtrueAssertions(objectNode, methodTableNode, assertionKind, /* helperCallArgs */ true); } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Create an assertion on the phi node if some information can be gleaned * from all of the constituent phi operands. * */ AssertionIndex Compiler::optAssertionGenPhiDefn(GenTree* tree) { if (!tree->IsPhiDefn()) { return NO_ASSERTION_INDEX; } // Try to find if all phi arguments are known to be non-null. bool isNonNull = true; for (GenTreePhi::Use& use : tree->AsOp()->gtGetOp2()->AsPhi()->Uses()) { if (!vnStore->IsKnownNonNull(use.GetNode()->gtVNPair.GetConservative())) { isNonNull = false; break; } } // All phi arguments are non-null implies phi rhs is non-null. if (isNonNull) { return optCreateAssertion(tree->AsOp()->gtOp1, nullptr, OAK_NOT_EQUAL); } return NO_ASSERTION_INDEX; } /***************************************************************************** * * If this statement creates a value assignment or assertion * then assign an index to the given value assignment by adding * it to the lookup table, if necessary. */ void Compiler::optAssertionGen(GenTree* tree) { tree->ClearAssertion(); // If there are QMARKs in the IR, we won't generate assertions // for conditionally executed code. // if (optLocalAssertionProp && ((tree->gtFlags & GTF_COLON_COND) != 0)) { return; } #ifdef DEBUG optAssertionPropCurrentTree = tree; #endif // For most of the assertions that we create below // the assertion is true after the tree is processed bool assertionProven = true; AssertionInfo assertionInfo; switch (tree->gtOper) { case GT_ASG: // VN takes care of non local assertions for assignments and data flow. if (optLocalAssertionProp) { assertionInfo = optCreateAssertion(tree->AsOp()->gtOp1, tree->AsOp()->gtOp2, OAK_EQUAL); } else { assertionInfo = optAssertionGenPhiDefn(tree); } break; case GT_OBJ: case GT_BLK: case GT_DYN_BLK: case GT_IND: case GT_NULLCHECK: // All indirections create non-null assertions assertionInfo = optCreateAssertion(tree->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); break; case GT_ARR_LENGTH: // An array length is an indirection (but doesn't derive from GenTreeIndir). assertionInfo = optCreateAssertion(tree->AsArrLen()->ArrRef(), nullptr, OAK_NOT_EQUAL); break; case GT_ARR_BOUNDS_CHECK: if (!optLocalAssertionProp) { assertionInfo = optCreateAssertion(tree, nullptr, OAK_NO_THROW); } break; case GT_ARR_ELEM: // An array element reference can create a non-null assertion assertionInfo = optCreateAssertion(tree->AsArrElem()->gtArrObj, nullptr, OAK_NOT_EQUAL); break; case GT_CALL: { // A virtual call can create a non-null assertion. We transform some virtual calls into non-virtual calls // with a GTF_CALL_NULLCHECK flag set. // Ignore tail calls because they have 'this` pointer in the regular arg list and an implicit null check. GenTreeCall* const call = tree->AsCall(); if (call->NeedsNullCheck() || (call->IsVirtual() && !call->IsTailCall())) { // Retrieve the 'this' arg. GenTree* thisArg = gtGetThisArg(call); assert(thisArg != nullptr); assertionInfo = optCreateAssertion(thisArg, nullptr, OAK_NOT_EQUAL); } } break; case GT_CAST: // We only create this assertion for global assertion prop if (!optLocalAssertionProp) { // This represets an assertion that we would like to prove to be true. It is not actually a true // assertion. // If we can prove this assertion true then we can eliminate this cast. assertionInfo = optCreateAssertion(tree->AsOp()->gtOp1, tree, OAK_SUBRANGE); assertionProven = false; } break; case GT_JTRUE: assertionInfo = optAssertionGenJtrue(tree); break; default: // All other gtOper node kinds, leave 'assertionIndex' = NO_ASSERTION_INDEX break; } // For global assertion prop we must store the assertion number in the tree node if (assertionInfo.HasAssertion() && assertionProven && !optLocalAssertionProp) { tree->SetAssertionInfo(assertionInfo); } } /***************************************************************************** * * Maps a complementary assertion to its original assertion so it can be * retrieved faster. */ void Compiler::optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index) { if (assertionIndex == NO_ASSERTION_INDEX || index == NO_ASSERTION_INDEX) { return; } assert(assertionIndex <= optMaxAssertionCount); assert(index <= optMaxAssertionCount); optComplementaryAssertionMap[assertionIndex] = index; optComplementaryAssertionMap[index] = assertionIndex; } /***************************************************************************** * * Given an assertion index, return the assertion index of the complementary * assertion or 0 if one does not exist. */ AssertionIndex Compiler::optFindComplementary(AssertionIndex assertIndex) { if (assertIndex == NO_ASSERTION_INDEX) { return NO_ASSERTION_INDEX; } AssertionDsc* inputAssertion = optGetAssertion(assertIndex); // Must be an equal or not equal assertion. if (inputAssertion->assertionKind != OAK_EQUAL && inputAssertion->assertionKind != OAK_NOT_EQUAL) { return NO_ASSERTION_INDEX; } AssertionIndex index = optComplementaryAssertionMap[assertIndex]; if (index != NO_ASSERTION_INDEX && index <= optAssertionCount) { return index; } for (AssertionIndex index = 1; index <= optAssertionCount; ++index) { // Make sure assertion kinds are complementary and op1, op2 kinds match. AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->Complementary(inputAssertion, !optLocalAssertionProp)) { optMapComplementary(assertIndex, index); return index; } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a lclNum, a fromType and a toType, return assertion index of the assertion that * claims that a variable's value is always a valid subrange of the formType. * Thus we can discard or omit a cast to fromType. Returns NO_ASSERTION_INDEX * if one such assertion could not be found in "assertions." */ AssertionIndex Compiler::optAssertionIsSubrange(GenTree* tree, var_types fromType, var_types toType, ASSERT_VALARG_TP assertions) { if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; index++) { AssertionDsc* curAssertion = optGetAssertion(index); if ((optLocalAssertionProp || BitVecOps::IsMember(apTraits, assertions, index - 1)) && // either local prop or use propagated assertions (curAssertion->assertionKind == OAK_SUBRANGE) && (curAssertion->op1.kind == O1K_LCLVAR)) { // For local assertion prop use comparison on locals, and use comparison on vns for global prop. bool isEqual = optLocalAssertionProp ? (curAssertion->op1.lcl.lclNum == tree->AsLclVarCommon()->GetLclNum()) : (curAssertion->op1.vn == vnStore->VNConservativeNormalValue(tree->gtVNPair)); if (!isEqual) { continue; } // If we have an unsigned fromType, then the loBound can't be negative // if (varTypeIsUnsigned(fromType)) { if (curAssertion->op2.u2.loBound < 0) { continue; } } // Make sure the toType is within current assertion's bounds. switch (toType) { case TYP_BYTE: case TYP_UBYTE: case TYP_SHORT: case TYP_USHORT: if ((curAssertion->op2.u2.loBound < AssertionDsc::GetLowerBoundForIntegralType(toType)) || (curAssertion->op2.u2.hiBound > AssertionDsc::GetUpperBoundForIntegralType(toType))) { continue; } break; case TYP_UINT: if (curAssertion->op2.u2.loBound < AssertionDsc::GetLowerBoundForIntegralType(toType)) { continue; } break; case TYP_INT: break; default: continue; } return index; } } return NO_ASSERTION_INDEX; } /********************************************************************************** * * Given a "tree" that is usually arg1 of a isinst/cast kind of GT_CALL (a class * handle), and "methodTableArg" which is a const int (a class handle), then search * if there is an assertion in "assertions", that asserts the equality of the two * class handles and then returns the index of the assertion. If one such assertion * could not be found, then it returns NO_ASSERTION_INDEX. * */ AssertionIndex Compiler::optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions) { if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; index++) { if (!optLocalAssertionProp && !BitVecOps::IsMember(apTraits, assertions, index - 1)) { continue; } AssertionDsc* curAssertion = optGetAssertion(index); if (curAssertion->assertionKind != OAK_EQUAL || (curAssertion->op1.kind != O1K_SUBTYPE && curAssertion->op1.kind != O1K_EXACT_TYPE)) { continue; } // If local assertion prop use "lcl" based comparison, if global assertion prop use vn based comparison. if ((optLocalAssertionProp) ? (curAssertion->op1.lcl.lclNum != tree->AsLclVarCommon()->GetLclNum()) : (curAssertion->op1.vn != vnStore->VNConservativeNormalValue(tree->gtVNPair))) { continue; } if (curAssertion->op2.kind == O2K_IND_CNS_INT) { if (methodTableArg->gtOper != GT_IND) { continue; } methodTableArg = methodTableArg->AsOp()->gtOp1; } else if (curAssertion->op2.kind != O2K_CONST_INT) { continue; } ssize_t methodTableVal = 0; GenTreeFlags iconFlags = GTF_EMPTY; if (!optIsTreeKnownIntValue(!optLocalAssertionProp, methodTableArg, &methodTableVal, &iconFlags)) { continue; } if (curAssertion->op2.u1.iconVal == methodTableVal) { return index; } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------------ // optVNConstantPropOnTree: Substitutes tree with an evaluated constant while // managing side-effects. // // Arguments: // block - The block containing the tree. // stmt - The statement in the block containing the tree. // tree - The tree node whose value is known at compile time. // The tree should have a constant value number. // // Return Value: // Returns a potentially new or a transformed tree node. // Returns nullptr when no transformation is possible. // // Description: // Transforms a tree node if its result evaluates to a constant. The // transformation can be a "ChangeOper" to a constant or a new constant node // with extracted side-effects. // // Before replacing or substituting the "tree" with a constant, extracts any // side effects from the "tree" and creates a comma separated side effect list // and then appends the transformed node at the end of the list. // This comma separated list is then returned. // // For JTrue nodes, side effects are not put into a comma separated list. If // the relop will evaluate to "true" or "false" statically, then the side-effects // will be put into new statements, presuming the JTrue will be folded away. // GenTree* Compiler::optVNConstantPropOnTree(BasicBlock* block, GenTree* tree) { if (tree->OperGet() == GT_JTRUE) { // Treat JTRUE separately to extract side effects into respective statements rather // than using a COMMA separated op1. return optVNConstantPropOnJTrue(block, tree); } // If relop is part of JTRUE, this should be optimized as part of the parent JTRUE. // Or if relop is part of QMARK or anything else, we simply bail here. else if (tree->OperIsCompare() && (tree->gtFlags & GTF_RELOP_JMP_USED)) { return nullptr; } // We want to use the Normal ValueNumber when checking for constants. ValueNumPair vnPair = tree->gtVNPair; ValueNum vnCns = vnStore->VNConservativeNormalValue(vnPair); // Check if node evaluates to a constant. if (!vnStore->IsVNConstant(vnCns)) { return nullptr; } GenTree* conValTree = nullptr; switch (vnStore->TypeOfVN(vnCns)) { case TYP_FLOAT: { float value = vnStore->ConstantValue<float>(vnCns); if (tree->TypeGet() == TYP_INT) { // Same sized reinterpretation of bits to integer conValTree = gtNewIconNode(*(reinterpret_cast<int*>(&value))); } else { // Implicit assignment conversion to float or double assert(varTypeIsFloating(tree->TypeGet())); conValTree = gtNewDconNode(value, tree->TypeGet()); } break; } case TYP_DOUBLE: { double value = vnStore->ConstantValue<double>(vnCns); if (tree->TypeGet() == TYP_LONG) { conValTree = gtNewLconNode(*(reinterpret_cast<INT64*>(&value))); } else { // Implicit assignment conversion to float or double assert(varTypeIsFloating(tree->TypeGet())); conValTree = gtNewDconNode(value, tree->TypeGet()); } break; } case TYP_LONG: { INT64 value = vnStore->ConstantValue<INT64>(vnCns); #ifdef TARGET_64BIT if (vnStore->IsVNHandle(vnCns)) { // Don't perform constant folding that involves a handle that needs // to be recorded as a relocation with the VM. if (!opts.compReloc) { conValTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns)); } } else #endif { switch (tree->TypeGet()) { case TYP_INT: // Implicit assignment conversion to smaller integer conValTree = gtNewIconNode(static_cast<int>(value)); break; case TYP_LONG: // Same type no conversion required conValTree = gtNewLconNode(value); break; case TYP_FLOAT: // No implicit conversions from long to float and value numbering will // not propagate through memory reinterpretations of different size. unreached(); break; case TYP_DOUBLE: // Same sized reinterpretation of bits to double conValTree = gtNewDconNode(*(reinterpret_cast<double*>(&value))); break; default: // Do not support such optimization. break; } } } break; case TYP_REF: { assert(vnStore->ConstantValue<size_t>(vnCns) == 0); // Support onle ref(ref(0)), do not support other forms (e.g byref(ref(0)). if (tree->TypeGet() == TYP_REF) { conValTree = gtNewIconNode(0, TYP_REF); } } break; case TYP_INT: { int value = vnStore->ConstantValue<int>(vnCns); #ifndef TARGET_64BIT if (vnStore->IsVNHandle(vnCns)) { // Don't perform constant folding that involves a handle that needs // to be recorded as a relocation with the VM. if (!opts.compReloc) { conValTree = gtNewIconHandleNode(value, vnStore->GetHandleFlags(vnCns)); } } else #endif { switch (tree->TypeGet()) { case TYP_REF: case TYP_INT: // Same type no conversion required conValTree = gtNewIconNode(static_cast<int>(value)); break; case TYP_LONG: // Implicit assignment conversion to larger integer conValTree = gtNewLconNode(static_cast<int>(value)); break; case TYP_FLOAT: // Same sized reinterpretation of bits to float conValTree = gtNewDconNode(*(reinterpret_cast<float*>(&value)), TYP_FLOAT); break; case TYP_DOUBLE: // No implicit conversions from int to double and value numbering will // not propagate through memory reinterpretations of different size. unreached(); break; default: // Do not support (e.g. bool(const int)). break; } } } break; case TYP_BYREF: // Do not support const byref optimization. break; default: // We do not record constants of other types. unreached(); break; } if (conValTree != nullptr) { // Were able to optimize. conValTree->gtVNPair = vnPair; GenTree* sideEffList = optExtractSideEffListFromConst(tree); if (sideEffList != nullptr) { // Replace as COMMA(side_effects, const value tree); assert((sideEffList->gtFlags & GTF_SIDE_EFFECT) != 0); return gtNewOperNode(GT_COMMA, conValTree->TypeGet(), sideEffList, conValTree); } else { // No side effects, replace as const value tree. return conValTree; } } else { // Was not able to optimize. return nullptr; } } //------------------------------------------------------------------------------ // optConstantAssertionProp: Possibly substitute a constant for a local use // // Arguments: // curAssertion - assertion to propagate // tree - tree to possibly modify // stmt - statement containing the tree // index - index of this assertion in the assertion table // // Returns: // Updated tree (may be the input tree, modified in place), or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optConstantAssertionProp(AssertionDsc* curAssertion, GenTreeLclVarCommon* tree, Statement* stmt DEBUGARG(AssertionIndex index)) { const unsigned lclNum = tree->GetLclNum(); if (lclNumIsCSE(lclNum)) { return nullptr; } GenTree* newTree = tree; // Update 'newTree' with the new value from our table // Typically newTree == tree and we are updating the node in place switch (curAssertion->op2.kind) { case O2K_CONST_DOUBLE: // There could be a positive zero and a negative zero, so don't propagate zeroes. if (curAssertion->op2.dconVal == 0.0) { return nullptr; } newTree->ChangeOperConst(GT_CNS_DBL); newTree->AsDblCon()->gtDconVal = curAssertion->op2.dconVal; break; case O2K_CONST_LONG: if (newTree->gtType == TYP_LONG) { newTree->ChangeOperConst(GT_CNS_NATIVELONG); newTree->AsIntConCommon()->SetLngValue(curAssertion->op2.lconVal); } else { newTree->ChangeOperConst(GT_CNS_INT); newTree->AsIntCon()->gtIconVal = (int)curAssertion->op2.lconVal; newTree->gtType = TYP_INT; } break; case O2K_CONST_INT: // Don't propagate handles if we need to report relocs. if (opts.compReloc && ((curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) != 0)) { return nullptr; } if (curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK) { // Here we have to allocate a new 'large' node to replace the old one newTree = gtNewIconHandleNode(curAssertion->op2.u1.iconVal, curAssertion->op2.u1.iconFlags & GTF_ICON_HDL_MASK); } else { bool isArrIndex = ((tree->gtFlags & GTF_VAR_ARR_INDEX) != 0); // If we have done constant propagation of a struct type, it is only valid for zero-init, // and we have to ensure that we have the right zero for the type. if (varTypeIsStruct(tree)) { assert(curAssertion->op2.u1.iconVal == 0); } #ifdef FEATURE_SIMD if (varTypeIsSIMD(tree)) { LclVarDsc* varDsc = lvaGetDesc(lclNum); var_types simdType = tree->TypeGet(); assert(varDsc->TypeGet() == simdType); CorInfoType simdBaseJitType = varDsc->GetSimdBaseJitType(); newTree = gtGetSIMDZero(simdType, simdBaseJitType, varDsc->GetStructHnd()); if (newTree == nullptr) { return nullptr; } } else #endif // FEATURE_SIMD { newTree->ChangeOperConst(GT_CNS_INT); newTree->AsIntCon()->gtIconVal = curAssertion->op2.u1.iconVal; newTree->ClearIconHandleMask(); if (newTree->TypeIs(TYP_STRUCT)) { // LCL_VAR can be init with a GT_CNS_INT, keep its type INT, not STRUCT. newTree->ChangeType(TYP_INT); } } // If we're doing an array index address, assume any constant propagated contributes to the index. if (isArrIndex) { newTree->AsIntCon()->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::ConstantIndexPseudoField); } newTree->gtFlags &= ~GTF_VAR_ARR_INDEX; } // Constant ints are of type TYP_INT, not any of the short forms. if (varTypeIsIntegral(newTree->TypeGet())) { #ifdef TARGET_64BIT var_types newType = (var_types)((curAssertion->op2.u1.iconFlags & GTF_ASSERTION_PROP_LONG) ? TYP_LONG : TYP_INT); if (newTree->TypeGet() != newType) { noway_assert(newTree->gtType != TYP_REF); newTree->gtType = newType; } #else if (newTree->TypeGet() != TYP_INT) { noway_assert(newTree->gtType != TYP_REF && newTree->gtType != TYP_LONG); newTree->gtType = TYP_INT; } #endif } break; default: return nullptr; } if (!optLocalAssertionProp) { assert(newTree->OperIsConst()); // We should have a simple Constant node for newTree assert(vnStore->IsVNConstant(curAssertion->op2.vn)); // The value number stored for op2 should be a valid // VN representing the constant newTree->gtVNPair.SetBoth(curAssertion->op2.vn); // Set the ValueNumPair to the constant VN from op2 // of the assertion } #ifdef DEBUG if (verbose) { printf("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); optPrintAssertion(curAssertion, index); gtDispTree(newTree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(newTree, tree, stmt); } //------------------------------------------------------------------------------ // optAssertionProp_LclVarTypeCheck: verify compatible types for copy prop // // Arguments: // tree - tree to possibly modify // lclVarDsc - local accessed by tree // copyVarDsc - local to possibly copy prop into tree // // Returns: // True if copy prop is safe. // // Notes: // Before substituting copyVar for lclVar, make sure using copyVar doesn't widen access. // bool Compiler::optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc) { /* Small struct field locals are stored using the exact width and loaded widened (i.e. lvNormalizeOnStore==false lvNormalizeOnLoad==true), because the field locals might end up embedded in the parent struct local with the exact width. In other words, a store to a short field local should always done using an exact width store [00254538] 0x0009 ------------ const int 0x1234 [002545B8] 0x000B -A--G--NR--- = short [00254570] 0x000A D------N---- lclVar short V43 tmp40 mov word ptr [L_043], 0x1234 Now, if we copy prop, say a short field local V43, to another short local V34 for the following tree: [04E18650] 0x0001 ------------ lclVar int V34 tmp31 [04E19714] 0x0002 -A---------- = int [04E196DC] 0x0001 D------N---- lclVar int V36 tmp33 We will end with this tree: [04E18650] 0x0001 ------------ lclVar int V43 tmp40 [04E19714] 0x0002 -A-----NR--- = int [04E196DC] 0x0001 D------N---- lclVar int V36 tmp33 EAX And eventually causing a fetch of 4-byte out from [L_043] :( mov EAX, dword ptr [L_043] The following check is to make sure we only perform the copy prop when we don't retrieve the wider value. */ if (copyVarDsc->lvIsStructField) { var_types varType = (var_types)copyVarDsc->lvType; // Make sure we don't retrieve the wider value. return !varTypeIsSmall(varType) || (varType == tree->TypeGet()); } // Called in the context of a single copy assertion, so the types should have been // taken care by the assertion gen logic for other cases. Just return true. return true; } //------------------------------------------------------------------------ // optCopyAssertionProp: copy prop use of one local with another // // Arguments: // curAssertion - assertion triggering the possible copy // tree - tree use to consider replacing // stmt - statment containing the tree // index - index of the assertion // // Returns: // Updated tree, or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optCopyAssertionProp(AssertionDsc* curAssertion, GenTreeLclVarCommon* tree, Statement* stmt DEBUGARG(AssertionIndex index)) { const AssertionDsc::AssertionDscOp1& op1 = curAssertion->op1; const AssertionDsc::AssertionDscOp2& op2 = curAssertion->op2; noway_assert(op1.lcl.lclNum != op2.lcl.lclNum); const unsigned lclNum = tree->GetLclNum(); // Make sure one of the lclNum of the assertion matches with that of the tree. if (op1.lcl.lclNum != lclNum && op2.lcl.lclNum != lclNum) { return nullptr; } // Extract the matching lclNum and ssaNum. const unsigned copyLclNum = (op1.lcl.lclNum == lclNum) ? op2.lcl.lclNum : op1.lcl.lclNum; unsigned copySsaNum = BAD_VAR_NUM; if (!optLocalAssertionProp) { // Extract the ssaNum of the matching lclNum. unsigned ssaNum = (op1.lcl.lclNum == lclNum) ? op1.lcl.ssaNum : op2.lcl.ssaNum; copySsaNum = (op1.lcl.lclNum == lclNum) ? op2.lcl.ssaNum : op1.lcl.ssaNum; if (ssaNum != tree->GetSsaNum()) { return nullptr; } } LclVarDsc* const copyVarDsc = lvaGetDesc(copyLclNum); LclVarDsc* const lclVarDsc = lvaGetDesc(lclNum); // Make sure the types are compatible. if (!optAssertionProp_LclVarTypeCheck(tree, lclVarDsc, copyVarDsc)) { return nullptr; } // Make sure we can perform this copy prop. if (optCopyProp_LclVarScore(lclVarDsc, copyVarDsc, curAssertion->op1.lcl.lclNum == lclNum) <= 0) { return nullptr; } tree->SetSsaNum(copySsaNum); tree->SetLclNum(copyLclNum); #ifdef DEBUG if (verbose) { printf("\nAssertion prop in " FMT_BB ":\n", compCurBB->bbNum); optPrintAssertion(curAssertion, index); gtDispTree(tree, nullptr, nullptr, true); } #endif // Update and morph the tree. return optAssertionProp_Update(tree, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp_LclVar: try and optimize a local var use via assertions // // Arguments: // assertions - set of live assertions // tree - local use to optimize // stmt - statement containing the tree // // Returns: // Updated tree, or nullptr // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTreeLclVarCommon* tree, Statement* stmt) { // If we have a var definition then bail or // If this is the address of the var then it will have the GTF_DONT_CSE // flag set and we don't want to to assertion prop on it. if (tree->gtFlags & (GTF_VAR_DEF | GTF_DONT_CSE)) { return nullptr; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } // See if the variable is equal to a constant or another variable. AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (curAssertion->assertionKind != OAK_EQUAL || curAssertion->op1.kind != O1K_LCLVAR) { continue; } // Copy prop. if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { // Cannot do copy prop during global assertion prop because of no knowledge // of kill sets. We will still make a == b copy assertions during the global phase to allow // for any implied assertions that can be retrieved. Because implied assertions look for // matching SSA numbers (i.e., if a0 == b1 and b1 == c0 then a0 == c0) they don't need kill sets. if (optLocalAssertionProp) { // Perform copy assertion prop. GenTree* newTree = optCopyAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); if (newTree != nullptr) { return newTree; } } continue; } // Constant prop. // // The case where the tree type could be different than the LclVar type is caused by // gtFoldExpr, specifically the case of a cast, where the fold operation changes the type of the LclVar // node. In such a case is not safe to perform the substitution since later on the JIT will assert mismatching // types between trees. const unsigned lclNum = tree->GetLclNum(); if (curAssertion->op1.lcl.lclNum == lclNum) { LclVarDsc* const lclDsc = lvaGetDesc(lclNum); // Verify types match if (tree->TypeGet() == lclDsc->lvType) { // If local assertion prop, just perform constant prop. if (optLocalAssertionProp) { return optConstantAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); } // If global assertion, perform constant propagation only if the VN's match. if (curAssertion->op1.vn == vnStore->VNConservativeNormalValue(tree->gtVNPair)) { return optConstantAssertionProp(curAssertion, tree, stmt DEBUGARG(assertionIndex)); } } } } return nullptr; } /***************************************************************************** * * Given a set of "assertions" to search, find an assertion that matches * op1Kind and lclNum, op2Kind and the constant value and is either equal or * not equal assertion. */ AssertionIndex Compiler::optLocalAssertionIsEqualOrNotEqual( optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions) { noway_assert((op1Kind == O1K_LCLVAR) || (op1Kind == O1K_EXACT_TYPE) || (op1Kind == O1K_SUBTYPE)); noway_assert((op2Kind == O2K_CONST_INT) || (op2Kind == O2K_IND_CNS_INT)); if (!optLocalAssertionProp && BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } for (AssertionIndex index = 1; index <= optAssertionCount; ++index) { AssertionDsc* curAssertion = optGetAssertion(index); if (optLocalAssertionProp || BitVecOps::IsMember(apTraits, assertions, index - 1)) { if ((curAssertion->assertionKind != OAK_EQUAL) && (curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.kind == op1Kind) && (curAssertion->op1.lcl.lclNum == lclNum) && (curAssertion->op2.kind == op2Kind)) { bool constantIsEqual = (curAssertion->op2.u1.iconVal == cnsVal); bool assertionIsEqual = (curAssertion->assertionKind == OAK_EQUAL); if (constantIsEqual || assertionIsEqual) { return index; } } } } return NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optGlobalAssertionIsEqualOrNotEqual: Look for an assertion in the specified // set that is one of op1 == op1, op1 != op2, or *op1 == op2, // where equality is based on value numbers. // // Arguments: // assertions: bit vector describing set of assertions // op1, op2: the treen nodes in question // // Returns: // Index of first matching assertion, or NO_ASSERTION_INDEX if no // assertions in the set are matches. // // Notes: // Assertions based on *op1 are the result of exact type tests and are // only returned when op1 is a local var with ref type and the assertion // is an exact type equality. // AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2) { if (BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if ((curAssertion->assertionKind != OAK_EQUAL && curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(op1->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNConservativeNormalValue(op2->gtVNPair))) { return assertionIndex; } // Look for matching exact type assertions based on vtable accesses if ((curAssertion->assertionKind == OAK_EQUAL) && (curAssertion->op1.kind == O1K_EXACT_TYPE) && op1->OperIs(GT_IND)) { GenTree* indirAddr = op1->AsIndir()->Addr(); if (indirAddr->OperIs(GT_LCL_VAR) && (indirAddr->TypeGet() == TYP_REF)) { // op1 is accessing vtable of a ref type local var if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(indirAddr->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNConservativeNormalValue(op2->gtVNPair))) { return assertionIndex; } } } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a set of "assertions" to search for, find an assertion that is either * op == 0 or op != 0 * */ AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqualZero(ASSERT_VALARG_TP assertions, GenTree* op1) { if (BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if ((curAssertion->assertionKind != OAK_EQUAL && curAssertion->assertionKind != OAK_NOT_EQUAL)) { continue; } if ((curAssertion->op1.vn == vnStore->VNConservativeNormalValue(op1->gtVNPair)) && (curAssertion->op2.vn == vnStore->VNZeroForType(op1->TypeGet()))) { return assertionIndex; } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a tree consisting of a RelOp and a set of available assertions * we try to propagate an assertion and modify the RelOp tree if we can. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' will be nullptr * Returns the modified tree, or nullptr if no assertion prop took place */ GenTree* Compiler::optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperKind() & GTK_RELOP); if (!optLocalAssertionProp) { // If global assertion prop then use value numbering. return optAssertionPropGlobal_RelOp(assertions, tree, stmt); } // // Currently only GT_EQ or GT_NE are supported Relops for local AssertionProp // if ((tree->gtOper != GT_EQ) && (tree->gtOper != GT_NE)) { return nullptr; } // If local assertion prop then use variable based prop. return optAssertionPropLocal_RelOp(assertions, tree, stmt); } //------------------------------------------------------------------------ // optAssertionProp: try and optimize a relop via assertion propagation // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // // Returns: // The modified tree, or nullptr if no assertion prop took place. // GenTree* Compiler::optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { GenTree* newTree = tree; GenTree* op1 = tree->AsOp()->gtOp1; GenTree* op2 = tree->AsOp()->gtOp2; // Look for assertions of the form (tree EQ/NE 0) AssertionIndex index = optGlobalAssertionIsEqualOrNotEqualZero(assertions, tree); if (index != NO_ASSERTION_INDEX) { // We know that this relop is either 0 or != 0 (1) AssertionDsc* curAssertion = optGetAssertion(index); #ifdef DEBUG if (verbose) { printf("\nVN relop based constant assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: ", index); printTreeID(tree); printf(" %s 0\n", (curAssertion->assertionKind == OAK_EQUAL) ? "==" : "!="); } #endif // Bail out if tree is not side effect free. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { JITDUMP("sorry, blocked by side effects\n"); return nullptr; } if (curAssertion->assertionKind == OAK_EQUAL) { tree->ChangeOperConst(GT_CNS_INT); tree->AsIntCon()->gtIconVal = 0; } else { tree->ChangeOperConst(GT_CNS_INT); tree->AsIntCon()->gtIconVal = 1; } newTree = fgMorphTree(tree); DISPTREE(newTree); return optAssertionProp_Update(newTree, tree, stmt); } // Else check if we have an equality check involving a local or an indir if (!tree->OperIs(GT_EQ, GT_NE)) { return nullptr; } // Bail out if tree is not side effect free. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { return nullptr; } if (!op1->OperIs(GT_LCL_VAR, GT_IND)) { return nullptr; } // Find an equal or not equal assertion involving "op1" and "op2". index = optGlobalAssertionIsEqualOrNotEqual(assertions, op1, op2); if (index == NO_ASSERTION_INDEX) { return nullptr; } AssertionDsc* curAssertion = optGetAssertion(index); bool assertionKindIsEqual = (curAssertion->assertionKind == OAK_EQUAL); // Allow or not to reverse condition for OAK_NOT_EQUAL assertions. bool allowReverse = true; // If the assertion involves "op2" and it is a constant, then check if "op1" also has a constant value. ValueNum vnCns = vnStore->VNConservativeNormalValue(op2->gtVNPair); if (vnStore->IsVNConstant(vnCns)) { #ifdef DEBUG if (verbose) { printf("\nVN relop based constant assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: ", index); printTreeID(op1); printf(" %s ", assertionKindIsEqual ? "==" : "!="); if (genActualType(op1->TypeGet()) == TYP_INT) { printf("%d\n", vnStore->ConstantValue<int>(vnCns)); } else if (op1->TypeGet() == TYP_LONG) { printf("%I64d\n", vnStore->ConstantValue<INT64>(vnCns)); } else if (op1->TypeGet() == TYP_DOUBLE) { printf("%f\n", vnStore->ConstantValue<double>(vnCns)); } else if (op1->TypeGet() == TYP_FLOAT) { printf("%f\n", vnStore->ConstantValue<float>(vnCns)); } else if (op1->TypeGet() == TYP_REF) { // The only constant of TYP_REF that ValueNumbering supports is 'null' assert(vnStore->ConstantValue<size_t>(vnCns) == 0); printf("null\n"); } else { printf("??unknown\n"); } gtDispTree(tree, nullptr, nullptr, true); } #endif // Change the oper to const. if (genActualType(op1->TypeGet()) == TYP_INT) { op1->ChangeOperConst(GT_CNS_INT); op1->AsIntCon()->gtIconVal = vnStore->ConstantValue<int>(vnCns); if (vnStore->IsVNHandle(vnCns)) { op1->gtFlags |= (vnStore->GetHandleFlags(vnCns) & GTF_ICON_HDL_MASK); } } else if (op1->TypeGet() == TYP_LONG) { op1->ChangeOperConst(GT_CNS_NATIVELONG); op1->AsIntConCommon()->SetLngValue(vnStore->ConstantValue<INT64>(vnCns)); if (vnStore->IsVNHandle(vnCns)) { op1->gtFlags |= (vnStore->GetHandleFlags(vnCns) & GTF_ICON_HDL_MASK); } } else if (op1->TypeGet() == TYP_DOUBLE) { double constant = vnStore->ConstantValue<double>(vnCns); op1->ChangeOperConst(GT_CNS_DBL); op1->AsDblCon()->gtDconVal = constant; // Nothing can be equal to NaN. So if IL had "op1 == NaN", then we already made op1 NaN, // which will yield a false correctly. Instead if IL had "op1 != NaN", then we already // made op1 NaN which will yield a true correctly. Note that this is irrespective of the // assertion we have made. allowReverse = (_isnan(constant) == 0); } else if (op1->TypeGet() == TYP_FLOAT) { float constant = vnStore->ConstantValue<float>(vnCns); op1->ChangeOperConst(GT_CNS_DBL); op1->AsDblCon()->gtDconVal = constant; // See comments for TYP_DOUBLE. allowReverse = (_isnan(constant) == 0); } else if (op1->TypeGet() == TYP_REF) { op1->ChangeOperConst(GT_CNS_INT); // The only constant of TYP_REF that ValueNumbering supports is 'null' noway_assert(vnStore->ConstantValue<size_t>(vnCns) == 0); op1->AsIntCon()->gtIconVal = 0; } else { noway_assert(!"unknown type in Global_RelOp"); } op1->gtVNPair.SetBoth(vnCns); // Preserve the ValueNumPair, as ChangeOperConst/SetOper will clear it. // set foldResult to either 0 or 1 bool foldResult = assertionKindIsEqual; if (tree->gtOper == GT_NE) { foldResult = !foldResult; } // Set the value number on the relop to 1 (true) or 0 (false) if (foldResult) { tree->gtVNPair.SetBoth(vnStore->VNOneForType(TYP_INT)); } else { tree->gtVNPair.SetBoth(vnStore->VNZeroForType(TYP_INT)); } } // If the assertion involves "op2" and "op1" is also a local var, then just morph the tree. else if (op2->gtOper == GT_LCL_VAR) { #ifdef DEBUG if (verbose) { printf("\nVN relop based copy assertion prop in " FMT_BB ":\n", compCurBB->bbNum); printf("Assertion index=#%02u: V%02d.%02d %s V%02d.%02d\n", index, op1->AsLclVar()->GetLclNum(), op1->AsLclVar()->GetSsaNum(), (curAssertion->assertionKind == OAK_EQUAL) ? "==" : "!=", op2->AsLclVar()->GetLclNum(), op2->AsLclVar()->GetSsaNum()); gtDispTree(tree, nullptr, nullptr, true); } #endif // If floating point, don't just substitute op1 with op2, this won't work if // op2 is NaN. Just turn it into a "true" or "false" yielding expression. if (op1->TypeGet() == TYP_DOUBLE || op1->TypeGet() == TYP_FLOAT) { // Note we can't trust the OAK_EQUAL as the value could end up being a NaN // violating the assertion. However, we create OAK_EQUAL assertions for floating // point only on JTrue nodes, so if the condition held earlier, it will hold // now. We don't create OAK_EQUAL assertion on floating point from GT_ASG // because we depend on value num which would constant prop the NaN. op1->ChangeOperConst(GT_CNS_DBL); op1->AsDblCon()->gtDconVal = 0; op2->ChangeOperConst(GT_CNS_DBL); op2->AsDblCon()->gtDconVal = 0; } // Change the op1 LclVar to the op2 LclVar else { noway_assert(varTypeIsIntegralOrI(op1->TypeGet())); op1->AsLclVarCommon()->SetLclNum(op2->AsLclVarCommon()->GetLclNum()); op1->AsLclVarCommon()->SetSsaNum(op2->AsLclVarCommon()->GetSsaNum()); } } else { return nullptr; } // Finally reverse the condition, if we have a not equal assertion. if (allowReverse && curAssertion->assertionKind == OAK_NOT_EQUAL) { gtReverseCond(tree); } newTree = fgMorphTree(tree); #ifdef DEBUG if (verbose) { gtDispTree(newTree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(newTree, tree, stmt); } /************************************************************************************* * * Given the set of "assertions" to look up a relop assertion about the relop "tree", * perform local variable name based relop assertion propagation on the tree. * */ GenTree* Compiler::optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperGet() == GT_EQ || tree->OperGet() == GT_NE); GenTree* op1 = tree->AsOp()->gtOp1; GenTree* op2 = tree->AsOp()->gtOp2; // For Local AssertionProp we only can fold when op1 is a GT_LCL_VAR if (op1->gtOper != GT_LCL_VAR) { return nullptr; } // For Local AssertionProp we only can fold when op2 is a GT_CNS_INT if (op2->gtOper != GT_CNS_INT) { return nullptr; } optOp1Kind op1Kind = O1K_LCLVAR; optOp2Kind op2Kind = O2K_CONST_INT; ssize_t cnsVal = op2->AsIntCon()->gtIconVal; var_types cmpType = op1->TypeGet(); // Don't try to fold/optimize Floating Compares; there are multiple zero values. if (varTypeIsFloating(cmpType)) { return nullptr; } // Find an equal or not equal assertion about op1 var. unsigned lclNum = op1->AsLclVarCommon()->GetLclNum(); noway_assert(lclNum < lvaCount); AssertionIndex index = optLocalAssertionIsEqualOrNotEqual(op1Kind, lclNum, op2Kind, cnsVal, assertions); if (index == NO_ASSERTION_INDEX) { return nullptr; } AssertionDsc* curAssertion = optGetAssertion(index); bool assertionKindIsEqual = (curAssertion->assertionKind == OAK_EQUAL); bool constantIsEqual = false; if (genTypeSize(cmpType) == TARGET_POINTER_SIZE) { constantIsEqual = (curAssertion->op2.u1.iconVal == cnsVal); } #ifdef TARGET_64BIT else if (genTypeSize(cmpType) == sizeof(INT32)) { // Compare the low 32-bits only constantIsEqual = (((INT32)curAssertion->op2.u1.iconVal) == ((INT32)cnsVal)); } #endif else { // We currently don't fold/optimize when the GT_LCL_VAR has been cast to a small type return nullptr; } noway_assert(constantIsEqual || assertionKindIsEqual); #ifdef DEBUG if (verbose) { printf("\nAssertion prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif // Return either CNS_INT 0 or CNS_INT 1. bool foldResult = (constantIsEqual == assertionKindIsEqual); if (tree->gtOper == GT_NE) { foldResult = !foldResult; } op2->AsIntCon()->gtIconVal = foldResult; op2->gtType = TYP_INT; return optAssertionProp_Update(op2, tree, stmt); } /***************************************************************************** * * Given a tree consisting of a Cast and a set of available assertions * we try to propagate an assertion and modify the Cast tree if we can. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' * will be nullptr. * * Returns the modified tree, or nullptr if no assertion prop took place. */ GenTree* Compiler::optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->gtOper == GT_CAST); var_types fromType = tree->CastFromType(); var_types toType = tree->AsCast()->gtCastType; GenTree* op1 = tree->AsCast()->CastOp(); // force the fromType to unsigned if GT_UNSIGNED flag is set if (tree->IsUnsigned()) { fromType = varTypeToUnsigned(fromType); } // If we have a cast involving floating point types, then bail. if (varTypeIsFloating(toType) || varTypeIsFloating(fromType)) { return nullptr; } // Skip over a GT_COMMA node(s), if necessary to get to the lcl. GenTree* lcl = op1; while (lcl->gtOper == GT_COMMA) { lcl = lcl->AsOp()->gtOp2; } // If we don't have a cast of a LCL_VAR then bail. if (lcl->gtOper != GT_LCL_VAR) { return nullptr; } AssertionIndex index = optAssertionIsSubrange(lcl, fromType, toType, assertions); if (index != NO_ASSERTION_INDEX) { LclVarDsc* varDsc = &lvaTable[lcl->AsLclVarCommon()->GetLclNum()]; if (varDsc->lvNormalizeOnLoad() || varTypeIsLong(varDsc->TypeGet())) { // For normalize on load variables it must be a narrowing cast to remove if (genTypeSize(toType) > genTypeSize(varDsc->TypeGet())) { // Can we just remove the GTF_OVERFLOW flag? if ((tree->gtFlags & GTF_OVERFLOW) == 0) { return nullptr; } else { #ifdef DEBUG if (verbose) { printf("\nSubrange prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif tree->gtFlags &= ~GTF_OVERFLOW; // This cast cannot overflow return optAssertionProp_Update(tree, tree, stmt); } } // GT_CAST long -> uint -> int // | // GT_LCL_VAR long // // Where the lclvar is known to be in the range of [0..MAX_UINT] // // A load of a 32-bit unsigned int is the same as a load of a 32-bit signed int // if (toType == TYP_UINT) { toType = TYP_INT; } // Change the "lcl" type to match what the cast wanted, by propagating the type // change down the comma nodes leading to the "lcl", if we skipped them earlier. GenTree* tmp = op1; while (tmp->gtOper == GT_COMMA) { tmp->gtType = toType; tmp = tmp->AsOp()->gtOp2; } noway_assert(tmp == lcl); tmp->gtType = toType; } #ifdef DEBUG if (verbose) { printf("\nSubrange prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif return optAssertionProp_Update(op1, tree, stmt); } return nullptr; } /***************************************************************************** * * Given a tree with an array bounds check node, eliminate it because it was * checked already in the program. */ GenTree* Compiler::optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { // Remove the bounds check as part of the GT_COMMA node since we need parent pointer to remove nodes. // When processing visits the bounds check, it sets the throw kind to None if the check is redundant. if ((tree->gtGetOp1()->OperGet() == GT_ARR_BOUNDS_CHECK) && ((tree->gtGetOp1()->gtFlags & GTF_ARR_BOUND_INBND) != 0)) { optRemoveCommaBasedRangeCheck(tree, stmt); return optAssertionProp_Update(tree, tree, stmt); } return nullptr; } //------------------------------------------------------------------------ // optAssertionProp_Ind: see if we can prove the indirection can't cause // and exception. // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // // Returns: // The modified tree, or nullptr if no assertion prop took place. // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { assert(tree->OperIsIndir()); if (!(tree->gtFlags & GTF_EXCEPT)) { return nullptr; } // Check for add of a constant. GenTree* op1 = tree->AsIndir()->Addr(); if ((op1->gtOper == GT_ADD) && (op1->AsOp()->gtOp2->gtOper == GT_CNS_INT)) { op1 = op1->AsOp()->gtOp1; } if (op1->gtOper != GT_LCL_VAR) { return nullptr; } #ifdef DEBUG bool vnBased = false; AssertionIndex index = NO_ASSERTION_INDEX; #endif if (optAssertionIsNonNull(op1, assertions DEBUGARG(&vnBased) DEBUGARG(&index))) { #ifdef DEBUG if (verbose) { (vnBased) ? printf("\nVN based non-null prop in " FMT_BB ":\n", compCurBB->bbNum) : printf("\nNon-null prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif tree->gtFlags &= ~GTF_EXCEPT; tree->gtFlags |= GTF_IND_NONFAULTING; // Set this flag to prevent reordering tree->gtFlags |= GTF_ORDER_SIDEEFF; return optAssertionProp_Update(tree, tree, stmt); } return nullptr; } //------------------------------------------------------------------------ // optAssertionIsNonNull: see if we can prove a tree's value will be non-null // based on assertions // // Arguments: // op - tree to check // assertions - set of live assertions // pVnBased - [out] set to true if value numbers were used // pIndex - [out] the assertion used in the proof // // Returns: // true if the tree's value will be non-null // // Notes: // Sets "pVnBased" if the assertion is value number based. If no matching // assertions are found from the table, then returns "NO_ASSERTION_INDEX." // // If both VN and assertion table yield a matching assertion, "pVnBased" // is only set and the return value is "NO_ASSERTION_INDEX." // bool Compiler::optAssertionIsNonNull(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex)) { bool vnBased = (!optLocalAssertionProp && vnStore->IsKnownNonNull(op->gtVNPair.GetConservative())); #ifdef DEBUG *pVnBased = vnBased; #endif if (vnBased) { #ifdef DEBUG *pIndex = NO_ASSERTION_INDEX; #endif return true; } AssertionIndex index = optAssertionIsNonNullInternal(op, assertions DEBUGARG(pVnBased)); #ifdef DEBUG *pIndex = index; #endif return index != NO_ASSERTION_INDEX; } //------------------------------------------------------------------------ // optAssertionIsNonNullInternal: see if we can prove a tree's value will // be non-null based on assertions // // Arguments: // op - tree to check // assertions - set of live assertions // pVnBased - [out] set to true if value numbers were used // // Returns: // index of assertion, or NO_ASSERTION_INDEX // AssertionIndex Compiler::optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased)) { #ifdef DEBUG // Initialize the out param // *pVnBased = false; #endif // If local assertion prop use lcl comparison, else use VN comparison. if (!optLocalAssertionProp) { if (BitVecOps::MayBeUninit(assertions) || BitVecOps::IsEmpty(apTraits, assertions)) { return NO_ASSERTION_INDEX; } // Look at both the top-level vn, and // the vn we get by stripping off any constant adds. // ValueNum vn = vnStore->VNConservativeNormalValue(op->gtVNPair); ValueNum vnBase = vn; VNFuncApp funcAttr; while (vnStore->GetVNFunc(vnBase, &funcAttr) && (funcAttr.m_func == (VNFunc)GT_ADD)) { if (vnStore->IsVNConstant(funcAttr.m_args[1]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[1]))) { vnBase = funcAttr.m_args[0]; } else if (vnStore->IsVNConstant(funcAttr.m_args[0]) && varTypeIsIntegral(vnStore->TypeOfVN(funcAttr.m_args[0]))) { vnBase = funcAttr.m_args[1]; } else { break; } } // Check each assertion to find if we have a vn != null assertion. // BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (curAssertion->assertionKind != OAK_NOT_EQUAL) { continue; } if (curAssertion->op2.vn != ValueNumStore::VNForNull()) { continue; } if ((curAssertion->op1.vn != vn) && (curAssertion->op1.vn != vnBase)) { continue; } #ifdef DEBUG *pVnBased = true; #endif return assertionIndex; } } else { unsigned lclNum = op->AsLclVarCommon()->GetLclNum(); // Check each assertion to find if we have a variable == or != null assertion. for (AssertionIndex index = 1; index <= optAssertionCount; index++) { AssertionDsc* curAssertion = optGetAssertion(index); if ((curAssertion->assertionKind == OAK_NOT_EQUAL) && // kind (curAssertion->op1.kind == O1K_LCLVAR) && // op1 (curAssertion->op2.kind == O2K_CONST_INT) && // op2 (curAssertion->op1.lcl.lclNum == lclNum) && (curAssertion->op2.u1.iconVal == 0)) { return index; } } } return NO_ASSERTION_INDEX; } /***************************************************************************** * * Given a tree consisting of a call and a set of available assertions, we * try to propagate a non-null assertion and modify the Call tree if we can. * Returns the modified tree, or nullptr if no assertion prop took place. * */ GenTree* Compiler::optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call) { if ((call->gtFlags & GTF_CALL_NULLCHECK) == 0) { return nullptr; } GenTree* op1 = gtGetThisArg(call); noway_assert(op1 != nullptr); if (op1->gtOper != GT_LCL_VAR) { return nullptr; } #ifdef DEBUG bool vnBased = false; AssertionIndex index = NO_ASSERTION_INDEX; #endif if (optAssertionIsNonNull(op1, assertions DEBUGARG(&vnBased) DEBUGARG(&index))) { #ifdef DEBUG if (verbose) { (vnBased) ? printf("\nVN based non-null prop in " FMT_BB ":\n", compCurBB->bbNum) : printf("\nNon-null prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(call, nullptr, nullptr, true); } #endif call->gtFlags &= ~GTF_CALL_NULLCHECK; call->gtFlags &= ~GTF_EXCEPT; noway_assert(call->gtFlags & GTF_SIDE_EFFECT); return call; } return nullptr; } /***************************************************************************** * * Given a tree consisting of a call and a set of available assertions, we * try to propagate an assertion and modify the Call tree if we can. Our * current modifications are limited to removing the nullptrCHECK flag from * the call. * We pass in the root of the tree via 'stmt', for local copy prop 'stmt' * will be nullptr. Returns the modified tree, or nullptr if no assertion prop * took place. * */ GenTree* Compiler::optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, Statement* stmt) { if (optNonNullAssertionProp_Call(assertions, call)) { return optAssertionProp_Update(call, call, stmt); } else if (!optLocalAssertionProp && (call->gtCallType == CT_HELPER)) { if (call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFINTERFACE) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFARRAY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFCLASS) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_ISINSTANCEOFANY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTINTERFACE) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTARRAY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTCLASS) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTANY) || call->gtCallMethHnd == eeFindHelper(CORINFO_HELP_CHKCASTCLASS_SPECIAL)) { GenTree* arg1 = gtArgEntryByArgNum(call, 1)->GetNode(); if (arg1->gtOper != GT_LCL_VAR) { return nullptr; } GenTree* arg2 = gtArgEntryByArgNum(call, 0)->GetNode(); unsigned index = optAssertionIsSubtype(arg1, arg2, assertions); if (index != NO_ASSERTION_INDEX) { #ifdef DEBUG if (verbose) { printf("\nDid VN based subtype prop for index #%02u in " FMT_BB ":\n", index, compCurBB->bbNum); gtDispTree(call, nullptr, nullptr, true); } #endif GenTree* list = nullptr; gtExtractSideEffList(call, &list, GTF_SIDE_EFFECT, true); if (list != nullptr) { arg1 = gtNewOperNode(GT_COMMA, call->TypeGet(), list, arg1); fgSetTreeSeq(arg1); } return optAssertionProp_Update(arg1, call, stmt); } } } return nullptr; } /***************************************************************************** * * Given a tree with a bounds check, remove it if it has already been checked in the program flow. */ GenTree* Compiler::optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { if (optLocalAssertionProp) { return nullptr; } assert(tree->gtOper == GT_ARR_BOUNDS_CHECK); #ifdef FEATURE_ENABLE_NO_RANGE_CHECKS if (JitConfig.JitNoRangeChks()) { #ifdef DEBUG if (verbose) { printf("\nFlagging check redundant due to JitNoRangeChks in " FMT_BB ":\n", compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif // DEBUG tree->gtFlags |= GTF_ARR_BOUND_INBND; return nullptr; } #endif // FEATURE_ENABLE_NO_RANGE_CHECKS BitVecOps::Iter iter(apTraits, assertions); unsigned index = 0; while (iter.NextElem(&index)) { AssertionIndex assertionIndex = GetAssertionIndex(index); if (assertionIndex > optAssertionCount) { break; } // If it is not a nothrow assertion, skip. AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (!curAssertion->IsBoundsCheckNoThrow()) { continue; } GenTreeBoundsChk* arrBndsChk = tree->AsBoundsChk(); // Set 'isRedundant' to true if we can determine that 'arrBndsChk' can be // classified as a redundant bounds check using 'curAssertion' bool isRedundant = false; #ifdef DEBUG const char* dbgMsg = "Not Set"; #endif // Do we have a previous range check involving the same 'vnLen' upper bound? if (curAssertion->op1.bnd.vnLen == vnStore->VNConservativeNormalValue(arrBndsChk->gtArrLen->gtVNPair)) { ValueNum vnCurIdx = vnStore->VNConservativeNormalValue(arrBndsChk->gtIndex->gtVNPair); // Do we have the exact same lower bound 'vnIdx'? // a[i] followed by a[i] if (curAssertion->op1.bnd.vnIdx == vnCurIdx) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[i] followed by a[i]"; #endif } // Are we using zero as the index? // It can always be considered as redundant with any previous value // a[*] followed by a[0] else if (vnCurIdx == vnStore->VNZeroForType(arrBndsChk->gtIndex->TypeGet())) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[*] followed by a[0]"; #endif } // Do we have two constant indexes? else if (vnStore->IsVNConstant(curAssertion->op1.bnd.vnIdx) && vnStore->IsVNConstant(vnCurIdx)) { // Make sure the types match. var_types type1 = vnStore->TypeOfVN(curAssertion->op1.bnd.vnIdx); var_types type2 = vnStore->TypeOfVN(vnCurIdx); if (type1 == type2 && type1 == TYP_INT) { int index1 = vnStore->ConstantValue<int>(curAssertion->op1.bnd.vnIdx); int index2 = vnStore->ConstantValue<int>(vnCurIdx); // the case where index1 == index2 should have been handled above assert(index1 != index2); // It can always be considered as redundant with any previous higher constant value // a[K1] followed by a[K2], with K2 >= 0 and K1 >= K2 if (index2 >= 0 && index1 >= index2) { isRedundant = true; #ifdef DEBUG dbgMsg = "a[K1] followed by a[K2], with K2 >= 0 and K1 >= K2"; #endif } } } // Extend this to remove additional redundant bounds checks: // i.e. a[i+1] followed by a[i] by using the VN(i+1) >= VN(i) // a[i] followed by a[j] when j is known to be >= i // a[i] followed by a[5] when i is known to be >= 5 } if (!isRedundant) { continue; } #ifdef DEBUG if (verbose) { printf("\nVN based redundant (%s) bounds check assertion prop for index #%02u in " FMT_BB ":\n", dbgMsg, assertionIndex, compCurBB->bbNum); gtDispTree(tree, nullptr, nullptr, true); } #endif if (arrBndsChk == stmt->GetRootNode()) { // We have a top-level bounds check node. // This can happen when trees are broken up due to inlining. // optRemoveStandaloneRangeCheck will return the modified tree (side effects or a no-op). GenTree* newTree = optRemoveStandaloneRangeCheck(arrBndsChk, stmt); return optAssertionProp_Update(newTree, arrBndsChk, stmt); } // Defer actually removing the tree until processing reaches its parent comma, since // optRemoveCommaBasedRangeCheck needs to rewrite the whole comma tree. arrBndsChk->gtFlags |= GTF_ARR_BOUND_INBND; return nullptr; } return nullptr; } /***************************************************************************** * * Called when we have a successfully performed an assertion prop. We have * the newTree in hand. This method will replace the existing tree in the * stmt with the newTree. * */ GenTree* Compiler::optAssertionProp_Update(GenTree* newTree, GenTree* tree, Statement* stmt) { assert(newTree != nullptr); assert(tree != nullptr); if (stmt == nullptr) { noway_assert(optLocalAssertionProp); } else { noway_assert(!optLocalAssertionProp); // If newTree == tree then we modified the tree in-place otherwise we have to // locate our parent node and update it so that it points to newTree. if (newTree != tree) { FindLinkData linkData = gtFindLink(stmt, tree); GenTree** useEdge = linkData.result; GenTree* parent = linkData.parent; noway_assert(useEdge != nullptr); if (parent != nullptr) { parent->ReplaceOperand(useEdge, newTree); } else { // If there's no parent, the tree being replaced is the root of the // statement. assert((stmt->GetRootNode() == tree) && (stmt->GetRootNodePointer() == useEdge)); stmt->SetRootNode(newTree); } // We only need to ensure that the gtNext field is set as it is used to traverse // to the next node in the tree. We will re-morph this entire statement in // optAssertionPropMain(). It will reset the gtPrev and gtNext links for all nodes. newTree->gtNext = tree->gtNext; // Old tree should not be referenced anymore. DEBUG_DESTROY_NODE(tree); } } // Record that we propagated the assertion. optAssertionPropagated = true; optAssertionPropagatedCurrentStmt = true; return newTree; } //------------------------------------------------------------------------ // optAssertionProp: try and optimize a tree via assertion propagation // // Arguments: // assertions - set of live assertions // tree - tree to possibly optimize // stmt - statement containing the tree // block - block containing the statement // // Returns: // The modified tree, or nullptr if no assertion prop took place. // // Notes: // stmt may be nullptr during local assertion prop // GenTree* Compiler::optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt, BasicBlock* block) { switch (tree->gtOper) { case GT_LCL_VAR: return optAssertionProp_LclVar(assertions, tree->AsLclVarCommon(), stmt); case GT_OBJ: case GT_BLK: case GT_DYN_BLK: case GT_IND: case GT_NULLCHECK: return optAssertionProp_Ind(assertions, tree, stmt); case GT_ARR_BOUNDS_CHECK: return optAssertionProp_BndsChk(assertions, tree, stmt); case GT_COMMA: return optAssertionProp_Comma(assertions, tree, stmt); case GT_CAST: return optAssertionProp_Cast(assertions, tree, stmt); case GT_CALL: return optAssertionProp_Call(assertions, tree->AsCall(), stmt); case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GT: case GT_GE: return optAssertionProp_RelOp(assertions, tree, stmt); case GT_JTRUE: if (block != nullptr) { return optVNConstantPropOnJTrue(block, tree); } return nullptr; default: return nullptr; } } //------------------------------------------------------------------------ // optImpliedAssertions: Given a tree node that makes an assertion this // method computes the set of implied assertions // that are also true. The updated assertions are // maintained on the Compiler object. // // Arguments: // assertionIndex : The id of the assertion. // activeAssertions : The assertions that are already true at this point. void Compiler::optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions) { noway_assert(!optLocalAssertionProp); noway_assert(assertionIndex != 0); noway_assert(assertionIndex <= optAssertionCount); AssertionDsc* curAssertion = optGetAssertion(assertionIndex); if (!BitVecOps::IsEmpty(apTraits, activeAssertions)) { const ASSERT_TP mappedAssertions = optGetVnMappedAssertions(curAssertion->op1.vn); if (mappedAssertions == nullptr) { return; } ASSERT_TP chkAssertions = BitVecOps::MakeCopy(apTraits, mappedAssertions); if (curAssertion->op2.kind == O2K_LCLVAR_COPY) { const ASSERT_TP op2Assertions = optGetVnMappedAssertions(curAssertion->op2.vn); if (op2Assertions != nullptr) { BitVecOps::UnionD(apTraits, chkAssertions, op2Assertions); } } BitVecOps::IntersectionD(apTraits, chkAssertions, activeAssertions); if (BitVecOps::IsEmpty(apTraits, chkAssertions)) { return; } // Check each assertion in chkAssertions to see if it can be applied to curAssertion BitVecOps::Iter chkIter(apTraits, chkAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } if (chkAssertionIndex == assertionIndex) { continue; } // Determine which one is a copy assertion and use the other to check for implied assertions. AssertionDsc* iterAssertion = optGetAssertion(chkAssertionIndex); if (curAssertion->IsCopyAssertion()) { optImpliedByCopyAssertion(curAssertion, iterAssertion, activeAssertions); } else if (iterAssertion->IsCopyAssertion()) { optImpliedByCopyAssertion(iterAssertion, curAssertion, activeAssertions); } } } // Is curAssertion a constant assignment of a 32-bit integer? // (i.e GT_LVL_VAR X == GT_CNS_INT) else if ((curAssertion->assertionKind == OAK_EQUAL) && (curAssertion->op1.kind == O1K_LCLVAR) && (curAssertion->op2.kind == O2K_CONST_INT)) { optImpliedByConstAssertion(curAssertion, activeAssertions); } } /***************************************************************************** * * Given a set of active assertions this method computes the set * of non-Null implied assertions that are also true */ void Compiler::optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions) { if (BitVecOps::IsEmpty(apTraits, activeAssertions)) { return; } // Check each assertion in activeAssertions to see if it can be applied to constAssertion BitVecOps::Iter chkIter(apTraits, activeAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } // chkAssertion must be Type/Subtype is equal assertion AssertionDsc* chkAssertion = optGetAssertion(chkAssertionIndex); if ((chkAssertion->op1.kind != O1K_SUBTYPE && chkAssertion->op1.kind != O1K_EXACT_TYPE) || (chkAssertion->assertionKind != OAK_EQUAL)) { continue; } // Search the assertion table for a non-null assertion on op1 that matches chkAssertion for (AssertionIndex impIndex = 1; impIndex <= optAssertionCount; impIndex++) { AssertionDsc* impAssertion = optGetAssertion(impIndex); // The impAssertion must be different from the chkAssertion if (impIndex == chkAssertionIndex) { continue; } // impAssertion must be a Non Null assertion on lclNum if ((impAssertion->assertionKind != OAK_NOT_EQUAL) || ((impAssertion->op1.kind != O1K_LCLVAR) && (impAssertion->op1.kind != O1K_VALUE_NUMBER)) || (impAssertion->op2.kind != O2K_CONST_INT) || (impAssertion->op1.vn != chkAssertion->op1.vn)) { continue; } // The bit may already be in the result set if (!BitVecOps::IsMember(apTraits, activeAssertions, impIndex - 1)) { BitVecOps::AddElemD(apTraits, activeAssertions, impIndex - 1); #ifdef DEBUG if (verbose) { printf("\nCompiler::optImpliedByTypeOfAssertions: %s Assertion #%02d, implies assertion #%02d", (chkAssertion->op1.kind == O1K_SUBTYPE) ? "Subtype" : "Exact-type", chkAssertionIndex, impIndex); } #endif } // There is at most one non-null assertion that is implied by the current chkIndex assertion break; } } } //------------------------------------------------------------------------ // optGetVnMappedAssertions: Given a value number, get the assertions // we have about the value number. // // Arguments: // vn - The given value number. // // Return Value: // The assertions we have about the value number. // ASSERT_VALRET_TP Compiler::optGetVnMappedAssertions(ValueNum vn) { ASSERT_TP set = BitVecOps::UninitVal(); if (optValueNumToAsserts->Lookup(vn, &set)) { return set; } return BitVecOps::UninitVal(); } /***************************************************************************** * * Given a const assertion this method computes the set of implied assertions * that are also true */ void Compiler::optImpliedByConstAssertion(AssertionDsc* constAssertion, ASSERT_TP& result) { noway_assert(constAssertion->assertionKind == OAK_EQUAL); noway_assert(constAssertion->op1.kind == O1K_LCLVAR); noway_assert(constAssertion->op2.kind == O2K_CONST_INT); ssize_t iconVal = constAssertion->op2.u1.iconVal; const ASSERT_TP chkAssertions = optGetVnMappedAssertions(constAssertion->op1.vn); if (chkAssertions == nullptr || BitVecOps::IsEmpty(apTraits, chkAssertions)) { return; } // Check each assertion in chkAssertions to see if it can be applied to constAssertion BitVecOps::Iter chkIter(apTraits, chkAssertions); unsigned chkIndex = 0; while (chkIter.NextElem(&chkIndex)) { AssertionIndex chkAssertionIndex = GetAssertionIndex(chkIndex); if (chkAssertionIndex > optAssertionCount) { break; } // The impAssertion must be different from the const assertion. AssertionDsc* impAssertion = optGetAssertion(chkAssertionIndex); if (impAssertion == constAssertion) { continue; } // The impAssertion must be an assertion about the same local var. if (impAssertion->op1.vn != constAssertion->op1.vn) { continue; } bool usable = false; switch (impAssertion->op2.kind) { case O2K_SUBRANGE: // Is the const assertion's constant, within implied assertion's bounds? usable = ((iconVal >= impAssertion->op2.u2.loBound) && (iconVal <= impAssertion->op2.u2.hiBound)); break; case O2K_CONST_INT: // Is the const assertion's constant equal/not equal to the implied assertion? usable = ((impAssertion->assertionKind == OAK_EQUAL) && (impAssertion->op2.u1.iconVal == iconVal)) || ((impAssertion->assertionKind == OAK_NOT_EQUAL) && (impAssertion->op2.u1.iconVal != iconVal)); break; default: // leave 'usable' = false; break; } if (usable) { BitVecOps::AddElemD(apTraits, result, chkIndex); #ifdef DEBUG if (verbose) { AssertionDsc* firstAssertion = optGetAssertion(1); printf("Compiler::optImpliedByConstAssertion: const assertion #%02d implies assertion #%02d\n", (constAssertion - firstAssertion) + 1, (impAssertion - firstAssertion) + 1); } #endif } } } /***************************************************************************** * * Given a copy assertion and a dependent assertion this method computes the * set of implied assertions that are also true. * For copy assertions, exact SSA num and LCL nums should match, because * we don't have kill sets and we depend on their value num for dataflow. */ void Compiler::optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result) { noway_assert(copyAssertion->IsCopyAssertion()); // Get the copyAssert's lcl/ssa nums. unsigned copyAssertLclNum = BAD_VAR_NUM; unsigned copyAssertSsaNum = SsaConfig::RESERVED_SSA_NUM; // Check if copyAssertion's op1 or op2 matches the depAssertion's op1. if (depAssertion->op1.lcl.lclNum == copyAssertion->op1.lcl.lclNum) { copyAssertLclNum = copyAssertion->op2.lcl.lclNum; copyAssertSsaNum = copyAssertion->op2.lcl.ssaNum; } else if (depAssertion->op1.lcl.lclNum == copyAssertion->op2.lcl.lclNum) { copyAssertLclNum = copyAssertion->op1.lcl.lclNum; copyAssertSsaNum = copyAssertion->op1.lcl.ssaNum; } // Check if copyAssertion's op1 or op2 matches the depAssertion's op2. else if (depAssertion->op2.kind == O2K_LCLVAR_COPY) { if (depAssertion->op2.lcl.lclNum == copyAssertion->op1.lcl.lclNum) { copyAssertLclNum = copyAssertion->op2.lcl.lclNum; copyAssertSsaNum = copyAssertion->op2.lcl.ssaNum; } else if (depAssertion->op2.lcl.lclNum == copyAssertion->op2.lcl.lclNum) { copyAssertLclNum = copyAssertion->op1.lcl.lclNum; copyAssertSsaNum = copyAssertion->op1.lcl.ssaNum; } } if (copyAssertLclNum == BAD_VAR_NUM || copyAssertSsaNum == SsaConfig::RESERVED_SSA_NUM) { return; } // Get the depAssert's lcl/ssa nums. unsigned depAssertLclNum = BAD_VAR_NUM; unsigned depAssertSsaNum = SsaConfig::RESERVED_SSA_NUM; if ((depAssertion->op1.kind == O1K_LCLVAR) && (depAssertion->op2.kind == O2K_LCLVAR_COPY)) { if ((depAssertion->op1.lcl.lclNum == copyAssertion->op1.lcl.lclNum) || (depAssertion->op1.lcl.lclNum == copyAssertion->op2.lcl.lclNum)) { depAssertLclNum = depAssertion->op2.lcl.lclNum; depAssertSsaNum = depAssertion->op2.lcl.ssaNum; } else if ((depAssertion->op2.lcl.lclNum == copyAssertion->op1.lcl.lclNum) || (depAssertion->op2.lcl.lclNum == copyAssertion->op2.lcl.lclNum)) { depAssertLclNum = depAssertion->op1.lcl.lclNum; depAssertSsaNum = depAssertion->op1.lcl.ssaNum; } } if (depAssertLclNum == BAD_VAR_NUM || depAssertSsaNum == SsaConfig::RESERVED_SSA_NUM) { return; } // Is depAssertion a constant assignment of a 32-bit integer? // (i.e GT_LVL_VAR X == GT_CNS_INT) bool depIsConstAssertion = ((depAssertion->assertionKind == OAK_EQUAL) && (depAssertion->op1.kind == O1K_LCLVAR) && (depAssertion->op2.kind == O2K_CONST_INT)); // Search the assertion table for an assertion on op1 that matches depAssertion // The matching assertion is the implied assertion. for (AssertionIndex impIndex = 1; impIndex <= optAssertionCount; impIndex++) { AssertionDsc* impAssertion = optGetAssertion(impIndex); // The impAssertion must be different from the copy and dependent assertions if (impAssertion == copyAssertion || impAssertion == depAssertion) { continue; } if (!AssertionDsc::SameKind(depAssertion, impAssertion)) { continue; } bool op1MatchesCopy = (copyAssertLclNum == impAssertion->op1.lcl.lclNum) && (copyAssertSsaNum == impAssertion->op1.lcl.ssaNum); bool usable = false; switch (impAssertion->op2.kind) { case O2K_SUBRANGE: usable = op1MatchesCopy && ((impAssertion->op2.u2.loBound <= depAssertion->op2.u2.loBound) && (impAssertion->op2.u2.hiBound >= depAssertion->op2.u2.hiBound)); break; case O2K_CONST_LONG: usable = op1MatchesCopy && (impAssertion->op2.lconVal == depAssertion->op2.lconVal); break; case O2K_CONST_DOUBLE: // Exact memory match because of positive and negative zero usable = op1MatchesCopy && (memcmp(&impAssertion->op2.dconVal, &depAssertion->op2.dconVal, sizeof(double)) == 0); break; case O2K_IND_CNS_INT: // This is the ngen case where we have an indirection of an address. noway_assert((impAssertion->op1.kind == O1K_EXACT_TYPE) || (impAssertion->op1.kind == O1K_SUBTYPE)); FALLTHROUGH; case O2K_CONST_INT: usable = op1MatchesCopy && (impAssertion->op2.u1.iconVal == depAssertion->op2.u1.iconVal); break; case O2K_LCLVAR_COPY: // Check if op1 of impAssertion matches copyAssertion and also op2 of impAssertion matches depAssertion. if (op1MatchesCopy && (depAssertLclNum == impAssertion->op2.lcl.lclNum && depAssertSsaNum == impAssertion->op2.lcl.ssaNum)) { usable = true; } else { // Otherwise, op2 of impAssertion should match copyAssertion and also op1 of impAssertion matches // depAssertion. usable = ((copyAssertLclNum == impAssertion->op2.lcl.lclNum && copyAssertSsaNum == impAssertion->op2.lcl.ssaNum) && (depAssertLclNum == impAssertion->op1.lcl.lclNum && depAssertSsaNum == impAssertion->op1.lcl.ssaNum)); } break; default: // leave 'usable' = false; break; } if (usable) { BitVecOps::AddElemD(apTraits, result, impIndex - 1); #ifdef DEBUG if (verbose) { AssertionDsc* firstAssertion = optGetAssertion(1); printf("\nCompiler::optImpliedByCopyAssertion: copyAssertion #%02d and depAssertion #%02d, implies " "assertion #%02d", (copyAssertion - firstAssertion) + 1, (depAssertion - firstAssertion) + 1, (impAssertion - firstAssertion) + 1); } #endif // If the depAssertion is a const assertion then any other assertions that it implies could also imply a // subrange assertion. if (depIsConstAssertion) { optImpliedByConstAssertion(impAssertion, result); } } } } #include "dataflow.h" /***************************************************************************** * * Dataflow visitor like callback so that all dataflow is in a single place * */ class AssertionPropFlowCallback { private: ASSERT_TP preMergeOut; ASSERT_TP preMergeJumpDestOut; ASSERT_TP* mJumpDestOut; ASSERT_TP* mJumpDestGen; BitVecTraits* apTraits; public: AssertionPropFlowCallback(Compiler* pCompiler, ASSERT_TP* jumpDestOut, ASSERT_TP* jumpDestGen) : preMergeOut(BitVecOps::UninitVal()) , preMergeJumpDestOut(BitVecOps::UninitVal()) , mJumpDestOut(jumpDestOut) , mJumpDestGen(jumpDestGen) , apTraits(pCompiler->apTraits) { } // At the start of the merge function of the dataflow equations, initialize premerge state (to detect change.) void StartMerge(BasicBlock* block) { if (VerboseDataflow()) { JITDUMP("StartMerge: " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "\n"); } BitVecOps::Assign(apTraits, preMergeOut, block->bbAssertionOut); BitVecOps::Assign(apTraits, preMergeJumpDestOut, mJumpDestOut[block->bbNum]); } // During merge, perform the actual merging of the predecessor's (since this is a forward analysis) dataflow flags. void Merge(BasicBlock* block, BasicBlock* predBlock, unsigned dupCount) { ASSERT_TP pAssertionOut; if (predBlock->bbJumpKind == BBJ_COND && (predBlock->bbJumpDest == block)) { pAssertionOut = mJumpDestOut[predBlock->bbNum]; if (dupCount > 1) { // Scenario where next block and conditional block, both point to the same block. // In such case, intersect the assertions present on both the out edges of predBlock. assert(predBlock->bbNext == block); BitVecOps::IntersectionD(apTraits, pAssertionOut, predBlock->bbAssertionOut); if (VerboseDataflow()) { JITDUMP("Merge : Duplicate flow, " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("pred " FMT_BB " ", predBlock->bbNum); Compiler::optDumpAssertionIndices("out1 -> ", mJumpDestOut[predBlock->bbNum], "; "); Compiler::optDumpAssertionIndices("out2 -> ", predBlock->bbAssertionOut, "\n"); } } } else { pAssertionOut = predBlock->bbAssertionOut; } if (VerboseDataflow()) { JITDUMP("Merge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "; "); JITDUMP("pred " FMT_BB " ", predBlock->bbNum); Compiler::optDumpAssertionIndices("out -> ", pAssertionOut, "\n"); } BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, pAssertionOut); } //------------------------------------------------------------------------ // MergeHandler: Merge assertions into the first exception handler/filter block. // // Arguments: // block - the block that is the start of a handler or filter; // firstTryBlock - the first block of the try for "block" handler; // lastTryBlock - the last block of the try for "block" handler;. // // Notes: // We can jump to the handler from any instruction in the try region. // It means we can propagate only assertions that are valid for the whole try region. void MergeHandler(BasicBlock* block, BasicBlock* firstTryBlock, BasicBlock* lastTryBlock) { BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, firstTryBlock->bbAssertionIn); BitVecOps::IntersectionD(apTraits, block->bbAssertionIn, lastTryBlock->bbAssertionOut); } // At the end of the merge store results of the dataflow equations, in a postmerge state. bool EndMerge(BasicBlock* block) { if (VerboseDataflow()) { JITDUMP("EndMerge : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("in -> ", block->bbAssertionIn, "\n\n"); } BitVecOps::DataFlowD(apTraits, block->bbAssertionOut, block->bbAssertionGen, block->bbAssertionIn); BitVecOps::DataFlowD(apTraits, mJumpDestOut[block->bbNum], mJumpDestGen[block->bbNum], block->bbAssertionIn); bool changed = (!BitVecOps::Equal(apTraits, preMergeOut, block->bbAssertionOut) || !BitVecOps::Equal(apTraits, preMergeJumpDestOut, mJumpDestOut[block->bbNum])); if (VerboseDataflow()) { if (changed) { JITDUMP("Changed : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("before out -> ", preMergeOut, "; "); Compiler::optDumpAssertionIndices("after out -> ", block->bbAssertionOut, ";\n "); Compiler::optDumpAssertionIndices("jumpDest before out -> ", preMergeJumpDestOut, "; "); Compiler::optDumpAssertionIndices("jumpDest after out -> ", mJumpDestOut[block->bbNum], ";\n\n"); } else { JITDUMP("Unchanged : " FMT_BB " ", block->bbNum); Compiler::optDumpAssertionIndices("out -> ", block->bbAssertionOut, "; "); Compiler::optDumpAssertionIndices("jumpDest out -> ", mJumpDestOut[block->bbNum], "\n\n"); } } return changed; } // Can be enabled to get detailed debug output about dataflow for assertions. bool VerboseDataflow() { #if 0 return VERBOSE; #endif return false; } }; /***************************************************************************** * * Compute the assertions generated by each block. */ ASSERT_TP* Compiler::optComputeAssertionGen() { ASSERT_TP* jumpDestGen = fgAllocateTypeForEachBlk<ASSERT_TP>(); for (BasicBlock* const block : Blocks()) { ASSERT_TP valueGen = BitVecOps::MakeEmpty(apTraits); GenTree* jtrue = nullptr; // Walk the statement trees in this basic block. for (Statement* const stmt : block->Statements()) { for (GenTree* const tree : stmt->TreeList()) { if (tree->gtOper == GT_JTRUE) { // A GT_TRUE is always the last node in a tree, so we can break here assert((tree->gtNext == nullptr) && (stmt->GetNextStmt() == nullptr)); jtrue = tree; break; } if (tree->GeneratesAssertion()) { AssertionInfo info = tree->GetAssertionInfo(); optImpliedAssertions(info.GetAssertionIndex(), valueGen); BitVecOps::AddElemD(apTraits, valueGen, info.GetAssertionIndex() - 1); } } } if (jtrue != nullptr) { // Copy whatever we have accumulated into jumpDest edge's valueGen. ASSERT_TP jumpDestValueGen = BitVecOps::MakeCopy(apTraits, valueGen); if (jtrue->GeneratesAssertion()) { AssertionInfo info = jtrue->GetAssertionInfo(); AssertionIndex valueAssertionIndex; AssertionIndex jumpDestAssertionIndex; if (info.IsNextEdgeAssertion()) { valueAssertionIndex = info.GetAssertionIndex(); jumpDestAssertionIndex = optFindComplementary(info.GetAssertionIndex()); } else // is jump edge assertion { valueAssertionIndex = optFindComplementary(info.GetAssertionIndex()); jumpDestAssertionIndex = info.GetAssertionIndex(); } if (valueAssertionIndex != NO_ASSERTION_INDEX) { // Update valueGen if we have an assertion for the bbNext edge optImpliedAssertions(valueAssertionIndex, valueGen); BitVecOps::AddElemD(apTraits, valueGen, valueAssertionIndex - 1); } if (jumpDestAssertionIndex != NO_ASSERTION_INDEX) { // Update jumpDestValueGen if we have an assertion for the bbJumpDest edge optImpliedAssertions(jumpDestAssertionIndex, jumpDestValueGen); BitVecOps::AddElemD(apTraits, jumpDestValueGen, jumpDestAssertionIndex - 1); } } jumpDestGen[block->bbNum] = jumpDestValueGen; } else { jumpDestGen[block->bbNum] = BitVecOps::MakeEmpty(apTraits); } block->bbAssertionGen = valueGen; #ifdef DEBUG if (verbose) { if (block == fgFirstBB) { printf("\n"); } printf(FMT_BB " valueGen = ", block->bbNum); optPrintAssertionIndices(block->bbAssertionGen); if (block->bbJumpKind == BBJ_COND) { printf(" => " FMT_BB " valueGen = ", block->bbJumpDest->bbNum); optPrintAssertionIndices(jumpDestGen[block->bbNum]); } printf("\n"); if (block == fgLastBB) { printf("\n"); } } #endif } return jumpDestGen; } /***************************************************************************** * * Initialize the assertion data flow flags that will be propagated. */ ASSERT_TP* Compiler::optInitAssertionDataflowFlags() { ASSERT_TP* jumpDestOut = fgAllocateTypeForEachBlk<ASSERT_TP>(); // The local assertion gen phase may have created unreachable blocks. // They will never be visited in the dataflow propagation phase, so they need to // be initialized correctly. This means that instead of setting their sets to // apFull (i.e. all possible bits set), we need to set the bits only for valid // assertions (note that at this point we are not creating any new assertions). // Also note that assertion indices start from 1. ASSERT_TP apValidFull = BitVecOps::MakeEmpty(apTraits); for (int i = 1; i <= optAssertionCount; i++) { BitVecOps::AddElemD(apTraits, apValidFull, i - 1); } // Initially estimate the OUT sets to everything except killed expressions // Also set the IN sets to 1, so that we can perform the intersection. for (BasicBlock* const block : Blocks()) { block->bbAssertionIn = BitVecOps::MakeCopy(apTraits, apValidFull); block->bbAssertionGen = BitVecOps::MakeEmpty(apTraits); block->bbAssertionOut = BitVecOps::MakeCopy(apTraits, apValidFull); jumpDestOut[block->bbNum] = BitVecOps::MakeCopy(apTraits, apValidFull); } // Compute the data flow values for all tracked expressions // IN and OUT never change for the initial basic block B1 BitVecOps::ClearD(apTraits, fgFirstBB->bbAssertionIn); return jumpDestOut; } // Callback data for the VN based constant prop visitor. struct VNAssertionPropVisitorInfo { Compiler* pThis; Statement* stmt; BasicBlock* block; VNAssertionPropVisitorInfo(Compiler* pThis, BasicBlock* block, Statement* stmt) : pThis(pThis), stmt(stmt), block(block) { } }; //------------------------------------------------------------------------------ // optExtractSideEffListFromConst // Extracts side effects from a tree so it can be replaced with a comma // separated list of side effects + a const tree. // // Note: // The caller expects that the root of the tree has no side effects and it // won't be extracted. Otherwise the resulting comma tree would be bigger // than the tree before optimization. // // Arguments: // tree - The tree node with constant value to extrace side-effects from. // // Return Value: // 1. Returns the extracted side-effects from "tree" // 2. When no side-effects are present, returns null. // // GenTree* Compiler::optExtractSideEffListFromConst(GenTree* tree) { assert(vnStore->IsVNConstant(vnStore->VNConservativeNormalValue(tree->gtVNPair))); GenTree* sideEffList = nullptr; // If we have side effects, extract them. if ((tree->gtFlags & GTF_SIDE_EFFECT) != 0) { // Do a sanity check to ensure persistent side effects aren't discarded and // tell gtExtractSideEffList to ignore the root of the tree. assert(!gtNodeHasSideEffects(tree, GTF_PERSISTENT_SIDE_EFFECTS)); // Exception side effects may be ignored because the root is known to be a constant // (e.g. VN may evaluate a DIV/MOD node to a constant and the node may still // have GTF_EXCEPT set, even if it does not actually throw any exceptions). bool ignoreRoot = true; gtExtractSideEffList(tree, &sideEffList, GTF_SIDE_EFFECT, ignoreRoot); JITDUMP("Extracted side effects from a constant tree [%06u]:\n", tree->gtTreeID); DISPTREE(sideEffList); } return sideEffList; } //------------------------------------------------------------------------------ // optVNConstantPropOnJTrue // Constant propagate on the JTrue node by extracting side effects and moving // them into their own statements. The relop node is then modified to yield // true or false, so the branch can be folded. // // Arguments: // block - The block that contains the JTrue. // test - The JTrue node whose relop evaluates to 0 or non-zero value. // // Return Value: // The jmpTrue tree node that has relop of the form "0 =/!= 0". // If "tree" evaluates to "true" relop is "0 == 0". Else relop is "0 != 0". // // Description: // Special treatment for JTRUE nodes' constant propagation. This is because // for JTRUE(1) or JTRUE(0), if there are side effects they need to be put // in separate statements. This is to prevent relop's constant // propagation from doing a simple minded conversion from // (1) STMT(JTRUE(RELOP(COMMA(sideEffect, OP1), OP2)), S.T. op1 =/!= op2 to // (2) STMT(JTRUE(COMMA(sideEffect, 1/0)). // // fgFoldConditional doesn't fold (2), a side-effecting JTRUE's op1. So, let us, // here, convert (1) as two statements: STMT(sideEffect), STMT(JTRUE(1/0)), // so that the JTRUE will get folded by fgFoldConditional. // // Note: fgFoldConditional is called from other places as well, which may be // sensitive to adding new statements. Hence the change is not made directly // into fgFoldConditional. // GenTree* Compiler::optVNConstantPropOnJTrue(BasicBlock* block, GenTree* test) { GenTree* relop = test->gtGetOp1(); // VN based assertion non-null on this relop has been performed. if (!relop->OperIsCompare()) { return nullptr; } // // Make sure GTF_RELOP_JMP_USED flag is set so that we can later skip constant // prop'ing a JTRUE's relop child node for a second time in the pre-order // tree walk. // assert((relop->gtFlags & GTF_RELOP_JMP_USED) != 0); // We want to use the Normal ValueNumber when checking for constants. ValueNum vnCns = vnStore->VNConservativeNormalValue(relop->gtVNPair); ValueNum vnLib = vnStore->VNLiberalNormalValue(relop->gtVNPair); if (!vnStore->IsVNConstant(vnCns)) { return nullptr; } // Prepare the tree for replacement so any side effects can be extracted. GenTree* sideEffList = optExtractSideEffListFromConst(relop); // Transform the relop's operands to be both zeroes. ValueNum vnZero = vnStore->VNZeroForType(TYP_INT); relop->AsOp()->gtOp1 = gtNewIconNode(0); relop->AsOp()->gtOp1->gtVNPair = ValueNumPair(vnZero, vnZero); relop->AsOp()->gtOp2 = gtNewIconNode(0); relop->AsOp()->gtOp2->gtVNPair = ValueNumPair(vnZero, vnZero); // Update the oper and restore the value numbers. bool evalsToTrue = (vnStore->CoercedConstantValue<INT64>(vnCns) != 0); relop->SetOper(evalsToTrue ? GT_EQ : GT_NE); relop->gtVNPair = ValueNumPair(vnLib, vnCns); // Insert side effects back after they were removed from the JTrue stmt. // It is important not to allow duplicates exist in the IR, that why we delete // these side effects from the JTrue stmt before insert them back here. while (sideEffList != nullptr) { Statement* newStmt; if (sideEffList->OperGet() == GT_COMMA) { newStmt = fgNewStmtNearEnd(block, sideEffList->gtGetOp1()); sideEffList = sideEffList->gtGetOp2(); } else { newStmt = fgNewStmtNearEnd(block, sideEffList); sideEffList = nullptr; } // fgMorphBlockStmt could potentially affect stmts after the current one, // for example when it decides to fgRemoveRestOfBlock. fgMorphBlockStmt(block, newStmt DEBUGARG(__FUNCTION__)); } return test; } //------------------------------------------------------------------------------ // optVNConstantPropCurStmt // Performs constant prop on the current statement's tree nodes. // // Assumption: // This function is called as part of a pre-order tree walk. // // Arguments: // tree - The currently visited tree node. // stmt - The statement node in which the "tree" is present. // block - The block that contains the statement that contains the tree. // // Return Value: // Returns the standard visitor walk result. // // Description: // Checks if a node is an R-value and evaluates to a constant. If the node // evaluates to constant, then the tree is replaced by its side effects and // the constant node. // Compiler::fgWalkResult Compiler::optVNConstantPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree) { // Don't perform const prop on expressions marked with GTF_DONT_CSE if (!tree->CanCSE()) { return WALK_CONTINUE; } // Don't propagate floating-point constants into a TYP_STRUCT LclVar // This can occur for HFA return values (see hfa_sf3E_r.exe) if (tree->TypeGet() == TYP_STRUCT) { return WALK_CONTINUE; } switch (tree->OperGet()) { // Make sure we have an R-value. case GT_ADD: case GT_SUB: case GT_DIV: case GT_MOD: case GT_UDIV: case GT_UMOD: case GT_EQ: case GT_NE: case GT_LT: case GT_LE: case GT_GE: case GT_GT: case GT_OR: case GT_XOR: case GT_AND: case GT_LSH: case GT_RSH: case GT_RSZ: case GT_NEG: case GT_CAST: case GT_INTRINSIC: break; case GT_INC_SATURATE: case GT_MULHI: assert(false && "Unexpected GT_INC_SATURATE/GT_MULHI node encountered before lowering"); break; case GT_JTRUE: break; case GT_MUL: // Don't transform long multiplies. if (tree->gtFlags & GTF_MUL_64RSLT) { return WALK_SKIP_SUBTREES; } break; case GT_LCL_VAR: // Make sure the local variable is an R-value. if ((tree->gtFlags & (GTF_VAR_DEF | GTF_DONT_CSE))) { return WALK_CONTINUE; } // Let's not conflict with CSE (to save the movw/movt). if (lclNumIsCSE(tree->AsLclVarCommon()->GetLclNum())) { return WALK_CONTINUE; } break; default: // Unknown node, continue to walk. return WALK_CONTINUE; } // Perform the constant propagation GenTree* newTree = optVNConstantPropOnTree(block, tree); if (newTree == nullptr) { // Not propagated, keep going. return WALK_CONTINUE; } // Successful propagation, mark as assertion propagated and skip // sub-tree (with side-effects) visits. // TODO #18291: at that moment stmt could be already removed from the stmt list. optAssertionProp_Update(newTree, tree, stmt); JITDUMP("After constant propagation on [%06u]:\n", tree->gtTreeID); DBEXEC(VERBOSE, gtDispStmt(stmt)); return WALK_SKIP_SUBTREES; } //------------------------------------------------------------------------------ // optVnNonNullPropCurStmt // Performs VN based non-null propagation on the tree node. // // Assumption: // This function is called as part of a pre-order tree walk. // // Arguments: // block - The block that contains the statement that contains the tree. // stmt - The statement node in which the "tree" is present. // tree - The currently visited tree node. // // Return Value: // None. // // Description: // Performs value number based non-null propagation on GT_CALL and // indirections. This is different from flow based assertions and helps // unify VN based constant prop and non-null prop in a single pre-order walk. // void Compiler::optVnNonNullPropCurStmt(BasicBlock* block, Statement* stmt, GenTree* tree) { ASSERT_TP empty = BitVecOps::UninitVal(); GenTree* newTree = nullptr; if (tree->OperGet() == GT_CALL) { newTree = optNonNullAssertionProp_Call(empty, tree->AsCall()); } else if (tree->OperIsIndir()) { newTree = optAssertionProp_Ind(empty, tree, stmt); } if (newTree) { assert(newTree == tree); optAssertionProp_Update(newTree, tree, stmt); } } //------------------------------------------------------------------------------ // optVNAssertionPropCurStmtVisitor // Unified Value Numbering based assertion propagation visitor. // // Assumption: // This function is called as part of a pre-order tree walk. // // Return Value: // WALK_RESULTs. // // Description: // An unified value numbering based assertion prop visitor that // performs non-null and constant assertion propagation based on // value numbers. // /* static */ Compiler::fgWalkResult Compiler::optVNAssertionPropCurStmtVisitor(GenTree** ppTree, fgWalkData* data) { VNAssertionPropVisitorInfo* pData = (VNAssertionPropVisitorInfo*)data->pCallbackData; Compiler* pThis = pData->pThis; pThis->optVnNonNullPropCurStmt(pData->block, pData->stmt, *ppTree); return pThis->optVNConstantPropCurStmt(pData->block, pData->stmt, *ppTree); } /***************************************************************************** * * Perform VN based i.e., data flow based assertion prop first because * even if we don't gen new control flow assertions, we still propagate * these first. * * Returns the skipped next stmt if the current statement or next few * statements got removed, else just returns the incoming stmt. */ Statement* Compiler::optVNAssertionPropCurStmt(BasicBlock* block, Statement* stmt) { // TODO-Review: EH successor/predecessor iteration seems broken. // See: SELF_HOST_TESTS_ARM\jit\Directed\ExcepFilters\fault\fault.exe if (block->bbCatchTyp == BBCT_FAULT) { return stmt; } // Preserve the prev link before the propagation and morph. Statement* prev = (stmt == block->firstStmt()) ? nullptr : stmt->GetPrevStmt(); // Perform VN based assertion prop first, in case we don't find // anything in assertion gen. optAssertionPropagatedCurrentStmt = false; VNAssertionPropVisitorInfo data(this, block, stmt); fgWalkTreePre(stmt->GetRootNodePointer(), Compiler::optVNAssertionPropCurStmtVisitor, &data); if (optAssertionPropagatedCurrentStmt) { fgMorphBlockStmt(block, stmt DEBUGARG("optVNAssertionPropCurStmt")); } // Check if propagation removed statements starting from current stmt. // If so, advance to the next good statement. Statement* nextStmt = (prev == nullptr) ? block->firstStmt() : prev->GetNextStmt(); return nextStmt; } /***************************************************************************** * * The entry point for assertion propagation */ void Compiler::optAssertionPropMain() { if (fgSsaPassesCompleted == 0) { return; } #ifdef DEBUG if (verbose) { printf("*************** In optAssertionPropMain()\n"); printf("Blocks/Trees at start of phase\n"); fgDispBasicBlocks(true); } #endif optAssertionInit(false); noway_assert(optAssertionCount == 0); // First discover all value assignments and record them in the table. for (BasicBlock* const block : Blocks()) { compCurBB = block; fgRemoveRestOfBlock = false; Statement* stmt = block->firstStmt(); while (stmt != nullptr) { // We need to remove the rest of the block. if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); stmt = stmt->GetNextStmt(); continue; } else { // Perform VN based assertion prop before assertion gen. Statement* nextStmt = optVNAssertionPropCurStmt(block, stmt); // Propagation resulted in removal of the remaining stmts, perform it. if (fgRemoveRestOfBlock) { stmt = stmt->GetNextStmt(); continue; } // Propagation removed the current stmt or next few stmts, so skip them. if (stmt != nextStmt) { stmt = nextStmt; continue; } } // Perform assertion gen for control flow based assertions. for (GenTree* const tree : stmt->TreeList()) { optAssertionGen(tree); } // Advance the iterator stmt = stmt->GetNextStmt(); } } if (optAssertionCount == 0) { // Zero out the bbAssertionIn values, as these can be referenced in RangeCheck::MergeAssertion // and this is sharedstate with the CSE phase: bbCseIn // for (BasicBlock* const block : Blocks()) { block->bbAssertionIn = BitVecOps::MakeEmpty(apTraits); } return; } #ifdef DEBUG fgDebugCheckLinks(); #endif // Allocate the bits for the predicate sensitive dataflow analysis bbJtrueAssertionOut = optInitAssertionDataflowFlags(); ASSERT_TP* jumpDestGen = optComputeAssertionGen(); // Modified dataflow algorithm for available expressions. DataFlow flow(this); AssertionPropFlowCallback ap(this, bbJtrueAssertionOut, jumpDestGen); if (ap.VerboseDataflow()) { JITDUMP("AssertionPropFlowCallback:\n\n") } flow.ForwardAnalysis(ap); for (BasicBlock* const block : Blocks()) { // Compute any implied non-Null assertions for block->bbAssertionIn optImpliedByTypeOfAssertions(block->bbAssertionIn); } #ifdef DEBUG if (verbose) { for (BasicBlock* const block : Blocks()) { printf(FMT_BB ":\n", block->bbNum); optDumpAssertionIndices(" in = ", block->bbAssertionIn, "\n"); optDumpAssertionIndices(" out = ", block->bbAssertionOut, "\n"); if (block->bbJumpKind == BBJ_COND) { printf(" " FMT_BB " = ", block->bbJumpDest->bbNum); optDumpAssertionIndices(bbJtrueAssertionOut[block->bbNum], "\n"); } } printf("\n"); } #endif // DEBUG ASSERT_TP assertions = BitVecOps::MakeEmpty(apTraits); // Perform assertion propagation (and constant folding) for (BasicBlock* const block : Blocks()) { BitVecOps::Assign(apTraits, assertions, block->bbAssertionIn); // TODO-Review: EH successor/predecessor iteration seems broken. // SELF_HOST_TESTS_ARM\jit\Directed\ExcepFilters\fault\fault.exe if (block->bbCatchTyp == BBCT_FAULT) { continue; } // Make the current basic block address available globally. compCurBB = block; fgRemoveRestOfBlock = false; // Walk the statement trees in this basic block Statement* stmt = block->FirstNonPhiDef(); while (stmt != nullptr) { // Propagation tells us to remove the rest of the block. Remove it. if (fgRemoveRestOfBlock) { fgRemoveStmt(block, stmt); stmt = stmt->GetNextStmt(); continue; } // Preserve the prev link before the propagation and morph, to check if propagation // removes the current stmt. Statement* prevStmt = (stmt == block->firstStmt()) ? nullptr : stmt->GetPrevStmt(); optAssertionPropagatedCurrentStmt = false; // set to true if a assertion propagation took place // and thus we must morph, set order, re-link for (GenTree* tree = stmt->GetTreeList(); tree != nullptr; tree = tree->gtNext) { optDumpAssertionIndices("Propagating ", assertions, " "); JITDUMP("for " FMT_BB ", stmt " FMT_STMT ", tree [%06d]", block->bbNum, stmt->GetID(), dspTreeID(tree)); JITDUMP(", tree -> "); JITDUMPEXEC(optPrintAssertionIndex(tree->GetAssertionInfo().GetAssertionIndex())); JITDUMP("\n"); GenTree* newTree = optAssertionProp(assertions, tree, stmt, block); if (newTree) { assert(optAssertionPropagatedCurrentStmt == true); tree = newTree; } // If this tree makes an assertion - make it available. if (tree->GeneratesAssertion()) { AssertionInfo info = tree->GetAssertionInfo(); optImpliedAssertions(info.GetAssertionIndex(), assertions); BitVecOps::AddElemD(apTraits, assertions, info.GetAssertionIndex() - 1); } } if (optAssertionPropagatedCurrentStmt) { #ifdef DEBUG if (verbose) { printf("Re-morphing this stmt:\n"); gtDispStmt(stmt); printf("\n"); } #endif // Re-morph the statement. fgMorphBlockStmt(block, stmt DEBUGARG("optAssertionPropMain")); } // Check if propagation removed statements starting from current stmt. // If so, advance to the next good statement. Statement* nextStmt = (prevStmt == nullptr) ? block->firstStmt() : prevStmt->GetNextStmt(); stmt = (stmt == nextStmt) ? stmt->GetNextStmt() : nextStmt; } optAssertionPropagatedCurrentStmt = false; // clear it back as we are done with stmts. } #ifdef DEBUG fgDebugCheckBBlist(); fgDebugCheckLinks(); #endif }
/* * SystemInfo.cpp * * Created on: May 21, 2018 * Author: root */ #include "SystemInfo.h" double g_cpu_used; unsigned long g_mem_total; unsigned long g_mem_used; unsigned long g_disk_total; unsigned long g_disk_used; unsigned long g_disk_read; unsigned long g_disk_write; unsigned long g_network_up; unsigned long g_network_down; bool quit_out = false; void get_cpuinfo(CPU_PACKED &cpuinfo) { char buff[256] = {0}; ifstream in("/proc/stat"); if (!in) { cout << "get cpu info failed" << endl; return; } in.getline(buff, sizeof(buff)); stringstream ss(buff); ss >> cpuinfo.name; ss >> cpuinfo.user; ss >> cpuinfo.nice; ss >> cpuinfo.system; ss >> cpuinfo.idle; ss >> cpuinfo.iowait; ss >> cpuinfo.irq; ss >> cpuinfo.softirg; in.close(); } double calc_cpuoccupy(CPU_PACKED cpuinfo1, CPU_PACKED cpuinfo2) { double info1d = cpuinfo1.user + cpuinfo1.nice + cpuinfo1.system + cpuinfo1.idle + cpuinfo1.softirg + cpuinfo1.iowait + cpuinfo1.irq; double info2d = cpuinfo2.user + cpuinfo2.nice + cpuinfo2.system + cpuinfo2.idle + cpuinfo2.softirg + cpuinfo2.iowait + cpuinfo2.irq; double sub1 = cpuinfo1.idle; double sub2 = cpuinfo2.idle; double cpu_use; if ((sub1 - sub2) != 0) cpu_use = 100.0 - ((sub2 - sub1) / (info2d - info1d)) * 100.0; else cpu_use = 0; //double cpu_use = cpuinfo1.user/info1d; return cpu_use; } void calc_memoccupy(MEM_PACKED &meminfo) { char buff[256] = {0}; string name; unsigned long free_mem; unsigned long cached; int index = 0; ifstream in("/proc/meminfo"); if (!in) { cout << "get cpu info failed" << endl; return; } stringstream ss; while (!in.eof() && index < 4) { in.getline(buff, sizeof(buff)); ss.str(""); ss << buff; if (index == 0) { ss >> name; ss >> meminfo.total_mem; } else if (index == 1) { ss >> name; ss >> free_mem; } else if (index == 3) { ss >> name; ss >> cached; } index++; } meminfo.used_mem = meminfo.total_mem - free_mem - cached; in.close(); } void calc_rwspeed(unsigned long &readsectors, unsigned long &writesectors) { ifstream in("/proc/diskstats"); if (!in) { cout << "get disk speed info failed with Reason:" << strerror(errno) << endl; return; } string line; while (!in.eof()) { getline(in, line); size_t pos = line.find("sda"); if (pos < line.size()) { line = line.substr(pos + 4, line.size()); break; } } vector<string> items = splitstring(line); readsectors = atol(items[2].c_str()); writesectors = atol(items[6].c_str()); in.close(); } void calc_diskoccupy(string path, DISK_PACKED &diskinfo) { struct statfs disk; if (statfs(path.c_str(), &disk) == -1) { cout << "Failed to get disk info with Reason:" << strerror(errno) << endl; return; } diskinfo.total_disk = disk.f_blocks * disk.f_bsize; diskinfo.avail_disk = disk.f_bavail * disk.f_bsize; diskinfo.free_disk = disk.f_bfree * disk.f_bsize; unsigned long reads1, writes1, reads2, writes2; calc_rwspeed(reads1, writes1); sleep(1); calc_rwspeed(reads2, writes2); diskinfo.read_speed = (reads2 - reads1) * disk.f_bsize; diskinfo.write_speed = (writes2 - writes1) * disk.f_bsize; } vector<string> splitstring(string str) { vector<string> result; string item; stringstream ss; ss << str; while (ss >> item) result.push_back(item); return result; } void read_netdev(unsigned long &ups, unsigned long &downs) { ifstream in("/proc/net/dev"); if (!in) { cout << "get network info failed" << endl; return; } string line; std::vector<string> lines; while (!in.eof()) { getline(in, line); if (in.fail()) break; lines.push_back(line); } vector<string> items = splitstring(lines[lines.size() - 1]); ups = atol(items[1].c_str()); downs = atol(items[9].c_str()); in.close(); } void calc_netspeed(NET_PACKED &netinfo) { unsigned long ups1, ups2, downs1, downs2; read_netdev(ups1, downs1); sleep(1); read_netdev(ups2, downs2); netinfo.upspeed = (float)(ups2 - ups1); netinfo.downspeed = (float)(downs2 - downs1); } void thread_cpu_monitor() { CPU_PACKED cpuinfo1, cpuinfo2; while (1) { get_cpuinfo(cpuinfo1); sleep(1); get_cpuinfo(cpuinfo2); g_cpu_used = calc_cpuoccupy(cpuinfo1, cpuinfo2); if (quit_out) break; } } void thread_mem_monitor() { MEM_PACKED meminfo; while (1) { calc_memoccupy(meminfo); g_mem_total = meminfo.total_mem; g_mem_used = meminfo.used_mem; if (quit_out) break; } } void thread_disk_monitor() { DISK_PACKED diskinfo; while (1) { calc_diskoccupy("/", diskinfo); g_disk_total = diskinfo.total_disk; g_disk_used = diskinfo.total_disk - diskinfo.avail_disk; g_disk_read = (diskinfo.read_speed >> 10); g_disk_write = (diskinfo.write_speed >> 10); if (quit_out) break; } } void thread_network_monitor() { NET_PACKED netinfo; while (1) { calc_netspeed(netinfo); g_network_up = netinfo.upspeed; g_network_down = netinfo.downspeed; if (quit_out) break; } } void sys_monitor() { thread t1(thread_cpu_monitor); t1.detach(); thread t2(thread_mem_monitor); t2.detach(); thread t3(thread_disk_monitor); t3.detach(); thread t4(thread_network_monitor); t4.detach(); }
;-------------------------------------------------------------------------------- ; LockAgahnimDoors: ; Returns: 0=Unlocked - 1=Locked ;-------------------------------------------------------------------------------- LockAgahnimDoors: LDA.l AgahnimDoorStyle : AND.w #$00FF BNE + ;#$0 = Never Locked LDA.w #$0000 : RTL + : CMP.w #$0001 : BNE + LDA $7EF3C5 : AND.w #$000F : CMP.w #$0002 : !BGE .unlock ; if we rescued zelda, skip JSR.w LockAgahnimDoorsCore : RTL + : CMP.w #$0002 : BNE + JSR.w LockAgahnimDoorsCore : BEQ .unlock PHX : PHY SEP #$30 JSL.l CheckEnoughCrystalsForTower REP #$30 PLY : PLX !BGE .crystalOrUnlock LDA #$0001 : RTL .crystalOrUnlock LDA InvertedMode : AND.w #$00FF : BEQ .unlock LDA $7EF2C3 : AND.w #$0020 : BNE .unlock ; Check if GT overlay is already on or not LDA $0308 : AND.w #$0080 : BEQ ++ ;If we are holding an item LDA #$0001 : RTL ;Keep the door locked ++ SEP #$30 JSL $099B6F ;Add tower break seal LDA $7EF2C3 : ORA #$20 : STA $7EF2C3 ; activate GT overlay REP #$30 LDA #$0001 ;Prevent door from opening that frame otherwise it glitchy RTL + .unlock LDA.w #$0000 ; fallback to never locked RTL ;-------------------------------------------------------------------------------- LockAgahnimDoorsCore: LDA $22 : CMP.w #1992 : !BLT + ; door too far left, skip CMP.w #2088 : !BGE + ; door too rat right, skip LDA $20 : CMP.w #1720 : !BGE + ; door too low, skip LDA.w #$0001 RTS + LDA.w #$0000 RTS ;-------------------------------------------------------------------------------- SmithDoorCheck: LDA.l SmithTravelsFreely : AND.w #$00FF : BEQ .orig ;If SmithTravelsFreely is set Frog/Smith can enter multi-entrance overworld doors JML.l Overworld_Entrance_BRANCH_RHO .orig ; The rest is equivlent to what we overwrote CPX.w #$0076 : !BGE + JML.l Overworld_Entrance_BRANCH_LAMBDA + JML.l Overworld_Entrance_BRANCH_RHO ;-------------------------------------------------------------------------------- AllowStartFromSingleEntranceCave: ; 16 Bit A, 16 bit XY ; do not need to preserve A or X or Y LDA $7EF3C8 : AND.w #$00FF ; What we wrote over PHA TAX LDA.l StartingAreaExitOffset, X BNE + JMP .done + DEC STA $00 ASL #2 : !ADD $00 : ASL #2 ; mult by 20 TAX LDA #$0016 : STA $7EC142 ; Cache the main screen designation LDA.l StartingAreaExitTable+$05, X : STA $7EC144 ; Cache BG1 V scroll LDA.l StartingAreaExitTable+$07, X : STA $7EC146 ; Cache BG1 H scroll LDA.l StartingAreaExitTable+$09, X : !ADD.w #$0010 : STA $7EC148 ; Cache Link's Y coordinate LDA.l StartingAreaExitTable+$0B, X : STA $7EC14A ; Cache Link's X coordinate LDA.l StartingAreaExitTable+$0D, X : STA $7EC150 ; Cache Camera Y coord lower bound. LDA.l StartingAreaExitTable+$0F, X : STA $7EC152 ; Cache Camera X coord lower bound. LDA.l StartingAreaExitTable+$03, X : STA $7EC14E ; Cache Link VRAM Location ; Handle the 2 "unknown" bytes, which control what area of the backgound ; relative to the camera? gets loaded with new tile data as the player moves around ; (because some overworld areas like Kak are too big for a single VRAM tilemap) LDA.l StartingAreaExitTable+$11, X : AND.w #$00FF BIT.w #$0080 : BEQ + : ORA #$FF00 : + ; Sign extend STA.l $7EC16A LDA.l StartingAreaExitTable+$12, X : AND.w #$00FF BIT.w #$0080 : BEQ + : ORA #$FF00 : + ; Sign extend STA.l $7EC16E LDA.w #$0000 : !SUB.l $7EC16A : STA $7EC16C LDA.w #$0000 : !SUB.l $7EC16E : STA $7EC170 LDA.l StartingAreaExitTable+$02, X : AND.w #$00FF STA $7EC14C ; Cache the overworld area number STA $7EC140 ; Cache the aux overworld area number STZ $0698 ;zero out door overlays in case starting overworld door is not set STZ $0699 ;zero out door overlays in case starting overworld door is not set SEP #$20 ; set 8-bit accumulator LDX $00 LDA.l StartingAreaOverworldDoor, X : STA.l $7F5099 ;Load overworld door REP #$20 ; reset 16-bit accumulator .done PLA RTL ;-------------------------------------------------------------------------------- AllowStartFromExit: LDX $1CE8 LDA.l ShouldStartatExit, X : BNE .doStart LDA.l $7EF3C8 ; what we wrote over JML.l AllowStartFromExitReturn .doStart LDA.l $028481, X ;Module_LocationMenu_starting_points ASL : TAX LDA.l $02D8D2, X : STA $A0 LDA.l $02D8D3, X : STA $A1 ; Go to pre-overworld mode LDA.b #$08 : STA $10 STZ $11 STZ $B0 STZ $010A STZ $04AA JSL Equipment_SearchForEquippedItemLong JSL HUD_RebuildLong2 JSL $0DDD32 ; Equipment_UpdateEquippedItemLong RTL ;-------------------------------------------------------------------------------- CheckHole: LDX.w #$0024 .nextHoleClassic LDA.b $00 : CMP.l $1BB800, X BNE .wrongMap16Classic LDA.w $040A : CMP.l $1BB826, X BEQ .matchedHoleClassic .wrongMap16Classic DEX #2 : BPL .nextHoleClassic LDX.w #$001E .nextHoleExtra LDA.b $00 : CMP.l ExtraHole_Map16, X BNE .wrongMap16Extra LDA.w $040A : CMP.l ExtraHole_Area, X BEQ .matchedHoleExtra .wrongMap16Extra DEX #2 : BPL .nextHoleExtra JML Overworld_Hole_GotoHoulihan .matchedHoleClassic JML Overworld_Hole_matchedHole .matchedHoleExtra SEP #$30 TXA : LSR A : TAX LDA.l ExtraHole_Entrance, X : STA.w $010E : STZ.w $010F JML Overworld_Hole_End ;-------------------------------------------------------------------------------- PreventEnterOnBonk: STA $00 ; part of what we wrote over LDA.l InvertedMode : AND.w #$00FF : BEQ .done LDA.l $5D : AND.w #$00FF : CMP.w #$0014 : BNE .done ;in mirror mode? LDA.b $8A : TAX : LDA.l OWTileWorldAssoc, X : AND.w #$00FF : CMP $7B : BEQ .done ; Are we bonking, or doing the superbunny glitch? ; If in inverted, are in mirror mode, and are bonking then do not enter JML.l PreventEnterOnBonk_BRANCH_IX .done LDX.w #$0102 ; rest of what we wrote over JML.l PreventEnterOnBonk_return ;-------------------------------------------------------------------------------- TurtleRockEntranceFix: LDA TurtleRockAutoOpenFix : BEQ .done LDA $8A : CMP.b #$47 : BNE .done ;If exiting to turtle rock ensure the entrance is open LDA.l $7EF2C7 : ORA.b #$20 : STA.l $7EF2C7 .done RTL ;-------------------------------------------------------------------------------- AnimatedEntranceFix: ;when an entrance animation tries to start PHA : PHX LDA.l InvertedMode : BEQ + ;If we are in inverted mode LDX $8A : LDA.l OWTileWorldAssoc, X : BNE + ;and in the light world PLX : PLA STZ $04C6 ; skip it. LDA #$00 RTL + PLX : PLA STA $02E4 ;what we wrote over STA $0FC1 ;what we wrote over STA $0710 ;what we wrote over RTL
// Copyright (c) 2020, QuantStack and XVega Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #ifndef XVEGA_ENCODING_KEY_HPP #define XVEGA_ENCODING_KEY_HPP #include <xproperty/xobserved.hpp> #include <xtl/xoptional.hpp> #include <xtl/xjson.hpp> #include <nlohmann/json.hpp> #include "../../encoding-channel-options/aggregate.hpp" #include "../../encoding-channel-options/bin.hpp" #include "../../encoding-channel-options/field.hpp" #include "../../encoding-channel-options/timeunit.hpp" #include "../../../../utils/custom_datatypes.hpp" namespace nl = nlohmann; namespace xv { struct Key : public xp::xobserved<Key> { XPROPERTY(xtl::xoptional<agg_type>, Key, aggregate); XPROPERTY(xtl::xoptional<bin_type>, Key, bin); XPROPERTY(xtl::xoptional<field_type>, Key, field); XPROPERTY(xtl::xoptional<time_unit_type>, Key, timeUnit); XPROPERTY(xtl::xoptional<string_vec_none_type>, Key, title); XPROPERTY(xtl::xoptional<std::string>, Key, type); }; XVEGA_API void to_json(nl::json& j, const Key& data); } #endif
#pragma once class FrameCounter { public: static void Update() ; static u32 m_FrameCount; static u32 m_LastFrameCount; static u64 m_LastFrameTime; static bool m_Display; };
#pragma once #include <thread> #include <future> #include <mutex> #include <functional> #include <queue> #include <vector> namespace goop { template<typename R> bool is_ready(std::future<R> const& f) { return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready; } class looper { public: looper(int concurrency = std::thread::hardware_concurrency()); template<typename Fun> std::future<std::invoke_result_t<Fun>> async(Fun&& fun) { using result_type = std::invoke_result_t<Fun>; auto promise = std::make_shared<std::promise<result_type>>(); { std::unique_lock lock(_mtx); _runners.push([promise, f = std::forward<Fun>(fun)]{ if constexpr (std::is_same_v<result_type, void>) { f(); promise->set_value(); } else { promise->set_value(f()); } }); } _cnd.notify_one(); return promise->get_future(); } template<typename Fun> void launch(Fun&& fun) { { std::unique_lock lock(_mtx); _runners.push([f = std::forward<Fun>(fun)]{ f(); }); } _cnd.notify_one(); } private: void loop(std::stop_token stop_token); static void loop_fun(std::stop_token stop_token, looper* self); std::vector<std::jthread> _threads; std::condition_variable _cnd; std::mutex _mtx; std::queue<std::function<void()>> _runners; }; }
/* ****************************************************************************** * * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // Created by raver119 on 13/11/17. // #include "testlayers.h" #include <graph/Graph.h> #include <graph/Node.h> #include <ops/declarable/CustomOperations.h> using namespace sd; using namespace sd::graph; class SanityTests : public testing::Test { public: }; TEST_F(SanityTests, VariableSpace_1) { VariableSpace variableSpace; variableSpace.putVariable(1, new Variable()); variableSpace.putVariable(1, 1, new Variable()); std::pair<int, int> pair(1, 2); variableSpace.putVariable(pair, new Variable()); } TEST_F(SanityTests, VariableSpace_2) { VariableSpace variableSpace; variableSpace.putVariable(1, new Variable(NDArrayFactory::create_<float>('c', {3, 3}))); variableSpace.putVariable(1, 1, new Variable(NDArrayFactory::create_<float>('c', {3, 3}))); std::pair<int, int> pair(1, 2); variableSpace.putVariable(pair, new Variable(NDArrayFactory::create_<float>('c', {3, 3}))); } TEST_F(SanityTests, Graph_1) { Graph graph; graph.getVariableSpace()->putVariable(1, new Variable(NDArrayFactory::create_<float>('c', {3, 3}))); graph.getVariableSpace()->putVariable(1, 1, new Variable(NDArrayFactory::create_<float>('c', {3, 3}))); std::pair<int, int> pair(1, 2); graph.getVariableSpace()->putVariable(pair, new Variable(NDArrayFactory::create_<float>('c', {3, 3}))); }
Route24_Script: call EnableAutoTextBoxDrawing ld hl, Route24TrainerHeaders ld de, Route24_ScriptPointers ld a, [wRoute24CurScript] call ExecuteCurMapScriptInTable ld [wRoute24CurScript], a ret Route24Script_513c0: xor a ld [wJoyIgnore], a ld [wRoute24CurScript], a ld [wCurMapScript], a ret Route24_ScriptPointers: dw Route24Script0 dw DisplayEnemyTrainerTextAndStartBattle dw EndTrainerBattle dw Route24Script3 dw Route24Script4 Route24Script0: CheckEvent EVENT_GOT_NUGGET jp nz, CheckFightingMapTrainers ld hl, CoordsData_5140e call ArePlayerCoordsInArray jp nc, CheckFightingMapTrainers xor a ldh [hJoyHeld], a ld a, $1 ldh [hSpriteIndexOrTextID], a call DisplayTextID CheckAndResetEvent EVENT_NUGGET_REWARD_AVAILABLE ret z ld a, D_DOWN ld [wSimulatedJoypadStatesEnd], a ld a, $1 ld [wSimulatedJoypadStatesIndex], a call StartSimulatingJoypadStates ld a, $4 ld [wRoute24CurScript], a ld [wCurMapScript], a ret CoordsData_5140e: dbmapcoord 10, 15 db -1 ; end Route24Script4: ld a, [wSimulatedJoypadStatesIndex] and a ret nz call Delay3 ld a, $0 ld [wRoute24CurScript], a ld [wCurMapScript], a ret Route24Script3: ld a, [wIsInBattle] cp $ff jp z, Route24Script_513c0 call UpdateSprites ld a, $f0 ld [wJoyIgnore], a SetEvent EVENT_BEAT_ROUTE24_ROCKET ld a, $1 ldh [hSpriteIndexOrTextID], a call DisplayTextID xor a ld [wJoyIgnore], a ld a, $0 ld [wRoute24CurScript], a ld [wCurMapScript], a ret Route24_TextPointers: dw Route24Text1 dw Route24Text2 dw Route24Text3 dw Route24Text4 dw Route24Text5 dw Route24Text6 dw Route24Text7 dw PickUpItemText Route24TrainerHeaders: def_trainers 2 Route24TrainerHeader0: trainer EVENT_BEAT_ROUTE_24_TRAINER_0, 4, Route24BattleText1, Route24EndBattleText1, Route24AfterBattleText1 Route24TrainerHeader1: trainer EVENT_BEAT_ROUTE_24_TRAINER_1, 1, Route24BattleText2, Route24EndBattleText2, Route24AfterBattleText2 Route24TrainerHeader2: trainer EVENT_BEAT_ROUTE_24_TRAINER_2, 1, Route24BattleText3, Route24EndBattleText3, Route24AfterBattleText3 Route24TrainerHeader3: trainer EVENT_BEAT_ROUTE_24_TRAINER_3, 1, Route24BattleText4, Route24EndBattleText4, Route24AfterBattleText4 Route24TrainerHeader4: trainer EVENT_BEAT_ROUTE_24_TRAINER_4, 1, Route24BattleText5, Route24EndBattleText5, Route24AfterBattleText5 Route24TrainerHeader5: trainer EVENT_BEAT_ROUTE_24_TRAINER_5, 1, Route24BattleText6, Route24EndBattleText6, Route24AfterBattleText6 db -1 ; end Route24Text1: text_asm ResetEvent EVENT_NUGGET_REWARD_AVAILABLE CheckEvent EVENT_GOT_NUGGET jr nz, .got_item ld hl, Route24Text_51510 call PrintText lb bc, NUGGET, 1 call GiveItem jr nc, .bag_full SetEvent EVENT_GOT_NUGGET ld hl, Route24Text_5151a call PrintText ld hl, Route24Text_51526 call PrintText ld hl, wd72d set 6, [hl] set 7, [hl] ld hl, Route24Text_5152b ld de, Route24Text_5152b call SaveEndBattleTextPointers ldh a, [hSpriteIndexOrTextID] ld [wSpriteIndex], a call EngageMapTrainer call InitBattleEnemyParameters xor a ldh [hJoyHeld], a ld a, $3 ld [wRoute24CurScript], a ld [wCurMapScript], a jp TextScriptEnd .got_item ld hl, Route24Text_51530 call PrintText jp TextScriptEnd .bag_full ld hl, Route24Text_51521 call PrintText SetEvent EVENT_NUGGET_REWARD_AVAILABLE jp TextScriptEnd Route24Text_51510: text_far _Route24Text_51510 sound_get_item_1 text_far _Route24Text_51515 text_end Route24Text_5151a: text_far _Route24Text_5151a sound_get_item_1 text_promptbutton text_end Route24Text_51521: text_far _Route24Text_51521 text_end Route24Text_51526: text_far _Route24Text_51526 text_end Route24Text_5152b: text_far _Route24Text_5152b text_end Route24Text_51530: text_far _Route24Text_51530 text_end Route24Text2: text_asm ld hl, Route24TrainerHeader0 call TalkToTrainer jp TextScriptEnd Route24Text3: text_asm ld hl, Route24TrainerHeader1 call TalkToTrainer jp TextScriptEnd Route24Text4: text_asm ld hl, Route24TrainerHeader2 call TalkToTrainer jp TextScriptEnd Route24Text5: text_asm ld hl, Route24TrainerHeader3 call TalkToTrainer jp TextScriptEnd Route24Text6: text_asm ld hl, Route24TrainerHeader4 call TalkToTrainer jp TextScriptEnd Route24Text7: text_asm ld hl, Route24TrainerHeader5 call TalkToTrainer jp TextScriptEnd Route24BattleText1: text_far _Route24BattleText1 text_end Route24EndBattleText1: text_far _Route24EndBattleText1 text_end Route24AfterBattleText1: text_far _Route24AfterBattleText1 text_end Route24BattleText2: text_far _Route24BattleText2 text_end Route24EndBattleText2: text_far _Route24EndBattleText2 text_end Route24AfterBattleText2: text_far _Route24AfterBattleText2 text_end Route24BattleText3: text_far _Route24BattleText3 text_end Route24EndBattleText3: text_far _Route24EndBattleText3 text_end Route24AfterBattleText3: text_far _Route24AfterBattleText3 text_end Route24BattleText4: text_far _Route24BattleText4 text_end Route24EndBattleText4: text_far _Route24EndBattleText4 text_end Route24AfterBattleText4: text_far _Route24AfterBattleText4 text_end Route24BattleText5: text_far _Route24BattleText5 text_end Route24EndBattleText5: text_far _Route24EndBattleText5 text_end Route24AfterBattleText5: text_far _Route24AfterBattleText5 text_end Route24BattleText6: text_far _Route24BattleText6 text_end Route24EndBattleText6: text_far _Route24EndBattleText6 text_end Route24AfterBattleText6: text_far _Route24AfterBattleText6 text_end
/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * 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 the copyright holders 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. */ #include "dev/net/sinic.hh" #include <deque> #include <limits> #include <string> #include "base/compiler.hh" #include "base/debug.hh" #include "base/inet.hh" #include "base/types.hh" #include "debug/EthernetAll.hh" #include "dev/net/etherlink.hh" #include "mem/packet.hh" #include "mem/packet_access.hh" #include "sim/eventq.hh" #include "sim/stats.hh" using namespace std; using namespace Net; namespace Sinic { const char *RxStateStrings[] = { "rxIdle", "rxFifoBlock", "rxBeginCopy", "rxCopy", "rxCopyDone" }; const char *TxStateStrings[] = { "txIdle", "txFifoBlock", "txBeginCopy", "txCopy", "txCopyDone" }; /////////////////////////////////////////////////////////////////////// // // Sinic PCI Device // Base::Base(const Params &p) : EtherDevBase(p), rxEnable(false), txEnable(false), intrDelay(p.intr_delay), intrTick(0), cpuIntrEnable(false), cpuPendingIntr(false), intrEvent(0), interface(NULL) { } Device::Device(const Params &p) : Base(p), rxUnique(0), txUnique(0), virtualRegs(p.virtual_count < 1 ? 1 : p.virtual_count), rxFifo(p.rx_fifo_size), txFifo(p.tx_fifo_size), rxKickTick(0), txKickTick(0), txEvent([this]{ txEventTransmit(); }, name()), rxDmaEvent([this]{ rxDmaDone(); }, name()), txDmaEvent([this]{ txDmaDone(); }, name()), dmaReadDelay(p.dma_read_delay), dmaReadFactor(p.dma_read_factor), dmaWriteDelay(p.dma_write_delay), dmaWriteFactor(p.dma_write_factor), sinicDeviceStats(this) { interface = new Interface(name() + ".int0", this); reset(); } Device::~Device() {} Device::DeviceStats::DeviceStats(Stats::Group *parent) : Stats::Group(parent, "SinicDevice"), ADD_STAT(totalVnicDistance, "Total vnic distance"), ADD_STAT(numVnicDistance, "Number of vnic distance measurements"), ADD_STAT(maxVnicDistance, "Maximum vnic distance"), ADD_STAT(avgVnicDistance, "Average vnic distance", totalVnicDistance / numVnicDistance), _maxVnicDistance(0) { } void Device::resetStats() { Base::resetStats(); sinicDeviceStats._maxVnicDistance = 0; } Port & Device::getPort(const std::string &if_name, PortID idx) { if (if_name == "interface") return *interface; return EtherDevBase::getPort(if_name, idx); } void Device::prepareIO(ContextID cpu, int index) { int size = virtualRegs.size(); if (index > size) panic("Trying to access a vnic that doesn't exist %d > %d\n", index, size); } //add stats for head of line blocking //add stats for average fifo length //add stats for average number of vnics busy void Device::prepareRead(ContextID cpu, int index) { using namespace Regs; prepareIO(cpu, index); VirtualReg &vnic = virtualRegs[index]; // update rx registers uint64_t rxdone = vnic.RxDone; rxdone = set_RxDone_Packets(rxdone, rxFifo.countPacketsAfter(rxFifoPtr)); rxdone = set_RxDone_Empty(rxdone, rxFifo.empty()); rxdone = set_RxDone_High(rxdone, rxFifo.size() > regs.RxFifoHigh); rxdone = set_RxDone_NotHigh(rxdone, rxLow); regs.RxData = vnic.RxData; regs.RxDone = rxdone; regs.RxWait = rxdone; // update tx regsiters uint64_t txdone = vnic.TxDone; txdone = set_TxDone_Packets(txdone, txFifo.packets()); txdone = set_TxDone_Full(txdone, txFifo.avail() < regs.TxMaxCopy); txdone = set_TxDone_Low(txdone, txFifo.size() < regs.TxFifoLow); regs.TxData = vnic.TxData; regs.TxDone = txdone; regs.TxWait = txdone; int head = 0xffff; if (!rxFifo.empty()) { int vnic = rxFifo.begin()->priv; if (vnic != -1 && virtualRegs[vnic].rxPacketOffset > 0) head = vnic; } regs.RxStatus = set_RxStatus_Head(regs.RxStatus, head); regs.RxStatus = set_RxStatus_Busy(regs.RxStatus, rxBusyCount); regs.RxStatus = set_RxStatus_Mapped(regs.RxStatus, rxMappedCount); regs.RxStatus = set_RxStatus_Dirty(regs.RxStatus, rxDirtyCount); } void Device::prepareWrite(ContextID cpu, int index) { prepareIO(cpu, index); } /** * I/O read of device register */ Tick Device::read(PacketPtr pkt) { assert(config.command & PCI_CMD_MSE); Addr daddr = pkt->getAddr(); assert(BARs[0]->range().contains(daddr)); daddr -= BARs[0]->addr(); ContextID cpu = pkt->req->contextId(); Addr index = daddr >> Regs::VirtualShift; Addr raddr = daddr & Regs::VirtualMask; if (!regValid(raddr)) panic("invalid register: cpu=%d vnic=%d da=%#x pa=%#x size=%d", cpu, index, daddr, pkt->getAddr(), pkt->getSize()); const Regs::Info &info = regInfo(raddr); if (!info.read) panic("read %s (write only): " "cpu=%d vnic=%d da=%#x pa=%#x size=%d", info.name, cpu, index, daddr, pkt->getAddr(), pkt->getSize()); panic("read %s (invalid size): " "cpu=%d vnic=%d da=%#x pa=%#x size=%d", info.name, cpu, index, daddr, pkt->getAddr(), pkt->getSize()); prepareRead(cpu, index); M5_VAR_USED uint64_t value = 0; if (pkt->getSize() == 4) { uint32_t reg = regData32(raddr); pkt->setLE(reg); value = reg; } if (pkt->getSize() == 8) { uint64_t reg = regData64(raddr); pkt->setLE(reg); value = reg; } DPRINTF(EthernetPIO, "read %s: cpu=%d vnic=%d da=%#x pa=%#x size=%d val=%#x\n", info.name, cpu, index, daddr, pkt->getAddr(), pkt->getSize(), value); // reading the interrupt status register has the side effect of // clearing it if (raddr == Regs::IntrStatus) devIntrClear(); return pioDelay; } /** * IPR read of device register Fault Device::iprRead(Addr daddr, ContextID cpu, uint64_t &result) { if (!regValid(daddr)) panic("invalid address: da=%#x", daddr); const Regs::Info &info = regInfo(daddr); if (!info.read) panic("reading %s (write only): cpu=%d da=%#x", info.name, cpu, daddr); DPRINTF(EthernetPIO, "IPR read %s: cpu=%d da=%#x\n", info.name, cpu, daddr); prepareRead(cpu, 0); if (info.size == 4) result = regData32(daddr); if (info.size == 8) result = regData64(daddr); DPRINTF(EthernetPIO, "IPR read %s: cpu=%s da=%#x val=%#x\n", info.name, cpu, result); return NoFault; } */ /** * I/O write of device register */ Tick Device::write(PacketPtr pkt) { assert(config.command & PCI_CMD_MSE); Addr daddr = pkt->getAddr(); assert(BARs[0]->range().contains(daddr)); daddr -= BARs[0]->addr(); ContextID cpu = pkt->req->contextId(); Addr index = daddr >> Regs::VirtualShift; Addr raddr = daddr & Regs::VirtualMask; if (!regValid(raddr)) panic("invalid register: cpu=%d, da=%#x pa=%#x size=%d", cpu, daddr, pkt->getAddr(), pkt->getSize()); const Regs::Info &info = regInfo(raddr); if (!info.write) panic("write %s (read only): " "cpu=%d vnic=%d da=%#x pa=%#x size=%d", info.name, cpu, index, daddr, pkt->getAddr(), pkt->getSize()); if (pkt->getSize() != info.size) panic("write %s (invalid size): " "cpu=%d vnic=%d da=%#x pa=%#x size=%d", info.name, cpu, index, daddr, pkt->getAddr(), pkt->getSize()); VirtualReg &vnic = virtualRegs[index]; DPRINTF(EthernetPIO, "write %s vnic %d: cpu=%d val=%#x da=%#x pa=%#x size=%d\n", info.name, index, cpu, info.size == 4 ? pkt->getLE<uint32_t>() : pkt->getLE<uint64_t>(), daddr, pkt->getAddr(), pkt->getSize()); prepareWrite(cpu, index); switch (raddr) { case Regs::Config: changeConfig(pkt->getLE<uint32_t>()); break; case Regs::Command: command(pkt->getLE<uint32_t>()); break; case Regs::IntrStatus: devIntrClear(regs.IntrStatus & pkt->getLE<uint32_t>()); break; case Regs::IntrMask: devIntrChangeMask(pkt->getLE<uint32_t>()); break; case Regs::RxData: if (Regs::get_RxDone_Busy(vnic.RxDone)) panic("receive machine busy with another request! rxState=%s", RxStateStrings[rxState]); vnic.rxUnique = rxUnique++; vnic.RxDone = Regs::RxDone_Busy; vnic.RxData = pkt->getLE<uint64_t>(); rxBusyCount++; if (Regs::get_RxData_Vaddr(pkt->getLE<uint64_t>())) { panic("vtophys not implemented in newmem"); } else { DPRINTF(EthernetPIO, "write RxData vnic %d (rxunique %d)\n", index, vnic.rxUnique); } if (vnic.rxIndex == rxFifo.end()) { DPRINTF(EthernetPIO, "request new packet...appending to rxList\n"); rxList.push_back(index); } else { DPRINTF(EthernetPIO, "packet exists...appending to rxBusy\n"); rxBusy.push_back(index); } if (rxEnable && (rxState == rxIdle || rxState == rxFifoBlock)) { rxState = rxFifoBlock; rxKick(); } break; case Regs::TxData: if (Regs::get_TxDone_Busy(vnic.TxDone)) panic("transmit machine busy with another request! txState=%s", TxStateStrings[txState]); vnic.txUnique = txUnique++; vnic.TxDone = Regs::TxDone_Busy; if (Regs::get_TxData_Vaddr(pkt->getLE<uint64_t>())) { panic("vtophys won't work here in newmem.\n"); } else { DPRINTF(EthernetPIO, "write TxData vnic %d (txunique %d)\n", index, vnic.txUnique); } if (txList.empty() || txList.front() != index) txList.push_back(index); if (txEnable && txState == txIdle && txList.front() == index) { txState = txFifoBlock; txKick(); } break; } return pioDelay; } void Device::devIntrPost(uint32_t interrupts) { if ((interrupts & Regs::Intr_Res)) panic("Cannot set a reserved interrupt"); regs.IntrStatus |= interrupts; DPRINTF(EthernetIntr, "interrupt written to intStatus: intr=%#x status=%#x mask=%#x\n", interrupts, regs.IntrStatus, regs.IntrMask); interrupts = regs.IntrStatus & regs.IntrMask; // Intr_RxHigh is special, we only signal it if we've emptied the fifo // and then filled it above the high watermark if (rxEmpty) rxEmpty = false; else interrupts &= ~Regs::Intr_RxHigh; // Intr_TxLow is special, we only signal it if we've filled up the fifo // and then dropped below the low watermark if (txFull) txFull = false; else interrupts &= ~Regs::Intr_TxLow; if (interrupts) { Tick when = curTick(); if ((interrupts & Regs::Intr_NoDelay) == 0) when += intrDelay; cpuIntrPost(when); } } void Device::devIntrClear(uint32_t interrupts) { if ((interrupts & Regs::Intr_Res)) panic("Cannot clear a reserved interrupt"); regs.IntrStatus &= ~interrupts; DPRINTF(EthernetIntr, "interrupt cleared from intStatus: intr=%x status=%x mask=%x\n", interrupts, regs.IntrStatus, regs.IntrMask); if (!(regs.IntrStatus & regs.IntrMask)) cpuIntrClear(); } void Device::devIntrChangeMask(uint32_t newmask) { if (regs.IntrMask == newmask) return; regs.IntrMask = newmask; DPRINTF(EthernetIntr, "interrupt mask changed: intStatus=%x intMask=%x masked=%x\n", regs.IntrStatus, regs.IntrMask, regs.IntrStatus & regs.IntrMask); if (regs.IntrStatus & regs.IntrMask) cpuIntrPost(curTick()); else cpuIntrClear(); } void Base::cpuIntrPost(Tick when) { // If the interrupt you want to post is later than an interrupt // already scheduled, just let it post in the coming one and don't // schedule another. // HOWEVER, must be sure that the scheduled intrTick is in the // future (this was formerly the source of a bug) /** * @todo this warning should be removed and the intrTick code should * be fixed. */ assert(when >= curTick()); assert(intrTick >= curTick() || intrTick == 0); if (!cpuIntrEnable) { DPRINTF(EthernetIntr, "interrupts not enabled.\n", intrTick); return; } if (when > intrTick && intrTick != 0) { DPRINTF(EthernetIntr, "don't need to schedule event...intrTick=%d\n", intrTick); return; } intrTick = when; if (intrTick < curTick()) { intrTick = curTick(); } DPRINTF(EthernetIntr, "going to schedule an interrupt for intrTick=%d\n", intrTick); if (intrEvent) intrEvent->squash(); intrEvent = new EventFunctionWrapper([this]{ cpuInterrupt(); }, name(), true); schedule(intrEvent, intrTick); } void Base::cpuInterrupt() { assert(intrTick == curTick()); // Whether or not there's a pending interrupt, we don't care about // it anymore intrEvent = 0; intrTick = 0; // Don't send an interrupt if there's already one if (cpuPendingIntr) { DPRINTF(EthernetIntr, "would send an interrupt now, but there's already pending\n"); } else { // Send interrupt cpuPendingIntr = true; DPRINTF(EthernetIntr, "posting interrupt\n"); intrPost(); } } void Base::cpuIntrClear() { if (!cpuPendingIntr) return; if (intrEvent) { intrEvent->squash(); intrEvent = 0; } intrTick = 0; cpuPendingIntr = false; DPRINTF(EthernetIntr, "clearing cchip interrupt\n"); intrClear(); } bool Base::cpuIntrPending() const { return cpuPendingIntr; } void Device::changeConfig(uint32_t newconf) { uint32_t changed = regs.Config ^ newconf; if (!changed) return; regs.Config = newconf; if ((changed & Regs::Config_IntEn)) { cpuIntrEnable = regs.Config & Regs::Config_IntEn; if (cpuIntrEnable) { if (regs.IntrStatus & regs.IntrMask) cpuIntrPost(curTick()); } else { cpuIntrClear(); } } if ((changed & Regs::Config_TxEn)) { txEnable = regs.Config & Regs::Config_TxEn; if (txEnable) txKick(); } if ((changed & Regs::Config_RxEn)) { rxEnable = regs.Config & Regs::Config_RxEn; if (rxEnable) rxKick(); } } void Device::command(uint32_t command) { if (command & Regs::Command_Intr) devIntrPost(Regs::Intr_Soft); if (command & Regs::Command_Reset) reset(); } void Device::reset() { using namespace Regs; memset(&regs, 0, sizeof(regs)); regs.Config = 0; if (params().rx_thread) regs.Config |= Config_RxThread; if (params().tx_thread) regs.Config |= Config_TxThread; if (params().rss) regs.Config |= Config_RSS; if (params().zero_copy) regs.Config |= Config_ZeroCopy; if (params().delay_copy) regs.Config |= Config_DelayCopy; if (params().virtual_addr) regs.Config |= Config_Vaddr; if (params().delay_copy && params().zero_copy) panic("Can't delay copy and zero copy"); regs.IntrMask = Intr_Soft | Intr_RxHigh | Intr_RxPacket | Intr_TxLow; regs.RxMaxCopy = params().rx_max_copy; regs.TxMaxCopy = params().tx_max_copy; regs.ZeroCopySize = params().zero_copy_size; regs.ZeroCopyMark = params().zero_copy_threshold; regs.VirtualCount = params().virtual_count; regs.RxMaxIntr = params().rx_max_intr; regs.RxFifoSize = params().rx_fifo_size; regs.TxFifoSize = params().tx_fifo_size; regs.RxFifoLow = params().rx_fifo_low_mark; regs.TxFifoLow = params().tx_fifo_threshold; regs.RxFifoHigh = params().rx_fifo_threshold; regs.TxFifoHigh = params().tx_fifo_high_mark; regs.HwAddr = params().hardware_address; if (regs.RxMaxCopy < regs.ZeroCopyMark) panic("Must be able to copy at least as many bytes as the threshold"); if (regs.ZeroCopySize >= regs.ZeroCopyMark) panic("The number of bytes to copy must be less than the threshold"); rxList.clear(); rxBusy.clear(); rxActive = -1; txList.clear(); rxBusyCount = 0; rxDirtyCount = 0; rxMappedCount = 0; rxState = rxIdle; txState = txIdle; rxFifo.clear(); rxFifoPtr = rxFifo.end(); txFifo.clear(); rxEmpty = false; rxLow = true; txFull = false; int size = virtualRegs.size(); virtualRegs.clear(); virtualRegs.resize(size); for (int i = 0; i < size; ++i) virtualRegs[i].rxIndex = rxFifo.end(); } void Device::rxDmaDone() { assert(rxState == rxCopy); rxState = rxCopyDone; DPRINTF(EthernetDMA, "end rx dma write paddr=%#x len=%d\n", rxDmaAddr, rxDmaLen); DDUMP(EthernetData, rxDmaData, rxDmaLen); // If the transmit state machine has a pending DMA, let it go first if (txState == txBeginCopy) txKick(); rxKick(); } void Device::rxKick() { VirtualReg *vnic = NULL; DPRINTF(EthernetSM, "rxKick: rxState=%s (rxFifo.size=%d)\n", RxStateStrings[rxState], rxFifo.size()); if (rxKickTick > curTick()) { DPRINTF(EthernetSM, "rxKick: exiting, can't run till %d\n", rxKickTick); return; } next: rxFifo.check(); if (rxState == rxIdle) goto exit; if (rxActive == -1) { if (rxState != rxFifoBlock) panic("no active vnic while in state %s", RxStateStrings[rxState]); DPRINTF(EthernetSM, "processing rxState=%s\n", RxStateStrings[rxState]); } else { vnic = &virtualRegs[rxActive]; DPRINTF(EthernetSM, "processing rxState=%s for vnic %d (rxunique %d)\n", RxStateStrings[rxState], rxActive, vnic->rxUnique); } switch (rxState) { case rxFifoBlock: if (DTRACE(EthernetSM)) { PacketFifo::iterator end = rxFifo.end(); int size = virtualRegs.size(); for (int i = 0; i < size; ++i) { VirtualReg *vn = &virtualRegs[i]; bool busy = Regs::get_RxDone_Busy(vn->RxDone); if (vn->rxIndex != end) { #ifndef NDEBUG bool dirty = vn->rxPacketOffset > 0; const char *status; if (busy && dirty) status = "busy,dirty"; else if (busy) status = "busy"; else if (dirty) status = "dirty"; else status = "mapped"; DPRINTF(EthernetSM, "vnic %d %s (rxunique %d), packet %d, slack %d\n", i, status, vn->rxUnique, rxFifo.countPacketsBefore(vn->rxIndex), vn->rxIndex->slack); #endif } else if (busy) { DPRINTF(EthernetSM, "vnic %d unmapped (rxunique %d)\n", i, vn->rxUnique); } } } if (!rxBusy.empty()) { rxActive = rxBusy.front(); rxBusy.pop_front(); vnic = &virtualRegs[rxActive]; if (vnic->rxIndex == rxFifo.end()) panic("continuing vnic without packet\n"); DPRINTF(EthernetSM, "continue processing for vnic %d (rxunique %d)\n", rxActive, vnic->rxUnique); rxState = rxBeginCopy; int vnic_distance = rxFifo.countPacketsBefore(vnic->rxIndex); sinicDeviceStats.totalVnicDistance += vnic_distance; sinicDeviceStats.numVnicDistance += 1; if (vnic_distance > sinicDeviceStats._maxVnicDistance) { sinicDeviceStats.maxVnicDistance = vnic_distance; sinicDeviceStats._maxVnicDistance = vnic_distance; } break; } if (rxFifoPtr == rxFifo.end()) { DPRINTF(EthernetSM, "receive waiting for data. Nothing to do.\n"); goto exit; } if (rxList.empty()) panic("Not idle, but nothing to do!"); assert(!rxFifo.empty()); rxActive = rxList.front(); rxList.pop_front(); vnic = &virtualRegs[rxActive]; DPRINTF(EthernetSM, "processing new packet for vnic %d (rxunique %d)\n", rxActive, vnic->rxUnique); // Grab a new packet from the fifo. vnic->rxIndex = rxFifoPtr++; vnic->rxIndex->priv = rxActive; vnic->rxPacketOffset = 0; vnic->rxPacketBytes = vnic->rxIndex->packet->length; assert(vnic->rxPacketBytes); rxMappedCount++; vnic->rxDoneData = 0; /* scope for variables */ { IpPtr ip(vnic->rxIndex->packet); if (ip) { DPRINTF(Ethernet, "ID is %d\n", ip->id()); vnic->rxDoneData |= Regs::RxDone_IpPacket; etherDeviceStats.rxIpChecksums++; if (cksum(ip) != 0) { DPRINTF(EthernetCksum, "Rx IP Checksum Error\n"); vnic->rxDoneData |= Regs::RxDone_IpError; } TcpPtr tcp(ip); UdpPtr udp(ip); if (tcp) { DPRINTF(Ethernet, "Src Port=%d, Dest Port=%d, Seq=%d, Ack=%d\n", tcp->sport(), tcp->dport(), tcp->seq(), tcp->ack()); vnic->rxDoneData |= Regs::RxDone_TcpPacket; etherDeviceStats.rxTcpChecksums++; if (cksum(tcp) != 0) { DPRINTF(EthernetCksum, "Rx TCP Checksum Error\n"); vnic->rxDoneData |= Regs::RxDone_TcpError; } } else if (udp) { vnic->rxDoneData |= Regs::RxDone_UdpPacket; etherDeviceStats.rxUdpChecksums++; if (cksum(udp) != 0) { DPRINTF(EthernetCksum, "Rx UDP Checksum Error\n"); vnic->rxDoneData |= Regs::RxDone_UdpError; } } } } rxState = rxBeginCopy; break; case rxBeginCopy: if (dmaPending() || drainState() != DrainState::Running) goto exit; rxDmaAddr = pciToDma(Regs::get_RxData_Addr(vnic->RxData)); rxDmaLen = min<unsigned>(Regs::get_RxData_Len(vnic->RxData), vnic->rxPacketBytes); /* * if we're doing zero/delay copy and we're below the fifo * threshold, see if we should try to do the zero/defer copy */ if ((Regs::get_Config_ZeroCopy(regs.Config) || Regs::get_Config_DelayCopy(regs.Config)) && !Regs::get_RxData_NoDelay(vnic->RxData) && rxLow) { if (rxDmaLen > regs.ZeroCopyMark) rxDmaLen = regs.ZeroCopySize; } rxDmaData = vnic->rxIndex->packet->data + vnic->rxPacketOffset; rxState = rxCopy; if (rxDmaAddr == 1LL) { rxState = rxCopyDone; break; } dmaWrite(rxDmaAddr, rxDmaLen, &rxDmaEvent, rxDmaData); break; case rxCopy: DPRINTF(EthernetSM, "receive machine still copying\n"); goto exit; case rxCopyDone: vnic->RxDone = vnic->rxDoneData; vnic->RxDone |= Regs::RxDone_Complete; rxBusyCount--; if (vnic->rxPacketBytes == rxDmaLen) { if (vnic->rxPacketOffset) rxDirtyCount--; // Packet is complete. Indicate how many bytes were copied vnic->RxDone = Regs::set_RxDone_CopyLen(vnic->RxDone, rxDmaLen); DPRINTF(EthernetSM, "rxKick: packet complete on vnic %d (rxunique %d)\n", rxActive, vnic->rxUnique); rxFifo.remove(vnic->rxIndex); vnic->rxIndex = rxFifo.end(); rxMappedCount--; } else { if (!vnic->rxPacketOffset) rxDirtyCount++; vnic->rxPacketBytes -= rxDmaLen; vnic->rxPacketOffset += rxDmaLen; vnic->RxDone |= Regs::RxDone_More; vnic->RxDone = Regs::set_RxDone_CopyLen(vnic->RxDone, vnic->rxPacketBytes); DPRINTF(EthernetSM, "rxKick: packet not complete on vnic %d (rxunique %d): " "%d bytes left\n", rxActive, vnic->rxUnique, vnic->rxPacketBytes); } rxActive = -1; rxState = rxBusy.empty() && rxList.empty() ? rxIdle : rxFifoBlock; if (rxFifo.empty()) { devIntrPost(Regs::Intr_RxEmpty); rxEmpty = true; } if (rxFifo.size() < regs.RxFifoLow) rxLow = true; if (rxFifo.size() > regs.RxFifoHigh) rxLow = false; devIntrPost(Regs::Intr_RxDMA); break; default: panic("Invalid rxState!"); } DPRINTF(EthernetSM, "entering next rxState=%s\n", RxStateStrings[rxState]); goto next; exit: /** * @todo do we want to schedule a future kick? */ DPRINTF(EthernetSM, "rx state machine exited rxState=%s\n", RxStateStrings[rxState]); } void Device::txDmaDone() { assert(txState == txCopy); txState = txCopyDone; DPRINTF(EthernetDMA, "tx dma read paddr=%#x len=%d\n", txDmaAddr, txDmaLen); DDUMP(EthernetData, txDmaData, txDmaLen); // If the receive state machine has a pending DMA, let it go first if (rxState == rxBeginCopy) rxKick(); txKick(); } void Device::transmit() { if (txFifo.empty()) { DPRINTF(Ethernet, "nothing to transmit\n"); return; } uint32_t interrupts; EthPacketPtr packet = txFifo.front(); if (!interface->sendPacket(packet)) { DPRINTF(Ethernet, "Packet Transmit: failed txFifo available %d\n", txFifo.avail()); return; } txFifo.pop(); #if TRACING_ON if (DTRACE(Ethernet)) { IpPtr ip(packet); if (ip) { DPRINTF(Ethernet, "ID is %d\n", ip->id()); TcpPtr tcp(ip); if (tcp) { DPRINTF(Ethernet, "Src Port=%d, Dest Port=%d, Seq=%d, Ack=%d\n", tcp->sport(), tcp->dport(), tcp->seq(), tcp->ack()); } } } #endif DDUMP(EthernetData, packet->data, packet->length); etherDeviceStats.txBytes += packet->length; etherDeviceStats.txPackets++; DPRINTF(Ethernet, "Packet Transmit: successful txFifo Available %d\n", txFifo.avail()); interrupts = Regs::Intr_TxPacket; if (txFifo.size() < regs.TxFifoLow) interrupts |= Regs::Intr_TxLow; devIntrPost(interrupts); } void Device::txKick() { VirtualReg *vnic; DPRINTF(EthernetSM, "txKick: txState=%s (txFifo.size=%d)\n", TxStateStrings[txState], txFifo.size()); if (txKickTick > curTick()) { DPRINTF(EthernetSM, "txKick: exiting, can't run till %d\n", txKickTick); return; } next: if (txState == txIdle) goto exit; assert(!txList.empty()); vnic = &virtualRegs[txList.front()]; switch (txState) { case txFifoBlock: assert(Regs::get_TxDone_Busy(vnic->TxDone)); if (!txPacket) { // Grab a new packet from the fifo. txPacket = make_shared<EthPacketData>(16384); txPacketOffset = 0; } if (txFifo.avail() - txPacket->length < Regs::get_TxData_Len(vnic->TxData)) { DPRINTF(EthernetSM, "transmit fifo full. Nothing to do.\n"); goto exit; } txState = txBeginCopy; break; case txBeginCopy: if (dmaPending() || drainState() != DrainState::Running) goto exit; txDmaAddr = pciToDma(Regs::get_TxData_Addr(vnic->TxData)); txDmaLen = Regs::get_TxData_Len(vnic->TxData); txDmaData = txPacket->data + txPacketOffset; txState = txCopy; dmaRead(txDmaAddr, txDmaLen, &txDmaEvent, txDmaData); break; case txCopy: DPRINTF(EthernetSM, "transmit machine still copying\n"); goto exit; case txCopyDone: vnic->TxDone = txDmaLen | Regs::TxDone_Complete; txPacket->simLength += txDmaLen; txPacket->length += txDmaLen; if ((vnic->TxData & Regs::TxData_More)) { txPacketOffset += txDmaLen; txState = txIdle; devIntrPost(Regs::Intr_TxDMA); break; } assert(txPacket->length <= txFifo.avail()); if ((vnic->TxData & Regs::TxData_Checksum)) { IpPtr ip(txPacket); if (ip) { TcpPtr tcp(ip); if (tcp) { tcp->sum(0); tcp->sum(cksum(tcp)); etherDeviceStats.txTcpChecksums++; } UdpPtr udp(ip); if (udp) { udp->sum(0); udp->sum(cksum(udp)); etherDeviceStats.txUdpChecksums++; } ip->sum(0); ip->sum(cksum(ip)); etherDeviceStats.txIpChecksums++; } } txFifo.push(txPacket); if (txFifo.avail() < regs.TxMaxCopy) { devIntrPost(Regs::Intr_TxFull); txFull = true; } txPacket = 0; transmit(); txList.pop_front(); txState = txList.empty() ? txIdle : txFifoBlock; devIntrPost(Regs::Intr_TxDMA); break; default: panic("Invalid txState!"); } DPRINTF(EthernetSM, "entering next txState=%s\n", TxStateStrings[txState]); goto next; exit: /** * @todo do we want to schedule a future kick? */ DPRINTF(EthernetSM, "tx state machine exited txState=%s\n", TxStateStrings[txState]); } void Device::transferDone() { if (txFifo.empty()) { DPRINTF(Ethernet, "transfer complete: txFifo empty...nothing to do\n"); return; } DPRINTF(Ethernet, "transfer complete: data in txFifo...schedule xmit\n"); reschedule(txEvent, clockEdge(Cycles(1)), true); } bool Device::rxFilter(const EthPacketPtr &packet) { if (!Regs::get_Config_Filter(regs.Config)) return false; panic("receive filter not implemented\n"); bool drop = true; return drop; } bool Device::recvPacket(EthPacketPtr packet) { etherDeviceStats.rxBytes += packet->length; etherDeviceStats.rxPackets++; DPRINTF(Ethernet, "Receiving packet from wire, rxFifo Available is %d\n", rxFifo.avail()); if (!rxEnable) { DPRINTF(Ethernet, "receive disabled...packet dropped\n"); return true; } if (rxFilter(packet)) { DPRINTF(Ethernet, "packet filtered...dropped\n"); return true; } if (rxFifo.size() >= regs.RxFifoHigh) devIntrPost(Regs::Intr_RxHigh); if (!rxFifo.push(packet)) { DPRINTF(Ethernet, "packet will not fit in receive buffer...packet dropped\n"); return false; } // If we were at the last element, back up one ot go to the new // last element of the list. if (rxFifoPtr == rxFifo.end()) --rxFifoPtr; devIntrPost(Regs::Intr_RxPacket); rxKick(); return true; } void Device::drainResume() { Drainable::drainResume(); // During drain we could have left the state machines in a waiting state and // they wouldn't get out until some other event occured to kick them. // This way they'll get out immediately txKick(); rxKick(); } //===================================================================== // // void Base::serialize(CheckpointOut &cp) const { // Serialize the PciDevice base class PciDevice::serialize(cp); SERIALIZE_SCALAR(rxEnable); SERIALIZE_SCALAR(txEnable); SERIALIZE_SCALAR(cpuIntrEnable); /* * Keep track of pending interrupt status. */ SERIALIZE_SCALAR(intrTick); SERIALIZE_SCALAR(cpuPendingIntr); Tick intrEventTick = 0; if (intrEvent) intrEventTick = intrEvent->when(); SERIALIZE_SCALAR(intrEventTick); } void Base::unserialize(CheckpointIn &cp) { // Unserialize the PciDevice base class PciDevice::unserialize(cp); UNSERIALIZE_SCALAR(rxEnable); UNSERIALIZE_SCALAR(txEnable); UNSERIALIZE_SCALAR(cpuIntrEnable); /* * Keep track of pending interrupt status. */ UNSERIALIZE_SCALAR(intrTick); UNSERIALIZE_SCALAR(cpuPendingIntr); Tick intrEventTick; UNSERIALIZE_SCALAR(intrEventTick); if (intrEventTick) { intrEvent = new EventFunctionWrapper([this]{ cpuInterrupt(); }, name(), true); schedule(intrEvent, intrEventTick); } } void Device::serialize(CheckpointOut &cp) const { int count; // Serialize the PciDevice base class Base::serialize(cp); if (rxState == rxCopy) panic("can't serialize with an in flight dma request rxState=%s", RxStateStrings[rxState]); if (txState == txCopy) panic("can't serialize with an in flight dma request txState=%s", TxStateStrings[txState]); /* * Serialize the device registers that could be modified by the OS. */ SERIALIZE_SCALAR(regs.Config); SERIALIZE_SCALAR(regs.IntrStatus); SERIALIZE_SCALAR(regs.IntrMask); SERIALIZE_SCALAR(regs.RxData); SERIALIZE_SCALAR(regs.TxData); /* * Serialize the virtual nic state */ int virtualRegsSize = virtualRegs.size(); SERIALIZE_SCALAR(virtualRegsSize); for (int i = 0; i < virtualRegsSize; ++i) { const VirtualReg *vnic = &virtualRegs[i]; std::string reg = csprintf("vnic%d", i); paramOut(cp, reg + ".RxData", vnic->RxData); paramOut(cp, reg + ".RxDone", vnic->RxDone); paramOut(cp, reg + ".TxData", vnic->TxData); paramOut(cp, reg + ".TxDone", vnic->TxDone); bool rxPacketExists = vnic->rxIndex != rxFifo.end(); paramOut(cp, reg + ".rxPacketExists", rxPacketExists); if (rxPacketExists) { int rxPacket = 0; auto i = rxFifo.begin(); while (i != vnic->rxIndex) { assert(i != rxFifo.end()); ++i; ++rxPacket; } paramOut(cp, reg + ".rxPacket", rxPacket); paramOut(cp, reg + ".rxPacketOffset", vnic->rxPacketOffset); paramOut(cp, reg + ".rxPacketBytes", vnic->rxPacketBytes); } paramOut(cp, reg + ".rxDoneData", vnic->rxDoneData); } int rxFifoPtr = -1; if (this->rxFifoPtr != rxFifo.end()) rxFifoPtr = rxFifo.countPacketsBefore(this->rxFifoPtr); SERIALIZE_SCALAR(rxFifoPtr); SERIALIZE_SCALAR(rxActive); SERIALIZE_SCALAR(rxBusyCount); SERIALIZE_SCALAR(rxDirtyCount); SERIALIZE_SCALAR(rxMappedCount); VirtualList::const_iterator i, end; for (count = 0, i = rxList.begin(), end = rxList.end(); i != end; ++i) paramOut(cp, csprintf("rxList%d", count++), *i); int rxListSize = count; SERIALIZE_SCALAR(rxListSize); for (count = 0, i = rxBusy.begin(), end = rxBusy.end(); i != end; ++i) paramOut(cp, csprintf("rxBusy%d", count++), *i); int rxBusySize = count; SERIALIZE_SCALAR(rxBusySize); for (count = 0, i = txList.begin(), end = txList.end(); i != end; ++i) paramOut(cp, csprintf("txList%d", count++), *i); int txListSize = count; SERIALIZE_SCALAR(txListSize); /* * Serialize rx state machine */ int rxState = this->rxState; SERIALIZE_SCALAR(rxState); SERIALIZE_SCALAR(rxEmpty); SERIALIZE_SCALAR(rxLow); rxFifo.serialize("rxFifo", cp); /* * Serialize tx state machine */ int txState = this->txState; SERIALIZE_SCALAR(txState); SERIALIZE_SCALAR(txFull); txFifo.serialize("txFifo", cp); bool txPacketExists = txPacket != nullptr; SERIALIZE_SCALAR(txPacketExists); if (txPacketExists) { txPacket->serialize("txPacket", cp); SERIALIZE_SCALAR(txPacketOffset); SERIALIZE_SCALAR(txPacketBytes); } /* * If there's a pending transmit, store the time so we can * reschedule it later */ Tick transmitTick = txEvent.scheduled() ? txEvent.when() - curTick() : 0; SERIALIZE_SCALAR(transmitTick); } void Device::unserialize(CheckpointIn &cp) { // Unserialize the PciDevice base class Base::unserialize(cp); /* * Unserialize the device registers that may have been written by the OS. */ UNSERIALIZE_SCALAR(regs.Config); UNSERIALIZE_SCALAR(regs.IntrStatus); UNSERIALIZE_SCALAR(regs.IntrMask); UNSERIALIZE_SCALAR(regs.RxData); UNSERIALIZE_SCALAR(regs.TxData); UNSERIALIZE_SCALAR(rxActive); UNSERIALIZE_SCALAR(rxBusyCount); UNSERIALIZE_SCALAR(rxDirtyCount); UNSERIALIZE_SCALAR(rxMappedCount); int rxListSize; UNSERIALIZE_SCALAR(rxListSize); rxList.clear(); for (int i = 0; i < rxListSize; ++i) { int value; paramIn(cp, csprintf("rxList%d", i), value); rxList.push_back(value); } int rxBusySize; UNSERIALIZE_SCALAR(rxBusySize); rxBusy.clear(); for (int i = 0; i < rxBusySize; ++i) { int value; paramIn(cp, csprintf("rxBusy%d", i), value); rxBusy.push_back(value); } int txListSize; UNSERIALIZE_SCALAR(txListSize); txList.clear(); for (int i = 0; i < txListSize; ++i) { int value; paramIn(cp, csprintf("txList%d", i), value); txList.push_back(value); } /* * Unserialize rx state machine */ int rxState; UNSERIALIZE_SCALAR(rxState); UNSERIALIZE_SCALAR(rxEmpty); UNSERIALIZE_SCALAR(rxLow); this->rxState = (RxState) rxState; rxFifo.unserialize("rxFifo", cp); int rxFifoPtr; UNSERIALIZE_SCALAR(rxFifoPtr); if (rxFifoPtr >= 0) { this->rxFifoPtr = rxFifo.begin(); for (int i = 0; i < rxFifoPtr; ++i) ++this->rxFifoPtr; } else { this->rxFifoPtr = rxFifo.end(); } /* * Unserialize tx state machine */ int txState; UNSERIALIZE_SCALAR(txState); UNSERIALIZE_SCALAR(txFull); this->txState = (TxState) txState; txFifo.unserialize("txFifo", cp); bool txPacketExists; UNSERIALIZE_SCALAR(txPacketExists); txPacket = 0; if (txPacketExists) { txPacket = make_shared<EthPacketData>(16384); txPacket->unserialize("txPacket", cp); UNSERIALIZE_SCALAR(txPacketOffset); UNSERIALIZE_SCALAR(txPacketBytes); } /* * unserialize the virtual nic registers/state * * this must be done after the unserialization of the rxFifo * because the packet iterators depend on the fifo being populated */ int virtualRegsSize; UNSERIALIZE_SCALAR(virtualRegsSize); virtualRegs.clear(); virtualRegs.resize(virtualRegsSize); for (int i = 0; i < virtualRegsSize; ++i) { VirtualReg *vnic = &virtualRegs[i]; std::string reg = csprintf("vnic%d", i); paramIn(cp, reg + ".RxData", vnic->RxData); paramIn(cp, reg + ".RxDone", vnic->RxDone); paramIn(cp, reg + ".TxData", vnic->TxData); paramIn(cp, reg + ".TxDone", vnic->TxDone); vnic->rxUnique = rxUnique++; vnic->txUnique = txUnique++; bool rxPacketExists; paramIn(cp, reg + ".rxPacketExists", rxPacketExists); if (rxPacketExists) { int rxPacket; paramIn(cp, reg + ".rxPacket", rxPacket); vnic->rxIndex = rxFifo.begin(); while (rxPacket--) ++vnic->rxIndex; paramIn(cp, reg + ".rxPacketOffset", vnic->rxPacketOffset); paramIn(cp, reg + ".rxPacketBytes", vnic->rxPacketBytes); } else { vnic->rxIndex = rxFifo.end(); } paramIn(cp, reg + ".rxDoneData", vnic->rxDoneData); } /* * If there's a pending transmit, reschedule it now */ Tick transmitTick; UNSERIALIZE_SCALAR(transmitTick); if (transmitTick) schedule(txEvent, curTick() + transmitTick); pioPort.sendRangeChange(); } } // namespace Sinic
.definelabel Shop_Item_Save_Offset, 0xD4 + (0x2C * 0x1C) + 0x10 Shop_Check_Sold_Out: lhu t6, 0x1c(a0) ; if var is under 0x32, never sell out addi t5, t6, -0x32 bltz t5, @@return li v0, 0 ; t2 = bit mask andi t1, t5, 0x07 li t2, 1 sllv t2, t2, t1 ; t1 = byte offset srl t1, t5, 3 ; load byte from save li t4, SAVE_CONTEXT add t4, t4, t1 lbu t3, (Shop_Item_Save_Offset)(t4) ; mask out the bit flag and t3, t3, t2 ; if not set then, do nothing li v0, 0 beqz t3, @@return nop ; Else, change to sold out li t5, 0x26 sh t5, 0x1c(a0) ; set item to SOLD OUT li v0, 1 ; return 1 @@return: jr ra nop Shop_Set_Sold_Out: lhu t6, 0x1c(a1) ; if var is under 0x32, never sell out addi t5, t6, -0x32 bltz t5, @@return li v0, 0 ; t2 = bit mask andi t1, t5, 0x07 li t2, 1 sllv t2, t2, t1 ; t1 = byte offset srl t1, t5, 3 ; load byte from save li t4, SAVE_CONTEXT add t4, t4, t1 lbu t3, (Shop_Item_Save_Offset)(t4) ; set and save the bit flag or t3, t3, t2 sb t3, (Shop_Item_Save_Offset)(t4) @@return: jr ra nop Shop_Keeper_Init_ID: addiu sp, sp, -0x10 sw ra, 0x08 (sp) slti at, a0, 0x32 beqz at, @@return move v0, a0 jalr t9 nop @@return: lw ra, 0x08 (sp) addiu sp, sp, 0x10 jr ra nop Deku_Check_Sold_Out: li t0, GLOBAL_CONTEXT li t1, SAVE_CONTEXT lhu t2, 0xA4(t0) ; current scene number li at, 0x3E ; Grotto Scene bne t2, at, @@continue ; If in grotto, use a free scene lbu t3, 0x1397(t1) ; Grotto ID addi t2, t3, -0xD6 @@continue: lhu t3, 0x1C(s0) ; var addi t3, t3, 1 li t4, 1 sllv t4, t4, t3 ; saleman item bitmask li at, 0x1C ; Permanant flag entry size mult t2, at mflo t5 ; Permanant flag entry offset add t6, t1, t5 lw t7, 0xE4(t6) ; Saleman bitflag (originally unused) and v0, t4, t7 ; return if flag is set jr ra nop Deku_Set_Sold_Out: li t0, GLOBAL_CONTEXT li t1, SAVE_CONTEXT lhu t2, 0xA4(t0) ; current scene number li at, 0x3E ; Grotto Scene bne t2, at, @@continue ; If in grotto, use a free scene lbu t3, 0x1397(t1) ; Grotto ID addi t2, t3, -0xD6 @@continue: lh t3, 0x1C(a0) ; var addi t3, t3, 1 li t4, 1 sllv t4, t4, t3 ; saleman item bitmask li at, 0x1C ; Permanant flag entry size mult t2, at mflo t5 ; Permanant flag entry offset add t6, t1, t5 lw t7, 0xE4(t6) ; Saleman bitflag [0xD0 (PFlag Table) + 0x10 (unused offself)] or t7, t4, t7 ; return if flag is set sw t7, 0xE4(t6) jr ra nop
; ; LZ4 decompressor by spke (v.1 28/08/2017) ; ; I wrote this LZ4 decompressor from scratch; however, I looked at previously released ; LZ4 decompressors by Piotr Drapich, see http://www.union.org.pl/download/z80/ ; and stephenw32768, see https://www.worldofspectrum.org/forums/discussion/45185/lz4-decoder/p2 ; Many of their good ideas ended up in my code too (my favourite trick invented by Piotr is ; reading extra bytes into C). I hope my added tricks are worthwhile to call this unpacker new. ; ; Piotr Drapich's and stephenw32768's unpackers are both very fast. Piotr's code takes about ; 33.8 t-states to unpack a byte. stephenw32768's unpacker unpacks a byte within about 34.4 t-states. ; This routine is about 2.4% faster than Piotr's, so it takes 33 t-states to unpack a byte, which ; is nearly reaching my personal target of decompressing at 1.5*LDIR. It uses 104 bytes of memory. ; ; the command line for the official LZ4 command line compressor is ; ; lz4.exe -16 --no-frame-crc <sourcefile> <outfile> ; ; where -16 gives you the best possible compression (which is not that great actually), ; and --no-frame-crc makes data somewhat easier to handle. You can download the binaries ; from http://lz4.github.io/lz4/ ; ; Of course, LZ4 decompression algorithm is (c) 2011-2015, Yann Collet. ; ; Drop me an email if you have any comments/ideas/suggestions: zxintrospec@gmail.com ; ;DEFINE DATA_HAS_HEADERS ; comment this line out if using to decompress a stripped (frameless) ZX4 data ;DEFINE ALLOW_UNCOMPRESSED ; uncomment to correctly process uncompressed blocks (i've no idea why you would do such a thing!) DecompressLZ4: ; generally speaking, .LZ4 file can contain multiple frames (compressed or uncompressed); ; each frame has header descriptors and may, in addition, contain checksums, ; see the details: https://docs.google.com/document/d/1cl8N1bmkTdIpPLtnlzbBSFAdUeyNo5fwfHbHU7VRNWY/edit ; we ignore pretty much all of this machinery and assume a single compressed frame. IFDEF DATA_HAS_HEADERS ld bc,4 : add hl,bc ; skip 4 "magic" bytes at the start of the frame IFNDEF ALLOW_UNCOMPRESSED ld a,(hl) ; must also skip "Frame Descriptor" (3 bytes) and "Block Size" (4 bytes) and 8 ; bit 3 of the "FLG" byte is 1 if "Content Size" is included... add 3+4 : ld c,a ; ..which may also need to be skipped ("Content Size" is 8 bytes long) add hl,bc ; skip all that needs to be skipped ELSE ld a,(hl) ; must also skip "Frame Descriptor" (3 bytes) and 8 ; bit 3 of the "FLG" byte is 1 if "Content Size" is included... add 3 : ld c,a ; ..which may also need to be skipped ("Content Size" is 8 bytes long) add hl,bc ; skip all that needs to be skipped ld c,(hl) : inc hl : ld b,(hl) : inc hl ld a,b : or c : ret z ; frame end marker? inc hl : ld a,(hl) : inc hl : rla : jr nc,Compressed ldir : ret Compressed: ld b,0 ENDIF ELSE ; also, this decompressor may be used to handle stripped (headerless) file generated by the tool developed by ; stephenw32768, see https://www.worldofspectrum.org/forums/discussion/comment/727516/#Comment_727516 ld b,0 ; B is assumed to zero throughout, which saves on clearing it ENDIF DecompressRaw: jr ReadToken ; this is optimized for shorter matches, because ; they are likely to be a lot more common ProcessMatch: inc hl exa : and #0F : add 4 : cp 15+4 : call z,GetLongLength ; MMMM+4<15+4 means match lengths between 0+4 and 14+4 ; MMMM+4=15+4 indicates a multi-byte length of the match ld c,a : ex (sp),hl : ex hl,de ; BC = len, DE = dest, HL = -offset, SP ->[src] add hl,de ; BC = len, DE = dest, HL = dest+-offset, SP->[src] ldir : pop hl ; BC = 0, DE = dest, HL = src ReadToken: ; first a byte token "LLLLMMMM" is read from the stream, ; where LLLL is the number of literals and MMM is ; a length of the match that follows the literals ld a,(hl) : exa : ld a,(hl) : inc hl ; token is read twice to be re-used later and #F0 : jr z,NoLiterals ; we definitely have literals to copy rrca : rrca : rrca : rrca : cp 15 : call z,GetLongLength ; LLLL<15 means 0..14 literals... ; LLLL=15 indicates a multi-byte number of literals CopyLiterals: ld c,a : ldir ; second, a two-byte offset value is given ; since every compressed block must end with 5 literals, ; or more, and since after the end of the block the end ; marker is given, which is 4 zero bytes, we can use ; zero offset as a marker of the end of the block ; (see https://github.com/lz4/lz4/wiki/lz4_Block_format.md) xor a NoLiterals: push de ; SP -> [dest] sub (hl) : inc hl : ld e,a sbc (hl) : sub e : ld d,a ; DE = -offset or e : jp nz,ProcessMatch ; ugly branching is optimized for speed pop de ;ret; a=(hl)=0 GetLongLength: ld c,(hl) : inc hl : add c : jr nc,SkipIncB inc b SkipIncB: inc c jr z,GetLongLength ret
; A004647: Powers of 2 written in base 8. ; 1,2,4,10,20,40,100,200,400,1000,2000,4000,10000,20000,40000,100000,200000,400000,1000000,2000000,4000000,10000000,20000000,40000000,100000000,200000000,400000000,1000000000,2000000000,4000000000,10000000000,20000000000,40000000000,100000000000,200000000000,400000000000,1000000000000,2000000000000,4000000000000,10000000000000,20000000000000,40000000000000,100000000000000,200000000000000,400000000000000,1000000000000000,2000000000000000,4000000000000000,10000000000000000,20000000000000000,40000000000000000,100000000000000000,200000000000000000,400000000000000000,1000000000000000000,2000000000000000000,4000000000000000000,10000000000000000000,20000000000000000000,40000000000000000000,100000000000000000000,200000000000000000000,400000000000000000000,1000000000000000000000,2000000000000000000000,4000000000000000000000,10000000000000000000000,20000000000000000000000,40000000000000000000000,100000000000000000000000,200000000000000000000000,400000000000000000000000,1000000000000000000000000,2000000000000000000000000,4000000000000000000000000,10000000000000000000000000,20000000000000000000000000,40000000000000000000000000,100000000000000000000000000,200000000000000000000000000,400000000000000000000000000,1000000000000000000000000000,2000000000000000000000000000,4000000000000000000000000000,10000000000000000000000000000,20000000000000000000000000000,40000000000000000000000000000,100000000000000000000000000000,200000000000000000000000000000,400000000000000000000000000000,1000000000000000000000000000000,2000000000000000000000000000000,4000000000000000000000000000000,10000000000000000000000000000000,20000000000000000000000000000000,40000000000000000000000000000000,100000000000000000000000000000000,200000000000000000000000000000000,400000000000000000000000000000000,1000000000000000000000000000000000 mov $1,2 pow $1,$0 seq $1,7094 ; Numbers in base 8. mov $0,$1
;; Basic I/O System (BIOS) only loads first 512 bytes of bootsector. Now we willwrite program fro larger than 512 bytes. section .boot bits 16 global boot boot: mov ax, 0x2401 int 0x15 mov ax, 0x3 int 0x10 mov [disk], dl mov ah, 0x2 ;read sectors mov al, 6 ;sectors to read mov ch, 0 ;cylinder idx mov dh, 0 ;head idx mov cl, 2 ;sector idx mov dl, [disk] ;disk idx mov bx, copy_target ;target pointer int 0x13 cli lgdt [gdt_pointer] mov eax, cr0 or eax, 0x1 mov cr0, eax mov ax, DATA_SEG mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax jmp CODE_SEG:boot2 gdt_start: dq 0x0 gdt_code: dw 0xFFFF dw 0x0 db 0x0 db 10011010b db 11001111b db 0x0 gdt_data: dw 0xFFFF dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 gdt_end: gdt_pointer: dw gdt_end - gdt_start dd gdt_start disk: db 0x0 CODE_SEG equ gdt_code - gdt_start DATA_SEG equ gdt_data - gdt_start times 510 - ($-$$) db 0 dw 0xaa55 copy_target: bits 32 hello: db "Writing Bootloader program for more than 512 bytes",0 boot2: mov esi, hello mov ebx, 0xb8000 .loop: lodsb or al, al ; is al==0? jz halt ; if al==0 or eax, 0x0F00 mov word [ebx], ax add ebx, 2 jmp .loop halt: mov esp, kernal_stack_top extern kmain call kmain cli hlt section .bss align 4 kernal_stack_bottom: equ $ resb 16384 ; 16KB kernal_stack_top:
// (C) Copyright John Maddock 2005. // Use, modification and distribution are 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) #include <iomanip>
// Q2.2.4.3. 魔方大厦 // WzhDnwzWzh #include <iostream> #include <cstdio> #include <cstring> #include <cmath> using namespace std; int n, p, f[201][201][201], sol = 0; bool vis[201][201][201]; int way[201][201][201]; inline int read() { int x = 0, w = 1; char ch = 0; while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + (ch - '0'); ch = getchar(); } return x * w; } int dfs(int x, int y, int z) { if (way[x][y][z] != 0) return way[x][y][z]; way[x][y][z] = (way[x][y][z] + 1) % p; vis[x][y][z] = true; if (x + 1 < n) if (f[x + 1][y][z] > f[x][y][z]) { way[x][y][z] += dfs(x + 1, y, z); way[x][y][z] %= p; } if (x - 1 >= 0) if (f[x - 1][y][z] > f[x][y][z]) { way[x][y][z] += dfs(x - 1, y, z); way[x][y][z] %= p; } if (y + 1 < n) if (f[x][y + 1][z] > f[x][y][z]) { way[x][y][z] += dfs(x, y + 1, z); way[x][y][z] %= p; } if (y - 1 >= 0) if (f[x][y - 1][z] > f[x][y][z]) { way[x][y][z] += dfs(x, y - 1, z); way[x][y][z] %= p; } if (z + 1 < n) if (f[x][y][z + 1] > f[x][y][z]) { way[x][y][z] += dfs(x, y, z + 1); way[x][y][z] %= p; } if (z - 1 >= 0) if (f[x][y][z - 1] > f[x][y][z]) { way[x][y][z] += dfs(x, y, z - 1); way[x][y][z] %= p; } return way[x][y][z]; } int main() { memset(vis, 0, sizeof(vis)); memset(way, 0, sizeof(way)); n = read(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) f[i][j][k] = read(); p = read(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) dfs(i, j, k); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { sol += way[i][j][k]; sol %= p; } cout << sol << endl; return 0; }
; A134286: Characteristic sequence for sequence A026905. ; 1,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0 mov $1,$0 add $1,1 cal $1,155972 ; The Partition Ruler
;====================================================================== ; VDU DRIVER FOR ECB-VDU PROJECT ; ; ORIGINALLY WRITTEN BY: ANDREW LYNCH ; REVISED/ENHANCED BY DAN WERNER -- 11/7/2009 ; ROMWBW ADAPTATION BY: WAYNE WARTHEN -- 11/9/2012 ; 80X25, 80X30 AND MODE INFO AT BOOT ADDED BY: PHIL SUMMERS -- 2/3/2019 ; ADD CURSOR STYLE OPTIONS, IMPLEMENT VDU_VDASCS FUNCTION : PHIL SUMMERS -- 19/10/2019 ;====================================================================== ; ; VDU-DW.ZIP IS THE DEFAULY 10X8 FONT THAT SUITS 80X25 AND 80X26 MODE. ; IN 80X30 MODE THE DESCENDERS ARE MISSING. AN ALTERNATE 8x8 FONT MAY ; DISPLAY BETTER. THIS CAN BE ADDED TO THE ECB-VDU FONT EPROM AND ; SELECTED VIA ONBOARD JUMPERS. THE FONT ROM CAN CONTAIN EIGHT 2Kb FONTS. ; ; TODO: ; - ADD REMAINING REGISTERS TO INIT ; - IMPLEMENT ALTERNATE DISPLAY MODES? ; ;====================================================================== ; VDU DRIVER - CONSTANTS ;====================================================================== ; VDU_BASE .EQU $F0 ; VDU_RAMRD .EQU VDU_BASE + $00 ; READ VDU VDU_RAMWR .EQU VDU_BASE + $01 ; WRITE VDU VDU_STAT .EQU VDU_BASE + $02 ; VDU STATUS/REGISTER VDU_REG .EQU VDU_BASE + $02 ; VDU STATUS/REGISTER VDU_DATA .EQU VDU_BASE + $03 ; VDU DATA REGISTER VDU_PPIA .EQU VDU_BASE + $04 ; PPI PORT A VDU_PPIB .EQU VDU_BASE + $05 ; PPI PORT B VDU_PPIC .EQU VDU_BASE + $06 ; PPI PORT C VDU_PPIX .EQU VDU_BASE + $07 ; PPI CONTROL PORT ; VDU_NOBL .EQU 00000000B ; NO BLINK VDU_NOCU .EQU 00100000B ; NO CURSOR VDU_BFAS .EQU 01000000B ; BLINK AT X16 RATE VDU_BSLO .EQU 01100000B ; BLINK AT X32 RATE ; VDU_BLOK .EQU 0 ; BLOCK CURSOR VDU_ULIN .EQU 1 ; UNDERLINE CURSOR ; VDU_CSTY .EQU VDU_BLOK ; DEFAULT CURSOR STYLE VDU_BLNK .EQU VDU_NOBL ; DEFAULT BLINK RATE ; TERMENABLE .SET TRUE ; INCLUDE TERMINAL PSEUDODEVICE DRIVER ; #IF (VDUSIZ=V80X24) DLINES .EQU 24 DROWS .EQU 80 DSCANL .EQU 10 #ENDIF #IF (VDUSIZ=V80X25) DLINES .EQU 25 DROWS .EQU 80 DSCANL .EQU 10 #ENDIF #IF (VDUSIZ=V80X30) DLINES .EQU 30 DROWS .EQU 80 DSCANL .EQU 8 #ENDIF #IF (VDUSIZ=V80X25B) DLINES .EQU 25 DROWS .EQU 80 DSCANL .EQU 12 #ENDIF #IF (VDUSIZ=V80X24B) DLINES .EQU 24 DROWS .EQU 80 DSCANL .EQU 12 #ENDIF ; #IF VDU_CSTY=VDU_BLOK VDU_R10 .EQU (VDU_BLNK + $00) VDU_R11 .EQU DSCANL-1 #ENDIF ; #IF VDU_CSTY=VDU_ULIN VDU_R10 .EQU (VDU_BLNK + DSCANL-1) VDU_R11 .EQU DSCANL-1 #ENDIF ; ;====================================================================== ; VDU DRIVER - INITIALIZATION ;====================================================================== ; VDU_INIT: LD IY,VDU_IDAT ; POINTER TO INSTANCE DATA ; CALL NEWLINE ; FORMATTING PRTS("VDU: IO=0x$") LD A,VDU_RAMRD CALL PRTHEXBYTE PRTS(" MODE=$") ; OUTPUT DISPLAY FORMAT LD A,DROWS CALL PRTDECB PRTS("X$") LD A,DLINES CALL PRTDECB CALL VDU_PROBE ; CHECK FOR HW EXISTENCE JR Z,VDU_INIT1 ; CONTINUE IF HW PRESENT ; ; HARDWARE NOT PRESENT PRTS(" NOT PRESENT$") OR $FF ; SIGNAL FAILURE RET ; VDU_INIT1: CALL VDU_CRTINIT ; INIT SY6845 VDU CHIP CALL VDU_VDARES CALL PPK_INIT ; INITIALIZE KEYBOARD DRIVER ; ; ADD OURSELVES TO VDA DISPATCH TABLE LD BC,VDU_FNTBL ; BC := FUNCTION TABLE ADDRESS LD DE,VDU_IDAT ; DE := VDU INSTANCE DATA PTR CALL VDA_ADDENT ; ADD ENTRY, A := UNIT ASSIGNED ; ; INITIALIZE EMULATION LD C,A ; ASSIGNED VIDEO UNIT IN C LD DE,VDU_FNTBL ; DE := FUNCTION TABLE ADDRESS LD HL,VDU_IDAT ; HL := VDU INSTANCE DATA PTR CALL TERM_ATTACH ; DO IT XOR A ; SIGNAL SUCCESS RET ; ;====================================================================== ; VDU DRIVER - VIDEO DISPLAY ADAPTER (VDA) FUNCTIONS ;====================================================================== ; VDU_FNTBL: .DW VDU_VDAINI .DW VDU_VDAQRY .DW VDU_VDARES .DW VDU_VDADEV .DW VDU_VDASCS .DW VDU_VDASCP .DW VDU_VDASAT .DW VDU_VDASCO .DW VDU_VDAWRC .DW VDU_VDAFIL .DW VDU_VDACPY .DW VDU_VDASCR .DW PPK_STAT .DW PPK_FLUSH .DW PPK_READ #IF (($ - VDU_FNTBL) != (VDA_FNCNT * 2)) .ECHO "*** INVALID VDU FUNCTION TABLE ***\n" !!!!! #ENDIF VDU_VDAINI: ; RESET VDA ; CURRENTLY IGNORES VIDEO MODE AND BITMAP DATA CALL VDU_VDARES ; RESET VDA XOR A ; SIGNAL SUCCESS RET VDU_VDAQRY: LD C,$00 ; MODE ZERO IS ALL WE KNOW LD DE,(DLINES*256)+DROWS ; D=DLINES, E=DROWS LD HL,0 ; EXTRACTION OF CURRENT BITMAP DATA NOT SUPPORTED XOR A ; SIGNAL SUCCESS RET VDU_VDARES: LD DE,0 LD (VDU_OFFSET),DE CALL VDU_XY LD A,' ' LD DE,1024*16 CALL VDU_FILL XOR A RET VDU_VDADEV: LD D,VDADEV_VDU ; D := DEVICE TYPE LD E,0 ; E := PHYSICAL UNIT IS ALWAYS ZERO LD H,0 ; H := 0, DRIVER HAS NO MODES LD L,VDU_BASE ; L := BASE I/O ADDRESS XOR A ; SIGNAL SUCCESS RET VDU_VDASCS: LD A,D ; GET CURSOR FINISH. AND 00001111B ; BOTTOM NIBBLE OF D LD L,A ; SAVE IN L FOR R11 LD A,D ; GET CURSOR START. AND 11110000B ; TOP NIBBLE IF D RRCA RRCA RRCA ; COMBINE CURSOR START RRCA ; AND CURSOR STYLE AND OR VDU_CSTY ; SAVE IN H FOR R10 LD H,A LD C,10 CALL VDU_WRREGX ; UPDATE CURSOR XOR A RET VDU_VDASCP: CALL VDU_XY XOR A RET VDU_VDASAT: XOR A RET VDU_VDASCO: XOR A RET VDU_VDAWRC: LD A,E CALL VDU_PUTCHAR XOR A RET VDU_VDAFIL: LD A,E ; FILL CHARACTER GOES IN A EX DE,HL ; FILL LENGTH GOES IN DE CALL VDU_FILL ; DO THE FILL XOR A ; SIGNAL SUCCESS RET VDU_VDACPY: ; LENGTH IN HL, SOURCE ROW/COL IN DE, DEST IS VDU_POS PUSH HL ; SAVE LENGTH CALL VDU_XY2IDX ; ROW/COL IN DE -> SOURCE ADR IN HL POP BC ; RECOVER LENGTH IN BC LD DE,(VDU_POS) ; PUT DEST IN DE JP VDU_BLKCPY ; DO A BLOCK COPY RET VDU_VDASCR: LD A,E ; LOAD E INTO A OR A ; SET FLAGS RET Z ; IF ZERO, WE ARE DONE PUSH DE ; SAVE E JP M,VDU_VDASCR1 ; E IS NEGATIVE, REVERSE SCROLL CALL VDU_SCROLL ; SCROLL FORWARD ONE LINE POP DE ; RECOVER E DEC E ; DECREMENT IT JR VDU_VDASCR ; LOOP VDU_VDASCR1: CALL VDU_RSCROLL ; SCROLL REVERSE ONE LINE POP DE ; RECOVER E INC E ; INCREMENT IT JR VDU_VDASCR ; LOOP ; ;====================================================================== ; VDU DRIVER - PRIVATE DRIVER FUNCTIONS ;====================================================================== ; ;---------------------------------------------------------------------- ; WAIT FOR VDU TO BE READY FOR A DATA READ/WRITE ;---------------------------------------------------------------------- ; VDU_WAITRDY: IN A,(VDU_STAT) ; READ STATUS OR A ; SET FLAGS RET M ; IF BIT 7 SET, THEN READY! JR VDU_WAITRDY ; KEEP CHECKING ; ;---------------------------------------------------------------------- ; UPDATE SY6845 REGISTERS ; VDU_WRREG WRITES VALUE IN A TO VDU REGISTER SPECIFIED IN C ; VDU_WRREGX WRITES VALUE IN HL TO VDU REGISTER PAIR IN C, C+1 ;---------------------------------------------------------------------- ; VDU_WRREG: PUSH AF ; SAVE VALUE TO WRITE LD A,C ; SET A TO VDU REGISTER TO SELECT OUT (VDU_REG),A ; WRITE IT TO SELECT THE REGISTER POP AF ; RECOVER VALUE TO WRITE OUT (VDU_DATA),A ; WRITE IT RET ; VDU_WRREGX: LD A,H ; SETUP MSB TO WRITE CALL VDU_WRREG ; DO IT INC C ; NEXT VDU REGISTER LD A,L ; SETUP LSB TO WRITE JR VDU_WRREG ; DO IT & RETURN ; ;---------------------------------------------------------------------- ; READ SY6845 REGISTERS ; VDU_RDREG READS VDU REGISTER SPECIFIED IN C AND RETURNS VALUE IN A ; VDU_RDREGX READS VDU REGISTER PAIR SPECIFIED BY C, C+1 ; AND RETURNS VALUE IN HL ;---------------------------------------------------------------------- ; VDU_RDREG: LD A,C ; SET A TO VDU REGISTER TO SELECT OUT (VDU_REG),A ; WRITE IT TO SELECT THE REGISTER IN A,(VDU_DATA) ; READ IT RET ; VDU_RDREGX: CALL VDU_RDREG ; GET VALUE FROM REGISTER IN C LD H,A ; SAVE IN H INC C ; BUMP TO NEXT REGISTER OF PAIR CALL VDU_RDREG ; READ THE VALUE LD L,A ; SAVE IT IN L RET ; ;---------------------------------------------------------------------- ; PROBE FOR VDU HARDWARE ;---------------------------------------------------------------------- ; ; ON RETURN, ZF SET INDICATES HARDWARE FOUND ; VDU_PROBE: ; WRITE TEST PATTERN $A5 $5A TO VRAM ADDRESS POINTER LD HL,$A55A ; POINT TO FIRST BYTE OF VRAM LD C,14 ; ADDRESS REGISTER PAIR CALL VDU_WRREGX ; UPDATE VRAM ADDRESS POINTER LD C,14 ; ADDRESS REGISTER PAIR CALL VDU_RDREGX ; READ IT BACK ; TOP TWO BITS ARE ZEROED IN COMPARE BECAUSE THE CRTC ; STORES ONLY A 14 BIT VALUE FOR REGISTER PAIR 14/15 LD A,$A5 & $3F ; FIRST BYTE TEST VALUE CP H ; COMPARE RET NZ ; ABORT IF NOT EQUAL LD A,$5A ; SECOND BYTE TEST VALUE CP L ; COMPARE RET ; RETURN WITH COMPARE RESULTS ; ;---------------------------------------------------------------------- ; SY6845 DISPLAY CONTROLLER CHIP INITIALIZATION ;---------------------------------------------------------------------- ; VDU_CRTINIT: LD C,0 ; START WITH REGISTER 0 LD B,16 ; INIT 16 REGISTERS LD HL,VDU_INIT6845 ; HL = POINTER TO THE DEFAULT VALUES VDU_CRTINIT1: LD A,(HL) ; GET VALUE CALL VDU_WRREG ; WRITE IT INC HL ; POINT TO NEXT VALUE INC C ; POINT TO NEXT REGISTER DJNZ VDU_CRTINIT1 ; LOOP RET ; ;---------------------------------------------------------------------- ; CONVERT XY COORDINATES IN DE INTO LINEAR INDEX IN HL ; D=ROW, E=COL ;---------------------------------------------------------------------- ; VDU_XY2IDX: LD A,E ; SAVE COLUMN NUMBER IN A LD H,D ; SET H TO ROW NUMBER LD E,DROWS ; SET E TO ROW LENGTH CALL MULT8 ; MULTIPLY TO GET ROW OFFSET LD E,A ; GET COLUMN BACK ADD HL,DE ; ADD IT IN RET ; RETURN ; ;---------------------------------------------------------------------- ; SET CURSOR POSITION TO ROW IN D AND COLUMN IN E ;---------------------------------------------------------------------- ; VDU_XY: LD A,E ; SAVE COLUMN NUMBER IN A LD H,D ; SET H TO ROW NUMBER LD E,DROWS ; SET E TO ROW LENGTH CALL MULT8 ; MULTIPLY TO GET ROW OFFSET LD E,A ; GET COLUMN BACK ADD HL,DE ; ADD IT IN LD (VDU_POS),HL ; SAVE THE RESULT (DISPLAY POSITION) LD DE,(VDU_OFFSET) ; NOW GET THE BUFFER OFFSET ADD HL,DE ; AND ADD THAT IN LD C,14 ; CURSOR POSITION REGISTER PAIR JP VDU_WRREGX ; DO IT AND RETURN ; ;---------------------------------------------------------------------- ; WRITE VALUE IN A TO CURRENT VDU BUFFER POSITION, ADVANCE CURSOR ;---------------------------------------------------------------------- ; VDU_PUTCHAR: LD B,A ; SAVE THE CHARACTER ; SET BUFFER WRITE POSITION LD HL,(VDU_OFFSET) LD DE,(VDU_POS) ADD HL,DE INC DE ; INC LD (VDU_POS),DE ; SAVE NEW SCREEN POSITION LD C,18 ; UPDATE ADDRESS REGISTER PAIR CALL VDU_WRREGX ; DO IT INC HL ; NEW CURSOR POSITION LD C,14 ; CURSOR POSITION REGISTER PAIR CALL VDU_WRREGX ; DO IT LD A,31 ; PREP VDU FOR DATA R/W OUT (VDU_REG),A CALL VDU_WAITRDY ; WAIT FOR VDU TO BE READY LD A,B OUT (VDU_RAMWR),A ; OUTPUT CHAR TO VDU RET ; ;---------------------------------------------------------------------- ; FILL AREA IN BUFFER WITH SPECIFIED CHARACTER AND CURRENT COLOR/ATTRIBUTE ; STARTING AT THE CURRENT FRAME BUFFER POSITION ; A: FILL CHARACTER ; DE: NUMBER OF CHARACTERS TO FILL ;---------------------------------------------------------------------- ; VDU_FILL: LD B,A ; SAVE THE FILL CHARACTER ; SET FILL START POSITION PUSH DE LD HL,(VDU_OFFSET) LD DE,(VDU_POS) ADD HL,DE LD C,18 CALL VDU_WRREGX POP DE ; FILL LOOP LD A,31 ; PREP VDU FOR DATA R/W OUT (VDU_REG),A VDU_FILL1: LD A,D ; CHECK NUMBER OF FILL CHARS LEFT OR E RET Z ; ALL DONE, RETURN CALL VDU_WAITRDY ; WAIT FOR VDU TO BE READY LD A,B OUT (VDU_RAMWR),A ; OUTPUT CHAR TO VDU DEC DE ; DECREMENT COUNT JR VDU_FILL1 ; LOOP ; ;---------------------------------------------------------------------- ; COPY A BLOCK (UP TO 255 BYTES) FROM HL TO FRAME BUFFER POSITION ; BC: NUMBER OF BYTES TO COPY ; HL: SOURCE POSITION ; DE: DESTINATION POSITION ;---------------------------------------------------------------------- ; VDU_BLKCPY: ; SETUP TO COPY FROM VDU SOURCE TO WORK BUFFER PUSH DE ; SAVE VDU DESTINATION ADR PUSH HL ; SAVE VDU SOURCE ADDRESS LD HL,(VDU_OFFSET) ; GET THE CURRENT OFFSET POP DE ; RECOVER SOURCE ADDRESS ADD HL,DE ; HL HAS TRUE SOURCE ADR OF VIDEO BUF W/ OFFSET LD DE,VDU_BUF ; POINT DE TO WORK BUFFER PUSH BC ; SAVE COPY LENGTH FOR LATER LD B,C ; NOW USE B FOR LENGTH (MAX COPY IS 255) LD C,18 ; SET SOURCE ADDRESS IN VDU (HL) CALL VDU_WRREGX ; DO IT LD A,31 ; PREP VDU FOR DATA R/W OUT (VDU_REG),A ; DO IT LD HL,VDU_BUF ; HL POINTS TO WORK BUFFER LD C,VDU_RAMRD ; LOAD C WITH VDU READ REGISTER VDU_BLKCPY1: ; VIDEO RAM -> BUFFER COPY LOOP CALL VDU_WAITRDY ; WAIT FOR VDU INI ; READ BYTE, DEC B, INC HL IN A,(VDU_DATA) ; BOGUS READ TO INCREMENT VDU RAM ADDRESS!!! JR NZ,VDU_BLKCPY1 ; LOOP TILL DONE ; SETUP TO COPY FROM WORK BUFFER TO VDU DEST POP BC ; RECOVER THE COPY LENGTH LD HL,(VDU_OFFSET) ; GET THE CURRENT VDU OFFSET POP DE ; RECOVER THE DEST ADDRESS ADD HL,DE ; HL HAS TRUE DEST ADR OF VIDEO BUF W/ OFFSET LD B,C ; NOW USE B FOR LENGTH (MAX COPY IS 255) LD C,18 ; SET DEST ADDRESS IN VDU (HL) CALL VDU_WRREGX ; DO IT LD A,31 ; PREP VDU FOR DATA R/W OUT (VDU_REG),A ; DO IT LD HL,VDU_BUF ; HL POINTS TO WORK BUFFER LD C,VDU_RAMWR ; LOAD C WITH VDU WRITE REGISTER VDU_BLKCPY2: ; BUFFER -> VIDEO RAM COPY LOOP CALL VDU_WAITRDY ; WAIT FOR VDU OUTI ; WRITE BYTE, DEC B, INC HL JR NZ,VDU_BLKCPY2 ; LOOP TILL DONE ; RET ; RETURN ; ;---------------------------------------------------------------------- ; SCROLL ENTIRE SCREEN FORWARD BY ONE LINE (CURSOR POSITION UNCHANGED) ;---------------------------------------------------------------------- ; VDU_SCROLL: ; SCROLL FORWARD BY ADDING ONE ROW TO DISPLAY START ADDRESS LD HL,(VDU_OFFSET) LD DE,DROWS ADD HL,DE LD (VDU_OFFSET),HL LD C,12 CALL VDU_WRREGX ; FILL EXPOSED LINE LD HL,(VDU_POS) PUSH HL LD HL,(DLINES-1)*DROWS LD (VDU_POS),HL LD DE,DROWS LD A,' ' CALL VDU_FILL POP HL LD (VDU_POS),HL ; ADJUST CURSOR POSITION AND RETURN LD HL,(VDU_OFFSET) LD DE,(VDU_POS) ADD HL,DE LD C,14 JP VDU_WRREGX ; ;---------------------------------------------------------------------- ; REVERSE SCROLL ENTIRE SCREEN BY ONE LINE (CURSOR POSITION UNCHANGED) ;---------------------------------------------------------------------- ; VDU_RSCROLL: ; SCROLL BACKWARD BY SUBTRACTING ONE ROW FROM DISPLAY START ADDRESS LD HL,(VDU_OFFSET) LD DE,-DROWS ADD HL,DE LD (VDU_OFFSET),HL LD C,12 CALL VDU_WRREGX ; FILL EXPOSED LINE LD HL,(VDU_POS) PUSH HL LD HL,0 LD (VDU_POS),HL LD DE,DROWS LD A,' ' CALL VDU_FILL POP HL LD (VDU_POS),HL ; ADJUST CURSOR POSITION AND RETURN LD HL,(VDU_OFFSET) LD DE,(VDU_POS) ADD HL,DE LD C,14 JP VDU_WRREGX ; ;================================================================================================== ; VDU DRIVER - DATA ;================================================================================================== ; VDU_POS .DW 0 ; CURRENT DISPLAY POSITION VDU_OFFSET .DW 0 ; CURRENT DISPLAY POSITION VDU_BUF .FILL 256,0 ; COPY BUFFER ; ;================================================================================================== ; ECB-VDU VIDEO MODE DESCRIPTION ;==================================================================================================\ ; ; CCIR 625/50 VERSION (USED IN MOST OF THE WORLD) ; JUMPER K1 2-3, K2 1-2 FOR 2MHz CHAR CLOCK ; ; THE CCIR 625/50 TELEVISION STANDARD HAS 625 LINES INTERLACED AT 50 FIELDS PER SECOND. THIS WORKS ; OUT AS 50 FIELDS OF 312.5 LINES PER SECOND NON-INTERLACED AS USED HERE. ; HORIZONTAL LINE WIDTH IS 64uS. FOR A 2 MHz CHARACTER CLOCK (R0+1)/2000000 = 64uS ; NEAREST NUMBER OF LINES IS 312 = (R4+1) * (R9+1) + R5. ; 15625 / 312 = 50.08 FIELDS PER SECOND (NEAR ENOUGH-DGG) ; ; ; .DB 078H ; R8 MODE B7=0 TRANSPARENT UPDATE DURING BLANKING ; ; B6=1 PIN 34 IS UPDATE STROBE ; ; B5=1 DELAY CURSOR 1 CHARACTER ; ; B4=1 DELAY DISPLAY ENABLE 1 CHARACTER ; ; B3=1 TRANSPARENT MEMORY ADDRESSING ; ; B2=0 RAM STRAIGHT BINARY ADDRESSING ; ; B1,B0=0 NON-INTERLACE VDU_INIT6845: #IF (VDUSIZ=V80X24) ;================================================================================================== ; VDU DRIVER - SY6845 REGISTER INITIALIZATION -80x24 10x8 ;================================================================================================== ; .DB 07FH ; R0 TOTAL NUMBER OF HORIZONTAL CHARACTERS (DETERMINES HSYNC) .DB DROWS ; R1 NUMBER OF HORIZONTAL CHARACTERS DISPLAYED (80 COLUMNS) .DB 060H ; R2 HORIZONTAL SYNC POSITION .DB 00CH ; R3 SYNC WIDTHS .DB 01EH ; R4 VERTICAL TOTAL (TOTAL CHARS IN A FRAME 30-1) .DB 002H ; R5 VERTICAL TOTAL ADJUST ( .DB DLINES ; R6 VERTICAL DISPLAYED (24 ROWS) .DB 01AH ; R7 VERTICAL SYNC .DB 078H ; R8 MODE .DB DSCANL-1 ; R9 SCAN LINE (LINES PER CHAR AND SPACING -1) .DB VDU_R10 ; R10 CURSOR START RASTER .DB VDU_R11 ; R11 CURSOR END RASTER .DB 00H ; R12 START ADDRESS HI .DB 00H ; R13 START ADDRESS LO .DB 00H ; R14 CURSOR ADDRESS HI .DB 00H ; R15 CURSOR ADDRESS LO #ENDIF #IF (VDUSIZ=V80X25) ;================================================================================================== ; VDU DRIVER - SY6845 REGISTER INITIALIZATION -80x25 10x8 ;================================================================================================== ; .DB 07FH ; R0 TOTAL NUMBER OF HORIZONTAL CHARACTERS (DETERMINES HSYNC) .DB DROWS ; R1 NUMBER OF HORIZONTAL CHARACTERS DISPLAYED =80 .DB 060H ; R2 HORIZONTAL SYNC POSITION .DB 00CH ; R3 SYNC WIDTHS .DB 01EH ; R4 VERTICAL TOTAL (TOTAL CHARS IN A FRAME 30-1) .DB 002H ; R5 VERTICAL TOTAL ADJUST ( .DB DLINES ; R6 VERTICAL DISPLAYED (25 ROWS) .DB 01BH ; R7 VERTICAL SYNC .DB 078H ; R8 MODE .DB DSCANL-1 ; R9 SCAN LINE (LINES PER CHAR AND SPACING -1) .DB VDU_R10 ; R10 CURSOR START RASTER .DB VDU_R11 ; R11 CURSOR END RASTER .DB 00H ; R12 START ADDRESS HI .DB 00H ; R13 START ADDRESS LO .DB 00H ; R14 CURSOR ADDRESS HI .DB 00H ; R15 CURSOR ADDRESS LO #ENDIF #IF (VDUSIZ=V80X30) ;================================================================================================== ; VDU DRIVER - SY6845 REGISTER INITIALIZATION -80x30 8x8 ;================================================================================================== ; .DB 07FH ; R0 TOTAL NUMBER OF HORIZONTAL CHARACTERS (DETERMINES HSYNC) .DB DROWS ; R1 NUMBER OF HORIZONTAL CHARACTERS DISPLAYED =80 .DB 060H ; R2 HORIZONTAL SYNC POSITION .DB 00CH ; R3 SYNC WIDTHS .DB 26H ; R4 VERTICAL TOTAL (TOTAL CHARS IN A FRAME -1) (39-1) .DB 00H ; R5 VERTICAL TOTAL ADJUST ( .DB DLINES ; R6 VERTICAL DISPLAYED (30 ROWS) .DB 22H ; R7 VERTICAL SYNC .DB 078H ; R8 MODE .DB DSCANL-1 ; R9 SCAN LINE (LINES PER CHAR AND SPACING -1) .DB VDU_R10 ; R10 CURSOR START RASTER .DB VDU_R11 ; R11 CURSOR END RASTER .DB 00H ; R12 START ADDRESS HI .DB 00H ; R13 START ADDRESS LO .DB 00H ; R14 CURSOR ADDRESS HI .DB 00H ; R15 CURSOR ADDRESS LO #ENDIF #IF (VDUSIZ=V80X25B) ;================================================================================================== ; VDU DRIVER - SY6845 REGISTER INITIALIZATION -80x25 12x8 TO SUIT BLOCK GRAPHICS ;================================================================================================== ; .DB 07FH ; R0 TOTAL NUMBER OF HORIZONTAL CHARACTERS (DETERMINES HSYNC) .DB DROWS ; R1 NUMBER OF HORIZONTAL CHARACTERS DISPLAYED =80 .DB 060H ; R2 HORIZONTAL SYNC POSITION .DB 00CH ; R3 SYNC WIDTHS .DB 19H ; R4 VERTICAL TOTAL (TOTAL CHARS IN A FRAME -1) (312/DLINES)-1 .DB 00H ; R5 VERTICAL TOTAL ADJUST (312-(R4+1)*DSCANL) .DB DLINES ; R6 VERTICAL DISPLAY .DB 019H ; R7 VERTICAL SYNC (DLINES .. R4) .DB 078H ; R8 MODE .DB DSCANL-1 ; R9 SCAN LINE (LINES PER CHAR AND SPACING -1) .DB VDU_R10 ; R10 CURSOR START RASTER .DB VDU_R11 ; R11 CURSOR END RASTER .DB 00H ; R12 START ADDRESS HI .DB 00H ; R13 START ADDRESS LO .DB 00H ; R14 CURSOR ADDRESS HI .DB 00H ; R15 CURSOR ADDRESS LO #ENDIF #IF (VDUSIZ=V80X24B) ;================================================================================================== ; VDU DRIVER - SY6845 REGISTER INITIALIZATION -80x24 12x8 TO SUIT BLOCK GRAPHICS ;================================================================================================== ; .DB 07FH ; R0 TOTAL NUMBER OF HORIZONTAL CHARACTERS (DETERMINES HSYNC) .DB DROWS ; R1 NUMBER OF HORIZONTAL CHARACTERS DISPLAYED =80 .DB 060H ; R2 HORIZONTAL SYNC POSITION .DB 00CH ; R3 SYNC WIDTHS .DB 19H ; R4 VERTICAL TOTAL (TOTAL CHARS IN A FRAME -1) (312/DLINES)-1 .DB 00H ; R5 VERTICAL TOTAL ADJUST (312-(R4+1)*DSCANL) .DB DLINES ; R6 VERTICAL DISPLAY .DB 018H ; R7 VERTICAL SYNC (DLINES .. R4) .DB 078H ; R8 MODE .DB DSCANL-1 ; R9 SCAN LINE (LINES PER CHAR AND SPACING -1) .DB VDU_R10 ; R10 CURSOR START RASTER .DB VDU_R11 ; R11 CURSOR END RASTER .DB 00H ; R12 START ADDRESS HI .DB 00H ; R13 START ADDRESS LO .DB 00H ; R14 CURSOR ADDRESS HI .DB 00H ; R15 CURSOR ADDRESS LO ; #ENDIF ; ;;================================================================================================== ; VDU DRIVER - INSTANCE DATA ;================================================================================================== ; VDU_IDAT: .DB VDU_PPIA .DB VDU_PPIB .DB VDU_PPIC .DB VDU_PPIX
bits 16 org 0x7c00 section .text player_x equ 2 player_length equ 5 player_y dw 10 player_fbl dw 0b_1010_0000_0000_0000 cpu_x equ 78 cpu_length equ 5 cpu_y dw 10 cpu_fbl dw 0b_1001_0000_0000_0000 ball_x dw 1 ball_y dw 1 ball_x_acc dw 1 ball_y_acc dw 1 ball_fbl dw 0b_1100_0000_0000_0000 ; RGB get_vga_address: mov ax, 0xb800 mov es, ax mov ah, 03h mov al, 05h ;set typematic rate/delay mov bh, 00h ;repeat delay: 250ms <-- this has to be 0 mov bl, 00h ;typematic rate: 30 int 16h call game_init game_loop: call screen_clear call draw_midline ; cpu mov di, cpu_x mov si, [cpu_y] mov dx, cpu_length mov cx, [cpu_fbl] call draw_paddle call move_ball key_event: mov ah, 1 int 0x16 jz .draw_player xor ah, ah int 0x16 .jump: cmp al, 'j' jne .kick cmp word[player_y], 24 - player_length jg .draw_player inc word[player_y] jmp .draw_player .kick: cmp al, 'k' jne .draw_player cmp word[player_y], 0 jle .draw_player dec word[player_y] jmp .draw_player .draw_player: mov di, player_x mov si, [player_y] mov dx, player_length mov cx, [player_fbl] call draw_paddle ; call delay jmp game_loop ;----------------------------- move_ball: .check_top: cmp word[ball_y], 0 jle .reflect_y .check_bottom: cmp word[ball_y], 24 jge .reflect_y jmp .check_left .reflect_y: not word[ball_y_acc] inc word[ball_y_acc] .check_left: cmp word[ball_x], 0 jle .reflect_x .check_right: cmp word[ball_x], 79 jge .reflect_x jmp .check_end .reflect_x: not word[ball_x_acc] inc word[ball_x_acc] .check_end: mov ax, word[ball_x_acc] add word[ball_x], ax mov ax, word[ball_y_acc] add word[ball_y], ax .draw_ball: imul di, word[ball_x], 2 imul si, word[ball_y],160 add di, si mov ax, [ball_fbl] mov word[es:di], ax ret delay: mov bx, [0x_046c] add bx, 5 .lp: cmp bx, [0x046c] jle .timeout jmp .lp .timeout: ret game_init: mov ah, 0 ; select vga mode mov al, 3 ; 25 x 80 16 color text mode int 0x10 mov ah, 1 ; cursor shape mov ch, 0x26 ; start scanline (bit 5 = 1) mov cl, 0x07 ; end scanline int 0x10 ; box mov ah, 2 ; cursor position mov dh, 24 ; dh = rows mov dl, 79 ; dl = columns int 0x10 ret screen_clear: xor di, di .clear: mov al, 0 mov ah, 0b_1111_0000 mov word[es:di], ax add di, 2 cmp di, (80 * 2) * 25 - 1 jl .clear ret draw_midline: ; 0-79 => 0 ~ 40 ~ 79 ; 0-159 => 0 ~ 80 ~ 158:159 ; 160-319 => 160 ~ 240 ~ 318:319 ; 320-479 => .init_mid: mov ah, 0b_0000_1111 mov al, 0 mov di, 80 .check_mid: cmp di, 80 + 160 * 24 jg .done .do_mid: mov word[es:di], ax .step_mid: add di, 160 * 2 jmp .check_mid .done: ret draw_paddle: ;; di:x si:y dx:length cx:char .init: imul di, di, 2 imul si, si, 160 add di, si .check: test dx, dx je .done .do: mov [es:di], cx .step: add di, 160 dec dx jmp .check .done: ret times 510 - ($-$$) db 0 dw 0xaa55
.model tiny .data display db "DOLL" count db 04h .code .startup mov ah, 00h mov al, 03h int 10h lea si, display mov dl, 24h x: mov ah, 02h mov dh, 0bh mov bh, 00h int 10h mov ah, 09h lodsb mov bh, 00h mov bl, 8fh mov cx, 01h int 10h inc dl dec count jnz x .exit end
@10 D=A @R13 M=D @R13 A=M-1 D=M @R13 D=M D=D-1 A=D D=M // Stack // return_address (PUSH_TRUE) @SP A=M M=-1 @SP M=M+1 @R15 A=M 0;JMP @Sys.init 0;JMP
/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** * \file opt_copy_propagation_elements.cpp * * Replaces usage of recently-copied components of variables with the * previous copy of the variable. * * This should reduce the number of MOV instructions in the generated * programs and help triggering other optimizations that live in GLSL * level. */ #include "ir.h" #include "ir_rvalue_visitor.h" #include "ir_basic_block.h" #include "ir_optimization.h" #include "compiler/glsl_types.h" #include "util/hash_table.h" #include "util/set.h" static bool debug = false; namespace { class acp_entry { public: DECLARE_LINEAR_ZALLOC_CXX_OPERATORS(acp_entry) /* If set, rhs_full indicates that this ACP entry represents a * whole-variable copy. The rhs_element[] array will still be filled, * to allow the swizzling from its components in case the variable * was a vector (and to simplify some of the erase() and write_vector() * logic). */ ir_variable *rhs_full; ir_variable *rhs_element[4]; unsigned rhs_channel[4]; /* Set of variables that use the variable associated with this acp_entry as * RHS. This has the "reverse references" of rhs_full/rhs_element. It is * used to speed up invalidating those references when the acp_entry * changes. */ set *dsts; }; class copy_propagation_state { public: DECLARE_RZALLOC_CXX_OPERATORS(copy_propagation_state); static copy_propagation_state* create(void *mem_ctx) { return new (mem_ctx) copy_propagation_state(NULL); } copy_propagation_state* clone() { return new (ralloc_parent(this)) copy_propagation_state(this); } void erase_all() { /* Individual elements were allocated from a linear allocator, so will * be destroyed when the state is destroyed. */ _mesa_hash_table_clear(acp, NULL); fallback = NULL; } void erase(ir_variable *var, unsigned write_mask) { acp_entry *entry = pull_acp(var); entry->rhs_full = NULL; for (int i = 0; i < 4; i++) { if (!entry->rhs_element[i]) continue; if ((write_mask & (1 << i)) == 0) continue; ir_variable *to_remove = entry->rhs_element[i]; entry->rhs_element[i] = NULL; remove_unused_var_from_dsts(entry, var, to_remove); } /* TODO: Check write mask, and possibly not clear everything. */ /* For any usage of our variable on the RHS, clear it out. */ set_foreach(entry->dsts, set_entry) { ir_variable *dst_var = (ir_variable *)set_entry->key; acp_entry *dst_entry = pull_acp(dst_var); for (int i = 0; i < 4; i++) { if (dst_entry->rhs_element[i] == var) dst_entry->rhs_element[i] = NULL; } if (dst_entry->rhs_full == var) dst_entry->rhs_full = NULL; _mesa_set_remove(entry->dsts, set_entry); } } acp_entry *read(ir_variable *var) { for (copy_propagation_state *s = this; s != NULL; s = s->fallback) { hash_entry *ht_entry = _mesa_hash_table_search(s->acp, var); if (ht_entry) return (acp_entry *) ht_entry->data; } return NULL; } void write_elements(ir_variable *lhs, ir_variable *rhs, unsigned write_mask, int swizzle[4]) { acp_entry *lhs_entry = pull_acp(lhs); lhs_entry->rhs_full = NULL; for (int i = 0; i < 4; i++) { if ((write_mask & (1 << i)) == 0) continue; ir_variable *to_remove = lhs_entry->rhs_element[i]; lhs_entry->rhs_element[i] = rhs; lhs_entry->rhs_channel[i] = swizzle[i]; remove_unused_var_from_dsts(lhs_entry, lhs, to_remove); } acp_entry *rhs_entry = pull_acp(rhs); _mesa_set_add(rhs_entry->dsts, lhs); } void write_full(ir_variable *lhs, ir_variable *rhs) { acp_entry *lhs_entry = pull_acp(lhs); if (lhs_entry->rhs_full == rhs) return; if (lhs_entry->rhs_full) { remove_from_dsts(lhs_entry->rhs_full, lhs); } else if (lhs->type->is_vector()) { for (int i = 0; i < 4; i++) { if (lhs_entry->rhs_element[i]) remove_from_dsts(lhs_entry->rhs_element[i], lhs); } } lhs_entry->rhs_full = rhs; acp_entry *rhs_entry = pull_acp(rhs); _mesa_set_add(rhs_entry->dsts, lhs); if (lhs->type->is_vector()) { for (int i = 0; i < 4; i++) { lhs_entry->rhs_element[i] = rhs; lhs_entry->rhs_channel[i] = i; } } } void remove_unused_var_from_dsts(acp_entry *lhs_entry, ir_variable *lhs, ir_variable *var) { if (!var) return; /* If lhs still uses var, don't remove anything. */ for (int j = 0; j < 4; j++) { if (lhs_entry->rhs_element[j] == var) return; } acp_entry *element = pull_acp(var); assert(element); _mesa_set_remove_key(element->dsts, lhs); } private: explicit copy_propagation_state(copy_propagation_state *fallback) { this->fallback = fallback; /* Use 'this' as context for the table, no explicit destruction * needed later. */ acp = _mesa_pointer_hash_table_create(this); lin_ctx = linear_alloc_parent(this, 0); } acp_entry *pull_acp(ir_variable *var) { hash_entry *ht_entry = _mesa_hash_table_search(acp, var); if (ht_entry) return (acp_entry *) ht_entry->data; /* If not found, create one and copy data from fallback if available. */ acp_entry *entry = new(lin_ctx) acp_entry(); _mesa_hash_table_insert(acp, var, entry); bool found = false; for (copy_propagation_state *s = fallback; s != NULL; s = s->fallback) { hash_entry *fallback_ht_entry = _mesa_hash_table_search(s->acp, var); if (fallback_ht_entry) { acp_entry *fallback_entry = (acp_entry *) fallback_ht_entry->data; *entry = *fallback_entry; entry->dsts = _mesa_set_clone(fallback_entry->dsts, this); found = true; break; } } if (!found) { entry->dsts = _mesa_pointer_set_create(this); } return entry; } void remove_from_dsts(ir_variable *var, ir_variable *to_remove) { acp_entry *entry = pull_acp(var); assert(entry); _mesa_set_remove_key(entry->dsts, to_remove); } /** Available Copy to Propagate table, from variable to the entry * containing the current sources that can be used. */ hash_table *acp; /** When a state is cloned, entries are copied on demand from fallback. */ copy_propagation_state *fallback; void *lin_ctx; }; class kill_entry : public exec_node { public: /* override operator new from exec_node */ DECLARE_LINEAR_ZALLOC_CXX_OPERATORS(kill_entry) kill_entry(ir_variable *var, int write_mask) { this->var = var; this->write_mask = write_mask; } ir_variable *var; unsigned int write_mask; }; class ir_copy_propagation_elements_visitor : public ir_rvalue_visitor { public: ir_copy_propagation_elements_visitor() { this->progress = false; this->killed_all = false; this->mem_ctx = ralloc_context(NULL); this->lin_ctx = linear_alloc_parent(this->mem_ctx, 0); this->shader_mem_ctx = NULL; this->kills = new(mem_ctx) exec_list; this->state = copy_propagation_state::create(mem_ctx); } ~ir_copy_propagation_elements_visitor() { ralloc_free(mem_ctx); } virtual ir_visitor_status visit(ir_dereference_variable *); void handle_loop(ir_loop *, bool keep_acp); virtual ir_visitor_status visit_enter(class ir_loop *); virtual ir_visitor_status visit_enter(class ir_function_signature *); virtual ir_visitor_status visit_leave(class ir_assignment *); virtual ir_visitor_status visit_enter(class ir_call *); virtual ir_visitor_status visit_enter(class ir_if *); virtual ir_visitor_status visit_leave(class ir_swizzle *); void handle_rvalue(ir_rvalue **rvalue); void add_copy(ir_assignment *ir); void kill(kill_entry *k); void handle_if_block(exec_list *instructions, exec_list *kills, bool *killed_all); copy_propagation_state *state; /** * List of kill_entry: The variables whose values were killed in this * block. */ exec_list *kills; bool progress; bool killed_all; /* Context for our local data structures. */ void *mem_ctx; void *lin_ctx; /* Context for allocating new shader nodes. */ void *shader_mem_ctx; }; } /* unnamed namespace */ ir_visitor_status ir_copy_propagation_elements_visitor::visit(ir_dereference_variable *ir) { if (this->in_assignee) return visit_continue; const acp_entry *entry = state->read(ir->var); if (entry && entry->rhs_full) { ir->var = (ir_variable *) entry->rhs_full; progress = true; } return visit_continue; } ir_visitor_status ir_copy_propagation_elements_visitor::visit_enter(ir_function_signature *ir) { /* Treat entry into a function signature as a completely separate * block. Any instructions at global scope will be shuffled into * main() at link time, so they're irrelevant to us. */ exec_list *orig_kills = this->kills; bool orig_killed_all = this->killed_all; this->kills = new(mem_ctx) exec_list; this->killed_all = false; copy_propagation_state *orig_state = state; this->state = copy_propagation_state::create(mem_ctx); visit_list_elements(this, &ir->body); delete this->state; this->state = orig_state; ralloc_free(this->kills); this->kills = orig_kills; this->killed_all = orig_killed_all; return visit_continue_with_parent; } ir_visitor_status ir_copy_propagation_elements_visitor::visit_leave(ir_assignment *ir) { ir_dereference_variable *lhs = ir->lhs->as_dereference_variable(); ir_variable *var = ir->lhs->variable_referenced(); kill_entry *k; if (lhs && var->type->is_vector()) k = new(this->lin_ctx) kill_entry(var, ir->write_mask); else k = new(this->lin_ctx) kill_entry(var, ~0); kill(k); add_copy(ir); return visit_continue; } ir_visitor_status ir_copy_propagation_elements_visitor::visit_leave(ir_swizzle *) { /* Don't visit the values of swizzles since they are handled while * visiting the swizzle itself. */ return visit_continue; } /** * Replaces dereferences of ACP RHS variables with ACP LHS variables. * * This is where the actual copy propagation occurs. Note that the * rewriting of ir_dereference means that the ir_dereference instance * must not be shared by multiple IR operations! */ void ir_copy_propagation_elements_visitor::handle_rvalue(ir_rvalue **ir) { int swizzle_chan[4]; ir_dereference_variable *deref_var; ir_variable *source[4] = {NULL, NULL, NULL, NULL}; int source_chan[4] = {0, 0, 0, 0}; int chans; bool noop_swizzle = true; if (!*ir) return; ir_swizzle *swizzle = (*ir)->as_swizzle(); if (swizzle) { deref_var = swizzle->val->as_dereference_variable(); if (!deref_var) return; swizzle_chan[0] = swizzle->mask.x; swizzle_chan[1] = swizzle->mask.y; swizzle_chan[2] = swizzle->mask.z; swizzle_chan[3] = swizzle->mask.w; chans = swizzle->type->vector_elements; } else { deref_var = (*ir)->as_dereference_variable(); if (!deref_var) return; swizzle_chan[0] = 0; swizzle_chan[1] = 1; swizzle_chan[2] = 2; swizzle_chan[3] = 3; chans = deref_var->type->vector_elements; } if (this->in_assignee) return; ir_variable *var = deref_var->var; /* Try to find ACP entries covering swizzle_chan[], hoping they're * the same source variable. */ const acp_entry *entry = state->read(var); if (entry) { for (int c = 0; c < chans; c++) { unsigned index = swizzle_chan[c]; ir_variable *src = entry->rhs_element[index]; if (!src) continue; source[c] = src; source_chan[c] = entry->rhs_channel[index]; if (source_chan[c] != swizzle_chan[c]) noop_swizzle = false; } } /* Make sure all channels are copying from the same source variable. */ if (!source[0]) return; for (int c = 1; c < chans; c++) { if (source[c] != source[0]) return; } if (!shader_mem_ctx) shader_mem_ctx = ralloc_parent(deref_var); /* Don't pointlessly replace the rvalue with itself (or a noop swizzle * of itself, which would just be deleted by opt_noop_swizzle). */ if (source[0] == var && noop_swizzle) return; if (debug) { printf("Copy propagation from:\n"); (*ir)->print(); } deref_var = new(shader_mem_ctx) ir_dereference_variable(source[0]); *ir = new(shader_mem_ctx) ir_swizzle(deref_var, source_chan[0], source_chan[1], source_chan[2], source_chan[3], chans); progress = true; if (debug) { printf("to:\n"); (*ir)->print(); printf("\n"); } } ir_visitor_status ir_copy_propagation_elements_visitor::visit_enter(ir_call *ir) { /* Do copy propagation on call parameters, but skip any out params */ foreach_two_lists(formal_node, &ir->callee->parameters, actual_node, &ir->actual_parameters) { ir_variable *sig_param = (ir_variable *) formal_node; ir_rvalue *ir = (ir_rvalue *) actual_node; if (sig_param->data.mode != ir_var_function_out && sig_param->data.mode != ir_var_function_inout) { ir->accept(this); } } if (!ir->callee->is_intrinsic()) { state->erase_all(); this->killed_all = true; } else { if (ir->return_deref) { kill(new(this->lin_ctx) kill_entry(ir->return_deref->var, ~0)); } foreach_two_lists(formal_node, &ir->callee->parameters, actual_node, &ir->actual_parameters) { ir_variable *sig_param = (ir_variable *) formal_node; if (sig_param->data.mode == ir_var_function_out || sig_param->data.mode == ir_var_function_inout) { ir_rvalue *ir = (ir_rvalue *) actual_node; ir_variable *var = ir->variable_referenced(); kill(new(this->lin_ctx) kill_entry(var, ~0)); } } } return visit_continue_with_parent; } void ir_copy_propagation_elements_visitor::handle_if_block(exec_list *instructions, exec_list *kills, bool *killed_all) { exec_list *orig_kills = this->kills; bool orig_killed_all = this->killed_all; this->kills = kills; this->killed_all = false; /* Populate the initial acp with a copy of the original */ copy_propagation_state *orig_state = state; this->state = orig_state->clone(); visit_list_elements(this, instructions); delete this->state; this->state = orig_state; *killed_all = this->killed_all; this->kills = orig_kills; this->killed_all = orig_killed_all; } ir_visitor_status ir_copy_propagation_elements_visitor::visit_enter(ir_if *ir) { ir->condition->accept(this); exec_list *new_kills = new(mem_ctx) exec_list; bool then_killed_all = false; bool else_killed_all = false; handle_if_block(&ir->then_instructions, new_kills, &then_killed_all); handle_if_block(&ir->else_instructions, new_kills, &else_killed_all); if (then_killed_all || else_killed_all) { state->erase_all(); killed_all = true; } else { foreach_in_list_safe(kill_entry, k, new_kills) kill(k); } ralloc_free(new_kills); /* handle_if_block() already descended into the children. */ return visit_continue_with_parent; } void ir_copy_propagation_elements_visitor::handle_loop(ir_loop *ir, bool keep_acp) { exec_list *orig_kills = this->kills; bool orig_killed_all = this->killed_all; this->kills = new(mem_ctx) exec_list; this->killed_all = false; copy_propagation_state *orig_state = state; if (keep_acp) { /* Populate the initial acp with a copy of the original */ this->state = orig_state->clone(); } else { this->state = copy_propagation_state::create(mem_ctx); } visit_list_elements(this, &ir->body_instructions); delete this->state; this->state = orig_state; if (this->killed_all) this->state->erase_all(); exec_list *new_kills = this->kills; this->kills = orig_kills; this->killed_all = this->killed_all || orig_killed_all; foreach_in_list_safe(kill_entry, k, new_kills) { kill(k); } ralloc_free(new_kills); } ir_visitor_status ir_copy_propagation_elements_visitor::visit_enter(ir_loop *ir) { handle_loop(ir, false); handle_loop(ir, true); /* already descended into the children. */ return visit_continue_with_parent; } /* Remove any entries currently in the ACP for this kill. */ void ir_copy_propagation_elements_visitor::kill(kill_entry *k) { state->erase(k->var, k->write_mask); /* If we were on a list, remove ourselves before inserting */ if (k->next) k->remove(); this->kills->push_tail(k); } /** * Adds directly-copied channels between vector variables to the available * copy propagation list. */ void ir_copy_propagation_elements_visitor::add_copy(ir_assignment *ir) { if (ir->condition) return; { ir_variable *lhs_var = ir->whole_variable_written(); ir_dereference_variable *rhs = ir->rhs->as_dereference_variable(); if (lhs_var != NULL && rhs && rhs->var != NULL && lhs_var != rhs->var) { if (lhs_var->data.mode == ir_var_shader_storage || lhs_var->data.mode == ir_var_shader_shared || rhs->var->data.mode == ir_var_shader_storage || rhs->var->data.mode == ir_var_shader_shared || lhs_var->data.precise != rhs->var->data.precise) { return; } state->write_full(lhs_var, rhs->var); return; } } int orig_swizzle[4] = {0, 1, 2, 3}; int swizzle[4]; ir_dereference_variable *lhs = ir->lhs->as_dereference_variable(); if (!lhs || !(lhs->type->is_scalar() || lhs->type->is_vector())) return; if (lhs->var->data.mode == ir_var_shader_storage || lhs->var->data.mode == ir_var_shader_shared) return; ir_dereference_variable *rhs = ir->rhs->as_dereference_variable(); if (!rhs) { ir_swizzle *swiz = ir->rhs->as_swizzle(); if (!swiz) return; rhs = swiz->val->as_dereference_variable(); if (!rhs) return; orig_swizzle[0] = swiz->mask.x; orig_swizzle[1] = swiz->mask.y; orig_swizzle[2] = swiz->mask.z; orig_swizzle[3] = swiz->mask.w; } if (rhs->var->data.mode == ir_var_shader_storage || rhs->var->data.mode == ir_var_shader_shared) return; /* Move the swizzle channels out to the positions they match in the * destination. We don't want to have to rewrite the swizzle[] * array every time we clear a bit of the write_mask. */ int j = 0; for (int i = 0; i < 4; i++) { if (ir->write_mask & (1 << i)) swizzle[i] = orig_swizzle[j++]; } int write_mask = ir->write_mask; if (lhs->var == rhs->var) { /* If this is a copy from the variable to itself, then we need * to be sure not to include the updated channels from this * instruction in the set of new source channels to be * copy-propagated from. */ for (int i = 0; i < 4; i++) { if (ir->write_mask & (1 << orig_swizzle[i])) write_mask &= ~(1 << i); } } if (lhs->var->data.precise != rhs->var->data.precise) return; state->write_elements(lhs->var, rhs->var, write_mask, swizzle); } bool do_copy_propagation_elements(exec_list *instructions) { ir_copy_propagation_elements_visitor v; visit_list_elements(&v, instructions); return v.progress; }
org 0x7c00 [bits 16] ; First, BIOS loads the bootsector into 0000:7C00. mov ax, 0x1301 mov bx, 0x000c mov cx, 5 mov dx, 0x0808 mov bp, msg int 0x10 jmp $ msg: db "HELLO", 0 times 510-($-$$) db 0 dw 0xAA55
/* * Copyright (C) 2012-2015 Open Source Robotics Foundation * * 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. * */ /* * Desc: Projector * Author: Jared Duke, John Hsu, Nate Koenig */ #include "gazebo/rendering/RTShaderSystem.hh" #include "gazebo/rendering/Conversions.hh" #include "gazebo/rendering/Visual.hh" #include "gazebo/rendering/Scene.hh" #include "gazebo/rendering/Projector.hh" using namespace gazebo; using namespace rendering; typedef std::map<std::string, Ogre::Pass*> OgrePassMap; typedef OgrePassMap::iterator OgrePassMapIterator; ///////////////////////////////////////////////// Projector::Projector(rendering::VisualPtr _parent) { this->visual = _parent; this->node = transport::NodePtr(new transport::Node()); this->node->Init(this->visual->GetScene()->GetName()); } ///////////////////////////////////////////////// Projector::~Projector() { this->SetEnabled(false); // Ogre cleanup Ogre::Root::getSingletonPtr()->removeFrameListener(&this->projector); } ///////////////////////////////////////////////// void Projector::Load(const std::string &_name, const math::Pose &_pose, const std::string &_textureName, double _nearClip, double _farClip, double _fov) { std::string topicName = std::string("~/") + _name; boost::replace_all(topicName, "::", "/"); this->controlSub = this->node->Subscribe(topicName, &Projector::OnMsg, this); if (!this->visual) return; int retryCount = 0; // Initialize the projector while (!this->projector.initialized && retryCount < 10) { // init this->projector.Init(this->visual, _textureName, _nearClip, _farClip, _fov); // set the projector pose relative to body this->projector.SetPose(_pose); if (!this->projector.initialized) { gzwarn << "starting projector failed, retrying in 1 sec.\n"; common::Time::MSleep(1000); ++retryCount; } } // Add the projector as an Ogre frame listener Ogre::Root::getSingletonPtr()->addFrameListener(&this->projector); this->projector.SetEnabled(true); // Start projector /*this->add_model_event_ = gazebo::event::Events::ConnectWorldUpdateStart( boost::bind(&Projector::ToggleProjector, this, true)); */ } ///////////////////////////////////////////////// void Projector::Load(sdf::ElementPtr _sdf) { math::Pose pose; std::string textureName; double nearClip = 0.1; double farClip = 10.0; double fov = M_PI * 0.25; if (_sdf->HasElement("pose")) pose = _sdf->Get<math::Pose>("pose"); if (_sdf->HasElement("texture_name")) textureName = _sdf->Get<std::string>("texture_name"); if (_sdf->HasElement("near_clip")) nearClip = _sdf->Get<double>("near_clip"); if (_sdf->HasElement("far_clip")) farClip = _sdf->Get<double>("far_clip"); if (_sdf->HasElement("fov")) fov = _sdf->Get<double>("fov"); this->Load(_sdf->Get<std::string>("name"), pose, textureName, nearClip, farClip, fov); } ///////////////////////////////////////////////// void Projector::Load(const msgs::Projector &_msg) { ignition::math::Pose3d pose; std::string textureName; double nearClip = 0.1; double farClip = 10.0; double fov = M_PI * 0.25; if (_msg.has_pose()) pose = msgs::ConvertIgn(_msg.pose()); if (_msg.has_texture()) textureName = _msg.texture(); if (_msg.has_near_clip()) nearClip = _msg.near_clip(); if (_msg.has_far_clip()) farClip = _msg.far_clip(); if (_msg.has_fov()) fov = _msg.fov(); this->Load(_msg.name(), pose, textureName, nearClip, farClip, fov); } ///////////////////////////////////////////////// void Projector::SetEnabled(bool _enabled) { this->projector.SetEnabled(_enabled); } ///////////////////////////////////////////////// void Projector::SetTexture(const std::string &_textureName) { this->projector.SetTexture(_textureName); } ///////////////////////////////////////////////// void Projector::Toggle() { // if not headless /*if (this->projector.initialized) { this->projector.SetEnabled(!this->projector.enabled); } else gzwarn << "could not start projector, toggle failed\n"; */ } ///////////////////////////////////////////////// VisualPtr Projector::GetParent() { return this->visual; } ///////////////////////////////////////////////// Projector::ProjectorFrameListener::ProjectorFrameListener() { this->enabled = false; this->initialized = false; this->usingShaders = false; this->node = NULL; this->filterNode = NULL; this->projectorQuery = NULL; this->frustum = NULL; this->filterFrustum = NULL; this->nodeName = "Projector"; this->filterNodeName = "ProjectorFilter"; } ///////////////////////////////////////////////// Projector::ProjectorFrameListener::~ProjectorFrameListener() { this->RemovePassFromMaterials(); if (this->node) { this->node->detachObject(this->frustum); this->visual->GetSceneNode()->removeAndDestroyChild(this->nodeName); this->node = NULL; } if (this->filterNode) { this->filterNode->detachObject(this->filterFrustum); this->visual->GetSceneNode()->removeAndDestroyChild(this->filterNodeName); this->filterNode = NULL; } delete this->frustum; delete this->filterFrustum; this->frustum = NULL; this->filterFrustum = NULL; if (this->projectorQuery) this->sceneMgr->destroyQuery(this->projectorQuery); this->visual.reset(); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::Init(VisualPtr _visual, const std::string &_textureName, double _near, double _far, double _fov) { if (this->initialized) return; if (_textureName.empty()) { gzerr << "Projector is missing a texture\n"; return; } this->visual = _visual; this->nodeName = this->visual->GetName() + "_Projector"; this->filterNodeName = this->visual->GetName() + "_ProjectorFilter"; this->frustum = new Ogre::Frustum(); this->filterFrustum = new Ogre::Frustum(); this->filterFrustum->setProjectionType(Ogre::PT_ORTHOGRAPHIC); this->sceneMgr = this->visual->GetScene()->GetManager(); this->projectorQuery = this->sceneMgr->createPlaneBoundedVolumeQuery( Ogre::PlaneBoundedVolumeList()); this->SetSceneNode(); this->SetTexture(_textureName); this->SetFrustumClipDistance(_near, _far); this->SetFrustumFOV(_fov); this->initialized = true; } ///////////////////////////////////////////////// bool Projector::ProjectorFrameListener::frameStarted( const Ogre::FrameEvent &/*_evt*/) { if (!this->initialized || !this->enabled || this->textureName.empty()) return true; this->AddPassToVisibleMaterials(); return true; } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetEnabled(bool _enabled) { this->enabled = _enabled; if (!this->enabled) this->RemovePassFromMaterials(); rendering::RTShaderSystem::Instance()->UpdateShaders(); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetUsingShaders(bool _usingShaders) { this->usingShaders = _usingShaders; } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetSceneNode() { if (this->node) { this->node->detachObject(this->frustum); this->visual->GetSceneNode()->removeAndDestroyChild(this->nodeName); this->node = NULL; } if (this->filterNode) { this->filterNode->detachObject(this->filterFrustum); this->visual->GetSceneNode()->removeAndDestroyChild(this->filterNodeName); this->filterNode = NULL; } this->node = this->visual->GetSceneNode()->createChildSceneNode( this->nodeName); this->filterNode = this->visual->GetSceneNode()->createChildSceneNode( this->filterNodeName); if (this->node) this->node->attachObject(this->frustum); if (this->filterNode) { this->filterNode->attachObject(this->filterFrustum); this->filterNode->setOrientation( Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3::UNIT_Y)); } } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetPose(const math::Pose &_pose) { Ogre::Quaternion ogreQuaternion = Conversions::Convert(_pose.rot); Ogre::Vector3 ogreVec = Conversions::Convert(_pose.pos); Ogre::Quaternion offsetQuaternion; this->node->setPosition(ogreVec); this->node->setOrientation(ogreQuaternion); this->filterNode->setPosition(ogreVec); offsetQuaternion = Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3::UNIT_Y); this->filterNode->setOrientation(offsetQuaternion + ogreQuaternion); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetTexture( const std::string &_textureName) { this->textureName = _textureName; } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetFrustumClipDistance(double _near, double _far) { this->frustum->setNearClipDistance(_near); this->filterFrustum->setNearClipDistance(_near); this->frustum->setFarClipDistance(_far); this->filterFrustum->setFarClipDistance(_far); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::SetFrustumFOV(double _fov) { this->frustum->setFOVy(Ogre::Radian(_fov)); this->filterFrustum->setFOVy(Ogre::Radian(_fov)); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::AddPassToAllMaterials() { std::list<std::string> allMaterials; Ogre::SceneManager::MovableObjectIterator it = this->sceneMgr->getMovableObjectIterator("Entity"); while (it.hasMoreElements()) { Ogre::Entity* entity = dynamic_cast<Ogre::Entity*>(it.getNext()); if (entity && entity->getName().find("visual") != std::string::npos) for (unsigned int i = 0; i < entity->getNumSubEntities(); i++) { allMaterials.push_back(entity->getSubEntity(i)->getMaterialName()); } } this->AddPassToMaterials(allMaterials); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::AddPassToVisibleMaterials() { std::list<std::string> newVisibleMaterials; Ogre::PlaneBoundedVolumeList volumeList; volumeList.push_back(this->frustum->getPlaneBoundedVolume()); this->projectorQuery->setVolumes(volumeList); Ogre::SceneQueryResult result = this->projectorQuery->execute(); // Find all visible materials Ogre::SceneQueryResultMovableList::iterator it; for (it = result.movables.begin(); it != result.movables.end(); ++it) { Ogre::Entity *entity = dynamic_cast<Ogre::Entity*>(*it); if (entity && entity->getName().find("visual") != std::string::npos) { for (unsigned int i = 0; i < entity->getNumSubEntities(); i++) { newVisibleMaterials.push_back( entity->getSubEntity(i)->getMaterialName()); } } } this->AddPassToMaterials(newVisibleMaterials); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::AddPassToMaterials( std::list<std::string> &_matList) { _matList.remove(""); _matList.unique(); std::string invisibleMaterial; std::list<std::string>::iterator visibleMaterial; // Loop through all existing passes, removing those for materials // not in the newlist and skipping pass creation for those in the // newlist that have already been created OgrePassMapIterator used = projectorTargets.begin(); while (used != projectorTargets.end()) { visibleMaterial = std::find(_matList.begin(), _matList.end(), used->first); // Remove the pass if it applies to a material not in the new list if (visibleMaterial == _matList.end()) { invisibleMaterial = used->first; ++used; this->RemovePassFromMaterial(invisibleMaterial); } // Otherwise remove it from the list of passes to be added else { _matList.remove(used->first); ++used; } } if (!_matList.empty()) { // Add pass for new materials while (!_matList.empty()) { this->AddPassToMaterial(_matList.front()); _matList.erase(_matList.begin()); } RTShaderSystem::Instance()->UpdateShaders(); } } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::AddPassToMaterial( const std::string &_matName) { if (this->projectorTargets.find(_matName) != this->projectorTargets.end()) { return; } Ogre::MaterialPtr mat = static_cast<Ogre::MaterialPtr>( Ogre::MaterialManager::getSingleton().getByName(_matName)); Ogre::Pass *pass = mat->getTechnique(0)->createPass(); if (this->usingShaders) { Ogre::Matrix4 viewProj = this->frustum->getProjectionMatrix() * this->frustum->getViewMatrix(); pass->setVertexProgram("Gazebo/TextureProjectionVP"); // pass->setFragmentProgram("GazeboWorlds/TexProjectionFP"); Ogre::GpuProgramParametersSharedPtr vsParams = pass->getVertexProgramParameters(); Ogre::GpuProgramParametersSharedPtr psParams = pass->getFragmentProgramParameters(); // vsParams->setNamedAutoConstant( // "worldViewProjMatrix", // GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); // vsParams->setNamedAutoConstant( // "worldMatrix",GpuProgramParameters::ACT_WORLD_MATRIX); // vsParams->setNamedConstant("texViewProjMatrix", viewProj); vsParams->setNamedAutoConstant( "worldMatrix", Ogre::GpuProgramParameters::ACT_WORLD_MATRIX); vsParams->setNamedConstant("texProjMatrix", viewProj); // psParams->setNamedConstant("projMap", viewProj); pass->setVertexProgramParameters(vsParams); // pass->setFragmentProgramParameters(psParams); } pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA); pass->setDepthBias(1); pass->setLightingEnabled(false); Ogre::TextureUnitState *texState = pass->createTextureUnitState(this->textureName); texState->setProjectiveTexturing(true, this->frustum); texState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_BORDER); texState->setTextureFiltering(Ogre::TFO_ANISOTROPIC); texState->setTextureBorderColour(Ogre::ColourValue(0.0, 0.0, 0.0, 0.0)); texState->setColourOperation(Ogre::LBO_ALPHA_BLEND); texState = pass->createTextureUnitState("projection_filter.png"); texState->setProjectiveTexturing(true, this->filterFrustum); texState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP); texState->setTextureFiltering(Ogre::TFO_NONE); this->projectorTargets[_matName] = pass; } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::RemovePassFromMaterials() { for (OgrePassMap::const_iterator it = this->projectorTargets.begin(); it != this->projectorTargets.end(); ++it) { it->second->getParent()->removePass(it->second->getIndex()); } this->projectorTargets.clear(); } ///////////////////////////////////////////////// void Projector::ProjectorFrameListener::RemovePassFromMaterial( const std::string &_matName) { this->projectorTargets[_matName]->getParent()->removePass( this->projectorTargets[_matName]->getIndex()); this->projectorTargets.erase(this->projectorTargets.find(_matName)); } ///////////////////////////////////////////////// void Projector::OnMsg(ConstProjectorPtr &_msg) { if (_msg->has_enabled()) this->projector.SetEnabled(_msg->enabled()); }
; First, let's include libraries INCLUDE "hardware.inc/hardware.inc" rev_Check_hardware_inc 3.0 INCLUDE "rgbds-structs/structs.asm" ; include the user-facing config file INCLUDE "kit_config.inc" ; A couple more hardware defines NB_SPRITES equ 40 ; I generally discourage the use of pseudo-instructions for a variety of reasons, ; but this one includes a label, and manually giving them different names is tedious. wait_vram: MACRO .waitVRAM\@ ldh a, [rSTAT] and STATF_BUSY jr nz, .waitVRAM\@ ENDM ; `ld b, X` followed by `ld c, Y` is wasteful (same with other reg pairs). ; This writes to both halves of the pair at once, without sacrificing readability ; Example usage: `lb bc, X, Y` lb: MACRO assert -128 <= (\2) && (\2) <= 255, "Second argument to `lb` must be 8-bit!" assert -128 <= (\3) && (\3) <= 255, "Third argument to `lb` must be 8-bit!" ld \1, (LOW(\2) << 8) | LOW(\3) ENDM ; SGB packet types RSRESET PAL01 rb 1 PAL23 rb 1 PAL12 rb 1 PAL03 rb 1 ATTR_BLK rb 1 ATTR_LIN rb 1 ATTR_DIV rb 1 ATTR_CHR rb 1 SOUND rb 1 ; $08 SOU_TRN rb 1 PAL_SET rb 1 PAL_TRN rb 1 ATRC_EN rb 1 TEST_EN rb 1 ICON_EN rb 1 DATA_SND rb 1 DATA_TRN rb 1 ; $10 MLT_REQ rb 1 JUMP rb 1 CHR_TRN rb 1 PCT_TRN rb 1 ATTR_TRN rb 1 ATTR_SET rb 1 MASK_EN rb 1 OBJ_TRN rb 1 ; $18 PAL_PRI rb 1 SGB_PACKET_SIZE equ 16 ; sgb_packet packet_type, nb_packets, data... sgb_packet: MACRO PACKET_SIZE equ _NARG - 1 ; Size of what's below db (\1 << 3) | (\2) REPT _NARG - 2 SHIFT db \2 ENDR ds SGB_PACKET_SIZE - PACKET_SIZE, 0 ENDM ; 64 bytes, should be sufficient for most purposes. If you're really starved on ; check your stack usage and consider setting this to 32 instead. 16 is probably not enough. STACK_SIZE equ $40 ; Use this to cause a crash. ; I don't recommend using this unless you want a condition: ; `call cc, Crash` is 3 bytes (`cc` being a condition); `error cc` is only 2 bytes ; This should help minimize the impact of error checking error: MACRO IF _NARG == 0 rst Crash ELSE assert Crash == $0038 ; This assembles to XX FF (with XX being the `jr` instruction) ; If the condition is fulfilled, this jumps to the operand: $FF ; $FF encodes the instruction `rst $38`! jr \1, @+1 ENDC ENDM
GLOBAL _getHour GLOBAL _getMinute GLOBAL _getSecond section .text get: out 70h, al in al, 71h ret _getHour: push rbp mov rbp, rsp call statusRegisterB mov rax, 0h mov al, 4h call get mov rsp, rbp pop rbp ret _getMinute: push rbp mov rbp, rsp call statusRegisterB mov rax, 0h mov al, 2h call get mov rsp, rbp pop rbp ret _getSecond: push rbp mov rbp, rsp call statusRegisterB mov rax, 0h call get mov rsp, rbp pop rbp ret statusRegisterB: push rbp mov rbp, rsp mov al,0x0B ; RTC Status Register B out 70h,al in al, 71h or al, 0x04 out 71h, al ; 24 hour format time mov rsp, rbp pop rbp ret
; sccz80 crt0 library - 8085 version SECTION code_crt0_sccz80 PUBLIC l_mult ; HL = DE * HL [signed] .l_mult ccmul: LD b,h LD c,l LD hl,0 ccmul1: LD a,c RRCA JP NC,ccmul2 ADD hl,de ccmul2: XOR a LD a,b RRA LD b,a LD a,c RRA LD c,a OR b RET Z XOR a RL de LD a,d OR e RET Z JP ccmul1
; A248675: Decimal expansion of r = sum_{n >= 0} floor(n/2)!/n!. ; Submitted by Jamie Morken(s2) ; 2,7,7,6,8,8,9,6,0,9,4,0,7,9,7,9,7,2,6,9,8,1,2,4,5,1,6,3,6,1,7,1,8,8,0,6,1,8,5,3,8,4,9,8,3,6,6,5,0,9,6,1,3,1,1,3,2,7,0,5,7,5,0,9,5,9,6,1,1,0,3,8,8,4,9,9,5,2,2,6,7,1,0,8,1,7,3,3,0,5,4,7,2,5,2,2,8,3,1,2 mov $1,1 mov $2,1 mov $3,$0 mul $3,5 lpb $3 add $1,$2 mov $5,$3 mul $5,2 add $5,1 mul $2,$5 add $1,$2 mov $5,$0 add $5,$0 mov $4,$5 cmp $4,0 add $5,$4 div $1,$5 mov $4,$0 cmp $4,0 mov $5,$0 add $5,$4 div $2,$5 sub $3,1 lpe mov $6,10 pow $6,$0 div $2,$6 div $1,$2 add $1,$6 mov $0,$1 mod $0,10
dnl AMD64 mpn_addmul_1 and mpn_submul_1 optimised for Intel Haswell. dnl Contributed to the GNU project by Torbjörn Granlund. dnl Copyright 2013 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb C AMD K8,K9 - C AMD K10 - C AMD bull - C AMD pile - C AMD steam - C AMD excavator - C AMD bobcat - C AMD jaguar - C Intel P4 - C Intel core2 - C Intel NHM - C Intel SBR - C Intel IBR - C Intel HWL 2.32 C Intel BWL 2.04 C Intel SKL 1.95 C Intel atom - C Intel SLM - C VIA nano - C The loop of this code is the result of running a code generation and C optimisation tool suite written by David Harvey and Torbjörn Granlund. C TODO C * Handle small n separately, for lower overhead. define(`rp', `%rdi') C rcx define(`up', `%rsi') C rdx define(`n_param', `%rdx') C r8 define(`v0_param',`%rcx') C r9 define(`n', `%rbp') define(`v0', `%rdx') ifdef(`OPERATION_addmul_1',` define(`ADDSUB', `add') define(`ADCSBB', `adc') define(`func', `mpn_addmul_1') ') ifdef(`OPERATION_submul_1',` define(`ADDSUB', `sub') define(`ADCSBB', `sbb') define(`func', `mpn_submul_1') ') ABI_SUPPORT(DOS64) ABI_SUPPORT(STD64) MULFUNC_PROLOGUE(mpn_addmul_1 mpn_submul_1) ASM_START() TEXT ALIGN(16) PROLOGUE(func) FUNC_ENTRY(4) push %rbx push %rbp push %r12 push %r13 mov n_param, n mov v0_param, v0 test $1, R8(n) jnz L(bx1) L(bx0): shr $2, n jc L(b10) L(b00): mulx( (up), %r13, %r12) mulx( 8,(up), %rbx, %rax) add %r12, %rbx adc $0, %rax mov (rp), %r12 mov 8(rp), %rcx mulx( 16,(up), %r9, %r8) lea -16(rp), rp lea 16(up), up ADDSUB %r13, %r12 jmp L(lo0) L(bx1): shr $2, n jc L(b11) L(b01): mulx( (up), %r11, %r10) jnz L(gt1) L(n1): ADDSUB %r11, (rp) mov $0, R32(%rax) adc %r10, %rax jmp L(ret) L(gt1): mulx( 8,(up), %r13, %r12) mulx( 16,(up), %rbx, %rax) lea 24(up), up add %r10, %r13 adc %r12, %rbx adc $0, %rax mov (rp), %r10 mov 8(rp), %r12 mov 16(rp), %rcx lea -8(rp), rp ADDSUB %r11, %r10 jmp L(lo1) L(b11): mulx( (up), %rbx, %rax) mov (rp), %rcx mulx( 8,(up), %r9, %r8) lea 8(up), up lea -24(rp), rp inc n C adjust n ADDSUB %rbx, %rcx jmp L(lo3) L(b10): mulx( (up), %r9, %r8) mulx( 8,(up), %r11, %r10) lea -32(rp), rp mov $0, R32(%rax) clc C clear cf jz L(end) C depends on old shift ALIGN(16) L(top): adc %rax, %r9 lea 32(rp), rp adc %r8, %r11 mulx( 16,(up), %r13, %r12) mov (rp), %r8 mulx( 24,(up), %rbx, %rax) lea 32(up), up adc %r10, %r13 adc %r12, %rbx adc $0, %rax mov 8(rp), %r10 mov 16(rp), %r12 ADDSUB %r9, %r8 mov 24(rp), %rcx mov %r8, (rp) ADCSBB %r11, %r10 L(lo1): mulx( (up), %r9, %r8) mov %r10, 8(rp) ADCSBB %r13, %r12 L(lo0): mov %r12, 16(rp) ADCSBB %rbx, %rcx L(lo3): mulx( 8,(up), %r11, %r10) mov %rcx, 24(rp) dec n jnz L(top) L(end): adc %rax, %r9 adc %r8, %r11 mov 32(rp), %r8 mov %r10, %rax adc $0, %rax mov 40(rp), %r10 ADDSUB %r9, %r8 mov %r8, 32(rp) ADCSBB %r11, %r10 mov %r10, 40(rp) adc $0, %rax L(ret): pop %r13 pop %r12 pop %rbp pop %rbx FUNC_EXIT() ret EPILOGUE()
;print whether a number is odd or even section .data msg1 : db 'Enter number : ' l1 : equ $-msg1 ans1 : db 'Odd', 10 l2 : equ $-ans1 ans2 : db 'Even', 10 l3 : equ $-ans2 section .bss d1 : resb 1 section .text global _start: _start: mov eax, 4 mov ebx, 1 mov ecx, msg1 mov edx, l1 int 80h mov eax, 3 mov ebx, 0 mov ecx, d1 mov edx, 1 int 80h sub byte[d1], 30h mov ax, word[d1] ;mov ah, 0 mov bl, 2 div bl cmp ah, 0 je if else: mov eax, 4 mov ebx, 1 mov ecx, ans1 mov edx, l2 int 80h mov eax, 1 mov ebx, 0 int 80h if: mov eax, 4 mov ebx, 1 mov ecx, ans2 mov edx, l3 int 80h mov eax, 1 mov ebx, 0 int 80h
; A217123: Number of possible ordered pairs (x, y) where x is the number of beads adjacent to at least one black bead and y the number of beads adjacent to at least one white bead in a binary necklace of length n. ; 2,3,4,6,8,10,14,18,22,26,32,38,44,50,58,66,74,82,92,102,112,122,134,146,158,170,184,198,212,226,242,258,274,290,308,326,344,362,382,402,422,442,464,486,508,530,554,578,602,626,652,678 mov $1,2 lpb $0 add $1,$0 trn $1,4 add $1,$0 trn $0,4 add $1,2 lpe mov $0,$1
; A343694: a(n) is the number of men's preference profiles in the stable marriage problem with n men and n women, such that all men prefer different women as their first choices. ; Submitted by Christian Krause ; 1,2,48,31104,955514880,2149908480000000,505542895416115200000000,16786680128857246009393152000000000,102199258264429373853760111996211036160000000000,143679021498505654124337567125614729953051527872512000000000000 add $0,1 mov $2,2 mov $3,$0 sub $3,2 mov $4,$0 lpb $3 mov $1,$0 mov $5,$2 mov $6,1 add $6,$4 pow $5,$6 mul $1,$5 mov $0,$1 add $2,1 sub $3,1 lpe
; A040007: Continued fraction for sqrt(11). ; Submitted by Christian Krause ; 3,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3,6,3 trn $0,1 mod $0,2 mul $0,3 add $0,3
#pragma once #include <steem/protocol/authority.hpp> #include <steem/protocol/steem_operations.hpp> #include <steem/chain/steem_object_types.hpp> #include <steem/chain/witness_objects.hpp> #include <boost/multi_index/composite_key.hpp> namespace steem { namespace chain { using protocol::beneficiary_route_type; using chainbase::t_vector; using chainbase::t_pair; #ifdef STEEM_ENABLE_SMT using protocol::votable_asset_info; #endif struct strcmp_less { bool operator()( const shared_string& a, const shared_string& b )const { return less( a.c_str(), b.c_str() ); } #ifndef ENABLE_STD_ALLOCATOR bool operator()( const shared_string& a, const string& b )const { return less( a.c_str(), b.c_str() ); } bool operator()( const string& a, const shared_string& b )const { return less( a.c_str(), b.c_str() ); } #endif private: inline bool less( const char* a, const char* b )const { return std::strcmp( a, b ) < 0; } }; class comment_object : public object < comment_object_type, comment_object > { comment_object() = delete; public: template< typename Constructor, typename Allocator > comment_object( Constructor&& c, allocator< Allocator > a ) :category( a ), parent_permlink( a ), permlink( a ), beneficiaries( a ) #ifdef STEEM_ENABLE_SMT , allowed_vote_assets( a ) #endif { c( *this ); } id_type id; shared_string category; account_name_type parent_author; shared_string parent_permlink; account_name_type author; shared_string permlink; time_point_sec last_update; time_point_sec created; time_point_sec active; ///< the last time this post was "touched" by voting or reply time_point_sec last_payout; uint16_t depth = 0; ///< used to track max nested depth uint32_t children = 0; ///< used to track the total number of children, grandchildren, etc... /// index on pending_payout for "things happning now... needs moderation" /// TRENDING = UNCLAIMED + PENDING share_type net_rshares; // reward is proportional to rshares^2, this is the sum of all votes (positive and negative) share_type abs_rshares; /// this is used to track the total abs(weight) of votes for the purpose of calculating cashout_time share_type vote_rshares; /// Total positive rshares from all votes. Used to calculate delta weights. Needed to handle vote changing and removal. share_type children_abs_rshares; /// this is used to calculate cashout time of a discussion. time_point_sec cashout_time; /// 24 hours from the weighted average of vote time time_point_sec max_cashout_time; uint64_t total_vote_weight = 0; /// the total weight of voting rewards, used to calculate pro-rata share of curation payouts uint16_t reward_weight = 0; /** tracks the total payout this comment has received over time, measured in SBD */ asset total_payout_value = asset(0, SBD_SYMBOL); asset curator_payout_value = asset(0, SBD_SYMBOL); asset beneficiary_payout_value = asset( 0, SBD_SYMBOL ); share_type author_rewards = 0; int32_t net_votes = 0; id_type root_comment; asset max_accepted_payout = asset( 1000000000, SBD_SYMBOL ); /// SBD value of the maximum payout this post will receive uint16_t percent_steem_dollars = STEEM_100_PERCENT; /// the percent of Steem Dollars to key, unkept amounts will be received as Steem Power bool allow_replies = true; /// allows a post to disable replies. bool allow_votes = true; /// allows a post to receive votes; bool allow_curation_rewards = true; using t_beneficiaries = t_vector< beneficiary_route_type >; t_beneficiaries beneficiaries; #ifdef STEEM_ENABLE_SMT using t_votable_assets = t_vector< t_pair< asset_symbol_type, votable_asset_info > >; t_votable_assets allowed_vote_assets; #endif }; class comment_content_object : public object< comment_content_object_type, comment_content_object > { comment_content_object() = delete; public: template< typename Constructor, typename Allocator > comment_content_object( Constructor&& c, allocator< Allocator > a ) : title( a ), body( a ), json_metadata( a ), reference( a ), type( a ), anonymous( a ) { c( *this ); } id_type id; comment_id_type comment; shared_string title; shared_string body; shared_string json_metadata; shared_string reference; //ADD shared_string type; shared_string anonymous; uint32_t affect_count = 0; }; /** * This index maintains the set of voter/comment pairs that have been used, voters cannot * vote on the same comment more than once per payout period. */ class comment_vote_object : public object< comment_vote_object_type, comment_vote_object> { public: template< typename Constructor, typename Allocator > comment_vote_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } id_type id; account_id_type voter; comment_id_type comment; uint64_t weight = 0; ///< defines the score this vote receives, used by vote payout calc. 0 if a negative vote or changed votes. int64_t rshares = 0; ///< The number of rshares this vote is responsible for int16_t vote_percent = 0; ///< The percent weight of the vote time_point_sec last_update; ///< The time of the last update of the vote int8_t num_changes = 0; }; struct by_comment_voter; struct by_voter_comment; typedef multi_index_container< comment_vote_object, indexed_by< ordered_unique< tag< by_id >, member< comment_vote_object, comment_vote_id_type, &comment_vote_object::id > >, ordered_unique< tag< by_comment_voter >, composite_key< comment_vote_object, member< comment_vote_object, comment_id_type, &comment_vote_object::comment>, member< comment_vote_object, account_id_type, &comment_vote_object::voter> > >, ordered_unique< tag< by_voter_comment >, composite_key< comment_vote_object, member< comment_vote_object, account_id_type, &comment_vote_object::voter>, member< comment_vote_object, comment_id_type, &comment_vote_object::comment> > > >, allocator< comment_vote_object > > comment_vote_index; struct by_cashout_time; /// cashout_time struct by_permlink; /// author, perm struct by_root; struct by_parent; struct by_last_update; /// parent_auth, last_update struct by_author_last_update; /** * @ingroup object_index */ typedef multi_index_container< comment_object, indexed_by< /// CONSENSUS INDICES - used by evaluators ordered_unique< tag< by_id >, member< comment_object, comment_id_type, &comment_object::id > >, ordered_unique< tag< by_cashout_time >, composite_key< comment_object, member< comment_object, time_point_sec, &comment_object::cashout_time>, member< comment_object, comment_id_type, &comment_object::id > > >, ordered_unique< tag< by_permlink >, /// used by consensus to find posts referenced in ops composite_key< comment_object, member< comment_object, account_name_type, &comment_object::author >, member< comment_object, shared_string, &comment_object::permlink > >, composite_key_compare< std::less< account_name_type >, strcmp_less > >, ordered_unique< tag< by_root >, composite_key< comment_object, member< comment_object, comment_id_type, &comment_object::root_comment >, member< comment_object, comment_id_type, &comment_object::id > > >, ordered_unique< tag< by_parent >, /// used by consensus to find posts referenced in ops composite_key< comment_object, member< comment_object, account_name_type, &comment_object::parent_author >, member< comment_object, shared_string, &comment_object::parent_permlink >, member< comment_object, comment_id_type, &comment_object::id > >, composite_key_compare< std::less< account_name_type >, strcmp_less, std::less< comment_id_type > > > /// NON_CONSENSUS INDICIES - used by APIs #ifndef IS_LOW_MEM , ordered_unique< tag< by_last_update >, composite_key< comment_object, member< comment_object, account_name_type, &comment_object::parent_author >, member< comment_object, time_point_sec, &comment_object::last_update >, member< comment_object, comment_id_type, &comment_object::id > >, composite_key_compare< std::less< account_name_type >, std::greater< time_point_sec >, std::less< comment_id_type > > >, ordered_unique< tag< by_author_last_update >, composite_key< comment_object, member< comment_object, account_name_type, &comment_object::author >, member< comment_object, time_point_sec, &comment_object::last_update >, member< comment_object, comment_id_type, &comment_object::id > >, composite_key_compare< std::less< account_name_type >, std::greater< time_point_sec >, std::less< comment_id_type > > > #endif >, allocator< comment_object > > comment_index; struct by_comment; typedef multi_index_container< comment_content_object, indexed_by< ordered_unique< tag< by_id >, member< comment_content_object, comment_content_id_type, &comment_content_object::id > >, ordered_unique< tag< by_comment >, member< comment_content_object, comment_id_type, &comment_content_object::comment > > >, allocator< comment_content_object > > comment_content_index; } } // steem::chain FC_REFLECT( steem::chain::comment_object, (id)(author)(permlink) (category)(parent_author)(parent_permlink) (last_update)(created)(active)(last_payout) (depth)(children) (net_rshares)(abs_rshares)(vote_rshares) (children_abs_rshares)(cashout_time)(max_cashout_time) (total_vote_weight)(reward_weight)(total_payout_value)(curator_payout_value)(beneficiary_payout_value)(author_rewards)(net_votes)(root_comment) (max_accepted_payout)(percent_steem_dollars)(allow_replies)(allow_votes)(allow_curation_rewards) (beneficiaries) #ifdef STEEM_ENABLE_SMT (allowed_vote_assets) #endif ) CHAINBASE_SET_INDEX_TYPE( steem::chain::comment_object, steem::chain::comment_index ) FC_REFLECT( steem::chain::comment_content_object, (id)(comment)(title)(body)(json_metadata)(reference)(type)(anonymous)(affect_count) ) CHAINBASE_SET_INDEX_TYPE( steem::chain::comment_content_object, steem::chain::comment_content_index ) FC_REFLECT( steem::chain::comment_vote_object, (id)(voter)(comment)(weight)(rshares)(vote_percent)(last_update)(num_changes) ) CHAINBASE_SET_INDEX_TYPE( steem::chain::comment_vote_object, steem::chain::comment_vote_index ) namespace helpers { using steem::chain::shared_string; template <> class index_statistic_provider<steem::chain::comment_index> { public: typedef steem::chain::comment_index IndexType; typedef typename steem::chain::comment_object::t_beneficiaries t_beneficiaries; #ifdef STEEM_ENABLE_SMT typedef typename steem::chain::comment_object::t_votable_assets t_votable_assets; #endif index_statistic_info gather_statistics(const IndexType& index, bool onlyStaticInfo) const { index_statistic_info info; gather_index_static_data(index, &info); if(onlyStaticInfo == false) { for(const auto& o : index) { info._item_additional_allocation += o.category.capacity()*sizeof(shared_string::value_type); info._item_additional_allocation += o.parent_permlink.capacity()*sizeof(shared_string::value_type); info._item_additional_allocation += o.permlink.capacity()*sizeof(shared_string::value_type); info._item_additional_allocation += o.beneficiaries.capacity()*sizeof(t_beneficiaries::value_type); #ifdef STEEM_ENABLE_SMT info._item_additional_allocation += o.allowed_vote_assets.capacity()*sizeof(t_votable_assets::value_type); #endif } } return info; } }; template <> class index_statistic_provider<steem::chain::comment_content_index> { public: typedef steem::chain::comment_content_index IndexType; index_statistic_info gather_statistics(const IndexType& index, bool onlyStaticInfo) const { index_statistic_info info; gather_index_static_data(index, &info); if(onlyStaticInfo == false) { for(const auto& o : index) { info._item_additional_allocation += o.title.capacity()*sizeof(shared_string::value_type); info._item_additional_allocation += o.body.capacity()*sizeof(shared_string::value_type); info._item_additional_allocation += o.json_metadata.capacity()*sizeof(shared_string::value_type); } } return info; } }; } /// namespace helpers
; FV-1 Testing ; ; Program: RMP servo POT ; ; POT0: Target value ; ; Check RMP servo ; skp RUN,main wldr RMP0,0,4096 ; setup RMP0 main: rdax POT0,0.5 ; load pot, scaled to ramp amp wrax REG0,1.0 ; save a copy sof 1.0,-0.25 ; offset sof -2.0,0.0 ; scale up sof -2.0,0.0 ; scale up wrax DACL,0.0 ; output target to DACL cho rdal,RMP0 ; load RMP0 wrax REG1,1.0 ; save a copy rdax REG0,-1.0 ; subtract target wrax RMP0_RATE,0.0 ; update ramp rate toward target ldax REG1 sof 1.0,-0.25 ; offset sof -2.0,0.0 ; scale up sof -2.0,0.0 ; scale up wrax DACR,0.0 ; output ramp value to DACR
%define CHAR_BIT 16 %define SCHAR_MAX 0x7FFF %define SCHAR_MIN 0x8000 %define UCHAR_MAX 0xFFFF %define CHAR_MAX 0x7FFF %define CHAR_MIN 0x8000 %define INT_MAX 0x7FFF %define INT_MIN 0x8000 %define UINT_MAX 0xFFFF