text stringlengths 1 1.05M |
|---|
; A044641: Numbers n such that string 1,0 occurs in the base 9 representation of n but not of n+1.
; 9,90,171,252,333,414,495,576,657,819,900,981,1062,1143,1224,1305,1386,1467,1548,1629,1710,1791,1872,1953,2034,2115,2196,2277,2358,2439,2520,2601,2682,2763,2844,2925,3006,3087,3168
mov $1,8
bin $1,$0
cmp $1,0
add $1,$0
mul $1,81
add $1,9
mov $0,$1
|
; check sorting of labels, especially when labels differ only in case
DEVICE ZXSPECTRUM128 : ORG $8000
; block 3. C
ccccC rrca
ccCcc rra
Ccccc cpl
cCccc ccf
ccccc rlca
; block 2. B
bbbbB rrca
bbBbb rra
Bbbbb cpl
bBbbb ccf
bbbbb rlca
; block 5. E
eeeeE rrca
eeEee rra
Eeeee cpl
eEeee ccf
eeeee rlca
; block 1. A
aaaaA rrca
aaAaa rra
Aaaaa cpl
aAaaa ccf
aaaaa rlca
; block 4. D
ddddD rrca
ddDdd rra
Ddddd cpl
dDddd ccf
ddddd rlca
; unreal emulator export
LABELSLIST "lstlab_sort.lbl"
; #CSpect map export
CSPECTMAP "lstlab_sort.exp"
; --sym was not exporting symbols starting with non-alpha character, ie. underscore labels
; This seems rather bug than feature, so changed for v1.18.1
; (I guess the original test was to hide macro labels only, the ones starting with digit)
_underscoreLabel nop
|
; Platform specific colour transformation
;
; Entry: a = colour
; Exit: a = colour to use on screen
; Used: hl,bc,f
;
MODULE code_clib
PUBLIC conio_map_colour
EXTERN __CLIB_CONIO_NATIVE_COLOUR
conio_map_colour:
ld c,__CLIB_CONIO_NATIVE_COLOUR
rr c
ret c
and 15
ld c,a
ld b,0
ld hl,table
add hl,bc
ld a,(hl)
ret
SECTION rodata_clib
table:
defb $0 ;BLACK -> BLACK
defb $1 ;BLUE -> BLUE
defb $2 ;GREEN -> GREEN
defb $3 ;CYAN -> CYAN
defb $4 ;RED -> RED
defb $5 ;MAGENTA -> MAGENTA
defb $e ;BROWN -> BRIGHT YELLOW
defb $7 ;LIGHTGRAY -> BRIGHT GREY
defb $8 ;DARKGRAY -> DARK GREY
defb $9 ;LIGHTBLUE -> BRIGHT BLUE
defb $a ;LIGHTGREEN -> BRIGHT GREEN
defb $b ;LIGHTCYAN -> BRIGHT CYAN
defb $c ;LIGHTRED -> BRIGHT RED
defb $d ;LIGHTMAGENTA -> BRIGHT MAGENTA
defb $6 ;YELLOW -> YELLOW
defb $f ;WHITE -> WHITE
|
/**
* Copyright (c) 2000-2001 Aaron D. Gifford
* Copyright (c) 2013-2014 Pavol Rusnak
* 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 contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``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 AUTHOR OR CONTRIBUTOR(S) 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 "sha2.hpp"
#include "memzero.h"
#include <cstdint>
#include <cstring>
#include <string>
/*
* ASSERT NOTE:
* Some sanity checking code is included using assert(). On my FreeBSD
* system, this additional code can be removed by compiling with NDEBUG
* defined. Check your own systems manpage on assert() to see how to
* compile WITHOUT the sanity checking code on your system.
*
* UNROLLED TRANSFORM LOOP NOTE:
* You can define SHA2_UNROLL_TRANSFORM to use the unrolled transform
* loop version for the hash transform rounds (defined using macros
* later in this file). Either define on the command line, for example:
*
* cc -DSHA2_UNROLL_TRANSFORM -o sha2 sha2.c sha2prog.c
*
* or define below:
*
* #define SHA2_UNROLL_TRANSFORM
*
*/
/*** SHA-256/384/512 Machine Architecture Definitions *****************/
/*
* BYTE_ORDER NOTE:
*
* Please make sure that your system defines BYTE_ORDER. If your
* architecture is little-endian, make sure it also defines
* LITTLE_ENDIAN and that the two (BYTE_ORDER and LITTLE_ENDIAN) are
* equivilent.
*
* If your system does not define the above, then you can do so by
* hand like this:
*
* #define LITTLE_ENDIAN 1234
* #define BIG_ENDIAN 4321
*
* And for little-endian machines, add:
*
* #define BYTE_ORDER LITTLE_ENDIAN
*
* Or for big-endian machines:
*
* #define BYTE_ORDER BIG_ENDIAN
*
* The FreeBSD machine this was written on defines BYTE_ORDER
* appropriately by including <sys/types.h> (which in turn includes
* <machine/endian.h> where the appropriate definitions are actually
* made).
*/
#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN)
#error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN
#endif
typedef uint8_t sha2_byte; /* Exactly 1 byte */
typedef uint32_t sha2_word32; /* Exactly 4 bytes */
typedef uint64_t sha2_word64; /* Exactly 8 bytes */
/*** SHA-256/384/512 Various Length Definitions ***********************/
/* NOTE: Most of these are in sha2.h */
#define SHA1_SHORT_BLOCK_LENGTH (SHA1_BLOCK_LENGTH - 8)
#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8)
#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16)
/*
* Macro for incrementally adding the unsigned 64-bit integer n to the
* unsigned 128-bit integer (represented using a two-element array of
* 64-bit words):
*/
#define ADDINC128(w,n) { \
(w)[0] += (sha2_word64)(n); \
if ((w)[0] < (n)) { \
(w)[1]++; \
} \
}
#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l))
/*** THE SIX LOGICAL FUNCTIONS ****************************************/
/*
* Bit shifting and rotation (used by the six SHA-XYZ logical functions:
*
* NOTE: In the original SHA-256/384/512 document, the shift-right
* function was named R and the rotate-right function was called S.
* (See: http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf on the
* web.)
*
* The newer NIST FIPS 180-2 document uses a much clearer naming
* scheme, SHR for shift-right, ROTR for rotate-right, and ROTL for
* rotate-left. (See:
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
* on the web.)
*
* WARNING: These macros must be used cautiously, since they reference
* supplied parameters sometimes more than once, and thus could have
* unexpected side-effects if used without taking this into account.
*/
/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
#define SHR(b,x) ((x) >> (b))
/* 32-bit Rotate-right (used in SHA-256): */
#define ROTR32(b,x) (((x) >> (b)) | ((x) << (32 - (b))))
/* 64-bit Rotate-right (used in SHA-384 and SHA-512): */
#define ROTR64(b,x) (((x) >> (b)) | ((x) << (64 - (b))))
/* 32-bit Rotate-left (used in SHA-1): */
#define ROTL32(b,x) (((x) << (b)) | ((x) >> (32 - (b))))
/* Two of six logical functions used in SHA-1, SHA-256, SHA-384, and SHA-512: */
#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z)))
#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
/* Function used in SHA-1: */
#define Parity(x,y,z) ((x) ^ (y) ^ (z))
/* Four of six logical functions used in SHA-256: */
#define Sigma0_256(x) (ROTR32(2, (x)) ^ ROTR32(13, (x)) ^ ROTR32(22, (x)))
#define Sigma1_256(x) (ROTR32(6, (x)) ^ ROTR32(11, (x)) ^ ROTR32(25, (x)))
#define sigma0_256(x) (ROTR32(7, (x)) ^ ROTR32(18, (x)) ^ SHR(3 , (x)))
#define sigma1_256(x) (ROTR32(17, (x)) ^ ROTR32(19, (x)) ^ SHR(10, (x)))
/* Four of six logical functions used in SHA-384 and SHA-512: */
#define Sigma0_512(x) (ROTR64(28, (x)) ^ ROTR64(34, (x)) ^ ROTR64(39, (x)))
#define Sigma1_512(x) (ROTR64(14, (x)) ^ ROTR64(18, (x)) ^ ROTR64(41, (x)))
#define sigma0_512(x) (ROTR64( 1, (x)) ^ ROTR64( 8, (x)) ^ SHR( 7, (x)))
#define sigma1_512(x) (ROTR64(19, (x)) ^ ROTR64(61, (x)) ^ SHR( 6, (x)))
/*** INTERNAL FUNCTION PROTOTYPES *************************************/
/* NOTE: These should not be accessed directly from outside this
* library -- they are intended for private internal visibility/use
* only.
*/
static void sha512_Last(trezor::SHA512_CTX*);
/*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/
/* Hash constant words K for SHA-1: */
#define K1_0_TO_19 0x5a827999UL
#define K1_20_TO_39 0x6ed9eba1UL
#define K1_40_TO_59 0x8f1bbcdcUL
#define K1_60_TO_79 0xca62c1d6UL
/* Initial hash value H for SHA-1: */
const sha2_word32 sha1_initial_hash_value[SHA1_DIGEST_LENGTH / sizeof(sha2_word32)] = {
0x67452301UL,
0xefcdab89UL,
0x98badcfeUL,
0x10325476UL,
0xc3d2e1f0UL
};
/* Hash constant words K for SHA-256: */
static const sha2_word32 K256[64] = {
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL,
0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL,
0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL,
0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL,
0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL,
0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL,
0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL,
0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL,
0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL,
0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL,
0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL,
0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL,
0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
/* Initial hash value H for SHA-256: */
const sha2_word32 sha256_initial_hash_value[8] = {
0x6a09e667UL,
0xbb67ae85UL,
0x3c6ef372UL,
0xa54ff53aUL,
0x510e527fUL,
0x9b05688cUL,
0x1f83d9abUL,
0x5be0cd19UL
};
/* Hash constant words K for SHA-384 and SHA-512: */
static const sha2_word64 K512[80] = {
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
};
/* Initial hash value H for SHA-512 */
const sha2_word64 sha512_initial_hash_value[8] = {
0x6a09e667f3bcc908ULL,
0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL,
0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL,
0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL,
0x5be0cd19137e2179ULL
};
/*
* Constant used by SHA256/384/512_End() functions for converting the
* digest to a readable hexadecimal character string:
*/
static const char *sha2_hex_digits = "0123456789abcdef";
/*** SHA-1: ***********************************************************/
void sha1_Init(trezor::SHA1_CTX* context) {
MEMCPY_BCOPY(context->state, sha1_initial_hash_value, SHA1_DIGEST_LENGTH);
memzero(context->buffer, SHA1_BLOCK_LENGTH);
context->bitcount = 0;
}
#ifdef SHA2_UNROLL_TRANSFORM
/* Unrolled SHA-1 round macros: */
#define ROUND1_0_TO_15(a,b,c,d,e) \
(e) = ROTL32(5, (a)) + Ch((b), (c), (d)) + (e) + \
K1_0_TO_19 + ( W1[j] = *data++ ); \
(b) = ROTL32(30, (b)); \
j++;
#define ROUND1_16_TO_19(a,b,c,d,e) \
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
(e) = ROTL32(5, a) + Ch(b,c,d) + e + K1_0_TO_19 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
(b) = ROTL32(30, b); \
j++;
#define ROUND1_20_TO_39(a,b,c,d,e) \
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
(e) = ROTL32(5, a) + Parity(b,c,d) + e + K1_20_TO_39 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
(b) = ROTL32(30, b); \
j++;
#define ROUND1_40_TO_59(a,b,c,d,e) \
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
(e) = ROTL32(5, a) + Maj(b,c,d) + e + K1_40_TO_59 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
(b) = ROTL32(30, b); \
j++;
#define ROUND1_60_TO_79(a,b,c,d,e) \
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f]; \
(e) = ROTL32(5, a) + Parity(b,c,d) + e + K1_60_TO_79 + ( W1[j&0x0f] = ROTL32(1, T1) ); \
(b) = ROTL32(30, b); \
j++;
void sha1_Transform(const sha2_word32* state_in, const sha2_word32* data, sha2_word32* state_out) {
sha2_word32 a, b, c, d, e;
sha2_word32 T1;
sha2_word32 W1[16];
int j;
/* Initialize registers with the prev. intermediate value */
a = state_in[0];
b = state_in[1];
c = state_in[2];
d = state_in[3];
e = state_in[4];
j = 0;
/* Rounds 0 to 15 unrolled: */
ROUND1_0_TO_15(a,b,c,d,e);
ROUND1_0_TO_15(e,a,b,c,d);
ROUND1_0_TO_15(d,e,a,b,c);
ROUND1_0_TO_15(c,d,e,a,b);
ROUND1_0_TO_15(b,c,d,e,a);
ROUND1_0_TO_15(a,b,c,d,e);
ROUND1_0_TO_15(e,a,b,c,d);
ROUND1_0_TO_15(d,e,a,b,c);
ROUND1_0_TO_15(c,d,e,a,b);
ROUND1_0_TO_15(b,c,d,e,a);
ROUND1_0_TO_15(a,b,c,d,e);
ROUND1_0_TO_15(e,a,b,c,d);
ROUND1_0_TO_15(d,e,a,b,c);
ROUND1_0_TO_15(c,d,e,a,b);
ROUND1_0_TO_15(b,c,d,e,a);
ROUND1_0_TO_15(a,b,c,d,e);
/* Rounds 16 to 19 unrolled: */
ROUND1_16_TO_19(e,a,b,c,d);
ROUND1_16_TO_19(d,e,a,b,c);
ROUND1_16_TO_19(c,d,e,a,b);
ROUND1_16_TO_19(b,c,d,e,a);
/* Rounds 20 to 39 unrolled: */
ROUND1_20_TO_39(a,b,c,d,e);
ROUND1_20_TO_39(e,a,b,c,d);
ROUND1_20_TO_39(d,e,a,b,c);
ROUND1_20_TO_39(c,d,e,a,b);
ROUND1_20_TO_39(b,c,d,e,a);
ROUND1_20_TO_39(a,b,c,d,e);
ROUND1_20_TO_39(e,a,b,c,d);
ROUND1_20_TO_39(d,e,a,b,c);
ROUND1_20_TO_39(c,d,e,a,b);
ROUND1_20_TO_39(b,c,d,e,a);
ROUND1_20_TO_39(a,b,c,d,e);
ROUND1_20_TO_39(e,a,b,c,d);
ROUND1_20_TO_39(d,e,a,b,c);
ROUND1_20_TO_39(c,d,e,a,b);
ROUND1_20_TO_39(b,c,d,e,a);
ROUND1_20_TO_39(a,b,c,d,e);
ROUND1_20_TO_39(e,a,b,c,d);
ROUND1_20_TO_39(d,e,a,b,c);
ROUND1_20_TO_39(c,d,e,a,b);
ROUND1_20_TO_39(b,c,d,e,a);
/* Rounds 40 to 59 unrolled: */
ROUND1_40_TO_59(a,b,c,d,e);
ROUND1_40_TO_59(e,a,b,c,d);
ROUND1_40_TO_59(d,e,a,b,c);
ROUND1_40_TO_59(c,d,e,a,b);
ROUND1_40_TO_59(b,c,d,e,a);
ROUND1_40_TO_59(a,b,c,d,e);
ROUND1_40_TO_59(e,a,b,c,d);
ROUND1_40_TO_59(d,e,a,b,c);
ROUND1_40_TO_59(c,d,e,a,b);
ROUND1_40_TO_59(b,c,d,e,a);
ROUND1_40_TO_59(a,b,c,d,e);
ROUND1_40_TO_59(e,a,b,c,d);
ROUND1_40_TO_59(d,e,a,b,c);
ROUND1_40_TO_59(c,d,e,a,b);
ROUND1_40_TO_59(b,c,d,e,a);
ROUND1_40_TO_59(a,b,c,d,e);
ROUND1_40_TO_59(e,a,b,c,d);
ROUND1_40_TO_59(d,e,a,b,c);
ROUND1_40_TO_59(c,d,e,a,b);
ROUND1_40_TO_59(b,c,d,e,a);
/* Rounds 60 to 79 unrolled: */
ROUND1_60_TO_79(a,b,c,d,e);
ROUND1_60_TO_79(e,a,b,c,d);
ROUND1_60_TO_79(d,e,a,b,c);
ROUND1_60_TO_79(c,d,e,a,b);
ROUND1_60_TO_79(b,c,d,e,a);
ROUND1_60_TO_79(a,b,c,d,e);
ROUND1_60_TO_79(e,a,b,c,d);
ROUND1_60_TO_79(d,e,a,b,c);
ROUND1_60_TO_79(c,d,e,a,b);
ROUND1_60_TO_79(b,c,d,e,a);
ROUND1_60_TO_79(a,b,c,d,e);
ROUND1_60_TO_79(e,a,b,c,d);
ROUND1_60_TO_79(d,e,a,b,c);
ROUND1_60_TO_79(c,d,e,a,b);
ROUND1_60_TO_79(b,c,d,e,a);
ROUND1_60_TO_79(a,b,c,d,e);
ROUND1_60_TO_79(e,a,b,c,d);
ROUND1_60_TO_79(d,e,a,b,c);
ROUND1_60_TO_79(c,d,e,a,b);
ROUND1_60_TO_79(b,c,d,e,a);
/* Compute the current intermediate hash value */
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
/* Clean up */
a = b = c = d = e = T1 = 0;
}
#else /* SHA2_UNROLL_TRANSFORM */
void sha1_Transform(const sha2_word32* state_in, const sha2_word32* data, sha2_word32* state_out) {
sha2_word32 a, b, c, d, e;
sha2_word32 T1;
sha2_word32 W1[16];
int j;
/* Initialize registers with the prev. intermediate value */
a = state_in[0];
b = state_in[1];
c = state_in[2];
d = state_in[3];
e = state_in[4];
j = 0;
do {
T1 = ROTL32(5, a) + Ch(b, c, d) + e + K1_0_TO_19 + (W1[j] = *data++);
e = d;
d = c;
c = ROTL32(30, b);
b = a;
a = T1;
j++;
} while (j < 16);
do {
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
T1 = ROTL32(5, a) + Ch(b,c,d) + e + K1_0_TO_19 + (W1[j&0x0f] = ROTL32(1, T1));
e = d;
d = c;
c = ROTL32(30, b);
b = a;
a = T1;
j++;
} while (j < 20);
do {
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
T1 = ROTL32(5, a) + Parity(b,c,d) + e + K1_20_TO_39 + (W1[j&0x0f] = ROTL32(1, T1));
e = d;
d = c;
c = ROTL32(30, b);
b = a;
a = T1;
j++;
} while (j < 40);
do {
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
T1 = ROTL32(5, a) + Maj(b,c,d) + e + K1_40_TO_59 + (W1[j&0x0f] = ROTL32(1, T1));
e = d;
d = c;
c = ROTL32(30, b);
b = a;
a = T1;
j++;
} while (j < 60);
do {
T1 = W1[(j+13)&0x0f] ^ W1[(j+8)&0x0f] ^ W1[(j+2)&0x0f] ^ W1[j&0x0f];
T1 = ROTL32(5, a) + Parity(b,c,d) + e + K1_60_TO_79 + (W1[j&0x0f] = ROTL32(1, T1));
e = d;
d = c;
c = ROTL32(30, b);
b = a;
a = T1;
j++;
} while (j < 80);
/* Compute the current intermediate hash value */
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
}
#endif /* SHA2_UNROLL_TRANSFORM */
void sha1_Update(trezor::SHA1_CTX* context, const sha2_byte *data, size_t len) {
unsigned int freespace, usedspace;
if (len == 0) {
/* Calling with no data is valid - we do nothing */
return;
}
usedspace = (context->bitcount >> 3) % SHA1_BLOCK_LENGTH;
if (usedspace > 0) {
/* Calculate how much free space is available in the buffer */
freespace = SHA1_BLOCK_LENGTH - usedspace;
if (len >= freespace) {
/* Fill the buffer completely and process it */
MEMCPY_BCOPY(((uint8_t*)context->buffer) + usedspace, data, freespace);
context->bitcount += freespace << 3;
len -= freespace;
data += freespace;
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
sha1_Transform(context->state, context->buffer, context->state);
} else {
/* The buffer is not yet full */
MEMCPY_BCOPY(((uint8_t*)context->buffer) + usedspace, data, len);
context->bitcount += len << 3;
/* Clean up: */
usedspace = freespace = 0;
return;
}
}
while (len >= SHA1_BLOCK_LENGTH) {
/* Process as many complete blocks as we can */
MEMCPY_BCOPY(context->buffer, data, SHA1_BLOCK_LENGTH);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
sha1_Transform(context->state, context->buffer, context->state);
context->bitcount += SHA1_BLOCK_LENGTH << 3;
len -= SHA1_BLOCK_LENGTH;
data += SHA1_BLOCK_LENGTH;
}
if (len > 0) {
/* There's left-overs, so save 'em */
MEMCPY_BCOPY(context->buffer, data, len);
context->bitcount += len << 3;
}
}
void sha1_Final(trezor::SHA1_CTX* context, sha2_byte digest[]) {
unsigned int usedspace;
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
usedspace = (context->bitcount >> 3) % SHA1_BLOCK_LENGTH;
/* Begin padding with a 1 bit: */
((uint8_t*)context->buffer)[usedspace++] = 0x80;
if (usedspace > SHA1_SHORT_BLOCK_LENGTH) {
memzero(((uint8_t*)context->buffer) + usedspace, SHA1_BLOCK_LENGTH - usedspace);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
/* Do second-to-last transform: */
sha1_Transform(context->state, context->buffer, context->state);
/* And prepare the last transform: */
usedspace = 0;
}
/* Set-up for the last transform: */
memzero(((uint8_t*)context->buffer) + usedspace, SHA1_SHORT_BLOCK_LENGTH - usedspace);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 14; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
/* Set the bit count: */
context->buffer[14] = context->bitcount >> 32;
context->buffer[15] = context->bitcount & 0xffffffff;
/* Final transform: */
sha1_Transform(context->state, context->buffer, context->state);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert FROM host byte order */
for (int j = 0; j < 5; j++) {
REVERSE32(context->state[j],context->state[j]);
}
#endif
MEMCPY_BCOPY(digest, context->state, SHA1_DIGEST_LENGTH);
}
/* Clean up state data: */
memzero(context, sizeof(trezor::SHA1_CTX));
}
char *sha1_End(trezor::SHA1_CTX* context, char buffer[]) {
sha2_byte digest[SHA1_DIGEST_LENGTH], *d = digest;
int i;
if (buffer != (char*)0) {
sha1_Final(context, digest);
for (i = 0; i < SHA1_DIGEST_LENGTH; i++) {
*buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
*buffer++ = sha2_hex_digits[*d & 0x0f];
d++;
}
*buffer = (char)0;
} else {
memzero(context, sizeof(trezor::SHA1_CTX));
}
memzero(digest, SHA1_DIGEST_LENGTH);
return buffer;
}
void sha1_Raw(const sha2_byte* data, size_t len, uint8_t digest[SHA1_DIGEST_LENGTH]) {
trezor::SHA1_CTX context;
sha1_Init(&context);
sha1_Update(&context, data, len);
sha1_Final(&context, digest);
}
char* sha1_Data(const sha2_byte* data, size_t len, char digest[SHA1_DIGEST_STRING_LENGTH]) {
trezor::SHA1_CTX context;
sha1_Init(&context);
sha1_Update(&context, data, len);
return sha1_End(&context, digest);
}
/*** SHA-256: *********************************************************/
void sha256_Init(trezor::SHA256_CTX* context) {
if (context == (trezor::SHA256_CTX*)0) {
return;
}
MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH);
memzero(context->buffer, SHA256_BLOCK_LENGTH);
context->bitcount = 0;
}
#ifdef SHA2_UNROLL_TRANSFORM
/* Unrolled SHA-256 round macros: */
#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \
T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \
K256[j] + (W256[j] = *data++); \
(d) += T1; \
(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
j++
#define ROUND256(a,b,c,d,e,f,g,h) \
s0 = W256[(j+1)&0x0f]; \
s0 = sigma0_256(s0); \
s1 = W256[(j+14)&0x0f]; \
s1 = sigma1_256(s1); \
T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \
(W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \
(d) += T1; \
(h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \
j++
void sha256_Transform(const sha2_word32* state_in, const sha2_word32* data, sha2_word32* state_out) {
sha2_word32 a, b, c, d, e, f, g, h, s0, s1;
sha2_word32 T1;
sha2_word32 W256[16];
int j;
/* Initialize registers with the prev. intermediate value */
a = state_in[0];
b = state_in[1];
c = state_in[2];
d = state_in[3];
e = state_in[4];
f = state_in[5];
g = state_in[6];
h = state_in[7];
j = 0;
do {
/* Rounds 0 to 15 (unrolled): */
ROUND256_0_TO_15(a,b,c,d,e,f,g,h);
ROUND256_0_TO_15(h,a,b,c,d,e,f,g);
ROUND256_0_TO_15(g,h,a,b,c,d,e,f);
ROUND256_0_TO_15(f,g,h,a,b,c,d,e);
ROUND256_0_TO_15(e,f,g,h,a,b,c,d);
ROUND256_0_TO_15(d,e,f,g,h,a,b,c);
ROUND256_0_TO_15(c,d,e,f,g,h,a,b);
ROUND256_0_TO_15(b,c,d,e,f,g,h,a);
} while (j < 16);
/* Now for the remaining rounds to 64: */
do {
ROUND256(a,b,c,d,e,f,g,h);
ROUND256(h,a,b,c,d,e,f,g);
ROUND256(g,h,a,b,c,d,e,f);
ROUND256(f,g,h,a,b,c,d,e);
ROUND256(e,f,g,h,a,b,c,d);
ROUND256(d,e,f,g,h,a,b,c);
ROUND256(c,d,e,f,g,h,a,b);
ROUND256(b,c,d,e,f,g,h,a);
} while (j < 64);
/* Compute the current intermediate hash value */
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
state_out[5] = state_in[5] + f;
state_out[6] = state_in[6] + g;
state_out[7] = state_in[7] + h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = 0;
}
#else /* SHA2_UNROLL_TRANSFORM */
void sha256_Transform(const sha2_word32* state_in, const sha2_word32* data, sha2_word32* state_out) {
sha2_word32 a, b, c, d, e, f, g, h, s0, s1;
sha2_word32 T1, T2, W256[16];
int j;
/* Initialize registers with the prev. intermediate value */
a = state_in[0];
b = state_in[1];
c = state_in[2];
d = state_in[3];
e = state_in[4];
f = state_in[5];
g = state_in[6];
h = state_in[7];
j = 0;
do {
/* Apply the SHA-256 compression function to update a..h with copy */
T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++);
T2 = Sigma0_256(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 16);
do {
/* Part of the message block expansion: */
s0 = W256[(j+1)&0x0f];
s0 = sigma0_256(s0);
s1 = W256[(j+14)&0x0f];
s1 = sigma1_256(s1);
/* Apply the SHA-256 compression function to update a..h */
T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] +
(W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0);
T2 = Sigma0_256(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 64);
/* Compute the current intermediate hash value */
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
state_out[5] = state_in[5] + f;
state_out[6] = state_in[6] + g;
state_out[7] = state_in[7] + h;
}
#endif /* SHA2_UNROLL_TRANSFORM */
void sha256_Update(trezor::SHA256_CTX* context, const sha2_byte *data, size_t len) {
unsigned int freespace, usedspace;
if (len == 0) {
/* Calling with no data is valid - we do nothing */
return;
}
usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
if (usedspace > 0) {
/* Calculate how much free space is available in the buffer */
freespace = SHA256_BLOCK_LENGTH - usedspace;
if (len >= freespace) {
/* Fill the buffer completely and process it */
MEMCPY_BCOPY(((uint8_t*)context->buffer) + usedspace, data, freespace);
context->bitcount += freespace << 3;
len -= freespace;
data += freespace;
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
sha256_Transform(context->state, context->buffer, context->state);
} else {
/* The buffer is not yet full */
MEMCPY_BCOPY(((uint8_t*)context->buffer) + usedspace, data, len);
context->bitcount += len << 3;
/* Clean up: */
usedspace = freespace = 0;
return;
}
}
while (len >= SHA256_BLOCK_LENGTH) {
/* Process as many complete blocks as we can */
MEMCPY_BCOPY(context->buffer, data, SHA256_BLOCK_LENGTH);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
sha256_Transform(context->state, context->buffer, context->state);
context->bitcount += SHA256_BLOCK_LENGTH << 3;
len -= SHA256_BLOCK_LENGTH;
data += SHA256_BLOCK_LENGTH;
}
if (len > 0) {
/* There's left-overs, so save 'em */
MEMCPY_BCOPY(context->buffer, data, len);
context->bitcount += len << 3;
}
}
void sha256_Final(trezor::SHA256_CTX* context, sha2_byte digest[]) {
unsigned int usedspace;
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH;
/* Begin padding with a 1 bit: */
((uint8_t*)context->buffer)[usedspace++] = 0x80;
if (usedspace > SHA256_SHORT_BLOCK_LENGTH) {
memzero(((uint8_t*)context->buffer) + usedspace, SHA256_BLOCK_LENGTH - usedspace);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
/* Do second-to-last transform: */
sha256_Transform(context->state, context->buffer, context->state);
/* And prepare the last transform: */
usedspace = 0;
}
/* Set-up for the last transform: */
memzero(((uint8_t*)context->buffer) + usedspace, SHA256_SHORT_BLOCK_LENGTH - usedspace);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 14; j++) {
REVERSE32(context->buffer[j],context->buffer[j]);
}
#endif
/* Set the bit count: */
context->buffer[14] = context->bitcount >> 32;
context->buffer[15] = context->bitcount & 0xffffffff;
/* Final transform: */
sha256_Transform(context->state, context->buffer, context->state);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert FROM host byte order */
for (int j = 0; j < 8; j++) {
REVERSE32(context->state[j],context->state[j]);
}
#endif
MEMCPY_BCOPY(digest, context->state, SHA256_DIGEST_LENGTH);
}
/* Clean up state data: */
memzero(context, sizeof(trezor::SHA256_CTX));
}
char *sha256_End(trezor::SHA256_CTX* context, char buffer[]) {
sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest;
int i;
if (buffer != (char*)0) {
sha256_Final(context, digest);
for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
*buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
*buffer++ = sha2_hex_digits[*d & 0x0f];
d++;
}
*buffer = (char)0;
} else {
memzero(context, sizeof(trezor::SHA256_CTX));
}
memzero(digest, SHA256_DIGEST_LENGTH);
return buffer;
}
void sha256_Raw(const sha2_byte* data, size_t len, uint8_t digest[SHA256_DIGEST_LENGTH]) {
trezor::SHA256_CTX context;
sha256_Init(&context);
sha256_Update(&context, data, len);
sha256_Final(&context, digest);
}
char* sha256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) {
trezor::SHA256_CTX context;
sha256_Init(&context);
sha256_Update(&context, data, len);
return sha256_End(&context, digest);
}
/*** SHA-512: *********************************************************/
void sha512_Init(trezor::SHA512_CTX* context) {
if (context == (trezor::SHA512_CTX*)0) {
return;
}
MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH);
memzero(context->buffer, SHA512_BLOCK_LENGTH);
context->bitcount[0] = context->bitcount[1] = 0;
}
#ifdef SHA2_UNROLL_TRANSFORM
/* Unrolled SHA-512 round macros: */
#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \
T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \
K512[j] + (W512[j] = *data++); \
(d) += T1; \
(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
j++
#define ROUND512(a,b,c,d,e,f,g,h) \
s0 = W512[(j+1)&0x0f]; \
s0 = sigma0_512(s0); \
s1 = W512[(j+14)&0x0f]; \
s1 = sigma1_512(s1); \
T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \
(W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \
(d) += T1; \
(h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \
j++
void sha512_Transform(const sha2_word64* state_in, const sha2_word64* data, sha2_word64* state_out) {
sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
sha2_word64 T1, W512[16];
int j;
/* Initialize registers with the prev. intermediate value */
a = state_in[0];
b = state_in[1];
c = state_in[2];
d = state_in[3];
e = state_in[4];
f = state_in[5];
g = state_in[6];
h = state_in[7];
j = 0;
do {
ROUND512_0_TO_15(a,b,c,d,e,f,g,h);
ROUND512_0_TO_15(h,a,b,c,d,e,f,g);
ROUND512_0_TO_15(g,h,a,b,c,d,e,f);
ROUND512_0_TO_15(f,g,h,a,b,c,d,e);
ROUND512_0_TO_15(e,f,g,h,a,b,c,d);
ROUND512_0_TO_15(d,e,f,g,h,a,b,c);
ROUND512_0_TO_15(c,d,e,f,g,h,a,b);
ROUND512_0_TO_15(b,c,d,e,f,g,h,a);
} while (j < 16);
/* Now for the remaining rounds up to 79: */
do {
ROUND512(a,b,c,d,e,f,g,h);
ROUND512(h,a,b,c,d,e,f,g);
ROUND512(g,h,a,b,c,d,e,f);
ROUND512(f,g,h,a,b,c,d,e);
ROUND512(e,f,g,h,a,b,c,d);
ROUND512(d,e,f,g,h,a,b,c);
ROUND512(c,d,e,f,g,h,a,b);
ROUND512(b,c,d,e,f,g,h,a);
} while (j < 80);
/* Compute the current intermediate hash value */
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
state_out[5] = state_in[5] + f;
state_out[6] = state_in[6] + g;
state_out[7] = state_in[7] + h;
/* Clean up */
a = b = c = d = e = f = g = h = T1 = 0;
}
#else /* SHA2_UNROLL_TRANSFORM */
void sha512_Transform(const sha2_word64* state_in, const sha2_word64* data, sha2_word64* state_out) {
sha2_word64 a, b, c, d, e, f, g, h, s0, s1;
sha2_word64 T1, T2, W512[16];
int j;
/* Initialize registers with the prev. intermediate value */
a = state_in[0];
b = state_in[1];
c = state_in[2];
d = state_in[3];
e = state_in[4];
f = state_in[5];
g = state_in[6];
h = state_in[7];
j = 0;
do {
/* Apply the SHA-512 compression function to update a..h with copy */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++);
T2 = Sigma0_512(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 16);
do {
/* Part of the message block expansion: */
s0 = W512[(j+1)&0x0f];
s0 = sigma0_512(s0);
s1 = W512[(j+14)&0x0f];
s1 = sigma1_512(s1);
/* Apply the SHA-512 compression function to update a..h */
T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] +
(W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0);
T2 = Sigma0_512(a) + Maj(a, b, c);
h = g;
g = f;
f = e;
e = d + T1;
d = c;
c = b;
b = a;
a = T1 + T2;
j++;
} while (j < 80);
/* Compute the current intermediate hash value */
state_out[0] = state_in[0] + a;
state_out[1] = state_in[1] + b;
state_out[2] = state_in[2] + c;
state_out[3] = state_in[3] + d;
state_out[4] = state_in[4] + e;
state_out[5] = state_in[5] + f;
state_out[6] = state_in[6] + g;
state_out[7] = state_in[7] + h;
}
#endif /* SHA2_UNROLL_TRANSFORM */
void sha512_Update(trezor::SHA512_CTX* context, const sha2_byte *data, size_t len) {
unsigned int freespace, usedspace;
if (len == 0) {
/* Calling with no data is valid - we do nothing */
return;
}
usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
if (usedspace > 0) {
/* Calculate how much free space is available in the buffer */
freespace = SHA512_BLOCK_LENGTH - usedspace;
if (len >= freespace) {
/* Fill the buffer completely and process it */
MEMCPY_BCOPY(((uint8_t*)context->buffer) + usedspace, data, freespace);
ADDINC128(context->bitcount, freespace << 3);
len -= freespace;
data += freespace;
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE64(context->buffer[j],context->buffer[j]);
}
#endif
sha512_Transform(context->state, context->buffer, context->state);
} else {
/* The buffer is not yet full */
MEMCPY_BCOPY(((uint8_t*)context->buffer) + usedspace, data, len);
ADDINC128(context->bitcount, len << 3);
/* Clean up: */
usedspace = freespace = 0;
return;
}
}
while (len >= SHA512_BLOCK_LENGTH) {
/* Process as many complete blocks as we can */
MEMCPY_BCOPY(context->buffer, data, SHA512_BLOCK_LENGTH);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE64(context->buffer[j],context->buffer[j]);
}
#endif
sha512_Transform(context->state, context->buffer, context->state);
ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3);
len -= SHA512_BLOCK_LENGTH;
data += SHA512_BLOCK_LENGTH;
}
if (len > 0) {
/* There's left-overs, so save 'em */
MEMCPY_BCOPY(context->buffer, data, len);
ADDINC128(context->bitcount, len << 3);
}
}
static void sha512_Last(trezor::SHA512_CTX* context) {
unsigned int usedspace;
usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH;
/* Begin padding with a 1 bit: */
((uint8_t*)context->buffer)[usedspace++] = 0x80;
if (usedspace > SHA512_SHORT_BLOCK_LENGTH) {
memzero(((uint8_t*)context->buffer) + usedspace, SHA512_BLOCK_LENGTH - usedspace);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 16; j++) {
REVERSE64(context->buffer[j],context->buffer[j]);
}
#endif
/* Do second-to-last transform: */
sha512_Transform(context->state, context->buffer, context->state);
/* And prepare the last transform: */
usedspace = 0;
}
/* Set-up for the last transform: */
memzero(((uint8_t*)context->buffer) + usedspace, SHA512_SHORT_BLOCK_LENGTH - usedspace);
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert TO host byte order */
for (int j = 0; j < 14; j++) {
REVERSE64(context->buffer[j],context->buffer[j]);
}
#endif
/* Store the length of input data (in bits): */
context->buffer[14] = context->bitcount[1];
context->buffer[15] = context->bitcount[0];
/* Final transform: */
sha512_Transform(context->state, context->buffer, context->state);
}
void sha512_Final(trezor::SHA512_CTX* context, sha2_byte digest[]) {
/* If no digest buffer is passed, we don't bother doing this: */
if (digest != (sha2_byte*)0) {
sha512_Last(context);
/* Save the hash data for output: */
#if BYTE_ORDER == LITTLE_ENDIAN
/* Convert FROM host byte order */
for (int j = 0; j < 8; j++) {
REVERSE64(context->state[j],context->state[j]);
}
#endif
MEMCPY_BCOPY(digest, context->state, SHA512_DIGEST_LENGTH);
}
/* Zero out state data */
memzero(context, sizeof(trezor::SHA512_CTX));
}
char *sha512_End(trezor::SHA512_CTX* context, char buffer[]) {
sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest;
int i;
if (buffer != (char*)0) {
sha512_Final(context, digest);
for (i = 0; i < SHA512_DIGEST_LENGTH; i++) {
*buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4];
*buffer++ = sha2_hex_digits[*d & 0x0f];
d++;
}
*buffer = (char)0;
} else {
memzero(context, sizeof(trezor::SHA512_CTX));
}
memzero(digest, SHA512_DIGEST_LENGTH);
return buffer;
}
void sha512_Raw(const sha2_byte* data, size_t len, uint8_t digest[SHA512_DIGEST_LENGTH]) {
trezor::SHA512_CTX context;
sha512_Init(&context);
sha512_Update(&context, data, len);
sha512_Final(&context, digest);
}
char* sha512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) {
trezor::SHA512_CTX context;
sha512_Init(&context);
sha512_Update(&context, data, len);
return sha512_End(&context, digest);
}
|
/*
This file is part of VROOM.
Copyright (c) 2015-2022, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include <asio.hpp>
#include <asio/ssl.hpp>
#include "routing/http_wrapper.h"
using asio::ip::tcp;
namespace vroom {
namespace routing {
const std::string HttpWrapper::HTTPS_PORT = "443";
HttpWrapper::HttpWrapper(const std::string& profile,
const Server& server,
const std::string& matrix_service,
const std::string& matrix_durations_key,
const std::string& route_service,
const std::string& extra_args)
: Wrapper(profile),
_server(server),
_matrix_service(matrix_service),
_matrix_durations_key(matrix_durations_key),
_route_service(route_service),
_extra_args(extra_args) {
}
std::string HttpWrapper::send_then_receive(const std::string& query) const {
std::string response;
try {
asio::io_service io_service;
tcp::resolver r(io_service);
tcp::resolver::query q(_server.host, _server.port);
tcp::socket s(io_service);
asio::connect(s, r.resolve(q));
asio::write(s, asio::buffer(query));
char buf[512];
std::error_code error;
for (;;) {
std::size_t len = s.read_some(asio::buffer(buf), error);
response.append(buf, len);
if (error == asio::error::eof) {
// Connection closed cleanly.
break;
} else {
if (error) {
throw std::system_error(error);
}
}
}
} catch (std::system_error& e) {
throw RoutingException("Failed to connect to " + _server.host + ":" +
_server.port);
}
// Removing headers.
auto start = response.find("{");
if (start == std::string::npos) {
throw RoutingException("Invalid routing response.");
}
auto end = response.rfind("}");
if (end == std::string::npos) {
throw RoutingException("Invalid routing response.");
}
std::string json_string = response.substr(start, end - start + 1);
return json_string;
}
std::string HttpWrapper::ssl_send_then_receive(const std::string& query) const {
std::string response;
try {
asio::io_service io_service;
asio::ssl::context ctx(asio::ssl::context::method::sslv23_client);
asio::ssl::stream<asio::ip::tcp::socket> ssock(io_service, ctx);
tcp::resolver r(io_service);
tcp::resolver::query q(_server.host, _server.port);
asio::connect(ssock.lowest_layer(), r.resolve(q));
ssock.handshake(asio::ssl::stream_base::handshake_type::client);
asio::write(ssock, asio::buffer(query));
char buf[512];
std::error_code error;
for (;;) {
std::size_t len = ssock.read_some(asio::buffer(buf), error);
response.append(buf, len);
if (error == asio::error::eof) {
// Connection closed cleanly.
break;
} else {
if (error) {
throw std::system_error(error);
}
}
}
} catch (std::system_error& e) {
throw RoutingException("Failed to connect to " + _server.host + ":" +
_server.port);
}
// Removing headers.
auto start = response.find("{");
assert(start != std::string::npos);
auto end = response.rfind("}");
assert(end != std::string::npos);
std::string json_string = response.substr(start, end - start + 1);
return json_string;
}
std::string HttpWrapper::run_query(const std::string& query) const {
return (_server.port == HTTPS_PORT) ? ssl_send_then_receive(query)
: send_then_receive(query);
}
void HttpWrapper::parse_response(rapidjson::Document& json_result,
const std::string& json_content) const {
#ifdef NDEBUG
json_result.Parse(json_content.c_str());
#else
assert(!json_result.Parse(json_content.c_str()).HasParseError());
#endif
}
Matrix<Cost> HttpWrapper::get_matrix(const std::vector<Location>& locs) const {
std::string query = this->build_query(locs, _matrix_service);
std::string json_string = this->run_query(query);
// Expected matrix size.
std::size_t m_size = locs.size();
rapidjson::Document json_result;
this->parse_response(json_result, json_string);
this->check_response(json_result, _matrix_service);
if (!json_result.HasMember(_matrix_durations_key.c_str())) {
throw RoutingException("Missing " + _matrix_durations_key + ".");
}
assert(json_result[_matrix_durations_key.c_str()].Size() == m_size);
// Build matrix while checking for unfound routes ('null' values) to
// avoid unexpected behavior.
Matrix<Cost> m(m_size);
std::vector<unsigned> nb_unfound_from_loc(m_size, 0);
std::vector<unsigned> nb_unfound_to_loc(m_size, 0);
for (rapidjson::SizeType i = 0; i < m_size; ++i) {
const auto& line = json_result[_matrix_durations_key.c_str()][i];
assert(line.Size() == m_size);
for (rapidjson::SizeType j = 0; j < line.Size(); ++j) {
if (duration_value_is_null(line[j])) {
// No route found between i and j. Just storing info as we
// don't know yet which location is responsible between i
// and j.
++nb_unfound_from_loc[i];
++nb_unfound_to_loc[j];
} else {
m[i][j] = get_duration_value(line[j]);
}
}
}
check_unfound(locs, nb_unfound_from_loc, nb_unfound_to_loc);
return m;
}
void HttpWrapper::add_route_info(Route& route) const {
// Ordering locations for the given steps, excluding
// breaks.
std::vector<Location> non_break_locations;
std::vector<unsigned> number_breaks_after;
for (const auto& step : route.steps) {
if (step.step_type == STEP_TYPE::BREAK) {
if (!number_breaks_after.empty()) {
++(number_breaks_after.back());
}
} else {
non_break_locations.push_back(step.location);
number_breaks_after.push_back(0);
}
}
assert(!non_break_locations.empty());
std::string query =
build_query(non_break_locations, _route_service, _extra_args);
std::string json_string = this->run_query(query);
rapidjson::Document json_result;
parse_response(json_result, json_string);
this->check_response(json_result, _route_service);
// Total distance and route geometry.
route.distance = round_cost(get_total_distance(json_result));
route.geometry = get_geometry(json_result);
auto nb_legs = get_legs_number(json_result);
assert(nb_legs == non_break_locations.size() - 1);
double sum_distance = 0;
// Start step has zero distance.
unsigned steps_rank = 0;
route.steps[0].distance = 0;
for (rapidjson::SizeType i = 0; i < nb_legs; ++i) {
const auto& step = route.steps[steps_rank];
// Next element in steps that is not a break and associated
// distance after current route leg.
auto& next_step = route.steps[steps_rank + number_breaks_after[i] + 1];
Duration next_duration = next_step.duration - step.duration;
double next_distance = get_distance_for_leg(json_result, i);
// Pro rata temporis distance update for breaks between current
// non-breaks steps.
for (unsigned b = 1; b <= number_breaks_after[i]; ++b) {
auto& break_step = route.steps[steps_rank + b];
if (next_duration == 0) {
break_step.distance = round_cost(sum_distance);
} else {
break_step.distance =
round_cost(sum_distance +
((break_step.duration - step.duration) * next_distance) /
next_duration);
}
}
sum_distance += next_distance;
next_step.distance = round_cost(sum_distance);
steps_rank += number_breaks_after[i] + 1;
}
}
} // namespace routing
} // namespace vroom
|
/*
* FILE: 61.rotate_list.cpp
* @author: Arafat Hasan Jenin <opendoor.arafat[at]gmail[dot]com>
* LINK: https://leetcode.com/problems/rotate-list/
* DATE CREATED: 11-03-22 16:15:14 (+06)
* LAST MODIFIED: 11-03-22 17:45:18 (+06)
* VERDICT: Accepetd
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if (head == nullptr || k == 0) return head;
ListNode* node = head;
int len = 0;
while (node->next != nullptr) {
node = node->next;
len++;
}
len++;
k %= len;
k = len - k;
node->next = head;
while (--k) {
head = head->next;
}
node = head;
head = head->next;
node->next = nullptr;
return head;
}
};
|
;
; ZX 81 specific routines
; by Stefano Bodrato, 29/07/2008
;
; Copy a variable from basic
;
; int __CALLEE__ zx_setint_callee(char *variable, int value);
;
; $Id: zx_setint_callee.asm,v 1.6 2016-06-26 20:32:09 dom Exp $
;
SECTION code_clib
PUBLIC zx_setint_callee
PUBLIC _zx_setint_callee
PUBLIC asm_zx_setint
EXTERN zx_locatenum
IF FORlambda
INCLUDE "target/lambda/def/lambdafp.def"
ELSE
INCLUDE "target/zx81/def/81fp.def"
ENDIF
zx_setint_callee:
_zx_setint_callee:
pop hl
pop de
ex (sp),hl
; enter : de = int value
; hl = char *variable
.asm_zx_setint
push de
push hl
call zx_locatenum
jr nc,store
; variable not found: create space for a new one
pop hl
push hl
ld c,0
vlcount:
ld a,(hl)
inc c
and a
inc hl
jr nz,vlcount
dec c
ld a,5 ; 5 bytes + len of VAR name
add c
ld c,a
ld b,0
ld hl,($4014) ; E_LINE
dec hl ; now HL points to end of VARS
IF FORlambda
call $1CB5
ELSE
;;ld hl,(16400) ; VARS
call $099E ; MAKE-ROOM
;;call $09A3 ; MAKE-ROOM (no test on available space)
ENDIF
inc hl
pop de ; point to VAR name
cp 6
push af
ld a,(de)
cp 97 ; ASCII Between a and z ?
jr c,isntlower
sub 32 ; Then transform in UPPER ASCII
.isntlower
sub 27 ; re-code to the ZX81 charset
and 63
ld b,a
pop af
ld a,b
jr nz,morethan1
or 96 ; fall here if the variable name is
ld (hl),a ; only one char long
inc hl
jr store2
morethan1:
; first letter of a long numeric variable name
or 160 ; has those odd bits added
ld (hl),a
lintlp:
inc de
ld a,(de) ; now we copy the body of the VAR name..
and a
jr z,endlint
cp 97 ; ASCII Between a and z ?
jr c,isntlower2
sub 32 ; Then transform in UPPER ASCII
.isntlower2
sub 27 ; re-code to the ZX81 charset
inc hl
ld (hl),a
djnz lintlp
endlint:
ld a,(hl)
or 128 ; .. then we fix the last char
ld (hl),a
inc hl
jr store2
store:
pop bc ; so we keep HL pointing just after the VAR name
store2:
pop bc
push hl ; save pointer to variable value
call ZXFP_STACK_BC
rst ZXFP_BEGIN_CALC
defb ZXFP_END_CALC ; Now HL points to the float on the FP stack
ld (ZXFP_STK_PTR),hl ; update the FP stack pointer (equalise)
pop de ; restore pointer to variable value
ld bc,5
ldir ; copy variable data
ret
|
/*******************************************************************************
* Copyright (c) 1991, 2015 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "omrcfg.h"
#include "omr.h"
#include "HeapMemoryPoolIterator.hpp"
#include "MemoryPool.hpp"
#include "MemorySubSpace.hpp"
/**
* Initialize the iterator to the beginning of the memory subspace list.
*/
void
MM_HeapMemoryPoolIterator::reset()
{
_memorySubSpace = _mssIterator.nextSubSpace();
_memoryPool = NULL;
_state = mm_heapmp_iterator_next_subspace;
}
/**
* Walk all memory pools for the given heap.
* The list traversal is preorder, in that all parent nodes are visited before any of their children.
*
* @return Next memory pool, or NULL if all pools have been processed.
*/
MM_MemoryPool *
MM_HeapMemoryPoolIterator::nextPool()
{
MM_MemoryPool *nextPool;
while(NULL != _memorySubSpace) {
switch(_state) {
case mm_heapmp_iterator_next_subspace:
if(NULL != _memorySubSpace->getMemoryPool()) {
_memoryPool = _memorySubSpace->getMemoryPool();
/* Does this Memory pool have children ? */
if(NULL != _memoryPool->getChildren()) {
/* Yes ..So we only return details of its children */
_memoryPool = _memoryPool->getChildren();
}
_state = mm_heapmp_iterator_next_memory_pool;
break;
}
_memorySubSpace = _mssIterator.nextSubSpace();
break;
case mm_heapmp_iterator_next_memory_pool:
nextPool = _memoryPool;
_memoryPool= _memoryPool->getNext();
/* Any more children ? */
if (NULL == _memoryPool) {
_memorySubSpace = _mssIterator.nextSubSpace();
_state = mm_heapmp_iterator_next_subspace;
}
return nextPool;
break;
}
}
return NULL;
}
/**
* Walk all memory pools for the given subspace. Based on nextPool() - the only difference is that when we want to move to next _memorySubSpace we set it to NULL.
* The list traversal is preorder, in that all parent nodes are visited before any of their children.
*
* @return Next memory pool, or NULL if all pools have been processed.
*/
MM_MemoryPool *
MM_HeapMemoryPoolIterator::nextPoolInSubSpace()
{
MM_MemoryPool *nextPool;
while (NULL != _memorySubSpace) {
switch(_state) {
case mm_heapmp_iterator_next_subspace:
if(NULL != _memorySubSpace->getMemoryPool()) {
_memoryPool = _memorySubSpace->getMemoryPool();
/* Does this Memory pool have children ? */
if(NULL != _memoryPool->getChildren()) {
/* Yes ..So we only return details of its children */
_memoryPool = _memoryPool->getChildren();
}
_state = mm_heapmp_iterator_next_memory_pool;
break;
}
_memorySubSpace = NULL;
break;
case mm_heapmp_iterator_next_memory_pool:
nextPool = _memoryPool;
_memoryPool= _memoryPool->getNext();
/* Any more children ? */
if (NULL == _memoryPool) {
_memorySubSpace = NULL;
_state = mm_heapmp_iterator_next_subspace;
}
return nextPool;
break;
}
}
return NULL;
}
|
;******************************************************************************
;* MEMCPY.ASM - MEMCPY - v2.2.1 *
;* *
;* Copyright (c) 2013-2017 Texas Instruments Incorporated *
;* http://www.ti.com/ *
;* *
;* 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 Texas Instruments Incorporated 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. *
;* *
;******************************************************************************
.text
.global memcpy
memcpy:
.asg r14, to
.asg r15, from
.asg r16, size
.asg r17, to_tmp
.asg 48, max_size
.asg r18, tmp
QBEQ return, size, 0
MOV to_tmp, to
start: LDI r0.b0, max_size
QBGE copy, r0.b0, size
MOV r0.b0, size
copy:
SUB size, size, r0.b0
LBBO &tmp, from, 0, b0
SBBO &tmp, to_tmp, 0, b0
QBEQ return, size, 0
ADD from, from, r0.b0
ADD to_tmp, to_tmp, r0.b0
JMP start
return:
JMP r3.w2
|
// Includes
#include "LightBulb/IO/PolicyGradientLearningRuleIO.hpp"
#include "LightBulb/NeuralNetwork/NeuralNetwork.hpp"
#include "LightBulb/IO/TemplateDeclaration.hpp"
// Libraray includes
#include <cereal/cereal.hpp>
#include <cereal/types/polymorphic.hpp>
#include <cereal/access.hpp>
namespace LightBulb
{
/**
* \brief Serializes a PolicyGradientLearningRule.
* \tparam Archive The archive type.
* \param archive The archive which should be used.
* \param learningRule The PolicyGradientLearningRule to serialize.
*/
template <class Archive>
void serialize(Archive& archive, PolicyGradientLearningRule& learningRule)
{
archive(cereal::base_class<AbstractReinforcementLearningRule>(&learningRule));
archive(cereal::make_nvp("valueFunctionNetwork", learningRule.valueFunctionNetwork));
}
DECLARE_SINGLE_SERIALIZATION_TEMPLATE(PolicyGradientLearningRule);
}
namespace cereal
{
template <class Archive>
void LoadAndConstruct<LightBulb::PolicyGradientLearningRule>::construct(Archive& ar, LightBulb::PolicyGradientLearningRule& learningRule)
{
using namespace LightBulb;
ar(base_class<AbstractReinforcementLearningRule>(&learningRule));
ar(cereal::make_nvp("valueFunctionNetwork", learningRule.valueFunctionNetwork));
}
}
#include "LightBulb/IO/UsedArchives.hpp"
CEREAL_REGISTER_TYPE(LightBulb::PolicyGradientLearningRule);
CEREAL_REGISTER_DYNAMIC_INIT(PolicyGradientLearningRule) |
/*
SjASMPlus Z80 Cross Compiler
This is modified sources of SjASM by Aprisobal - aprisobal@tut.by
Copyright (c) 2005 Sjoerd Mastijn
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim
that you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "reader.h"
#include "sjio.h"
#include "z80.h"
#include "global.h"
#include "support.h"
#include "parser/struct.h"
#include <boost/algorithm/string/case_conv.hpp>
using boost::algorithm::to_upper_copy;
#include "parser.h"
bool synerr;
// FIXME: errors.cpp
extern Assembler *Asm;
char sline[LINEMAX2], sline2[LINEMAX2];
int comlin = 0;
int substituteDepthCount = 0, comnxtlin;
char dirDEFl[] = "def", dirDEFu[] = "DEF"; /* added for ReplaceDefine */
void initLegacyParser() {
comlin = 0;
}
bool parseExpPrim(const char *&p, AInt &nval) {
bool res = false;
skipWhiteSpace(p);
if (!*p) {
return false;
}
if (*p == '(') {
++p;
res = parseExpression(p, nval);
if (!need(p, ')')) {
Error("')' expected"s);
return false;
}
} else if (*p == '{') {
++p;
res = parseExpression(p, nval);
/*if (nval < 0x4000) {
Error("Address in {..} must be more than 4000h", 0); return 0;
} */
if (nval > 0xFFFE) {
Error("Address in {..} must be less than FFFEh"s);
return false;
}
if (!need(p, '}')) {
Error("'}' expected"s);
return false;
}
nval = (AInt) (memGetByte(nval) + (memGetByte(nval + 1) << 8));
return true;
} else if (isdigit((unsigned char) *p) || (*p == '#' && isalnum((unsigned char) *(p + 1))) ||
(*p == '$' && isalnum((unsigned char) *(p + 1))) || *p == '%') {
res = getConstant(p, nval);
} else if (isalpha((unsigned char) *p) || *p == '_' || *p == '.' || *p == '@') {
res = Asm->Labels.getLabelValue(p, nval);
} else if (*p == '?' &&
(isalpha((unsigned char) *(p + 1)) || *(p + 1) == '_' || *(p + 1) == '.' || *(p + 1) == '@')) {
++p;
res = Asm->Labels.getLabelValue(p, nval);
} else if (Asm->Em.isPagedMemory() && *p == '$' && *(p + 1) == '$') {
++p;
++p;
nval = Asm->Em.getPage();
return true;
} else if (*p == '$') {
++p;
nval = Asm->Em.getCPUAddress();
return true;
} else if (!(res = getCharConst(p, nval))) {
if (synerr) {
Error("Syntax error"s, p, CATCHALL);
}
return false;
}
return res;
}
bool ParseExpUnair(const char *&p, AInt &nval) {
int oper;
if ((oper = need(p, "! ~ + - ")) || (oper = needA(p, "not", '!', "low", 'l', "high", 'h', true))) {
AInt right;
switch (oper) {
case '!':
if (!ParseExpUnair(p, right)) {
return false;
}
nval = -!right;
break;
case '~':
if (!ParseExpUnair(p, right)) {
return false;
}
nval = ~right;
break;
case '+':
if (!ParseExpUnair(p, right)) {
return false;
}
nval = right;
break;
case '-':
if (!ParseExpUnair(p, right)) {
return false;
}
nval = ~right + 1;
break;
case 'l':
if (!ParseExpUnair(p, right)) {
return false;
}
nval = right & 255;
break;
case 'h':
if (!ParseExpUnair(p, right)) {
return false;
}
nval = (right >> 8) & 255;
break;
default:
Error("Parser error"s);
return false;
}
return true;
} else {
return parseExpPrim(p, nval);
}
}
bool ParseExpMul(const char *&p, AInt &nval) {
AInt left, right;
int oper;
if (!ParseExpUnair(p, left)) {
return false;
}
while ((oper = need(p, "* / % ")) || (oper = needA(p, "mod", '%'))) {
if (!ParseExpUnair(p, right)) {
return false;
}
switch (oper) {
case '*':
left *= right;
break;
case '/':
if (right) {
left /= right;
} else {
Error("Division by zero"s);
left = 0;
}
break;
case '%':
if (right) {
left %= right;
} else {
Error("Division by zero"s);
left = 0;
}
break;
default:
Error("Parser error"s);
break;
}
}
nval = left;
return true;
}
bool ParseExpAdd(const char *&p, AInt &nval) {
AInt left, right;
int oper;
if (!ParseExpMul(p, left)) {
return false;
}
while ((oper = need(p, "+ - "))) {
if (!ParseExpMul(p, right)) {
return false;
}
switch (oper) {
case '+':
left += right;
break;
case '-':
left -= right;
break;
default:
Error("Parser error"s);
break;
}
}
nval = left;
return true;
}
bool ParseExpShift(const char *&p, AInt &nval) {
AInt left, right;
unsigned long l;
int oper;
if (!ParseExpAdd(p, left)) {
return false;
}
while ((oper = need(p, "<<>>")) || (oper = needA(p, "shl", '<' + '<', "shr", '>'))) {
if (oper == '>' + '>' && *p == '>') {
++p;
oper = '>' + '@';
}
if (!ParseExpAdd(p, right)) {
return false;
}
switch (oper) {
case '<' + '<':
left <<= right;
break;
case '>':
case '>' + '>':
left >>= right;
break;
case '>' + '@':
l = left;
l >>= right;
left = l;
break;
default:
Error("Parser error"s);
break;
}
}
nval = left;
return true;
}
bool ParseExpMinMax(const char *&p, AInt &nval) {
AInt left, right;
int oper;
if (!ParseExpShift(p, left)) {
return false;
}
while ((oper = need(p, "<?>?"))) {
if (!ParseExpShift(p, right)) {
return false;
}
switch (oper) {
case '<' + '?':
left = left < right ? left : right;
break;
case '>' + '?':
left = left > right ? left : right;
break;
default:
Error("Parser error"s);
break;
}
}
nval = left;
return true;
}
bool ParseExpCmp(const char *&p, AInt &nval) {
AInt left, right;
int oper;
if (!ParseExpMinMax(p, left)) {
return false;
}
while ((oper = need(p, "<=>=< > "))) {
if (!ParseExpMinMax(p, right)) {
return false;
}
switch (oper) {
case '<':
left = -(left < right);
break;
case '>':
left = -(left > right);
break;
case '<' + '=':
left = -(left <= right);
break;
case '>' + '=':
left = -(left >= right);
break;
default:
Error("Parser error"s);
break;
}
}
nval = left;
return true;
}
bool ParseExpEqu(const char *&p, AInt &nval) {
AInt left, right;
int oper;
if (!ParseExpCmp(p, left)) {
return false;
}
while ((oper = need(p, "=_==!="))) {
if (!ParseExpCmp(p, right)) {
return false;
}
switch (oper) {
case '=':
case '=' + '=':
left = -(left == right);
break;
case '!' + '=':
left = -(left != right);
break;
default:
Error("Parser error"s);
break;
}
}
nval = left;
return true;
}
bool ParseExpBitAnd(const char *&p, AInt &nval) {
AInt left, right;
if (!ParseExpEqu(p, left)) {
return false;
}
while (need(p, "&_") || needA(p, "and", '&')) {
if (!ParseExpEqu(p, right)) {
return false;
}
left &= right;
}
nval = left;
return true;
}
bool ParseExpBitXor(const char *&p, AInt &nval) {
AInt left, right;
if (!ParseExpBitAnd(p, left)) {
return false;
}
while (need(p, "^ ") || needA(p, "xor", '^')) {
if (!ParseExpBitAnd(p, right)) {
return false;
}
left ^= right;
}
nval = left;
return true;
}
bool ParseExpBitOr(const char *&p, AInt &nval) {
AInt left, right;
if (!ParseExpBitXor(p, left)) {
return false;
}
while (need(p, "|_") || needA(p, "or", '|')) {
if (!ParseExpBitXor(p, right)) {
return false;
}
left |= right;
}
nval = left;
return true;
}
bool ParseExpLogAnd(const char *&p, AInt &nval) {
AInt left, right;
if (!ParseExpBitOr(p, left)) {
return false;
}
while (need(p, "&&")) {
if (!ParseExpBitOr(p, right)) {
return false;
}
left = -(left && right);
}
nval = left;
return true;
}
bool ParseExpLogOr(const char *&p, AInt &nval) {
AInt left, right;
if (!ParseExpLogAnd(p, left)) {
return false;
}
while (need(p, "||")) {
if (!ParseExpLogAnd(p, right)) {
return false;
}
left = -(left || right);
}
nval = left;
return true;
}
bool parseExpression(const char *&p, AInt &nval) {
if (ParseExpLogOr(p, nval)) {
return true;
}
nval = 0;
return false;
}
/*
* Preprocesses a line buffer:
* - applies DEFINEs
* - applies MACROs
* - strips comments
* - replaces multiline comments' tails with spaces
*/
char *substituteMacros(const char *lp, char *dest) {
bool SubstitutedSome = false, Substituted;
char *nl = dest;
char *rp = nl, QChar;
const char *kp;
optional<std::string> Id;
std::string Repl;
if (++substituteDepthCount > 20) {
Fatal("Over 20 macro/define substitutions nested"s);
}
while (true) {
if (comlin || comnxtlin) {
if (matchStr(lp, "*/")) {
*rp = ' '; // Insert a space in place of a multi-line comment tail
++rp;
if (comnxtlin) {
--comnxtlin;
} else {
--comlin;
}
continue;
}
}
if ((*lp == ';' || peekMatchStr(lp, "//")) && !comlin && !comnxtlin) {
*rp = 0; // Reached a line comment. Terminate.
return nl;
}
if (matchStr(lp, "/*")) {
++comnxtlin;
continue;
}
if (*lp == '"' || *lp == '\'') {
QChar = *lp;
if (!comlin && !comnxtlin) {
*rp = *lp;
++rp;
}
++lp;
while (true) {
if (!*lp) {
*rp = 0;
return nl;
}
if (!comlin && !comnxtlin) {
*rp = *lp;
}
if (*lp == QChar) {
if (!comlin && !comnxtlin) {
++rp;
}
++lp;
break;
}
if (*lp == '\\') {
++lp;
if (!comlin && !comnxtlin) {
++rp;
*rp = *lp;
}
}
if (!comlin && !comnxtlin) {
++rp;
}
++lp;
}
continue;
}
if (comlin || comnxtlin) {
if (!*lp) {
*rp = 0;
break;
}
++lp;
continue;
}
if (!isalpha((unsigned char) *lp) && *lp != '_') {
if (!(*rp = *lp)) {
break;
}
++rp;
++lp;
continue;
}
Id = getID(lp);
Substituted = true;
if (auto Def = Asm->getDefine(*Id)) {
Repl = *Def;
} else {
Repl = Asm->Macros.getReplacement(*Id);
if (Asm->Macros.labelPrefix().empty() || Repl.empty()) {
Substituted = false;
Repl = (*Id);
}
}
if (const auto &Arr = Asm->getDefArray(*Id)) {
AInt val;
while (*(lp++) && (*lp <= ' ' || *lp == '['));
if (!parseExpression(lp, val)) {
Error("[ARRAY] Expression error"s, CATCHALL);
break;
}
while (*lp == ']' && *(lp++));
if (val < 0) {
Error("Number of cell must be positive"s, CATCHALL);
break;
}
if (Arr->size() > (unsigned) val) {
Repl = (*Arr)[val];
} else {
Error("Cell of array not found"s, CATCHALL);
}
}
if (Substituted) {
kp = lp - (*Id).size();
while (*(kp--) && *kp <= ' ');
kp = kp - 4;
if (cmpHStr(kp, "ifdef")) {
Substituted = false;
Repl = *Id;
} else {
--kp;
if (cmpHStr(kp, "ifndef")) {
Substituted = false;
Repl = *Id;
} else if (cmpHStr(kp, "define")) {
Substituted = false;
Repl = *Id;
} else if (cmpHStr(kp, "defarray")) {
Substituted = false;
Repl = *Id;
}
}
}
if (Substituted) {
SubstitutedSome = true;
}
if (!Repl.empty()) {
for (auto c : Repl) {
*rp = c;
++rp;
}
if (to_upper_copy(Repl) == "AF"s && *lp == '\'') { // Copy apostrophe in AF'
*rp = *lp;
++rp;
++lp;
}
*rp = '\0';
}
}
if (strlen(nl) > LINEMAX - 1) {
Fatal("Line too long after macro expansion"s);
}
if (SubstitutedSome) {
return substituteMacros(nl, (dest == sline) ? sline2 : sline);
}
return nl;
}
void parseLabel(const char *&P) {
std::string LUnparsed;
AInt val;
if (isWhiteSpaceChar(*P)) {
return;
}
if (Asm->options().IsPseudoOpBOF && parseDirective(P, P)) {
while (*P == ':') {
++P;
}
return;
}
while (*P && !isWhiteSpaceChar(*P) && *P != ':' && *P != '=') {
LUnparsed += *P;
++P;
}
if (*P == ':') {
++P;
}
skipWhiteSpace(P);
IsLabelNotFound = 0;
if (isdigit((unsigned char) LUnparsed[0])) {
if (needEQU(P) || needDEFL(P)) {
Error("Number labels only allowed as address labels"s);
return;
}
val = atoi(LUnparsed.c_str());
//_COUT CurrentLine _CMDL " " _CMDL val _CMDL " " _CMDL CurAddress _ENDL;
if (pass == 1) {
Asm->Labels.insertLocal(CompiledCurrentLine, val, Asm->Em.getCPUAddress());
}
} else {
bool IsDEFL = false;
if (needEQU(P)) {
if (!parseExpression(P, val)) {
Error("Expression error"s, P);
val = 0;
}
} else if (needDEFL(P)) {
if (!parseExpression(P, val)) {
Error("Expression error"s, P);
val = 0;
}
IsDEFL = true;
} else {
int gl = 0;
const char *p = P;
optional<std::string> Name;
skipWhiteSpace(p);
if (*p == '@') {
++p;
gl = 1;
}
if ((Name = getID(p)) && Asm->Structs.emit(*Name, LUnparsed, p, gl)) {
P = (char *) p;
return;
}
val = Asm->Em.getCPUAddress();
}
optional<std::string> L;
if (!(L = Asm->Labels.validateLabel(LUnparsed))) {
return;
}
// Copy label name to last parsed label variable
if (!IsDEFL) {
Asm->Labels.setLastParsedLabel(*L);
}
if (pass == LASTPASS) {
if (IsDEFL && !Asm->Labels.insert(*L, val, false, IsDEFL)) {
Error("Duplicate label"s, *L, PASS3);
}
AInt oval;
const char *t = LUnparsed.c_str();
if (!Asm->Labels.getLabelValue(t, oval)) {
Fatal("Internal error. parseLabel()"s);
}
/*if (val!=oval) Error("Label has different value in pass 2",temp);*/
if (!IsDEFL && val != oval) {
Warning("Label has different value in pass 3"s,
"previous value "s + std::to_string(oval) + " not equal "s + std::to_string(val));
//_COUT "" _CMDL filename _CMDL ":" _CMDL CurrentLocalLine _CMDL ":(DEBUG) " _CMDL "Label has different value in pass 2: ";
//_COUT val _CMDL "!=" _CMDL oval _ENDL;
Asm->Labels.updateValue(*L, val);
}
} else if (pass == 2 && !Asm->Labels.insert(*L, val, false, IsDEFL) && !Asm->Labels.updateValue(*L, val)) {
Error("Duplicate label"s, *L, PASS2);
} else if (!Asm->Labels.insert(*L, val, false, IsDEFL)) {
Error("Duplicate label"s, *L, PASS1);
}
}
}
bool parseMacro(const char *&P) {
int gl = 0;
const char *p = P;
optional<std::string> Name;
skipWhiteSpace(p);
if (*p == '@') {
gl = 1;
++p;
}
if (!(Name = getID(p))) {
return false;
}
MacroResult R;
if ((R = Asm->Macros.emit(*Name, p, line)) == MacroResult::NotFound) {
if (Asm->Structs.emit(*Name, ""s, p, gl)) {
P = (char *) p;
return true;
}
} else if (R == MacroResult::Success) {
P = p;
std::string tmp{line};
while (Asm->Macros.readLine(line, LINEMAX)) {
parseLineSafe(P);
}
std::strncpy(line, tmp.c_str(), LINEMAX);
return true;
} else if (R == MacroResult::NotEnoughArgs) {
Error("Not enough arguments for macro"s, *Name);
return false;
} else if (R == MacroResult::TooManyArgs) {
Error("Too many arguments for macro"s, *Name);
return true;
}
return false;
}
void parseInstruction(const char *BOL, const char *&BOI) {
if (parseDirective(BOL, BOI)) {
return;
}
Z80::getOpCode(BOI);
}
unsigned char win2dos[] = //taken from HorrorWord %)))
{
0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0,
0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1,
0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xF0, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xF2, 0xF3,
0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF1, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0x20, 0x80, 0x81, 0x82, 0x83,
0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94,
0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5,
0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6,
0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF
};
void parseLine(const char *&P, bool ParseLabels) {
/*++CurrentGlobalLine;*/
substituteDepthCount = comnxtlin = 0;
if (!RepeatStack.empty()) {
RepeatInfo &dup = RepeatStack.top();
if (!dup.Complete) {
P = line;
dup.Lines.emplace_back(P);
parseDirective_REPT(P);
return;
}
}
P = substituteMacros(line);
const char *BOL = P;
if (Asm->options().ConvertWindowsToDOS) {
auto *lp2 = (unsigned char *) P;
while (*(lp2++)) {
if ((*lp2) >= 128) {
*lp2 = win2dos[(*lp2) - 128];
}
}
}
if (comlin) {
comlin += comnxtlin;
Asm->Listing.listLineSkip(line);
return;
}
comlin += comnxtlin;
if (!*P) {
Asm->Listing.listLine(line);
return;
}
if (ParseLabels) {
parseLabel(P);
}
if (skipWhiteSpace(P)) {
Asm->Listing.listLine(line);
return;
}
parseMacro(P);
if (skipWhiteSpace(P)) {
Asm->Listing.listLine(line);
return;
}
parseInstruction(BOL, P);
if (skipWhiteSpace(P)) {
Asm->Listing.listLine(line);
return;
}
if (*P) {
Error("Unexpected"s, P, LASTPASS);
}
Asm->Listing.listLine(line);
}
void parseLineSafe(const char *&P, bool ParseLabels) {
char *tmp = NULL, *tmp2 = NULL;
const char *rp = P;
if (sline[0] > 0) {
tmp = STRDUP(sline);
if (tmp == NULL) {
Fatal("Out of memory!"s);
}
}
if (sline2[0] > 0) {
tmp2 = STRDUP(sline2);
if (tmp2 == NULL) {
Fatal("Out of memory!"s);
}
}
CompiledCurrentLine++;
parseLine(P, ParseLabels);
*sline = 0;
*sline2 = 0;
if (tmp2 != NULL) {
STRCPY(sline2, LINEMAX2, tmp2);
free(tmp2);
}
if (tmp != NULL) {
STRCPY(sline, LINEMAX2, tmp);
free(tmp);
}
P = rp;
}
void parseStructLine(const char *&P, CStruct &St) {
substituteDepthCount = comnxtlin = 0;
P = substituteMacros(line);
if (comlin) {
comlin += comnxtlin;
return;
}
comlin += comnxtlin;
if (!*P) {
return;
}
parseStructLabel(P, St);
if (skipWhiteSpace(P)) {
return;
}
parseStructMember(P, St);
if (skipWhiteSpace(P)) {
return;
}
if (*P) {
Error("[STRUCT] Unexpected"s, P);
}
}
int getBytes(const char *&P, int *E, int Add, int DC) {
AInt val;
int t = 0;
while (true) {
skipWhiteSpace(P);
if (!*P) {
Error("Expression expected"s, SUPPRESS);
break;
}
if (t == 128) {
Error("Too many arguments"s, P, SUPPRESS);
break;
}
if (*P == '"') {
P++;
do {
if (!*P || *P == '"') {
Error("Syntax error"s, P, SUPPRESS);
E[t] = -1;
return t;
}
if (t == 128) {
Error("Too many arguments"s, P, SUPPRESS);
E[t] = -1;
return t;
}
getCharConstChar(P, val);
check8(val);
E[t++] = (val + Add) & 255;
} while (*P != '"');
++P;
if (DC && t) {
E[t - 1] |= 128;
}
/* (begin add) */
} else if ((*P == 0x27) && (!*(P + 2) || *(P + 2) != 0x27)) {
P++;
do {
if (!*P || *P == 0x27) {
Error("Syntax error"s, P, SUPPRESS);
E[t] = -1;
return t;
}
if (t == 128) {
Error("Too many arguments"s, P, SUPPRESS);
E[t] = -1;
return t;
}
getCharConstCharSingle(P, val);
check8(val);
E[t++] = (val + Add) & 255;
} while (*P != 0x27);
++P;
if (DC && t) {
E[t - 1] |= 128;
}
/* (end add) */
} else {
if (parseExpression(P, val)) {
check8(val);
E[t++] = (val + Add) & 255;
} else {
Error("Syntax error"s, P, SUPPRESS);
break;
}
}
skipWhiteSpace(P);
if (*P != ',') {
break;
}
++P;
}
E[t] = -1;
return t;
}
unsigned long luaCalculate(const char *str) {
AInt val;
if (!parseExpression(str, val)) {
return 0;
} else {
return val;
}
}
void luaParseLine(char *str) {
char *ml;
ml = STRDUP(line);
if (ml == nullptr) {
Fatal("Out of memory!"s);
return;
}
STRCPY(line, LINEMAX, str);
parseLineSafe(lp);
STRCPY(line, LINEMAX, ml);
free(ml);
}
void luaParseCode(char *str) {
char *ml;
ml = STRDUP(line);
if (ml == nullptr) {
Fatal("Out of memory!"s);
return;
}
STRCPY(line, LINEMAX, str);
parseLineSafe(lp, false);
STRCPY(line, LINEMAX, ml);
free(ml);
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r8
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x1cd4b, %rsi
lea addresses_WT_ht+0x134eb, %rdi
nop
nop
nop
nop
xor %r13, %r13
mov $53, %rcx
rep movsb
inc %r13
lea addresses_D_ht+0x204b, %rsi
nop
nop
nop
nop
nop
xor %r12, %r12
mov $0x6162636465666768, %r8
movq %r8, %xmm0
and $0xffffffffffffffc0, %rsi
movaps %xmm0, (%rsi)
nop
sub $32313, %r12
lea addresses_UC_ht+0x1d29e, %rsi
lea addresses_D_ht+0xce9b, %rdi
xor %r9, %r9
mov $126, %rcx
rep movsl
and $19906, %rsi
lea addresses_UC_ht+0xaa0b, %rsi
lea addresses_normal_ht+0x7733, %rdi
nop
xor %rbx, %rbx
mov $116, %rcx
rep movsl
nop
nop
add $31265, %rsi
lea addresses_WT_ht+0x12f4b, %r12
nop
nop
sub %r8, %r8
movw $0x6162, (%r12)
nop
nop
nop
nop
nop
xor $48525, %r9
lea addresses_A_ht+0x1520b, %rsi
lea addresses_WC_ht+0x894b, %rdi
nop
nop
nop
inc %r12
mov $72, %rcx
rep movsq
and %rbx, %rbx
lea addresses_normal_ht+0xd5f6, %rsi
lea addresses_D_ht+0x1e14b, %rdi
nop
nop
nop
nop
nop
inc %r13
mov $36, %rcx
rep movsb
nop
and $28933, %r13
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r14
push %rax
push %rcx
push %rdx
// Faulty Load
lea addresses_WC+0x1e54b, %rcx
clflush (%rcx)
add %r11, %r11
movups (%rcx), %xmm5
vpextrq $1, %xmm5, %rdx
lea oracles, %r14
and $0xff, %rdx
shlq $12, %rdx
mov (%r14,%rdx,1), %rdx
pop %rdx
pop %rcx
pop %rax
pop %r14
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WC', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_WC', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'}
{'38': 21829}
38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
*/
|
strlen:
enter 0,0
mov edx, [ ebp + 8 ]
mov eax, 0
.back:
test byte [ edx + eax ], 0xff
jz .exit
inc eax
jmp .back
.exit:
leave
ret |
;===================================================================================================
; PRESET DATA HEADER
;===================================================================================================
presetheader_lowleg:
dw presetSRAM_lowleg ; location of SRAM
dw presetpersistent_lowleg ; location of persistent data
;===================================================================================================
%menu_header("Low% NMG (legacy)", 15)
%submenu("Escape", presetmenu_lowleg_escape)
%submenu("Eastern Palace", presetmenu_lowleg_eastern)
%submenu("Desert Palace", presetmenu_lowleg_desert)
%submenu("Tower of Hera", presetmenu_lowleg_hera)
%submenu("Agahnim's Tower", presetmenu_lowleg_aga)
%submenu("Palace of Darkness", presetmenu_lowleg_pod)
%submenu("Thieves' Town", presetmenu_lowleg_thieves)
%submenu("Skull Woods", presetmenu_lowleg_skull)
%submenu("Ice Palace", presetmenu_lowleg_ice)
%submenu("Swamp Palace", presetmenu_lowleg_swamp)
%submenu("Misery Mire", presetmenu_lowleg_mire)
%submenu("Turtle Rock", presetmenu_lowleg_trock)
%submenu("Ganon's Tower", presetmenu_lowleg_gtower)
%submenu("Ganon", presetmenu_lowleg_ganon)
%submenu("Bosses", presetmenu_lowleg_boss)
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; HYRULE CASTLE
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_escape:
%menu_header("Escape", 14)
;---------------------------------------------------------------------------------------------------
%preset_UW("Link's Bed", "lowleg", "escape", "bed")
dw $0104 ; Screen ID
dw $0940, $215A ; Link Coords
dw $0900, $2110 ; Camera HV
db $00 ; Item
db $02 ; Link direction
;-----------------------------
db $00 ; Entrance
db $20 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Courtyard", "lowleg", "escape", "courtyard")
dw $0055 ; Screen ID
dw $0A78, $0BC6 ; Link Coords
dw $0A00, $0B10 ; Camera HV
db $00 ; Item
db $02 ; Link direction
;-----------------------------
db $7D ; Entrance
db $AF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "escape", "entrance")
dw $001B ; Screen ID
dw $07F9, $0709 ; Link Coords
dw $0785, $06AB ; Camera HV
db $00 ; Item
db $00 ; Link direction
;-----------------------------
dw $0804, $0718 ; Scroll X,Y
dw $05B2 ; Tilemap position
;dw $0005 ; Scroll mod Y
;dw $0009 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("1st Key Guard", "lowleg", "escape", "1st_keyguard")
dw $0001 ; Screen ID
dw $02F8, $0062 ; Link Coords
dw $0280, $0000 ; Camera HV
db $00 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $80 ; Room layout / Floor
db $0C ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Stealth Room", "lowleg", "escape", "stealth_room")
dw $0082 ; Screen ID
dw $040B, $1178 ; Link Coords
dw $0400, $110B ; Camera HV
db $00 ; Item
db $04 ; Link direction
;-----------------------------
db $04 ; Entrance
db $EF ; Room layout / Floor
db $0C ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE064, $0001) ; Room $72 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("2nd Key Guard", "lowleg", "escape", "2nd_keyguard")
dw $0071 ; Screen ID
dw $02AD, $0F78 ; Link Coords
dw $0200, $0F0B ; Camera HV
db $00 ; Item
db $06 ; Link direction
;-----------------------------
db $04 ; Entrance
db $2F ; Room layout / Floor
db $8C ; Door / Peg state / Layer
dw $0001 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Ball 'n Chains", "lowleg", "escape", "ball_n_chains")
dw $0070 ; Screen ID
dw $0050, $0E2D ; Link Coords
dw $0000, $0E00 ; Camera HV
db $00 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $0E ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE062, $0003) ; Room $71 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Backtracking", "lowleg", "escape", "backtracking")
dw $0080 ; Screen ID
dw $0050, $1026 ; Link Coords
dw $0000, $1000 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $8D ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0004 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE062, $0003) ; Room $71 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Key Guard Revisited", "lowleg", "escape", "keyguard_revisited")
dw $0072 ; Screen ID
dw $04F8, $0F2D ; Link Coords
dw $0480, $0F00 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $AF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Throne Room", "lowleg", "escape", "throne_room")
dw $0051 ; Screen ID
dw $02F8, $0A8E ; Link Coords
dw $0280, $0A21 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $C1 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Snake Avoidance Room", "lowleg", "escape", "snake_avoidance_room")
dw $0041 ; Screen ID
dw $03A8, $082D ; Link Coords
dw $0300, $0800 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $D1 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Sewer Rooms", "lowleg", "escape", "water_rooms")
dw $0032 ; Screen ID
dw $04F8, $061F ; Link Coords
dw $0480, $0600 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $CF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Key Rat", "lowleg", "escape", "keyrat")
dw $0021 ; Screen ID
dw $02F8, $052D ; Link Coords
dw $0280, $0500 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $AF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Into Sanctuary", "lowleg", "escape", "into_sanctuary")
dw $0011 ; Screen ID
dw $0378, $022D ; Link Coords
dw $0300, $0200 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $04 ; Entrance
db $5F ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFC2, $0001) ; Room $21 sprite deaths
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; EASTERN
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_eastern:
%menu_header("Eastern Palace", 15)
;---------------------------------------------------------------------------------------------------
%preset_UW("Before Cutscene", "lowleg", "eastern", "before_cutscene")
dw $0002 ; Screen ID
dw $04F8, $01B8 ; Link Coords
dw $0480, $0110 ; Camera HV
db $09 ; Item
db $02 ; Link direction
;-----------------------------
db $04 ; Entrance
db $A0 ; Room layout / Floor
db $8D ; Door / Peg state / Layer
dw $000A ; Dead sprites
;-----------------------------
%write8_enable()
%write8($7E0642, $01) ; Room puzzle state
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("After Cutscene", "lowleg", "eastern", "after_cutscene")
dw $0012 ; Screen ID
dw $04F8, $027A ; Link Coords
dw $0480, $020D ; Camera HV
db $09 ; Item
db $02 ; Link direction
;-----------------------------
db $04 ; Entrance
db $C0 ; Room layout / Floor
db $08 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Octorok OW", "lowleg", "eastern", "octorok")
dw $001D ; Screen ID
dw $0B10, $07DC ; Link Coords
dw $0A9E, $071E ; Camera HV
db $09 ; Item
db $02 ; Link direction
;-----------------------------
dw $0B1B, $078B ; Scroll X,Y
dw $0894 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0002 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("EP Overworld", "lowleg", "eastern", "outside_palace")
dw $002E ; Screen ID
dw $0C70, $0A08 ; Link Coords
dw $0C00, $0A00 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
dw $0C7D, $0A6D ; Scroll X,Y
dw $0000 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "eastern", "entrance")
dw $001E ; Screen ID
dw $0F50, $0637 ; Link Coords
dw $0EDE, $0600 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
dw $0F5B, $066F ; Scroll X,Y
dw $005A ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF2 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Stalfos Room", "lowleg", "eastern", "stalfos_room")
dw $00A8 ; Screen ID
dw $1128, $1577 ; Link Coords
dw $1100, $150A ; Camera HV
db $09 ; Item
db $04 ; Link direction
;-----------------------------
db $08 ; Entrance
db $70 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Big Chest Room 1", "lowleg", "eastern", "big_chest_room_1")
dw $00A8 ; Screen ID
dw $11C6, $1478 ; Link Coords
dw $1100, $140B ; Camera HV
db $09 ; Item
db $06 ; Link direction
;-----------------------------
db $08 ; Entrance
db $50 ; Room layout / Floor
db $0E ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Dark Key Room", "lowleg", "eastern", "dark_key_room")
dw $00BA ; Screen ID
dw $14CA, $1678 ; Link Coords
dw $1400, $160B ; Camera HV
db $09 ; Item
db $06 ; Link direction
;-----------------------------
db $08 ; Entrance
db $00 ; Room layout / Floor
db $82 ; Door / Peg state / Layer
dw $0010 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Big Key Damage Boost", "lowleg", "eastern", "big_key_dmg_boost")
dw $00B9 ; Screen ID
dw $1225, $1678 ; Link Coords
dw $1200, $160B ; Camera HV
db $09 ; Item
db $04 ; Link direction
;-----------------------------
db $08 ; Entrance
db $C0 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE0F4, $0050) ; Room $BA sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Big Chest Room 2", "lowleg", "eastern", "big_chest_room_2")
dw $00A8 ; Screen ID
dw $11B2, $1478 ; Link Coords
dw $1100, $140B ; Camera HV
db $09 ; Item
db $06 ; Link direction
;-----------------------------
db $08 ; Entrance
db $50 ; Room layout / Floor
db $0E ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Gifted with Greenies", "lowleg", "eastern", "gwg")
dw $00A9 ; Screen ID
dw $12F8, $142B ; Link Coords
dw $1280, $1400 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $08 ; Entrance
db $C0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pot Room", "lowleg", "eastern", "pot_room")
dw $0099 ; Screen ID
dw $1278, $132D ; Link Coords
dw $1200, $1300 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $08 ; Entrance
db $A0 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $00D8 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Zeldagamer Room", "lowleg", "eastern", "zeldagamer_room")
dw $00D9 ; Screen ID
dw $1228, $1B78 ; Link Coords
dw $1200, $1B0B ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
db $08 ; Entrance
db $21 ; Room layout / Floor
db $80 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Double Reddies", "lowleg", "eastern", "double_reddies")
dw $00D8 ; Screen ID
dw $1178, $1B31 ; Link Coords
dw $1100, $1B00 ; Camera HV
db $03 ; Item
db $06 ; Direction
;-----------------------------
db $08 ; Entrance
db $31 ; Room layout
db $80 ; Door / Peg state / Layer
dw $0700 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Armos", "lowleg", "eastern", "armos")
dw $00D8 ; Screen ID
dw $1178, $1A30 ; Link Coords
dw $1100, $1A00 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $08 ; Entrance
db $11 ; Room layout / Floor
db $80 ; Door / Peg state / Layer
dw $07FF ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; DESERT
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_desert:
%menu_header("Desert Palace", 14)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Eastern Palace", "lowleg", "desert", "outside_eastern_palace")
dw $001E ; Screen ID
dw $0F50, $0638 ; Link Coords
dw $0ED6, $0600 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $0F5B, $066D ; Scroll X,Y
dw $005A ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Eastern Palace Spinspeed", "lowleg", "desert", "ep_spinspeed")
dw $0105 ; Screen ID
dw $0A78, $21C2 ; Link Coords
dw $0A00, $2110 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
db $45 ; Entrance
db $20 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write8_enable()
%write8($7EC167, $05) ; Underworld exit cache
%write8($7EC165, $20) ; Underworld exit cache
%write8($7EC166, $25) ; Underworld exit cache
%write16_enable()
%write16($7EC140, $001E) ; Underworld exit cache
%write16($7EC142, $0016) ; Underworld exit cache
%write16($7EC144, $06D7) ; Underworld exit cache
%write16($7EC146, $0C76) ; Underworld exit cache
%write16($7EC148, $0736) ; Underworld exit cache
%write16($7EC14A, $0CF0) ; Underworld exit cache
%write16($7EC14C, $001E) ; Underworld exit cache
%write16($7EC14E, $0710) ; Underworld exit cache
%write16($7EC150, $0744) ; Underworld exit cache
%write16($7EC152, $0CFB) ; Underworld exit cache
%write16($7EC154, $0600) ; Underworld exit cache
%write16($7EC156, $091E) ; Underworld exit cache
%write16($7EC158, $0C00) ; Underworld exit cache
%write16($7EC15A, $0F00) ; Underworld exit cache
%write16($7EC15C, $0520) ; Underworld exit cache
%write16($7EC15E, $0A00) ; Underworld exit cache
%write16($7EC160, $0B00) ; Underworld exit cache
%write16($7EC162, $1000) ; Underworld exit cache
%write16($7EC16A, $0009) ; Underworld exit cache
%write16($7EC16C, $FFF7) ; Underworld exit cache
%write16($7EC16E, $000A) ; Underworld exit cache
%write16($7EC170, $FFF6) ; Underworld exit cache
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Bridge Screen", "lowleg", "desert", "bridge_screen")
dw $002E ; Screen ID
dw $0C13, $0A69 ; Link Coords
dw $0C00, $0A0B ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
dw $0C85, $0A78 ; Scroll X,Y
dw $0000 ; Tilemap position
;dw $FFF5 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Unholy Spinspeed", "lowleg", "desert", "unholy_spinspeed")
dw $002A ; Screen ID
dw $0407, $0B9A ; Link Coords
dw $0400, $0B1E ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
dw $0485, $0B8D ; Scroll X,Y
dw $0900 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Water Dash", "lowleg", "desert", "water_dash")
dw $002C ; Screen ID
dw $08D2, $0BE2 ; Link Coords
dw $0860, $0B1E ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $08DD, $0B8D ; Scroll X,Y
dw $090C ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Desert Palace", "lowleg", "desert", "outside_desert_palace")
dw $003A ; Screen ID
dw $040E, $0F88 ; Link Coords
dw $0400, $0F1E ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
dw $0485, $0F8B ; Scroll X,Y
dw $0880 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "desert", "desert_entrance")
dw $0030 ; Screen ID
dw $0128, $0CBA ; Link Coords
dw $00AA, $0C5B ; Camera HV
db $0C ; Item
db $00 ; Link direction
;-----------------------------
dw $012F, $0CC3 ; Scroll X,Y
dw $0294 ; Tilemap position
;dw $0008 ; Scroll mod Y
;dw $FFF6 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Key Bonk", "lowleg", "desert", "keybonk")
dw $0073 ; Screen ID
dw $0778, $0F22 ; Link Coords
dw $0700, $0F00 ; Camera HV
db $0C ; Item
db $00 ; Link direction
;-----------------------------
db $09 ; Entrance
db $3F ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE068, $0001) ; Room $74 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pre Cannonball Room", "lowleg", "desert", "pre_cannonball_room")
dw $0085 ; Screen ID
dw $0ACB, $1078 ; Link Coords
dw $0A00, $100B ; Camera HV
db $0C ; Item
db $06 ; Link direction
;-----------------------------
db $09 ; Entrance
db $4F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F()
%write8($7F23DC, $00) ; Bastard door
%write8($7F23E3, $00)
%write8($7F249C, $00)
%write8($7F24A3, $00)
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pot Room", "lowleg", "desert", "pot_room")
dw $0073 ; Screen ID
dw $0725, $0F78 ; Link Coords
dw $0700, $0F0B ; Camera HV
db $0C ; Item
db $04 ; Link direction
;-----------------------------
db $09 ; Entrance
db $3F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE08A, $001C) ; Room $85 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Desert 2 Spinspeed", "lowleg", "desert", "desert2_spinspeed")
dw $0083 ; Screen ID
dw $0678, $11C3 ; Link Coords
dw $0600, $1110 ; Camera HV
db $0C ; Item
db $02 ; Link direction
;-----------------------------
db $09 ; Entrance
db $2F ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Popo Genocide", "lowleg", "desert", "popo_genocide_room")
dw $0053 ; Screen ID
dw $0678, $0AC6 ; Link Coords
dw $0600, $0A10 ; Camera HV
db $0C ; Item
db $02 ; Link direction
;-----------------------------
db $0C ; Entrance
db $01 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Torches", "lowleg", "desert", "torches")
dw $0043 ; Screen ID
dw $0778, $092E ; Link Coords
dw $0700, $0900 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $0C ; Entrance
db $31 ; Room layout / Floor
db $0D ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE026, $06E0) ; Room $53 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Lanmolas", "lowleg", "desert", "lanmolas")
dw $0043 ; Screen ID
dw $0678, $082E ; Link Coords
dw $0600, $0800 ; Camera HV
db $09 ; Item
db $00 ; Link direction
;-----------------------------
db $0C ; Entrance
db $81 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; HERA
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_hera:
%menu_header("Tower of Hera", 12)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Desert Palace", "lowleg", "hera", "outside_desert_palace")
dw $0030 ; Screen ID
dw $0128, $0C41 ; Link Coords
dw $00A2, $0C00 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $012F, $0C6D ; Scroll X,Y
dw $0016 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $000E ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Fake Flippers", "lowleg", "hera", "fake_flippers")
dw $003C ; Screen ID
dw $09E0, $0F7C ; Link Coords
dw $0900, $0F1E ; Camera HV
db $03 ; Item
db $06 ; Link direction
;-----------------------------
dw $097D, $0F8B ; Scroll X,Y
dw $0820 ; Tilemap position
;dw $FFF2 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Death Mountain", "lowleg", "hera", "dm")
dw $00F1 ; Screen ID
dw $0378, $1FC1 ; Link Coords
dw $0300, $1F10 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
db $06 ; Entrance
db $F0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("After Mirror", "lowleg", "hera", "after_mirror")
dw $0003 ; Screen ID
dw $071E, $03C0 ; Link Coords
dw $06AA, $031E ; Camera HV
db $03 ; Item
db $06 ; Link direction
;-----------------------------
dw $0729, $038D ; Scroll X,Y
dw $1816 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF6 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Quickhop", "lowleg", "hera", "quickhop")
dw $0003 ; Screen ID
dw $081B, $0138 ; Link Coords
dw $07A5, $00D4 ; Camera HV
db $14 ; Item
db $04 ; Link direction
;-----------------------------
dw $0824, $0143 ; Scroll X,Y
dw $0638 ; Tilemap position
;dw $000A ; Scroll mod Y
;dw $000B ; Scroll mod X
;-----------------------------
%write8_enable()
%write8($7E031F, $90) ; iframes from mirror
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "hera", "entrance")
dw $0003 ; Screen ID
dw $08F0, $0085 ; Link Coords
dw $087C, $0021 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $08FB, $0090 ; Scroll X,Y
dw $00D0 ; Tilemap position
;dw $000D ; Scroll mod Y
;dw $FFF4 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Tile room", "lowleg", "hera", "tile_room")
dw $0077 ; Screen ID
dw $0E78, $0E45 ; Link Coords
dw $0E00, $0E00 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $33 ; Entrance
db $C1 ; Room layout / Floor
db $0C ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Torches", "lowleg", "hera", "torches")
dw $0087 ; Screen ID
dw $0F78, $10BC ; Link Coords
dw $0F00, $1010 ; Camera HV
db $14 ; Item
db $02 ; Link direction
;-----------------------------
db $33 ; Entrance
db $10 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Beetles", "lowleg", "hera", "beetles")
dw $0077 ; Screen ID
dw $0F68, $0F4E ; Link Coords
dw $0EF0, $0EE2 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $33 ; Entrance
db $F1 ; Room layout / Floor
db $0C ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Petting Zoo", "lowleg", "hera", "petting_zoo")
dw $0031 ; Screen ID
dw $03B8, $067C ; Link Coords
dw $0300, $060F ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $33 ; Entrance
db $92 ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0580 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Bumper Skip", "lowleg", "hera", "bumper_skip")
dw $0027 ; Screen ID
dw $0E38, $0471 ; Link Coords
dw $0E00, $0404 ; Camera HV
db $03 ; Item
db $00 ; Direction
;-----------------------------
db $33 ; Entrance
db $C3 ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0064 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Moldorm", "lowleg", "hera", "moldorm")
dw $0017 ; Screen ID
dw $0FA8, $027A ; Link Coords
dw $0F00, $020D ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $33 ; Entrance
db $D4 ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFCE, $0024) ; Room $27 sprite deaths
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; AGAHNIM'S TOWER
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_aga:
%menu_header("Agahnim's Tower", 14)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Hera", "lowleg", "aga", "outside_hera")
dw $0003 ; Screen ID
dw $08F0, $007C ; Link Coords
dw $087C, $0018 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $08FB, $0087 ; Scroll X,Y
dw $0050 ; Tilemap position
;dw $0006 ; Scroll mod Y
;dw $FFF4 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("First Rupee Tree", "lowleg", "aga", "first_rupee_tree")
dw $00E6 ; Screen ID
dw $0C78, $1DB8 ; Link Coords
dw $0C00, $1D10 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
db $2F ; Entrance
db $E0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE14E, $0008) ; Room $E7 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Lost Woods", "lowleg", "aga", "lost_woods")
dw $0002 ; Screen ID
dw $0406, $007A ; Link Coords
dw $0400, $0016 ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
dw $048D, $0085 ; Scroll X,Y
dw $0100 ; Tilemap position
;dw $0008 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("After Grove", "lowleg", "aga", "after_grove")
dw $0000 ; Screen ID
dw $00A0, $00CB ; Link Coords
dw $0022, $006B ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $00A7, $00DA ; Scroll X,Y
dw $0306 ; Tilemap position
;dw $FFF3 ; Scroll mod Y
;dw $000E ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("After Lost Woods", "lowleg", "aga", "after_lost_woods")
dw $0000 ; Screen ID
dw $0388, $03D0 ; Link Coords
dw $0300, $031E ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $0385, $038D ; Scroll X,Y
dw $1860 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Castle Screen", "lowleg", "aga", "castle_screen")
dw $001A ; Screen ID
dw $05E5, $0728 ; Link Coords
dw $0500, $06CA ; Camera HV
db $03 ; Item
db $06 ; Link direction
;-----------------------------
dw $057D, $0737 ; Scroll X,Y
dw $0620 ; Tilemap position
;dw $FFF6 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "aga", "entrance")
dw $001B ; Screen ID
dw $07F8, $065C ; Link Coords
dw $077E, $0600 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
dw $0803, $066D ; Scroll X,Y
dw $002E ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF2 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Prize Pack Guards", "lowleg", "aga", "prize_pack_guards")
dw $00E0 ; Screen ID
dw $00DA, $1C78 ; Link Coords
dw $0000, $1C0B ; Camera HV
db $03 ; Item
db $06 ; Link direction
;-----------------------------
db $24 ; Entrance
db $01 ; Room layout / Floor
db $82 ; Door / Peg state / Layer
dw $0003 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Dark Room of Despair", "lowleg", "aga", "dark_room_of_despair")
dw $00D0 ; Screen ID
dw $010A, $1A78 ; Link Coords
dw $0100, $1A0B ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
db $24 ; Entrance
db $12 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE140, $000F) ; Room $E0 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Dark Room of Melancholy", "lowleg", "aga", "dark_room_of_melancholy")
dw $00C0 ; Screen ID
dw $0125, $1978 ; Link Coords
dw $0100, $190B ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
db $24 ; Entrance
db $33 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE120, $0020) ; Room $D0 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spear Guards", "lowleg", "aga", "spear_guards")
dw $00C0 ; Screen ID
dw $0178, $182C ; Link Coords
dw $0100, $1800 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $24 ; Entrance
db $13 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0018 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Circle of Pots", "lowleg", "aga", "circle_of_pots")
dw $00B0 ; Screen ID
dw $0078, $16C4 ; Link Coords
dw $0000, $1610 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
db $24 ; Entrance
db $04 ; Room layout / Floor
db $81 ; Door / Peg state / Layer
dw $003F ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Catwalk", "lowleg", "aga", "catwalk")
dw $0040 ; Screen ID
dw $012C, $0978 ; Link Coords
dw $0100, $090B ; Camera HV
db $03 ; Item
db $04 ; Link direction
;-----------------------------
db $24 ; Entrance
db $35 ; Room layout / Floor
db $0E ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE0E0, $043F) ; Room $B0 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Agahnim", "lowleg", "aga", "agahnim")
dw $0030 ; Screen ID
dw $0078, $062D ; Link Coords
dw $0000, $0600 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $24 ; Entrance
db $06 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0001 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; PALACE OF DARKNESS
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_pod:
%menu_header("Palace of Darkness", 14)
;---------------------------------------------------------------------------------------------------
%preset_OW("Pyramid", "lowleg", "pod", "pyramid")
dw $005B ; Screen ID
dw $07F0, $0660 ; Link Coords
dw $0778, $0602 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
dw $07F7, $066F ; Scroll X,Y
dw $002E ; Tilemap position
;dw $FFFE ; Scroll mod Y
;dw $FFF8 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Palace Overworld Screen", "lowleg", "pod", "pod_overworld")
dw $006E ; Screen ID
dw $0C70, $0A0C ; Link Coords
dw $0C00, $0A00 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
dw $0C7D, $0A6D ; Scroll X,Y
dw $0000 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "pod", "entrance")
dw $005E ; Screen ID
dw $0F50, $064C ; Link Coords
dw $0EDE, $0600 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
dw $0F5B, $066F ; Scroll X,Y
dw $005A ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF2 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Main Hub (Small Key)", "lowleg", "pod", "main_hub_small_key")
dw $004A ; Screen ID
dw $14F8, $081B ; Link Coords
dw $1480, $0800 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $80 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Main Hub (Big Key)", "lowleg", "pod", "main_hub_bk")
dw $004A ; Screen ID
dw $14F8, $081A ; Link Coords
dw $1480, $0800 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $80 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Main Hub (Hammerjump)", "lowleg", "pod", "main_hub_hammeryump")
dw $004A ; Screen ID
dw $14F8, $0818 ; Link Coords
dw $1480, $0800 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $80 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Hammerjump", "lowleg", "pod", "hammeryump")
dw $002A ; Screen ID
dw $1478, $0424 ; Link Coords
dw $1400, $0400 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $C0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pre Sexy Statue", "lowleg", "pod", "before_sexy_statue")
dw $003A ; Screen ID
dw $1578, $062C ; Link Coords
dw $1500, $0600 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $D0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Sexy Statue Room", "lowleg", "pod", "sexy_statue_room")
dw $002A ; Screen ID
dw $15B4, $04F8 ; Link Coords
dw $1500, $048B ; Camera HV
db $03 ; Item
db $06 ; Link direction
;-----------------------------
db $26 ; Entrance
db $D0 ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mimics", "lowleg", "pod", "mimics")
dw $002B ; Screen ID
dw $1678, $0413 ; Link Coords
dw $1600, $0400 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $40 ; Room layout / Floor
db $C1 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write8_enable()
%write8($7E0642, $01) ; Room puzzle state (?)
%write8($7E0646, $01) ; hold switch
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Statue", "lowleg", "pod", "statue")
dw $001B ; Screen ID
dw $1678, $0320 ; Link Coords
dw $1600, $0300 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $20 ; Room layout / Floor
db $CD ; Door / Peg state / Layer
dw $0038 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Basement", "lowleg", "pod", "basement")
dw $001B ; Screen ID
dw $1790, $0251 ; Link Coords
dw $1700, $0200 ; Camera HV
db $04 ; Item
db $02 ; Link direction
;-----------------------------
db $26 ; Entrance
db $90 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Turtle Room", "lowleg", "pod", "turtle_room")
dw $000B ; Screen ID
dw $1678, $00C8 ; Link Coords
dw $1600, $0010 ; Camera HV
db $04 ; Item
db $02 ; Link direction
;-----------------------------
db $26 ; Entrance
db $0F ; Room layout / Floor
db $C1 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Helmasaur", "lowleg", "pod", "helma")
dw $006A ; Screen ID
dw $1578, $0C24 ; Link Coords
dw $1500, $0C00 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $26 ; Entrance
db $5F ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0010 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; THIEVES' TOWN
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_thieves:
%menu_header("Thieves' Town", 18)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside PoD", "lowleg", "thieves", "outside_pod")
dw $005E ; Screen ID
dw $0F50, $063E ; Link Coords
dw $0ED6, $0600 ; Camera HV
db $04 ; Item
db $02 ; Link direction
;-----------------------------
dw $0F5B, $066D ; Scroll X,Y
dw $005A ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Overworld Hammerdash", "lowleg", "thieves", "ow_hammerdash")
dw $006E ; Screen ID
dw $0C06, $0A6A ; Link Coords
dw $0C00, $0A0C ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
dw $0C85, $0A79 ; Scroll X,Y
dw $0000 ; Tilemap position
;dw $FFF4 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Grove", "lowleg", "thieves", "grove")
dw $0072 ; Screen ID
dw $04DA, $0C0C ; Link Coords
dw $045C, $0C00 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
dw $04E1, $0C6D ; Scroll X,Y
dw $000C ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0004 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Usain Bolt", "lowleg", "thieves", "usain_bolt")
dw $002A ; Screen ID
dw $0407, $0B99 ; Link Coords
dw $0400, $0B1E ; Camera HV
db $08 ; Item
db $00 ; Link direction
;-----------------------------
dw $0485, $0B8D ; Scroll X,Y
dw $0900 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("After Activating Flute", "lowleg", "thieves", "after_activating_flute")
dw $0018 ; Screen ID
dw $01CA, $0798 ; Link Coords
dw $014C, $0734 ; Camera HV
db $08 ; Item
db $04 ; Link direction
;-----------------------------
dw $01D1, $07A3 ; Scroll X,Y
dw $092A ; Tilemap position
;dw $000A ; Scroll mod Y
;dw $0004 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("After Warp", "lowleg", "thieves", "darkworld")
dw $0050 ; Screen ID
dw $0161, $0553 ; Link Coords
dw $00E3, $04F5 ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
dw $0168, $0562 ; Scroll X,Y
dw $079E ; Tilemap position
;dw $FFFB ; Scroll mod Y
;dw $000D ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "thieves", "entrance")
dw $0058 ; Screen ID
dw $01F8, $07C2 ; Link Coords
dw $017E, $0764 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
dw $0203, $07D1 ; Scroll X,Y
dw $0BAE ; Tilemap position
;dw $000C ; Scroll mod Y
;dw $FFF2 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("After Big Key", "lowleg", "thieves", "after_big_key")
dw $00DB ; Screen ID
dw $17BA, $1B68 ; Link Coords
dw $1700, $1AFB ; Camera HV
db $04 ; Item
db $06 ; Link direction
;-----------------------------
db $34 ; Entrance
db $FF ; Room layout / Floor
db $0C ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Stalfos Hallway", "lowleg", "thieves", "blind_hallway")
dw $00CC ; Screen ID
dw $1978, $181D ; Link Coords
dw $1900, $1800 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $34 ; Entrance
db $DF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE138, $0080) ; Room $DC sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Conveyor Gibos", "lowleg", "thieves", "conveyor_gibos")
dw $00BC ; Screen ID
dw $181D, $1778 ; Link Coords
dw $1800, $170B ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
db $34 ; Entrance
db $2F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0340 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Hellway", "lowleg", "thieves", "hellway")
dw $00BB ; Screen ID
dw $1716, $1778 ; Link Coords
dw $1700, $170B ; Camera HV
db $01 ; Item
db $04 ; Link direction
;-----------------------------
db $34 ; Entrance
db $3F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write8_enable()
%write8($7E0ABD, $01) ; Palette swap
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Bombable Floor", "lowleg", "thieves", "bombable_floor")
dw $0065 ; Screen ID
dw $0AE7, $0D78 ; Link Coords
dw $0A00, $0D0B ; Camera HV
db $01 ; Item
db $06 ; Link direction
;-----------------------------
db $34 ; Entrance
db $20 ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Backtracking", "lowleg", "thieves", "backtracking_1")
dw $0064 ; Screen ID
dw $0878, $0D28 ; Link Coords
dw $0800, $0D00 ; Camera HV
db $01 ; Item
db $00 ; Link direction
;-----------------------------
db $34 ; Entrance
db $20 ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Basement", "lowleg", "thieves", "basement")
dw $00BC ; Screen ID
dw $1878, $162A ; Link Coords
dw $1800, $1600 ; Camera HV
db $01 ; Item
db $00 ; Link direction
;-----------------------------
db $34 ; Entrance
db $0F ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Prison", "lowleg", "thieves", "prison")
dw $0045 ; Screen ID
dw $0AE4, $0978 ; Link Coords
dw $0A00, $090B ; Camera HV
db $04 ; Item
db $06 ; Link direction
;-----------------------------
db $34 ; Entrance
db $2E ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0002 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("After Mitts", "lowleg", "thieves", "after_mitts")
dw $0044 ; Screen ID
dw $08DC, $0978 ; Link Coords
dw $0800, $090B ; Camera HV
db $04 ; Item
db $06 ; Link direction
;-----------------------------
db $34 ; Entrance
db $2E ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE00A, $0162) ; Room $45 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pot Hammerdash", "lowleg", "thieves", "pot_hammerdash")
dw $0045 ; Screen ID
dw $0A78, $082C ; Link Coords
dw $0A00, $0800 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $34 ; Entrance
db $0E ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE008, $0080) ; Room $44 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Blind", "lowleg", "thieves", "blind")
dw $00BC ; Screen ID
dw $1978, $1619 ; Link Coords
dw $1900, $1600 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $34 ; Entrance
db $5F ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0002 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; SKULL WOODS
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_skull:
%menu_header("Skull Woods", 8)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Thieves'", "lowleg", "skull", "outside_thieves")
dw $0058 ; Screen ID
dw $01F8, $07C8 ; Link Coords
dw $0176, $076A ; Camera HV
db $04 ; Item
db $02 ; Link direction
;-----------------------------
dw $0203, $07D7 ; Scroll X,Y
dw $0B2E ; Tilemap position
;dw $FFF6 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Mummy Room", "lowleg", "skull", "mummy_room")
dw $0040 ; Screen ID
dw $0248, $0250 ; Link Coords
dw $01CA, $01F0 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $024F, $025F ; Scroll X,Y
dw $0EBA ; Tilemap position
;dw $FFFE ; Scroll mod Y
;dw $0006 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Bomb Jump", "lowleg", "skull", "bomb_jump")
dw $0040 ; Screen ID
dw $02E8, $025B ; Link Coords
dw $0266, $01FD ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $02F3, $026A ; Scroll X,Y
dw $0F4E ; Tilemap position
;dw $0003 ; Scroll mod Y
;dw $000A ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Key Pot", "lowleg", "skull", "key_pot")
dw $0056 ; Screen ID
dw $0D1A, $0B78 ; Link Coords
dw $0D00, $0B0C ; Camera HV
db $01 ; Item
db $04 ; Link direction
;-----------------------------
db $29 ; Entrance
db $7F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Skull Entrance", "lowleg", "skull", "skull_entrance")
dw $0040 ; Screen ID
dw $0098, $00CA ; Link Coords
dw $0012, $0066 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
dw $009F, $00D5 ; Scroll X,Y
dw $0282 ; Tilemap position
;dw $000A ; Scroll mod Y
;dw $FFFE ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mummy Hellway", "lowleg", "skull", "mummy_hellway")
dw $0049 ; Screen ID
dw $12DC, $0978 ; Link Coords
dw $1200, $090B ; Camera HV
db $05 ; Item
db $06 ; Link direction
;-----------------------------
db $2B ; Entrance
db $2F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE032, $0003) ; Room $59 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mummy Key", "lowleg", "skull", "mummy_key")
dw $0049 ; Screen ID
dw $1278, $0815 ; Link Coords
dw $1200, $0800 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $2B ; Entrance
db $0F ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0801 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mothula", "lowleg", "skull", "mothula")
dw $0039 ; Screen ID
dw $12D0, $0778 ; Link Coords
dw $1200, $070B ; Camera HV
db $05 ; Item
db $06 ; Link direction
;-----------------------------
db $2B ; Entrance
db $2F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0002 ; Dead sprites
;-----------------------------
%write_7F()
%write8($7F2BDC, $00) ; Bastard door
%write8($7F2BE3, $00)
%write8($7F2C9C, $00)
%write8($7F2CA3, $00)
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; ICE PALACE
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_ice:
%menu_header("Ice Palace", 16)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Skull", "lowleg", "ice", "outside_skull")
dw $0040 ; Screen ID
dw $0098, $00CB ; Link Coords
dw $0016, $0069 ; Camera HV
db $14 ; Item
db $02 ; Link direction
;-----------------------------
dw $00A3, $00D6 ; Scroll X,Y
dw $0282 ; Tilemap position
;dw $0007 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Bridge Warp", "lowleg", "ice", "bridge_warp")
dw $002C ; Screen ID
dw $0898, $0A0C ; Link Coords
dw $0820, $0A00 ; Camera HV
db $08 ; Item
db $00 ; Link direction
;-----------------------------
dw $089F, $0A6D ; Scroll X,Y
dw $0004 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Lottery", "lowleg", "ice", "lottery")
dw $0055 ; Screen ID
dw $0BE1, $0587 ; Link Coords
dw $0B00, $051E ; Camera HV
db $08 ; Item
db $06 ; Link direction
;-----------------------------
dw $0B7D, $058D ; Scroll X,Y
dw $0920 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Catfish", "lowleg", "ice", "medallion")
dw $0057 ; Screen ID
dw $0F70, $040C ; Link Coords
dw $0EFE, $0400 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $0F7B, $046F ; Scroll X,Y
dw $009E ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF2 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Zora's Domain", "lowleg", "ice", "zoras_domain")
dw $000F ; Screen ID
dw $0F40, $0215 ; Link Coords
dw $0ECD, $0200 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $0F4A, $026F ; Scroll X,Y
dw $0098 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF3 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Tiny Warp Dik", "lowleg", "ice", "tiny_warp")
dw $000F ; Screen ID
dw $0F40, $0221 ; Link Coords
dw $0ECD, $0200 ; Camera HV
db $14 ; Item
db $02 ; Link direction
;-----------------------------
dw $0F4A, $026F ; Scroll X,Y
dw $0098 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF3 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "ice", "ice_entrance")
dw $0075 ; Screen ID
dw $0CB8, $0DCB ; Link Coords
dw $0C32, $0D69 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $0CBF, $0DD6 ; Scroll X,Y
dw $0BC6 ; Tilemap position
;dw $0007 ; Scroll mod Y
;dw $FFFE ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Ice 2", "lowleg", "ice", "ice2")
dw $000E ; Screen ID
dw $1D1E, $0178 ; Link Coords
dw $1D00, $010C ; Camera HV
db $05 ; Item
db $04 ; Link direction
;-----------------------------
db $2D ; Entrance
db $30 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0001 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Penguin Switch Room", "lowleg", "ice", "penguin_switch_room")
dw $001E ; Screen ID
dw $1DD8, $0378 ; Link Coords
dw $1D00, $030B ; Camera HV
db $05 ; Item
db $06 ; Link direction
;-----------------------------
db $2D ; Entrance
db $3F ; Room layout / Floor
db $82 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDF9C, $000B) ; Room $0E sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Bombable Floor", "lowleg", "ice", "bombable_floor")
dw $001E ; Screen ID
dw $1D78, $0314 ; Link Coords
dw $1D00, $0300 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $2D ; Entrance
db $3F ; Room layout / Floor
db $81 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFBE, $0071) ; Room $1F sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Conveyor Room", "lowleg", "ice", "conveyor_room")
dw $003E ; Screen ID
dw $1D78, $06D0 ; Link Coords
dw $1D00, $0610 ; Camera HV
db $01 ; Item
db $02 ; Link direction
;-----------------------------
db $2D ; Entrance
db $1E ; Room layout / Floor
db $C1 ; Door / Peg state / Layer
dw $0006 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("IPBJ", "lowleg", "ice", "ipbj")
dw $003E ; Screen ID
dw $1C78, $07D3 ; Link Coords
dw $1C00, $0710 ; Camera HV
db $01 ; Item
db $02 ; Link direction
;-----------------------------
db $2D ; Entrance
db $AE ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0306 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Penguin Lineup Room", "lowleg", "ice", "penguin_room")
dw $004E ; Screen ID
dw $1DB8, $0862 ; Link Coords
dw $1D00, $0800 ; Camera HV
db $01 ; Item
db $00 ; Link direction
;-----------------------------
db $2D ; Entrance
db $1E ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Lonely Firebar", "lowleg", "ice", "lonely_firebar")
dw $005E ; Screen ID
dw $1D10, $0B78 ; Link Coords
dw $1D00, $0B0B ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
db $2D ; Entrance
db $3D ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE05C, $001F) ; Room $6E sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Last Two Screens", "lowleg", "ice", "last_two_screens")
dw $009E ; Screen ID
dw $1D50, $1378 ; Link Coords
dw $1D00, $130B ; Camera HV
db $04 ; Item
db $06 ; Link direction
;-----------------------------
db $2D ; Entrance
db $3B ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Kholdstare", "lowleg", "ice", "kholdstare")
dw $00CE ; Screen ID
dw $1D40, $18AA ; Link Coords
dw $1D00, $1810 ; Camera HV
db $04 ; Item
db $02 ; Link direction
;-----------------------------
db $2D ; Entrance
db $1A ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; SWAMP PALACE
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_swamp:
%menu_header("Swamp Palace", 18)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Ice", "lowleg", "swamp", "outside_ice")
dw $0075 ; Screen ID
dw $0CB8, $0DCB ; Link Coords
dw $0C3E, $0D6D ; Camera HV
db $14 ; Item
db $02 ; Link direction
;-----------------------------
dw $0CC3, $0DDA ; Scroll X,Y
dw $0BC6 ; Tilemap position
;dw $0003 ; Scroll mod Y
;dw $FFF2 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Link's House", "lowleg", "swamp", "links_house")
dw $002C ; Screen ID
dw $08B8, $0B23 ; Link Coords
dw $0840, $0AC5 ; Camera HV
db $08 ; Item
db $02 ; Link direction
;-----------------------------
dw $08BF, $0B32 ; Scroll X,Y
dw $0608 ; Tilemap position
;dw $FFFB ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Swamp Overworld", "lowleg", "swamp", "swamp_overworld")
dw $0073 ; Screen ID
dw $07AF, $0DD9 ; Link Coords
dw $0700, $0D1E ; Camera HV
db $04 ; Item
db $02 ; Link direction
;-----------------------------
dw $0785, $0D93 ; Scroll X,Y
dw $08A0 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Dam", "lowleg", "swamp", "dam")
dw $003B ; Screen ID
dw $0778, $0EF0 ; Link Coords
dw $06FA, $0E91 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $077F, $0EFE ; Scroll X,Y
dw $0520 ; Tilemap position
;dw $000F ; Scroll mod Y
;dw $0006 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "swamp", "entrance")
dw $007B ; Screen ID
dw $0778, $0EEF ; Link Coords
dw $06FA, $0E91 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
dw $077F, $0EFE ; Scroll X,Y
dw $0520 ; Tilemap position
;dw $000F ; Scroll mod Y
;dw $0006 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("First Key Pot", "lowleg", "swamp", "first_key_pot")
dw $0028 ; Screen ID
dw $1078, $0426 ; Link Coords
dw $1000, $0400 ; Camera HV
db $14 ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $C0 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $000E ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Tiny Hallway Key", "lowleg", "swamp", "hallway_key_1")
dw $0037 ; Screen ID
dw $0EF8, $0728 ; Link Coords
dw $0E80, $0700 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $AF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Water Lever 1", "lowleg", "swamp", "water_lever_1")
dw $0037 ; Screen ID
dw $0E78, $071D ; Link Coords
dw $0E00, $0700 ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $AF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Main Hub", "lowleg", "swamp", "main_hub")
dw $0037 ; Screen ID
dw $0E18, $0778 ; Link Coords
dw $0E00, $070B ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
db $25 ; Entrance
db $AF ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Water Lever 2", "lowleg", "swamp", "water_lever_2")
dw $0036 ; Screen ID
dw $0C17, $0678 ; Link Coords
dw $0C00, $060B ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
db $25 ; Entrance
db $CF ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0032 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFEA, $0240) ; Room $35 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Sociable Firebar", "lowleg", "swamp", "sociable_firebar")
dw $0034 ; Screen ID
dw $0878, $072C ; Link Coords
dw $0800, $06BF ; Camera HV
db $04 ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $EF ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFEA, $0240) ; Room $35 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Backtracking", "lowleg", "swamp", "backtracking")
dw $0035 ; Screen ID
dw $0A19, $0678 ; Link Coords
dw $0A00, $060B ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
db $25 ; Entrance
db $8F ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFEA, $0240) ; Room $35 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Hookshot", "lowleg", "swamp", "hookshot")
dw $0035 ; Screen ID
dw $0BDA, $0778 ; Link Coords
dw $0B00, $070B ; Camera HV
db $04 ; Item
db $06 ; Link direction
;-----------------------------
db $25 ; Entrance
db $BF ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFE8, $0001) ; Room $34 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Hookdash", "lowleg", "swamp", "hookdash")
dw $0036 ; Screen ID
dw $0CF8, $062C ; Link Coords
dw $0C80, $0600 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $CF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Water Lever 3", "lowleg", "swamp", "water_lever_3")
dw $0026 ; Screen ID
dw $0DA8, $0426 ; Link Coords
dw $0D00, $0400 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $1F ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0400 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Restock Room", "lowleg", "swamp", "restock")
dw $0066 ; Screen ID
dw $0D78, $0D2A ; Link Coords
dw $0D00, $0D00 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $BE ; Room layout / Floor
db $0D ; Door / Peg state / Layer
dw $0080 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE06C, $0002) ; Room $76 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Phelps Way", "lowleg", "swamp", "phelps_way")
dw $0016 ; Screen ID
dw $0D78, $02D8 ; Link Coords
dw $0D00, $0210 ; Camera HV
db $0E ; Item
db $02 ; Link direction
;-----------------------------
db $25 ; Entrance
db $9F ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Arrghus", "lowleg", "swamp", "arrghus")
dw $0016 ; Screen ID
dw $0C78, $0212 ; Link Coords
dw $0C00, $0200 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $25 ; Entrance
db $8F ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0004 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; MISERY MIRE
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_mire:
%menu_header("Misery Mire", 19)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Swamp", "lowleg", "mire", "outside_swamp")
dw $007B ; Screen ID
dw $0778, $0EEB ; Link Coords
dw $06F2, $0E8D ; Camera HV
db $05 ; Item
db $02 ; Link direction
;-----------------------------
dw $077F, $00EFA ; Scroll X,Y
dw $049E ; Tilemap position
;dw $FFF4 ; Scroll mod Y
;dw $FFFC ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Death Mountain", "lowleg", "mire", "dm")
dw $0003 ; Screen ID
dw $067B, $0328 ; Link Coords
dw $060D, $02CA ; Camera HV
db $0E ; Item
db $06 ; Link direction
;-----------------------------
dw $0682, $0337 ; Scroll X,Y
dw $1600 ; Tilemap position
;dw $FFF6 ; Scroll mod Y
;dw $FFF3 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Free Flutedash", "lowleg", "mire", "free_flutedash")
dw $0003 ; Screen ID
dw $06C1, $004B ; Link Coords
dw $0653, $0000 ; Camera HV
db $0C ; Item
db $06 ; Link direction
;-----------------------------
dw $06C8, $006D ; Scroll X,Y
dw $000A ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFFD ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Mire Portal", "lowleg", "mire", "darkworld_warp")
dw $0030 ; Screen ID
dw $008E, $0FA8 ; Link Coords
dw $000C, $0F1E ; Camera HV
db $08 ; Item
db $06 ; Link direction
;-----------------------------
dw $0099, $0F8D ; Scroll X,Y
dw $1880 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFF4 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Mire Entrance", "lowleg", "mire", "entrance")
dw $0070 ; Screen ID
dw $0128, $0CE6 ; Link Coords
dw $00A6, $0C82 ; Camera HV
db $10 ; Item
db $00 ; Link direction
;-----------------------------
dw $0133, $0CF1 ; Scroll X,Y
dw $0414 ; Tilemap position
;dw $000C ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mire 2", "lowleg", "mire", "mire2")
dw $0098 ; Screen ID
dw $1188, $132A ; Link Coords
dw $1100, $1300 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $27 ; Entrance
db $B0 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Main Hub", "lowleg", "mire", "main_hub")
dw $00D2 ; Screen ID
dw $0578, $1A1C ; Link Coords
dw $0500, $1A00 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $27 ; Entrance
db $DF ; Room layout / Floor
db $81 ; Door / Peg state / Layer
dw $03EF ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Beat the Fireball", "lowleg", "mire", "beat_the_fireball")
dw $00B2 ; Screen ID
dw $0578, $17E2 ; Link Coords
dw $0500, $1710 ; Camera HV
db $05 ; Item
db $02 ; Link direction
;-----------------------------
db $27 ; Entrance
db $3F ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Bari Key", "lowleg", "mire", "bari_key")
dw $00C2 ; Screen ID
dw $0415, $1978 ; Link Coords
dw $0400, $190B ; Camera HV
db $05 ; Item
db $04 ; Link direction
;-----------------------------
db $27 ; Entrance
db $EF ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Sluggulas", "lowleg", "mire", "sluggulas")
dw $00C1 ; Screen ID
dw $0278, $19CF ; Link Coords
dw $0200, $1910 ; Camera HV
db $05 ; Item
db $02 ; Link direction
;-----------------------------
db $27 ; Entrance
db $2F ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0200 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Torches", "lowleg", "mire", "torches")
dw $00D1 ; Screen ID
dw $02A8, $1A28 ; Link Coords
dw $0200, $1A00 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $27 ; Entrance
db $0F ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0040 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spark Gamble", "lowleg", "mire", "spark_gamble")
dw $00C1 ; Screen ID
dw $03D6, $1878 ; Link Coords
dw $0300, $180B ; Camera HV
db $05 ; Item
db $06 ; Link direction
;-----------------------------
db $27 ; Entrance
db $1F ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Big Chest Room", "lowleg", "mire", "big_chest_room")
dw $00C3 ; Screen ID
dw $06D8, $1978 ; Link Coords
dw $0600, $190B ; Camera HV
db $0E ; Item
db $06 ; Link direction
;-----------------------------
db $27 ; Entrance
db $6F ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spike Key", "lowleg", "mire", "spike_key")
dw $00C3 ; Screen ID
dw $0678, $1814 ; Link Coords
dw $0600, $1800 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $27 ; Entrance
db $4F ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Wizzrobe", "lowleg", "mire", "wizzrobe")
dw $00B3 ; Screen ID
dw $0624, $1678 ; Link Coords
dw $0600, $160B ; Camera HV
db $0E ; Item
db $04 ; Link direction
;-----------------------------
db $27 ; Entrance
db $0F ; Room layout / Floor
db $4E ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Basement", "lowleg", "mire", "basement")
dw $00A2 ; Screen ID
dw $04F8, $1444 ; Link Coords
dw $0480, $1400 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $27 ; Entrance
db $CF ; Room layout / Floor
db $4C ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE0E4, $0001) ; Room $B2 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spooky Action 1", "lowleg", "mire", "spooky_action_1")
dw $0093 ; Screen ID
dw $0612, $1378 ; Link Coords
dw $0600, $130B ; Camera HV
db $05 ; Item
db $04 ; Link direction
;-----------------------------
db $27 ; Entrance
db $2E ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spooky Action 2", "lowleg", "mire", "spooky_action_2")
dw $0092 ; Screen ID
dw $0515, $1378 ; Link Coords
dw $0500, $130B ; Camera HV
db $05 ; Item
db $04 ; Link direction
;-----------------------------
db $27 ; Entrance
db $7E ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Vitreous", "lowleg", "mire", "vitty")
dw $00A0 ; Screen ID
dw $0078, $1428 ; Link Coords
dw $0000, $1400 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $27 ; Entrance
db $CF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE0A4, $0200) ; Room $92 sprite deaths
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; TURTLE ROCK
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_trock:
%menu_header("Turtle Rock", 17)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Mire", "lowleg", "trock", "outside_mire")
dw $0070 ; Screen ID
dw $0128, $0CDA ; Link Coords
dw $00A6, $0C7C ; Camera HV
db $14 ; Item
db $02 ; Link direction
;-----------------------------
dw $0133, $0CE9 ; Scroll X,Y
dw $0414 ; Tilemap position
;dw $0004 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Ice Rod Overworld", "lowleg", "trock", "icerod_overworld")
dw $003F ; Screen ID
dw $0F70, $0E07 ; Link Coords
dw $0EF6, $0E00 ; Camera HV
db $08 ; Item
db $00 ; Link direction
;-----------------------------
dw $0F7B, $0E6D ; Scroll X,Y
dw $001E ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Death Mountain", "lowleg", "trock", "dm")
dw $0003 ; Screen ID
dw $067B, $0328 ; Link Coords
dw $060D, $02CA ; Camera HV
db $08 ; Item
db $06 ; Link direction
;-----------------------------
dw $0682, $0337 ; Scroll X,Y
dw $1600 ; Tilemap position
;dw $FFF6 ; Scroll mod Y
;dw $FFF3 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Squirrels", "lowleg", "trock", "squirrels")
dw $00DF ; Screen ID
dw $1EF8, $1BD9 ; Link Coords
dw $1E80, $1B10 ; Camera HV
db $0E ; Item
db $02 ; Link direction
;-----------------------------
db $1F ; Entrance
db $A1 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0003 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Peg Puzzle", "lowleg", "trock", "peg_puzzle")
dw $0005 ; Screen ID
dw $0DE1, $0077 ; Link Coords
dw $0D00, $0013 ; Camera HV
db $0E ; Item
db $06 ; Link direction
;-----------------------------
dw $0D7D, $0082 ; Scroll X,Y
dw $0060 ; Tilemap position
;dw $000B ; Scroll mod Y
;dw $0000 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "trock", "entrance")
dw $0047 ; Screen ID
dw $0F08, $013D ; Link Coords
dw $0E96, $00DB ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
dw $0F13, $014A ; Scroll X,Y
dw $0614 ; Tilemap position
;dw $0003 ; Scroll mod Y
;dw $000A ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Torches", "lowleg", "trock", "torches")
dw $00C6 ; Screen ID
dw $0DCD, $1878 ; Link Coords
dw $0D00, $180B ; Camera HV
db $12 ; Item
db $06 ; Link direction
;-----------------------------
db $35 ; Entrance
db $D0 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0028 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Roller Room", "lowleg", "trock", "roller_room")
dw $00C7 ; Screen ID
dw $0E78, $1820 ; Link Coords
dw $0E00, $1800 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $35 ; Entrance
db $C0 ; Room layout / Floor
db $81 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pokey 0", "lowleg", "trock", "pokey_0")
dw $00C6 ; Screen ID
dw $0C78, $182B ; Link Coords
dw $0C00, $1800 ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
db $35 ; Entrance
db $C0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Chomps", "lowleg", "trock", "chomps")
dw $00B6 ; Screen ID
dw $0C78, $1718 ; Link Coords
dw $0C00, $1700 ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
db $35 ; Entrance
db $20 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0020 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pokey 1", "lowleg", "trock", "pokey_1")
dw $0014 ; Screen ID
dw $0819, $0278 ; Link Coords
dw $0800, $020B ; Camera HV
db $12 ; Item
db $04 ; Link direction
;-----------------------------
db $35 ; Entrance
db $CF ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pokeys 2", "lowleg", "trock", "pokeys_2")
dw $0014 ; Screen ID
dw $0878, $03C4 ; Link Coords
dw $0800, $0310 ; Camera HV
db $12 ; Item
db $02 ; Link direction
;-----------------------------
db $35 ; Entrance
db $EF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFA6, $0040) ; Room $13 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Crystaroller", "lowleg", "trock", "crystaroller")
dw $0014 ; Screen ID
dw $0878, $022B ; Link Coords
dw $0800, $0200 ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
db $35 ; Entrance
db $CF ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FDFC8, $0028) ; Room $24 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Dark Maze", "lowleg", "trock", "dark_maze")
dw $0004 ; Screen ID
dw $0878, $0025 ; Link Coords
dw $0800, $0000 ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
db $35 ; Entrance
db $0F ; Room layout / Floor
db $40 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Laser Skip", "lowleg", "trock", "laser_skip")
dw $00C5 ; Screen ID
dw $0A78, $19DE ; Link Coords
dw $0A00, $1910 ; Camera HV
db $12 ; Item
db $02 ; Link direction
;-----------------------------
db $35 ; Entrance
db $6E ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0040 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Switch Room", "lowleg", "trock", "switch_room")
dw $00C5 ; Screen ID
dw $0A18, $1978 ; Link Coords
dw $0A00, $190B ; Camera HV
db $12 ; Item
db $04 ; Link direction
;-----------------------------
db $35 ; Entrance
db $6E ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0040 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE12A, $0010) ; Room $D5 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Trinexx", "lowleg", "trock", "trinexx")
dw $00B4 ; Screen ID
dw $0878, $161D ; Link Coords
dw $0800, $1600 ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
db $35 ; Entrance
db $CD ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; GANON'S TOWER
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_gtower:
%menu_header("Ganon's Tower", 21)
;---------------------------------------------------------------------------------------------------
%preset_OW("Outside Turtle Rock", "lowleg", "gtower", "outside_trock")
dw $0047 ; Screen ID
dw $0F08, $013E ; Link Coords
dw $0E96, $00E0 ; Camera HV
db $0E ; Item
db $02 ; Link direction
;-----------------------------
dw $0F13, $014D ; Scroll X,Y
dw $0712 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $FFFA ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Entrance", "lowleg", "gtower", "entrance")
dw $0043 ; Screen ID
dw $08F8, $003A ; Link Coords
dw $087A, $0000 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
dw $08FF, $006F ; Scroll X,Y
dw $0050 ; Tilemap position
;dw $0000 ; Scroll mod Y
;dw $0006 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spike Skip", "lowleg", "gtower", "spike_skip")
dw $008B ; Screen ID
dw $1715, $1078 ; Link Coords
dw $1700, $100C ; Camera HV
db $04 ; Item
db $04 ; Link direction
;-----------------------------
db $37 ; Entrance
db $10 ; Room layout / Floor
db $82 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Pre Firesnakes Room", "lowleg", "gtower", "pre_firesnakes_room")
dw $009B ; Screen ID
dw $16D4, $1278 ; Link Coords
dw $1600, $120B ; Camera HV
db $12 ; Item
db $06 ; Link direction
;-----------------------------
db $37 ; Entrance
db $00 ; Room layout / Floor
db $42 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F()
%write8($7F23DC, $00) ; Bastard door
%write8($7F23E3, $00)
%write8($7F249C, $00)
%write8($7F24A3, $00)
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Bombable Floor", "lowleg", "gtower", "bombable_floor")
dw $009C ; Screen ID
dw $1978, $1224 ; Link Coords
dw $1900, $1200 ; Camera HV
db $01 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $D0 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0002 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Ice Armos", "lowleg", "gtower", "ice_armos")
dw $001C ; Screen ID
dw $199F, $03A8 ; Link Coords
dw $1900, $0310 ; Camera HV
db $05 ; Item
db $02 ; Link direction
;-----------------------------
db $37 ; Entrance
db $3F ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Floor 3", "lowleg", "gtower", "floor_3")
dw $000C ; Screen ID
dw $18F8, $0026 ; Link Coords
dw $1880, $0000 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $C1 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mimics 1", "lowleg", "gtower", "mimics1")
dw $006B ; Screen ID
dw $1678, $0CD8 ; Link Coords
dw $1600, $0C10 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
db $37 ; Entrance
db $82 ; Room layout / Floor
db $C1 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Mimics 2", "lowleg", "gtower", "mimics2")
dw $006B ; Screen ID
dw $16D8, $0D78 ; Link Coords
dw $1600, $0D0B ; Camera HV
db $03 ; Item
db $06 ; Link direction
;-----------------------------
db $37 ; Entrance
db $22 ; Room layout / Floor
db $C2 ; Door / Peg state / Layer
dw $0240 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Spike Room", "lowleg", "gtower", "spike_room")
dw $006B ; Screen ID
dw $1778, $0C1C ; Link Coords
dw $1700, $0C00 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $92 ; Room layout / Floor
db $41 ; Door / Peg state / Layer
dw $2640 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Gauntlet 1", "lowleg", "gtower", "gauntlet")
dw $005C ; Screen ID
dw $1978, $0A23 ; Link Coords
dw $1900, $0A00 ; Camera HV
db $03 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $92 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Gauntlet 3", "lowleg", "gtower", "gauntlet3")
dw $005D ; Screen ID
dw $1A78, $0AE0 ; Link Coords
dw $1A00, $0A10 ; Camera HV
db $03 ; Item
db $02 ; Link direction
;-----------------------------
db $37 ; Entrance
db $03 ; Room layout / Floor
db $81 ; Door / Peg state / Layer
dw $00FD ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Lanmola 2", "lowleg", "gtower", "lanmola2")
dw $006C ; Screen ID
dw $19D5, $0D78 ; Link Coords
dw $1900, $0D0B ; Camera HV
db $05 ; Item
db $04 ; Link direction
;-----------------------------
db $37 ; Entrance
db $33 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE03A, $0EFD) ; Room $5D sprite deaths
%write16($7FE05A, $00C9) ; Room $6D sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Wizzrobes 1", "lowleg", "gtower", "wizz1")
dw $006C ; Screen ID
dw $1878, $0C26 ; Link Coords
dw $1800, $0C00 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $03 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Wizzrobes 2", "lowleg", "gtower", "wizz2")
dw $00A5 ; Screen ID
dw $0B78, $1524 ; Link Coords
dw $0B00, $1500 ; Camera HV
db $12 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $B4 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $008C ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Torches 1", "lowleg", "gtower", "torches1")
dw $0095 ; Screen ID
dw $0BD3, $1278 ; Link Coords
dw $0B00, $120B ; Camera HV
db $09 ; Item
db $06 ; Link direction
;-----------------------------
db $37 ; Entrance
db $54 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_7F_16()
%write16($7FE0CA, $00EF) ; Room $A5 sprite deaths
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Torches 2", "lowleg", "gtower", "torches2")
dw $0096 ; Screen ID
dw $0D78, $13A2 ; Link Coords
dw $0D00, $1310 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $34 ; Room layout / Floor
db $00 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Helma Key", "lowleg", "gtower", "helma_key")
dw $003D ; Screen ID
dw $1B78, $0718 ; Link Coords
dw $1B00, $0700 ; Camera HV
db $05 ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $35 ; Room layout / Floor
db $81 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write8_enable()
%write8($7E045A, $04) ; torches
%write8($7E04F0, $AF)
%write8($7E04F1, $B7)
%write8($7E04F2, $98)
%write8($7E04F3, $82)
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Bombable Wall", "lowleg", "gtower", "bombable_wall")
dw $003D ; Screen ID
dw $1B16, $0678 ; Link Coords
dw $1B00, $060B ; Camera HV
db $01 ; Item
db $04 ; Link direction
;-----------------------------
db $37 ; Entrance
db $15 ; Room layout / Floor
db $02 ; Door / Peg state / Layer
dw $000C ; Dead sprites
;-----------------------------
%write8_enable()
%write8($7E045A, $04) ; torches
%write8($7E04F0, $98)
%write8($7E04F1, $A0)
%write8($7E04F2, $7A)
%write8($7E04F3, $64)
%write_7F()
%write8($7F23DC, $00) ; Bastard door
%write8($7F23E3, $00)
%write8($7F249C, $00)
%write8($7F24A3, $00)
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Moldorm 2", "lowleg", "gtower", "moldorm_2")
dw $003D ; Screen ID
dw $1A78, $07D0 ; Link Coords
dw $1A00, $0710 ; Camera HV
db $05 ; Item
db $02 ; Link direction
;-----------------------------
db $37 ; Entrance
db $25 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_UW("Agahnim 2", "lowleg", "gtower", "agahnim_2")
dw $001D ; Screen ID
dw $1A78, $0226 ; Link Coords
dw $1A00, $0200 ; Camera HV
db $0E ; Item
db $00 ; Link direction
;-----------------------------
db $37 ; Entrance
db $86 ; Room layout / Floor
db $01 ; Door / Peg state / Layer
dw $0000 ; Dead sprites
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; GANON
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_ganon:
%menu_header("Ganon", 2)
;---------------------------------------------------------------------------------------------------
%preset_OW("Ganon", "lowleg", "ganon", "pyramid")
dw $005B ; Screen ID
dw $07F0, $0668 ; Link Coords
dw $0778, $060A ; Camera HV
db $0E ; Item
db $02 ; Link direction
;-----------------------------
dw $07F7, $0677 ; Scroll X,Y
dw $002E ; Tilemap position
;dw $FFF6 ; Scroll mod Y
;dw $FFF8 ; Scroll mod X
;-----------------------------
%write_end()
;---------------------------------------------------------------------------------------------------
%preset_OW("Ganon (Full Magic)", "lowleg", "ganon", "pyramid_magic")
dw $005B ; Screen ID
dw $07F0, $0669 ; Link Coords
dw $0778, $060B ; Camera HV
db $0E ; Item
db $02 ; Link direction
;-----------------------------
dw $07F7, $0678 ; Scroll X,Y
dw $002E ; Tilemap position
;dw $FFF5 ; Scroll mod Y
;dw $FFF8 ; Scroll mod X
;-----------------------------
%write_end()
;===================================================================================================
;---------------------------------------------------------------------------------------------------
; BOSSES
;---------------------------------------------------------------------------------------------------
;===================================================================================================
presetmenu_lowleg_boss:
%menu_header("Bosses", 14)
%existing_preset("lowleg", "eastern", "armos")
%existing_preset("lowleg", "desert", "lanmolas")
%existing_preset("lowleg", "hera", "moldorm")
%existing_preset("lowleg", "aga", "agahnim")
%existing_preset("lowleg", "pod", "helma")
%existing_preset("lowleg", "thieves", "blind")
%existing_preset("lowleg", "skull", "mothula")
%existing_preset("lowleg", "ice", "kholdstare")
%existing_preset("lowleg", "swamp", "arrghus")
%existing_preset("lowleg", "mire", "vitty")
%existing_preset("lowleg", "trock", "trinexx")
%existing_preset("lowleg", "gtower", "agahnim_2")
%existing_preset("lowleg", "ganon", "pyramid")
%existing_preset("lowleg", "ganon", "pyramid_magic")
;===================================================================================================
presetpersistent_lowleg:
;===================================================================================================
presetpersistent_lowleg_escape:
;-----------------------------
.bed
%write_sq()
..end
;-----------------------------
.courtyard
..end
;-----------------------------
.entrance
..end
;-----------------------------
.1st_keyguard
..end
;-----------------------------
.stealth_room
..end
;-----------------------------
.2nd_keyguard
%write8($7E0FC7, $01) ; Prize pack index
..end
;-----------------------------
.ball_n_chains
..end
;-----------------------------
.backtracking
..end
;-----------------------------
.keyguard_revisited
..end
;-----------------------------
.throne_room
..end
;-----------------------------
.snake_avoidance_room
..end
;-----------------------------
.water_rooms
..end
;-----------------------------
.keyrat
..end
;-----------------------------
.into_sanctuary
..end
;===================================================================================================
presetpersistent_lowleg_eastern:
;-----------------------------
.before_cutscene
%write8($7E0FC8, $02) ; Prize pack index
..end
;-----------------------------
.after_cutscene
..end
;-----------------------------
.octorok
..end
;-----------------------------
.outside_palace
..end
;-----------------------------
.entrance
%write8($7E0FC8, $03) ; Prize pack index
..end
;-----------------------------
.stalfos_room
..end
;-----------------------------
.big_chest_room_1
%write8($7E0FCC, $01) ; Prize pack index
..end
;-----------------------------
.dark_key_room
..end
;-----------------------------
.big_key_dmg_boost
%write8($7E0FC8, $05) ; Prize pack index
..end
;-----------------------------
.big_chest_room_2
%write8($7E0CFB, $1D) ; Rupee pull kills
%write8($7E0CFC, $04) ; Rupee pull hits
..end
;-----------------------------
.gwg
..end
;-----------------------------
.pot_room
%write8($7E0FC8, $00) ; Prize pack index
..end
;-----------------------------
.zeldagamer_room
..end
;-----------------------------
.double_reddies
..end
;-----------------------------
.armos
%write8($7E0FC8, $02) ; Prize pack index
..end
;===================================================================================================
presetpersistent_lowleg_desert:
;-----------------------------
.outside_eastern_palace
..end
;-----------------------------
.ep_spinspeed
..end
;-----------------------------
.bridge_screen
..end
;-----------------------------
.unholy_spinspeed
..end
;-----------------------------
.water_dash
..end
;-----------------------------
.outside_desert_palace
..end
;-----------------------------
.desert_entrance
..end
;-----------------------------
.keybonk
..end
;-----------------------------
.pre_cannonball_room
..end
;-----------------------------
.pot_room
%write8($7E0FC8, $03) ; Prize pack index
..end
;-----------------------------
.desert2_spinspeed
..end
;-----------------------------
.popo_genocide_room
..end
;-----------------------------
.torches
%write8($7E0FC8, $04) ; Prize pack index
..end
;-----------------------------
.lanmolas
..end
;===================================================================================================
presetpersistent_lowleg_hera:
;-----------------------------
.outside_desert_palace
..end
;-----------------------------
.fake_flippers
..end
;-----------------------------
.dm
%write8($7E0FC9, $01) ; Prize pack index
..end
;-----------------------------
.after_mirror
..end
;-----------------------------
.quickhop
%write_mirror($1C, $08, $38, $01)
..end
;-----------------------------
.entrance
..end
;-----------------------------
.tile_room
..end
;-----------------------------
.torches
..end
;-----------------------------
.beetles
..end
;-----------------------------
.petting_zoo
%write8($7E0FCC, $02) ; Prize pack index
..end
;-----------------------------
.bumper_skip
..end
;-----------------------------
.moldorm
%write8($7E0FC8, $05) ; Prize pack index
..end
;===================================================================================================
presetpersistent_lowleg_aga:
;-----------------------------
.outside_hera
..end
;-----------------------------
.first_rupee_tree
%write8($7E0CFB, $04) ; Rupee pull kills
%write8($7E0CFC, $01) ; Rupee pull hits
..end
;-----------------------------
.lost_woods
%write8($7E0CFB, $01) ; Rupee pull kills
%write8($7E0CFC, $00) ; Rupee pull hits
..end
;-----------------------------
.after_grove
%write8($7E0CFB, $03) ; Rupee pull kills
%write8($7E0CFC, $00) ; Rupee pull hits
..end
;-----------------------------
.after_lost_woods
%write8($7E0CFB, $01) ; Rupee pull kills
%write8($7E0CFC, $00) ; Rupee pull hits
..end
;-----------------------------
.castle_screen
%write8($7E0CFB, $03) ; Rupee pull kills
%write8($7E0CFC, $00) ; Rupee pull hits
..end
;-----------------------------
.entrance
..end
;-----------------------------
.prize_pack_guards
%write8($7E0FC8, $07) ; Prize pack index
..end
;-----------------------------
.dark_room_of_despair
..end
;-----------------------------
.dark_room_of_melancholy
..end
;-----------------------------
.spear_guards
..end
;-----------------------------
.circle_of_pots
%write8($7E0FC7, $02) ; Prize pack index
..end
;-----------------------------
.catwalk
..end
;-----------------------------
.agahnim
..end
;===================================================================================================
presetpersistent_lowleg_pod:
;-----------------------------
.pyramid
..end
;-----------------------------
.pod_overworld
..end
;-----------------------------
.entrance
..end
;-----------------------------
.main_hub_small_key
..end
;-----------------------------
.main_hub_bk
..end
;-----------------------------
.main_hub_hammeryump
..end
;-----------------------------
.hammeryump
..end
;-----------------------------
.before_sexy_statue
%write8($7E0FCD, $01) ; Prize pack index
..end
;-----------------------------
.sexy_statue_room
..end
;-----------------------------
.mimics
..end
;-----------------------------
.statue
%write8($7E0FCB, $02) ; Prize pack index
..end
;-----------------------------
.basement
..end
;-----------------------------
.turtle_room
..end
;-----------------------------
.helma
%write8($7E0FC8, $01) ; Prize pack index
..end
;===================================================================================================
presetpersistent_lowleg_thieves:
;-----------------------------
.outside_pod
..end
;-----------------------------
.ow_hammerdash
..end
;-----------------------------
.grove
..end
;-----------------------------
.usain_bolt
%write_mirror($9D, $04, $9C, $0A)
..end
;-----------------------------
.after_activating_flute
..end
;-----------------------------
.darkworld
..end
;-----------------------------
.entrance
..end
;-----------------------------
.after_big_key
..end
;-----------------------------
.blind_hallway
..end
;-----------------------------
.conveyor_gibos
..end
;-----------------------------
.hellway
..end
;-----------------------------
.bombable_floor
..end
;-----------------------------
.backtracking_1
..end
;-----------------------------
.basement
..end
;-----------------------------
.prison
..end
;-----------------------------
.after_mitts
..end
;-----------------------------
.pot_hammerdash
..end
;-----------------------------
.blind
..end
;===================================================================================================
presetpersistent_lowleg_skull:
;-----------------------------
.outside_thieves
..end
;-----------------------------
.cursed_dwarf
..end
;-----------------------------
.getting_tempered
..end
;-----------------------------
.fence_dash
..end
;-----------------------------
.dash_to_sw
..end
;-----------------------------
.mummy_room
..end
;-----------------------------
.bomb_jump
%write8($7E0FCC, $04) ; Prize pack index
..end
;-----------------------------
.key_pot
..end
;-----------------------------
.skull_entrance
..end
;-----------------------------
.mummy_hellway
..end
;-----------------------------
.mummy_key
..end
;-----------------------------
.mothula
..end
;===================================================================================================
presetpersistent_lowleg_ice:
;-----------------------------
.outside_skull
..end
;-----------------------------
.bridge_warp
%write8($7E02A2, $00) ; slot 4 altitude
%write_mirror($98, $00, $CB, $00)
..end
;-----------------------------
.lottery
%write8($7E0FC8, $02) ; Prize pack index
..end
;-----------------------------
.medallion
..end
;-----------------------------
.zoras_domain
%write_mirror($9D, $0E, $A6, $02)
..end
;-----------------------------
.tiny_warp
..end
;-----------------------------
.ice_entrance
..end
;-----------------------------
.ice2
..end
;-----------------------------
.penguin_switch_room
%write8($7E0FCC, $05) ; Prize pack index
..end
;-----------------------------
.bombable_floor
%write8($7E0FC9, $02) ; Prize pack index
..end
;-----------------------------
.conveyor_room
%write8($7E0FCA, $02) ; Prize pack index
..end
;-----------------------------
.ipbj
..end
;-----------------------------
.penguin_room
..end
;-----------------------------
.lonely_firebar
%write8($7E0FC9, $06) ; Prize pack index
..end
;-----------------------------
.last_two_screens
..end
;-----------------------------
.kholdstare
..end
;===================================================================================================
presetpersistent_lowleg_swamp:
;-----------------------------
.outside_ice
%write8($7E02A2, $A8) ; slot 4 altitude
..end
;-----------------------------
.links_house
%write_mirror($B8, $0C, $CB, $0D)
..end
;-----------------------------
.swamp_overworld
..end
;-----------------------------
.dam
%write_mirror($7C, $07, $07, $0F)
..end
;-----------------------------
.entrance
..end
;-----------------------------
.first_key_pot
..end
;-----------------------------
.hallway_key_1
..end
;-----------------------------
.water_lever_1
..end
;-----------------------------
.main_hub
..end
;-----------------------------
.water_lever_2
..end
;-----------------------------
.sociable_firebar
..end
;-----------------------------
.backtracking
..end
;-----------------------------
.hookshot
%write8($7E0FC8, $03) ; Prize pack index
..end
;-----------------------------
.hookdash
..end
;-----------------------------
.water_lever_3
..end
;-----------------------------
.restock
..end
;-----------------------------
.phelps_way
..end
;-----------------------------
.arrghus
..end
;===================================================================================================
presetpersistent_lowleg_mire:
;-----------------------------
.outside_swamp
%write8($7E02A2, $00) ; slot 4 altitude
..end
;-----------------------------
.dm
%write_mirror($7C, $07, $FD, $0E)
..end
;-----------------------------
.free_flutedash
%write8($7E02A2, $0F) ; slot 4 altitude
%write_mirror($1C, $08, $3D, $01)
..end
;-----------------------------
.darkworld_warp
%write8($7E02A2, $8B) ; slot 4 altitude
..end
;-----------------------------
.entrance
..end
;-----------------------------
.mire2
..end
;-----------------------------
.main_hub
%write8($7E0FC8, $04) ; Prize pack index
..end
;-----------------------------
.beat_the_fireball
..end
;-----------------------------
.bari_key
..end
;-----------------------------
.sluggulas
..end
;-----------------------------
.torches
%write8($7E0FCA, $03) ; Prize pack index
..end
;-----------------------------
.spark_gamble
..end
;-----------------------------
.big_chest_room
..end
;-----------------------------
.spike_key
..end
;-----------------------------
.wizzrobe
..end
;-----------------------------
.basement
..end
;-----------------------------
.spooky_action_1
..end
;-----------------------------
.spooky_action_2
..end
;-----------------------------
.vitty
..end
;===================================================================================================
presetpersistent_lowleg_trock:
;-----------------------------
.outside_mire
..end
;-----------------------------
.icerod_overworld
%write_mirror($28, $01, $DA, $0C)
..end
;-----------------------------
.dm
..end
;-----------------------------
.squirrels
..end
;-----------------------------
.peg_puzzle
..end
;-----------------------------
.entrance
..end
;-----------------------------
.torches
%write8($7E02A2, $00) ; slot 4 altitude
%write8($7E0FCC, $06) ; Prize pack index
..end
;-----------------------------
.roller_room
..end
;-----------------------------
.pokey_0
..end
;-----------------------------
.chomps
%write8($7E0FCD, $02) ; Prize pack index
..end
;-----------------------------
.pokey_1
..end
;-----------------------------
.pokeys_2
%write8($7E0FCD, $04) ; Prize pack index
..end
;-----------------------------
.crystaroller
%write8($7E0FCD, $06) ; Prize pack index
..end
;-----------------------------
.dark_maze
..end
;-----------------------------
.laser_skip
..end
;-----------------------------
.switch_room
..end
;-----------------------------
.trinexx
..end
;===================================================================================================
presetpersistent_lowleg_gtower:
;-----------------------------
.outside_trock
..end
;-----------------------------
.entrance
..end
;-----------------------------
.spike_skip
..end
;-----------------------------
.pre_firesnakes_room
..end
;-----------------------------
.bombable_floor
..end
;-----------------------------
.ice_armos
%write8($7E02A2, $00) ; slot 4 altitude
..end
;-----------------------------
.floor_3
%write8($7E0B08, $40) ; Arc variable
%write8($7E0B09, $00) ; Arc variable
..end
;-----------------------------
.mimics1
..end
;-----------------------------
.mimics2
%write8($7E0FCB, $04) ; Prize pack index
..end
;-----------------------------
.spike_room
%write8($7E0FCB, $05) ; Prize pack index
..end
;-----------------------------
.gauntlet
..end
;-----------------------------
.gauntlet3
%write8($7E0FCC, $02) ; Prize pack index
..end
;-----------------------------
.lanmola2
%write8($7E0FCC, $04) ; Prize pack index
..end
;-----------------------------
.wizz1
..end
;-----------------------------
.wizz2
%write8($7E0FC7, $04) ; Prize pack index
..end
;-----------------------------
.torches1
%write8($7E0FC7, $06) ; Prize pack index
..end
;-----------------------------
.torches2
..end
;-----------------------------
.helma_key
..end
;-----------------------------
.bombable_wall
..end
;-----------------------------
.moldorm_2
..end
;-----------------------------
.agahnim_2
..end
;===================================================================================================
presetpersistent_lowleg_ganon:
;-----------------------------
.pyramid
%write8($7E0B08, $40) ; ganon bats
%write8($7E0B09, $00) ; ganon bats
..end
;-----------------------------
.pyramid_magic
..end
;===================================================================================================
presetSRAM_lowleg:
;-----------------------------
.escape
;-----------------------------
..bed
%write8($7EF36F, $FF) ; Keys
%writeroom($104, $0002)
...end
;-----------------------------
..courtyard
%write8($7EF3C8, $03) ; Spawn point
%write8($7EF359, $01) ; Sword
%write8($7EF3C5, $01) ; Game state
%write8($7EF35A, $01) ; Shield
%write8($7EF3C6, $11) ; Game flags A
%writeroom($055, $000F)
...end
;-----------------------------
..entrance
...end
;-----------------------------
..1st_keyguard
%write8($7EF36F, $00) ; Keys
%writeroom($050, $0005)
%writeroom($060, $0005)
%writeroom($001, $000C)
%writeroom($061, $000F)
...end
;-----------------------------
..stealth_room
%writeroom($072, $840F)
%writeroom($082, $000F)
...end
;-----------------------------
..2nd_keyguard
%writeroom($071, $0002)
%writeroom($081, $000F)
...end
;-----------------------------
..ball_n_chains
%write8($7EF341, $01) ; Boomerang
%write8($7EF341, $00) ; Boomerang
%writeroom($070, $0008)
%writeroom($071, $841B)
...end
;-----------------------------
..backtracking
%write8($7EF3C8, $02) ; Spawn point
%write8($7EF3CC, $01) ; Follower
%write8($7EF34A, $01) ; Lamp
%write16sram($7EF366, $4000) ; Big keys
%writeroom($080, $043C)
...end
;-----------------------------
..keyguard_revisited
...end
;-----------------------------
..throne_room
%writeroom($051, $000F)
...end
;-----------------------------
..snake_avoidance_room
%write8($7EF3C8, $04) ; Spawn point
%writeroom($041, $000F)
...end
;-----------------------------
..water_rooms
%writeroom($032, $801F)
%writeroom($042, $000C)
...end
;-----------------------------
..keyrat
%writeroom($022, $8003)
%writeroom($021, $0003)
...end
;-----------------------------
..into_sanctuary
%writeroom($011, $2005)
%writeroom($021, $840F)
...end
;-----------------------------
.eastern
;-----------------------------
..before_cutscene
%writeroom($002, $000F)
...end
;-----------------------------
..after_cutscene
%write8($7EF29B, $20) ; Overworld 1B overlay
%write8($7EF3C7, $01) ; Map marker
%write8($7EF3C8, $01) ; Spawn point
%write8($7EF3CC, $00) ; Follower
%write8($7EF3C5, $02) ; Game state
%write8($7EF3C6, $15) ; Game flags A
%writeroom($012, $000F)
...end
;-----------------------------
..octorok
%write16sram($7EF360, $D2) ; Rupees
...end
;-----------------------------
..outside_palace
...end
;-----------------------------
..entrance
...end
;-----------------------------
..stalfos_room
%write8($7EF36F, $00) ; Keys
%writeroom($0A8, $0005)
%writeroom($0A9, $000F)
%writeroom($0B9, $000F)
%writeroom($0C9, $000F)
...end
;-----------------------------
..big_chest_room_1
%write8($7EF36E, $10) ; Magic
%writeroom($0A8, $000F)
...end
;-----------------------------
..dark_key_room
%writeroom($0AA, $000A)
%writeroom($0BA, $0008)
...end
;-----------------------------
..big_key_dmg_boost
%write16sram($7EF360, $E7) ; Rupees
%writeroom($0BA, $840C)
%writeroom($0B9, $800F)
...end
;-----------------------------
..big_chest_room_2
%write8($7EF36D, $0C) ; Health
%write16sram($7EF366, $6000) ; Big keys
%writeroom($0A8, $200F)
%writeroom($0B8, $8015)
...end
;-----------------------------
..gwg
%write8($7EF377, $0A) ; Arrows
%write8($7EF340, $02) ; Bow
%writeroom($0A9, $201F)
...end
;-----------------------------
..pot_room
%write8($7EF36E, $20) ; Magic
%writeroom($099, $C403)
...end
;-----------------------------
..zeldagamer_room
%write8($7EF377, $14) ; Arrows
%writeroom($0DA, $0002)
%writeroom($0D9, $0003)
...end
;-----------------------------
..double_reddies
%writeroom($0D8, $0001)
...end
;-----------------------------
..armos
%write8($7EF34F, $00) ; Bottles
%write8($7EF377, $12) ; Arrows
%writeroom($0D8, $0005)
...end
;-----------------------------
.desert
;-----------------------------
..outside_eastern_palace
%write8($7EF377, $00) ; Arrows
%write8($7EF340, $01) ; Bow
%write8($7EF36C, $20) ; Max HP
%write8($7EF374, $04) ; Pendants
%write8($7EF36D, $20) ; Health
%write8($7EF36E, $80) ; Magic
%writeroom($0C8, $0801)
...end
;-----------------------------
..ep_spinspeed
%write8($7EF36F, $FF) ; Keys
%write8($7EF3C7, $03) ; Map marker
%write8($7EF355, $01) ; Boots
%write8($7EF379, $FC) ; Ability
%writeroom($105, $0002)
...end
;-----------------------------
..bridge_screen
...end
;-----------------------------
..unholy_spinspeed
...end
;-----------------------------
..water_dash
%write8($7EF34E, $01) ; Book of Mudora
%writeroom($107, $F002)
...end
;-----------------------------
..outside_desert_palace
...end
;-----------------------------
..desert_entrance
...end
;-----------------------------
..keybonk
%write8($7EF36F, $00) ; Keys
%write8($7EF377, $05) ; Arrows
%write8($7EF340, $02) ; Bow
%writeroom($074, $0003)
%writeroom($084, $000F)
%writeroom($073, $0001)
...end
;-----------------------------
..pre_cannonball_room
%writeroom($073, $0405)
%writeroom($075, $0002)
%writeroom($085, $400A)
...end
;-----------------------------
..pot_room
%write8($7EF377, $0A) ; Arrows
%write16sram($7EF366, $7000) ; Big keys
%writeroom($075, $0017)
%writeroom($085, $400E)
...end
;-----------------------------
..desert2_spinspeed
%write8($7EF377, $14) ; Arrows
%write8($7EF354, $01) ; Gloves
%writeroom($073, $041F)
%writeroom($083, $0007)
...end
;-----------------------------
..popo_genocide_room
%write8($7EF37F, $00) ; Key for dungeon $03
%writeroom($053, $0008)
%writeroom($063, $840A)
...end
;-----------------------------
..torches
%writeroom($043, $6401)
%writeroom($053, $240F)
...end
;-----------------------------
..lanmolas
%write8($7EF377, $19) ; Arrows
%write8($7EF36E, $70) ; Magic
%writeroom($043, $E48D)
...end
;-----------------------------
.hera
;-----------------------------
..outside_desert_palace
%write8($7EF377, $0C) ; Arrows
%write8($7EF36C, $28) ; Max HP
%write8($7EF374, $06) ; Pendants
%write8($7EF36D, $28) ; Health
%write8($7EF36E, $80) ; Magic
%writeroom($033, $0802)
...end
;-----------------------------
..fake_flippers
...end
;-----------------------------
..dm
%write8($7EF36F, $FF) ; Keys
%write8($7EF377, $0B) ; Arrows
%write8($7EF3C8, $05) ; Spawn point
%write8($7EF3CC, $04) ; Follower
%writeroom($0F0, $000F)
%writeroom($0F1, $000F)
...end
;-----------------------------
..after_mirror
%write8($7EF353, $02) ; Magic Mirror
%write8($7EF3C8, $01) ; Spawn point
%write8($7EF3CC, $00) ; Follower
...end
;-----------------------------
..quickhop
...end
;-----------------------------
..entrance
...end
;-----------------------------
..tile_room
%write8($7EF36F, $00) ; Keys
%write8($7EF386, $01) ; Key for dungeon $0A
%writeroom($077, $800F)
%writeroom($087, $0402)
...end
;-----------------------------
..torches
%writeroom($087, $040E)
...end
;-----------------------------
..beetles
%write16sram($7EF366, $7020) ; Big keys
%write8($7EF36E, $70) ; Magic
%write8($7EF386, $00) ; Key for dungeon $0A
%writeroom($087, $041F)
...end
;-----------------------------
..petting_zoo
%write8($7EF343, $01) ; Bombs
%writeroom($031, $800F)
...end
;-----------------------------
..bumper_skip
%write8($7EF357, $01) ; Moon Pearl
%write8($7EF36D, $20) ; Health
%writeroom($027, $001F) ; Room $0027
...end
;-----------------------------
..moldorm
%writeroom($017, $000F)
...end
;-----------------------------
.aga
;-----------------------------
..outside_hera
%write8($7EF3C7, $04) ; Map marker
%write8($7EF36C, $30) ; Max HP
%write8($7EF374, $07) ; Pendants
%write8($7EF36D, $30) ; Health
%write8($7EF36E, $80) ; Magic
%writeroom($007, $080F)
...end
;-----------------------------
..first_rupee_tree
%write8($7EF36F, $FF) ; Keys
%writeroom($0E6, $000F)
%writeroom($0E7, $000F)
...end
;-----------------------------
..lost_woods
%write8($7EF377, $0A) ; Arrows
%write16sram($7EF360, $F8) ; Rupees
...end
;-----------------------------
..after_grove
%write8($7EF3C7, $05) ; Map marker
%write8($7EF300, $40) ; Overworld $80: Unknown (..?.....)
%write8($7EF359, $02) ; Sword
...end
;-----------------------------
..after_lost_woods
%write8($7EF3C7, $05) ; Map marker
%write8($7EF300, $40) ; Overworld $80: Unknown (..?.....)
%write16sram($7EF360, $148) ; Rupees
...end
;-----------------------------
..castle_screen
...end
;-----------------------------
..entrance
%write8($7EF29B, $60) ; Overworld $1B: Unknown (..??....)
...end
;-----------------------------
..prize_pack_guards
%write8($7EF36F, $00) ; Keys
%write8($7EF377, $08) ; Arrows
%writeroom($0E0, $000A)
...end
;-----------------------------
..dark_room_of_despair
%writeroom($0D0, $0004)
%writeroom($0E0, $201E)
...end
;-----------------------------
..dark_room_of_melancholy
%writeroom($0C0, $0001)
%writeroom($0D0, $801F)
...end
;-----------------------------
..spear_guards
%writeroom($0C0, $240F)
...end
;-----------------------------
..circle_of_pots
%write8($7EF377, $03) ; Arrows
%writeroom($0B0, $000C)
...end
;-----------------------------
..catwalk
%write8($7EF377, $07) ; Arrows
%write16sram($7EF360, $149) ; Rupees
%writeroom($040, $0001)
%writeroom($0B0, $240F)
...end
;-----------------------------
..agahnim
%writeroom($030, $840A)
%writeroom($040, $000B)
...end
;-----------------------------
.pod
;-----------------------------
..pyramid
%write8($7EF3C7, $06) ; Map marker
%write8($7EF3C5, $03) ; Game state
%write8($7EF282, $20) ; Overworld 02 overlay
%write8($7EF3CA, $40) ; LW/DW
%writeroom($020, $0802)
...end
;-----------------------------
..pod_overworld
...end
;-----------------------------
..entrance
%write8($7EF2DE, $20) ; Overworld 5E overlay
%write16sram($7EF360, $DB) ; Rupees
...end
;-----------------------------
..main_hub_small_key
%write8($7EF343, $03) ; Bombs
%write8($7EF36F, $00) ; Keys
%write8($7EF382, $01) ; Key for dungeon $06
%writeroom($04A, $200F)
%writeroom($009, $0018)
...end
;-----------------------------
..main_hub_bk
%write8($7EF343, $04) ; Bombs
%write8($7EF36F, $01) ; Keys
%writeroom($00A, $001F)
%writeroom($03A, $800F)
...end
;-----------------------------
..main_hub_hammeryump
%write8($7EF36F, $00) ; Keys
%write16sram($7EF366, $7220) ; Big keys
%write8($7EF382, $00) ; Key for dungeon $06
%writeroom($00A, $801F)
%writeroom($03A, $801F)
...end
;-----------------------------
..hammeryump
%writeroom($02A, $402F)
...end
;-----------------------------
..before_sexy_statue
%write8($7EF34B, $01) ; Hammer
%write8($7EF36F, $01) ; Keys
%write8($7EF36D, $28) ; Health
%write8($7EF382, $01) ; Key for dungeon $06
%writeroom($01A, $301A)
%writeroom($019, $802F)
...end
;-----------------------------
..sexy_statue_room
%write8($7EF377, $06) ; Arrows
...end
;-----------------------------
..mimics
%write8($7EF343, $06) ; Bombs
%write8($7EF36D, $30) ; Health
%writeroom($02B, $000A)
...end
;-----------------------------
..statue
%write8($7EF377, $07) ; Arrows
%writeroom($01B, $0002)
...end
;-----------------------------
..basement
%write8($7EF377, $06) ; Arrows
%writeroom($01B, $008E)
...end
;-----------------------------
..turtle_room
%write8($7EF36F, $00) ; Keys
%writeroom($00B, $200C)
...end
;-----------------------------
..helma
%writeroom($06A, $8005)
%writeroom($00B, $200F)
...end
;-----------------------------
.thieves
;-----------------------------
..outside_pod
%write8($7EF3C7, $07) ; Map marker
%write8($7EF36C, $38) ; Max HP
%write8($7EF36D, $38) ; Health
%write8($7EF37A, $02) ; Crystals
%write8($7EF382, $00) ; Key for dungeon $06
%writeroom($05A, $0801)
...end
;-----------------------------
..ow_hammerdash
...end
;-----------------------------
..grove
...end
;-----------------------------
..usain_bolt
%write8($7EF34C, $02) ; Flute
%write8($7EF3CA, $00) ; LW/DW
...end
;-----------------------------
..after_activating_flute
%write8($7EF298, $20) ; Overworld 18 overlay
%write8($7EF34C, $03) ; Flute
...end
;-----------------------------
..darkworld
%write8($7EF3CA, $40) ; LW/DW
...end
;-----------------------------
..entrance
%write8($7EF2D8, $20) ; Overworld 58 overlay
...end
;-----------------------------
..after_big_key
%write8($7EF36F, $00) ; Keys
%write16sram($7EF366, $7230) ; Big keys
%writeroom($0CC, $000F)
%writeroom($0DC, $000F)
%writeroom($0CB, $000F)
%writeroom($0DB, $002F)
...end
;-----------------------------
..blind_hallway
%writeroom($0CC, $800F)
...end
;-----------------------------
..conveyor_gibos
%writeroom($0BC, $C407)
...end
;-----------------------------
..hellway
%writeroom($0BB, $0001)
...end
;-----------------------------
..bombable_floor
%writeroom($064, $0003)
%writeroom($065, $0002)
%writeroom($0AB, $8402)
%writeroom($0BB, $000B)
...end
;-----------------------------
..backtracking_1
%write8($7EF343, $05) ; Bombs
%write8($7EF343, $05) ; Bombs
%writeroom($065, $0103)
...end
;-----------------------------
..basement
%write8($7EF343, $06) ; Bombs
%writeroom($0BC, $C40F)
%writeroom($0BB, $000F)
...end
;-----------------------------
..prison
%writeroom($045, $000A)
...end
;-----------------------------
..after_mitts
%write8($7EF354, $02) ; Gloves
%write8($7EF3CC, $06) ; Follower
%writeroom($044, $4017)
%writeroom($045, $00FF)
...end
;-----------------------------
..pot_hammerdash
%write8($7EF377, $0B) ; Arrows
...end
;-----------------------------
..blind
...end
;-----------------------------
.skull
;-----------------------------
..outside_thieves
%write8($7EF36C, $40) ; Max HP
%write8($7EF3CC, $00) ; Follower
%write8($7EF36D, $40) ; Health
%write8($7EF37A, $22) ; Crystals
%write8($7EF387, $00) ; Key for dungeon $0B
%writeroom($0AC, $0A01)
...end
;-----------------------------
..cursed_dwarf
%write8($7EF343, $04) ; Bombs
%write8($7EF2D8, $22) ; Overworld $58: Unknown (...?...?)
%write16sram($7EF360, $208) ; Rupees
%write8($7EF343, $06) ; Bombs
%writeroom($106, $F012)
...end
;-----------------------------
..getting_tempered
%write8($7EF3CC, $07) ; Follower
...end
;-----------------------------
..fence_dash
%write8($7EF3CC, $00) ; Follower
%write8($7EF3C9, $20) ; Game flags B
%writeroom($121, $0002)
...end
;-----------------------------
..dash_to_sw
%writeroom($11C, $0011)
...end
;-----------------------------
..mummy_room
...end
;-----------------------------
..bomb_jump
%write8($7EF377, $10) ; Arrows
%write16sram($7EF366, $72B0) ; Big keys
%writeroom($057, $001A)
...end
;-----------------------------
..key_pot
%write8($7EF343, $03) ; Bombs
%write8($7EF36F, $00) ; Keys
%write8($7EF345, $01) ; Fire Rod
%write8($7EF36D, $30) ; Health
%write8($7EF343, $04) ; Bombs
%write8($7EF343, $05) ; Bombs
%writeroom($056, $0005)
%writeroom($058, $0012)
...end
;-----------------------------
..skull_entrance
%write8($7EF2C0, $20) ; Overworld 40 overlay
%write8($7EF384, $01) ; Key for dungeon $08
%write8($7EF36E, $70) ; Magic
%writeroom($056, $0407)
...end
;-----------------------------
..mummy_hellway
%write8($7EF36F, $00) ; Keys
%writeroom($049, $2002)
%writeroom($059, $800A)
...end
;-----------------------------
..mummy_key
%write8($7EF36E, $30) ; Magic
%writeroom($049, $A00F)
...end
;-----------------------------
..mothula
%writeroom($039, $4402)
...end
;-----------------------------
.ice
;-----------------------------
..outside_skull
%write8($7EF36C, $48) ; Max HP
%write8($7EF384, $00) ; Key for dungeon $08
%write8($7EF36D, $48) ; Health
%write8($7EF36E, $80) ; Magic
%write8($7EF37A, $62) ; Crystals
%writeroom($029, $0801)
%writeroom($039, $4403)
...end
;-----------------------------
..bridge_warp
%write8($7EF3CA, $00) ; LW/DW
...end
;-----------------------------
..lottery
%write8($7EF3CA, $40) ; LW/DW
...end
;-----------------------------
..medallion
...end
;-----------------------------
..zoras_domain
%write8($7EF349, $01) ; Quake Medallion
%write8($7EF3CA, $00) ; LW/DW
...end
;-----------------------------
..tiny_warp
%write8($7EF379, $FE) ; Ability
%write8($7EF356, $01) ; Flippers
%write16sram($7EF360, $14) ; Rupees
...end
;-----------------------------
..ice_entrance
%write8($7EF3CA, $40) ; LW/DW
...end
;-----------------------------
..ice2
%write8($7EF36F, $00) ; Keys
%write8($7EF36E, $70) ; Magic
%writeroom($00E, $0001)
...end
;-----------------------------
..penguin_switch_room
%write8($7EF36E, $60) ; Magic
%writeroom($00E, $8403)
%writeroom($01E, $0003)
%writeroom($02E, $0004)
...end
;-----------------------------
..bombable_floor
%writeroom($01F, $0002)
...end
;-----------------------------
..conveyor_room
%write8($7EF343, $01) ; Bombs
%write8($7EF343, $02) ; Bombs
%write8($7EF343, $04) ; Bombs
%writeroom($01E, $0007)
%writeroom($03E, $0004)
...end
;-----------------------------
..ipbj
%write8($7EF36D, $40) ; Health
%writeroom($03E, $4407)
...end
;-----------------------------
..penguin_room
%write8($7EF343, $00) ; Bombs
%write8($7EF343, $01) ; Bombs
%write8($7EF343, $03) ; Bombs
%writeroom($04E, $400C)
...end
;-----------------------------
..lonely_firebar
%write8($7EF36D, $38) ; Health
%writeroom($05E, $0001)
%writeroom($06E, $0004)
...end
;-----------------------------
..last_two_screens
%writeroom($05E, $0003)
%writeroom($07E, $0002)
%writeroom($09E, $0003)
...end
;-----------------------------
..kholdstare
%write8($7EF36E, $80) ; Magic
%writeroom($0BE, $0001)
%writeroom($0CE, $0004)
...end
;-----------------------------
.swamp
;-----------------------------
..outside_ice
%write8($7EF36C, $50) ; Max HP
%write8($7EF36D, $50) ; Health
%write8($7EF385, $00) ; Key for dungeon $09
%write8($7EF37A, $66) ; Crystals
%writeroom($0DE, $0804)
...end
;-----------------------------
..links_house
%write8($7EF3CA, $00) ; LW/DW
...end
;-----------------------------
..swamp_overworld
%write8($7EF3CA, $40) ; LW/DW
...end
;-----------------------------
..dam
%write8($7EF3CA, $00) ; LW/DW
...end
;-----------------------------
..entrance
%write8($7EF2BB, $20) ; Overworld 3B overlay
%write8($7EF2FB, $20) ; Overworld 7B overlay
%write8($7EF3CA, $40) ; LW/DW
%writeroom($10B, $008F)
%writeroom($028, $0100)
...end
;-----------------------------
..first_key_pot
%write8($7EF36F, $00) ; Keys
%writeroom($028, $811F)
...end
;-----------------------------
..hallway_key_1
%write8($7EF343, $01) ; Bombs
%writeroom($038, $440A)
%writeroom($037, $1003)
...end
;-----------------------------
..water_lever_1
%writeroom($037, $340F)
...end
;-----------------------------
..main_hub
%writeroom($037, $348F)
...end
;-----------------------------
..water_lever_2
%writeroom($036, $200F)
%writeroom($035, $040F)
...end
;-----------------------------
..sociable_firebar
%writeroom($034, $000F)
%writeroom($035, $848F)
...end
;-----------------------------
..backtracking
%write16sram($7EF366, $76B0) ; Big keys
%writeroom($054, $000F)
%writeroom($035, $849F)
...end
;-----------------------------
..hookshot
...end
;-----------------------------
..hookdash
%write8($7EF342, $01) ; Hookshot
%writeroom($036, $641F)
...end
;-----------------------------
..water_lever_3
%write8($7EF377, $15) ; Arrows
%writeroom($026, $8007)
...end
;-----------------------------
..restock
%writeroom($066, $0003)
%writeroom($076, $008E)
...end
;-----------------------------
..phelps_way
%write8($7EF343, $02) ; Bombs
%writeroom($016, $000C)
%writeroom($066, $000F)
...end
;-----------------------------
..arrghus
%write8($7EF36D, $48) ; Health
%writeroom($016, $440F)
...end
;-----------------------------
.mire
;-----------------------------
..outside_swamp
%write8($7EF36C, $58) ; Max HP
%write8($7EF36D, $58) ; Health
%write8($7EF381, $00) ; Key for dungeon $05
%write8($7EF37A, $76) ; Crystals
%writeroom($006, $0802)
...end
;-----------------------------
..dm
%write8($7EF2BB, $00) ; Overworld $3B
%write8($7EF2FB, $00) ; Overworld $7B
%write8($7EF3CA, $00) ; LW/DW
%writeroom($10B, $000F)
%writeroom($028, $801F)
...end
;-----------------------------
..free_flutedash
%write8($7EF348, $01) ; Ether Medallion
...end
;-----------------------------
..darkworld_warp
%write8($7EF346, $01) ; Ice Rod
...end
;-----------------------------
..entrance
%write8($7EF2F0, $20) ; Overworld 70 overlay
%write8($7EF36E, $60) ; Magic
%write8($7EF3CA, $40) ; LW/DW
...end
;-----------------------------
..mire2
%write8($7EF36F, $00) ; Keys
%writeroom($098, $0003)
...end
;-----------------------------
..main_hub
%write8($7EF36E, $50) ; Magic
%writeroom($0D2, $000F)
...end
;-----------------------------
..beat_the_fireball
%write8($7EF36F, $01) ; Keys
%writeroom($0B2, $0001)
%writeroom($0C2, $000F)
%writeroom($0B3, $0402)
...end
;-----------------------------
..bari_key
%write8($7EF36F, $00) ; Keys
%writeroom($0C2, $400F)
...end
;-----------------------------
..sluggulas
%writeroom($0C1, $C403)
...end
;-----------------------------
..torches
%write8($7EF36E, $80) ; Magic
%writeroom($0D1, $0008)
...end
;-----------------------------
..spark_gamble
%write16sram($7EF366, $77B0) ; Big keys
%write8($7EF36E, $40) ; Magic
%writeroom($097, $010F)
%writeroom($0B1, $0007)
%writeroom($0C1, $C407)
%writeroom($0D1, $001B)
...end
;-----------------------------
..big_chest_room
%write8($7EF36D, $50) ; Health
%writeroom($0C3, $000A)
...end
;-----------------------------
..spike_key
%write8($7EF350, $01) ; Cane of Somaria
%writeroom($0C3, $001F)
...end
;-----------------------------
..wizzrobe
%write8($7EF36D, $38) ; Health
%writeroom($0B3, $841A)
...end
;-----------------------------
..basement
%write8($7EF36D, $40) ; Health
%writeroom($0A2, $800F)
%writeroom($0B2, $800D)
...end
;-----------------------------
..spooky_action_1
%write8($7EF36E, $38) ; Magic
%writeroom($093, $000E)
...end
;-----------------------------
..spooky_action_2
%write8($7EF36E, $30) ; Magic
%writeroom($092, $0005)
...end
;-----------------------------
..vitty
%write8($7EF343, $01) ; Bombs
%write8($7EF377, $14) ; Arrows
%write8($7EF36E, $40) ; Magic
%writeroom($092, $400F)
%writeroom($0A0, $800F)
%writeroom($091, $0005)
...end
;-----------------------------
.trock
;-----------------------------
..outside_mire
%write8($7EF377, $0C) ; Arrows
%write8($7EF383, $00) ; Key for dungeon $07
%write8($7EF36C, $60) ; Max HP
%write8($7EF36D, $60) ; Health
%write8($7EF36E, $80) ; Magic
%write8($7EF37A, $77) ; Crystals
%writeroom($090, $0802)
...end
;-----------------------------
..icerod_overworld
%write8($7EF3CA, $00) ; LW/DW
...end
;-----------------------------
..dm
%write8($7EF2B7, $02) ; Overworld 37 bomb wall
%write8($7EF343, $00) ; Bombs
%write8($7EF346, $01) ; Ice Rod
%writeroom($120, $001A)
...end
;-----------------------------
..squirrels
%write8($7EF36F, $FF) ; Keys
%writeroom($0DF, $0003)
%writeroom($0EF, $0003)
...end
;-----------------------------
..peg_puzzle
...end
;-----------------------------
..entrance
%write8($7EF287, $20) ; Overworld 07 overlay
%write8($7EF2C7, $20) ; Overworld 47 overlay
%write8($7EF36E, $60) ; Magic
%write8($7EF3CA, $40) ; LW/DW
...end
;-----------------------------
..torches
%write8($7EF343, $01) ; Bombs
%write8($7EF36F, $00) ; Keys
%write8($7EF36E, $70) ; Magic
%writeroom($0C6, $000F)
%writeroom($0D6, $8005)
...end
;-----------------------------
..roller_room
%write8($7EF36D, $58) ; Health
%write8($7EF36E, $38) ; Magic
%writeroom($0C7, $000F)
...end
;-----------------------------
..pokey_0
%write8($7EF36D, $40) ; Health
%write8($7EF36E, $30) ; Magic
%writeroom($0C6, $800F)
%writeroom($0B7, $002A)
...end
;-----------------------------
..chomps
%write8($7EF36D, $60) ; Health
%writeroom($0B6, $3402)
...end
;-----------------------------
..pokey_1
%write8($7EF377, $11) ; Arrows
%write8($7EF36E, $28) ; Magic
%writeroom($014, $000F)
%writeroom($0B6, $B41A)
%writeroom($015, $000F)
...end
;-----------------------------
..pokeys_2
%write16sram($7EF366, $77B8) ; Big keys
%write8($7EF36E, $78) ; Magic
%writeroom($014, $401F)
%writeroom($013, $8405)
...end
;-----------------------------
..crystaroller
%writeroom($014, $C01F)
%writeroom($024, $800C)
...end
;-----------------------------
..dark_maze
%writeroom($004, $C01A)
...end
;-----------------------------
..laser_skip
%write8($7EF36D, $58) ; Health
%write8($7EF36E, $70) ; Magic
%writeroom($0B5, $000F)
%writeroom($0C5, $000A)
...end
;-----------------------------
..switch_room
%writeroom($0C5, $800A)
%writeroom($0D5, $008A)
...end
;-----------------------------
..trinexx
%write8($7EF36E, $60) ; Magic
%writeroom($0B4, $800F)
%writeroom($0C4, $800F)
...end
;-----------------------------
.gtower
;-----------------------------
..outside_trock
%write8($7EF3C7, $08) ; Map marker
%write8($7EF36C, $68) ; Max HP
%write8($7EF36D, $68) ; Health
%write8($7EF36E, $80) ; Magic
%write8($7EF37A, $7F) ; Crystals
%writeroom($0A4, $0802)
...end
;-----------------------------
..entrance
%write8($7EF2C3, $20) ; Overworld 43 overlay
...end
;-----------------------------
..spike_skip
%write8($7EF36F, $01) ; Keys
%writeroom($00C, $000F)
%writeroom($08C, $0008)
%writeroom($08B, $0404)
...end
;-----------------------------
..pre_firesnakes_room
%writeroom($08B, $040E)
%writeroom($09B, $8408)
...end
;-----------------------------
..bombable_floor
%write8($7EF377, $16) ; Arrows
%write8($7EF36D, $60) ; Health
%writeroom($09C, $000F)
%writeroom($07D, $201E)
%writeroom($09B, $840F)
...end
;-----------------------------
..ice_armos
%writeroom($01C, $0001)
%writeroom($08C, $0009)
...end
;-----------------------------
..floor_3
%write8($7EF377, $0E) ; Arrows
%write8($7EF389, $01) ; Key for dungeon $0D
%write16sram($7EF366, $77BC) ; Big keys
%writeroom($01C, $0035)
...end
;-----------------------------
..mimics1
%write8($7EF377, $0D) ; Arrows
%write8($7EF36D, $48) ; Health
%writeroom($06B, $000C)
...end
;-----------------------------
..mimics2
%write8($7EF377, $0E) ; Arrows
%writeroom($06B, $000E)
...end
;-----------------------------
..spike_room
%write8($7EF377, $0A) ; Arrows
%writeroom($06B, $800F)
...end
;-----------------------------
..gauntlet
%writeroom($05C, $000C)
%writeroom($05B, $8005)
...end
;-----------------------------
..gauntlet3
%write8($7EF377, $08) ; Arrows
%writeroom($05D, $000C)
...end
;-----------------------------
..lanmola2
%write8($7EF36D, $40) ; Health
%write8($7EF36E, $70) ; Magic
%writeroom($06C, $0001)
%writeroom($05D, $000E)
%writeroom($06D, $000A)
...end
;-----------------------------
..wizz1
%write8($7EF36E, $20) ; Magic
%writeroom($06C, $000B)
...end
;-----------------------------
..wizz2
%write8($7EF36D, $48) ; Health
%write8($7EF36E, $18) ; Magic
%writeroom($0A5, $000B)
...end
;-----------------------------
..torches1
%write8($7EF36E, $10) ; Magic
%writeroom($095, $0005)
%writeroom($0A5, $000F)
...end
;-----------------------------
..torches2
%write8($7EF36E, $80) ; Magic
%writeroom($096, $000B)
...end
;-----------------------------
..helma_key
%write8($7EF36E, $40) ; Magic
%writeroom($03D, $0001)
...end
;-----------------------------
..bombable_wall
%write8($7EF36D, $40) ; Health
%writeroom($03D, $4405)
...end
;-----------------------------
..moldorm_2
%write8($7EF343, $00) ; Bombs
%write8($7EF36F, $00) ; Keys
%write8($7EF36D, $38) ; Health
%writeroom($03D, $740F)
...end
;-----------------------------
..agahnim_2
%writeroom($04C, $0005)
%writeroom($01D, $800C)
%writeroom($04D, $800F)
...end
;-----------------------------
.ganon
;-----------------------------
..pyramid
%write8($7EF2DB, $20) ; Overworld 5B overlay
%write8($7EF389, $00) ; Key for dungeon $0D
%writeroom($00D, $0802)
...end
;-----------------------------
..pyramid_magic
%write8($7EF36E, $80) ; Magic
...end
;===================================================================================================
presetend_lowleg:
print "lowleg size: $", hex(presetend_lowleg-presetheader_lowleg) |
; A123684: Alternate A016777(n) with A000027(n).
; 1,1,4,2,7,3,10,4,13,5,16,6,19,7,22,8,25,9,28,10,31,11,34,12,37,13,40,14,43,15,46,16,49,17,52,18,55,19,58,20,61,21,64,22,67,23,70,24,73,25,76,26,79,27,82,28,85,29,88,30,91,31,94,32,97,33,100,34,103,35,106,36,109,37,112,38,115,39,118,40,121,41,124,42,127,43,130,44,133,45,136,46,139,47,142,48,145,49,148,50,151,51,154,52,157,53,160,54,163,55,166,56,169,57,172,58,175,59,178,60,181,61,184,62,187,63,190,64,193,65,196,66,199,67,202,68,205,69,208,70,211,71,214,72,217,73,220,74,223,75,226,76,229,77,232,78,235,79,238,80,241,81,244,82,247,83,250,84,253,85,256,86,259,87,262,88,265,89,268,90,271,91,274,92,277,93,280,94,283,95,286,96,289,97,292,98,295,99,298,100,301,101,304,102,307,103,310,104,313,105,316,106,319,107,322,108,325,109,328,110,331,111,334,112,337,113,340,114,343,115,346,116,349,117,352,118,355,119,358,120,361,121,364,122,367,123,370,124,373,125
add $0,1
mov $1,$0
mul $1,2
div $1,4
mov $2,$0
mod $0,2
lpb $0,1
sub $0,$0
add $1,$2
lpe
|
; A143971: Triangle read by rows, (3n-2) subsequences decrescendo
; 1,4,1,7,4,1,10,7,4,1,13,10,7,4,1,16,13,10,7,4,1,19,16,13,10,7,4,1,22,19,16,13,10,7,4,1,25,22,19,16,13,10,7,4,1,28,25,22,19,16,13,10,7,4,1,31,28,25,22,19,16,13,10,7,4,1
mov $1,2
add $1,$0
mul $0,2
sub $1,1
add $0,$1
lpb $0,1
mov $1,$2
add $1,1
mov $2,$0
sub $0,1
trn $1,$2
sub $0,$1
trn $0,2
sub $2,1
sub $1,$2
lpe
add $1,1
|
; A343639: a(n) = (Sum of digits of 9*n) / 9.
; 0,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,2,2,1,1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,2,2,2,2,1,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,2,1,1,1,1,2,2,2,2,2,2,2,1,1,1,2,2,2,2,2,2,2,2,1,1,2,2,2,2,2,2,2,2,2
mul $0,9
seq $0,7953 ; Digital sum (i.e., sum of digits) of n; also called digsum(n).
div $0,9
|
/*
* Copyright (C) 2009 Google 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:
*
* * 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 Google Inc. 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 "platform/fonts/WebFontDecoder.h"
#include "platform/Histogram.h"
#include "platform/SharedBuffer.h"
#include "platform/TraceEvent.h"
#include "platform/fonts/FontCache.h"
#include "platform/graphics/skia/SkiaUtils.h"
#include "public/platform/Platform.h"
#include "third_party/harfbuzz-ng/src/hb.h"
#include "third_party/ots/include/ots-memory-stream.h"
#include "third_party/skia/include/core/SkStream.h"
#include "wtf/CurrentTime.h"
#include <stdarg.h>
namespace blink {
namespace {
class BlinkOTSContext final : public ots::OTSContext {
DISALLOW_NEW();
public:
void Message(int level, const char *format, ...) override;
ots::TableAction GetTableAction(uint32_t tag) override;
const String& getErrorString() { return m_errorString; }
private:
String m_errorString;
};
void BlinkOTSContext::Message(int level, const char *format, ...)
{
va_list args;
va_start(args, format);
#if COMPILER(MSVC)
int result = _vscprintf(format, args);
#else
char ch;
int result = vsnprintf(&ch, 1, format, args);
#endif
va_end(args);
if (result <= 0) {
m_errorString = String("OTS Error");
} else {
Vector<char, 256> buffer;
unsigned len = result;
buffer.grow(len + 1);
va_start(args, format);
vsnprintf(buffer.data(), buffer.size(), format, args);
va_end(args);
m_errorString = StringImpl::create(reinterpret_cast<const LChar*>(buffer.data()), len);
}
}
#if !defined(HB_VERSION_ATLEAST)
#define HB_VERSION_ATLEAST(major, minor, micro) 0
#endif
ots::TableAction BlinkOTSContext::GetTableAction(uint32_t tag)
{
const uint32_t cbdtTag = OTS_TAG('C', 'B', 'D', 'T');
const uint32_t cblcTag = OTS_TAG('C', 'B', 'L', 'C');
const uint32_t colrTag = OTS_TAG('C', 'O', 'L', 'R');
const uint32_t cpalTag = OTS_TAG('C', 'P', 'A', 'L');
#if HB_VERSION_ATLEAST(1, 0, 0)
const uint32_t gdefTag = OTS_TAG('G', 'D', 'E', 'F');
const uint32_t gposTag = OTS_TAG('G', 'P', 'O', 'S');
const uint32_t gsubTag = OTS_TAG('G', 'S', 'U', 'B');
#endif
switch (tag) {
// Google Color Emoji Tables
case cbdtTag:
case cblcTag:
// Windows Color Emoji Tables
case colrTag:
case cpalTag:
#if HB_VERSION_ATLEAST(1, 0, 0)
// Let HarfBuzz handle how to deal with broken tables.
case gdefTag:
case gposTag:
case gsubTag:
#endif
return ots::TABLE_ACTION_PASSTHRU;
default:
return ots::TABLE_ACTION_DEFAULT;
}
}
void recordDecodeSpeedHistogram(const char* data, size_t length, double decodeTime, size_t decodedSize)
{
if (decodeTime <= 0)
return;
double kbPerSecond = decodedSize / (1000 * decodeTime);
if (length >= 4) {
if (data[0] == 'w' && data[1] == 'O' && data[2] == 'F' && data[3] == 'F') {
DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, woffHistogram, new CustomCountHistogram("WebFont.DecodeSpeed.WOFF", 1000, 300000, 50));
woffHistogram.count(kbPerSecond);
return;
}
if (data[0] == 'w' && data[1] == 'O' && data[2] == 'F' && data[3] == '2') {
DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, woff2Histogram, new CustomCountHistogram("WebFont.DecodeSpeed.WOFF2", 1000, 300000, 50));
woff2Histogram.count(kbPerSecond);
return;
}
}
DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, sfntHistogram, new CustomCountHistogram("WebFont.DecodeSpeed.SFNT", 1000, 300000, 50));
sfntHistogram.count(kbPerSecond);
}
} // namespace
// static
bool WebFontDecoder::supportsFormat(const String& format)
{
return equalIgnoringCase(format, "woff") || equalIgnoringCase(format, "woff2");
}
PassRefPtr<SkTypeface> WebFontDecoder::decode(SharedBuffer* buffer)
{
if (!buffer) {
setErrorString("Empty Buffer");
return nullptr;
}
// This is the largest web font size which we'll try to transcode.
// TODO(bashi): 30MB seems low. Update the limit if necessary.
static const size_t maxWebFontSize = 30 * 1024 * 1024; // 30 MB
if (buffer->size() > maxWebFontSize) {
setErrorString("Web font size more than 30MB");
return nullptr;
}
// Most web fonts are compressed, so the result can be much larger than
// the original.
ots::ExpandingMemoryStream output(buffer->size(), maxWebFontSize);
double start = currentTime();
BlinkOTSContext otsContext;
const char* data = buffer->data();
TRACE_EVENT_BEGIN0("blink", "DecodeFont");
bool ok = otsContext.Process(&output, reinterpret_cast<const uint8_t*>(data), buffer->size());
TRACE_EVENT_END0("blink", "DecodeFont");
if (!ok) {
setErrorString(otsContext.getErrorString());
return nullptr;
}
const size_t decodedLength = output.Tell();
recordDecodeSpeedHistogram(data, buffer->size(), currentTime() - start, decodedLength);
sk_sp<SkData> skData = SkData::MakeWithCopy(output.get(), decodedLength);
SkMemoryStream* stream = new SkMemoryStream(skData);
#if OS(WIN)
RefPtr<SkTypeface> typeface = adoptRef(FontCache::fontCache()->fontManager()->createFromStream(stream));
#else
RefPtr<SkTypeface> typeface = fromSkSp(SkTypeface::MakeFromStream(stream));
#endif
if (!typeface) {
setErrorString("Not a valid font data");
return nullptr;
}
return typeface.release();
}
} // namespace blink
|
//
// Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "MouseInput.h"
//-------------------------------------------------------------------------------------------------
MouseInput::MouseInput() :
m_pDirectInput8W(NULL),
m_pMouseDevice(NULL),
m_bMouseAcquired(false),
m_hWatchThread(NULL),
m_lThreadStop(0),
m_pCallback(NULL),
m_hWnd(NULL),
m_hInstance(NULL),
m_uiMouseEventsPerSecond(100),
m_bEmulation(true),
m_EmulatePosition(0.0f)
{
increase_timer_precision(); // increases accuracy of Sleep() to 2 ms (orignal - 15 ms)
}
//-------------------------------------------------------------------------------------------------
MouseInput::~MouseInput()
{
Terminate();
}
//-------------------------------------------------------------------------------------------------
ALVR_RESULT MouseInput::Init(HINSTANCE hinst, HWND hWnd, MouseInputCallback *pCallback, UINT mouseEventsPerSecond)
{
Terminate();
m_hWnd = hWnd;
m_hInstance = hinst;
m_pCallback = pCallback;
m_uiMouseEventsPerSecond = mouseEventsPerSecond;
m_hWatchThread = CreateThread(NULL, 0, ThreadProc, this, 0, NULL);
CHECK_RETURN(m_hWatchThread != NULL, ALVR_FAIL, L"CreateThread(0 failed");
return ALVR_OK;
}
//-------------------------------------------------------------------------------------------------
ALVR_RESULT MouseInput::InitDirectInput()
{
HRESULT hr = S_OK;
hr = DirectInput8Create(m_hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8W, (void**)&m_pDirectInput8W, NULL);
CHECK_HRESULT_ERROR_RETURN(hr, L"DirectInput8Create() failed");
hr = m_pDirectInput8W->CreateDevice(GUID_SysMouse, &m_pMouseDevice, NULL);
CHECK_HRESULT_ERROR_RETURN(hr, L"m_pDirectInput8W->CreateDevice() failed");
hr = m_pMouseDevice->SetCooperativeLevel(m_hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
CHECK_HRESULT_ERROR_RETURN(hr, L"SetCooperativeLevel() failed");
hr = m_pMouseDevice->SetDataFormat(&c_dfDIMouse);
CHECK_HRESULT_ERROR_RETURN(hr, L"SetDataFormat() failed");
m_bMouseAcquired = m_pMouseDevice->Acquire() == DI_OK;
return ALVR_OK;
}
//-------------------------------------------------------------------------------------------------
ALVR_RESULT MouseInput::Terminate()
{
// stop thread
if (m_hWatchThread != NULL)
{
// tell thread to stop
m_lThreadStop = 1;
// wait
while (true)
{
DWORD ExitCode = 0;
if (!GetExitCodeThread(m_hWatchThread, &ExitCode) || ExitCode != STILL_ACTIVE)
{
break;
}
Sleep(2);
}
m_lThreadStop = 0;
}
m_pMouseDevice.Release();
m_pDirectInput8W.Release();
m_bMouseAcquired = false;
m_pCallback = NULL;
m_hWnd = NULL;
m_hInstance = NULL;
m_uiMouseEventsPerSecond = 100;
return ALVR_OK;
}
//-------------------------------------------------------------------------------------------------
ALVR_RESULT MouseInput::TryMouseUpdate(bool &bLeftDown)
{
bLeftDown = false;
ALVR_RESULT res = ALVR_OK;
HRESULT hr = S_OK;
if(m_pMouseDevice == NULL)
{
return res;
}
m_pMouseDevice->Poll();
DIMOUSESTATE mouseState;
for (int i = 0; i < 3; i++) // try 3 times
{
if ((hr = m_pMouseDevice->GetDeviceState(sizeof(mouseState), &mouseState)) != DI_OK)
{
m_pMouseDevice->Unacquire();
m_bMouseAcquired = m_pMouseDevice->Acquire() == DI_OK;
}
else
{
break;
}
}
if (hr == S_OK)
{
res = ALVR_FALSE;
// update mouse pos here
LONG posX = mouseState.lX;
LONG posY = mouseState.lY;
bLeftDown = (mouseState.rgbButtons[0] & 0x80) != 0;
bool bRightDown = (mouseState.rgbButtons[1] & 0x80) != 0;
if (posX == 0 && posY == 0 )
{
GetCursorPos(&m_LastMousePos);
}
else
{
m_LastMousePos.x += posX;
m_LastMousePos.y += posY;
}
RECT client;
GetClientRect(m_hWnd, &client);
POINT leftTop;
leftTop.x = client.left;
leftTop.y = client.top;
ClientToScreen(m_hWnd, &leftTop);
POINT rightBottom;
rightBottom.x = client.right;
rightBottom.y = client.bottom;
ClientToScreen(m_hWnd, &rightBottom);
long centerX = (rightBottom.x + leftTop.x) / 2 - (rightBottom.x - leftTop.x) / 4;
if (m_pCallback != NULL)
{
m_pCallback->MouseEvent(centerX, m_LastMousePos.y, bLeftDown, bRightDown);
res = ALVR_OK;
}
}
return res;
}
//-------------------------------------------------------------------------------------------------
ALVR_RESULT MouseInput::TryMouseEmulate(bool &bLeftDown)
{
RECT client;
GetClientRect(m_hWnd, &client);
POINT leftTop;
leftTop.x = client.left;
leftTop.y = client.top;
ClientToScreen(m_hWnd, &leftTop);
POINT rightBottom;
rightBottom.x = client.right;
rightBottom.y = client.bottom;
ClientToScreen(m_hWnd, &rightBottom);
long centerX = (rightBottom.x + leftTop.x) / 2 - (rightBottom.x - leftTop.x) / 4;
long centerY = (rightBottom.y + leftTop.y) / 2;
m_EmulatePosition += 2;
if (m_EmulatePosition > rightBottom.y - leftTop.y)
{
m_EmulatePosition = 0;
}
long x = centerX;
long y = (long)m_EmulatePosition + leftTop.y;
bLeftDown = true;
if (m_pCallback != NULL)
{
m_pCallback->MouseEvent(x, y, bLeftDown, false);
}
return ALVR_OK;
}
//-------------------------------------------------------------------------------------------------
DWORD WINAPI MouseInput::ThreadProc(_In_ LPVOID lpParameter)
{
return ((MouseInput*)lpParameter)->ThreadRun();
}
//-------------------------------------------------------------------------------------------------
DWORD MouseInput::ThreadRun()
{
InitDirectInput();
double dStartTime = high_precision_clock() / 10000000.; // in sec
int iEventCountInOneSec = 0;
while (!m_lThreadStop)
{
HRESULT hr = S_OK;
bool bLeftDown = false;
if (m_bEmulation)
{
hr = TryMouseEmulate(bLeftDown);
}
else
{
hr = TryMouseUpdate(bLeftDown);
}
double dCurrentTime = high_precision_clock() / 10000000.; // in sec
if (dCurrentTime - dStartTime >= 1.0) // second passed
{
iEventCountInOneSec = 0;
dStartTime = dCurrentTime;
}
if (hr == S_OK && bLeftDown) // event sent
{
iEventCountInOneSec++;
}
UINT uiEventsLeftInSecond = m_uiMouseEventsPerSecond - iEventCountInOneSec;
if (uiEventsLeftInSecond == 0)
{
uiEventsLeftInSecond = 1;
}
double dTimeLefInSecond = 1.0 - (dCurrentTime - dStartTime);
DWORD sleepTime = (DWORD)(dTimeLefInSecond * 1000 / uiEventsLeftInSecond);
if (sleepTime == 0)
{
sleepTime = 1;
}
Sleep(sleepTime);
}
return 0;
}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
|
; A105734: For n>2, a(n) > 0 is such that a(n-1)^2+4*a(n-2)*a(n) is a minimal square, with a(1)=1, a(2)=1.
; 1,1,2,3,2,1,1,2,3,2,1,1,2,3,2,1,1,2,3,2,1,1
bin $0,2
pow $0,3
mod $0,5
mov $1,$0
add $1,1
|
/*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/helpers/ptr_math.h"
#include "shared/test/common/helpers/debug_manager_state_restore.h"
#include "shared/test/common/helpers/unit_test_helper.h"
#include "shared/test/common/mocks/mock_allocation_properties.h"
#include "shared/test/common/mocks/mock_device.h"
#include "shared/test/common/test_macros/test.h"
#include "shared/test/unit_test/command_stream/compute_mode_tests.h"
#include "test_traits_common.h"
using namespace NEO;
HWCMDTEST_F(IGFX_XE_HP_CORE, ComputeModeRequirements, givenCoherencyWithoutSharedHandlesWhenCommandSizeIsCalculatedThenCorrectCommandSizeIsReturned) {
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
SetUpImpl<FamilyType>();
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdsSize = sizeof(STATE_COMPUTE_MODE);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
overrideComputeModeRequest<FamilyType>(false, false, false);
EXPECT_FALSE(getCsrHw<FamilyType>()->isComputeModeNeeded());
overrideComputeModeRequest<FamilyType>(false, true, false);
EXPECT_FALSE(getCsrHw<FamilyType>()->isComputeModeNeeded());
overrideComputeModeRequest<FamilyType>(true, true, false);
auto retSize = getCsrHw<FamilyType>()->getCmdSizeForComputeMode();
EXPECT_TRUE(getCsrHw<FamilyType>()->isComputeModeNeeded());
EXPECT_EQ(cmdsSize, retSize);
overrideComputeModeRequest<FamilyType>(true, false, false);
retSize = getCsrHw<FamilyType>()->getCmdSizeForComputeMode();
EXPECT_TRUE(getCsrHw<FamilyType>()->isComputeModeNeeded());
EXPECT_EQ(cmdsSize, retSize);
}
HWCMDTEST_F(IGFX_XE_HP_CORE, ComputeModeRequirements, givenCoherencyWithSharedHandlesWhenCommandSizeIsCalculatedThenCorrectCommandSizeIsReturned) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
overrideComputeModeRequest<FamilyType>(false, false, true);
EXPECT_FALSE(getCsrHw<FamilyType>()->isComputeModeNeeded());
overrideComputeModeRequest<FamilyType>(false, true, true);
EXPECT_FALSE(getCsrHw<FamilyType>()->isComputeModeNeeded());
auto cmdsSize = sizeof(STATE_COMPUTE_MODE) + sizeof(PIPE_CONTROL);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
overrideComputeModeRequest<FamilyType>(true, true, true);
auto retSize = getCsrHw<FamilyType>()->getCmdSizeForComputeMode();
EXPECT_TRUE(getCsrHw<FamilyType>()->isComputeModeNeeded());
EXPECT_EQ(cmdsSize, retSize);
overrideComputeModeRequest<FamilyType>(true, false, true);
retSize = getCsrHw<FamilyType>()->getCmdSizeForComputeMode();
EXPECT_TRUE(getCsrHw<FamilyType>()->isComputeModeNeeded());
EXPECT_EQ(cmdsSize, retSize);
}
struct ForceNonCoherentSupportedMatcher {
template <PRODUCT_FAMILY productFamily>
static constexpr bool isMatched() {
if constexpr (HwMapper<productFamily>::GfxProduct::supportsCmdSet(IGFX_XE_HP_CORE)) {
return TestTraits<NEO::ToGfxCoreFamily<productFamily>::get()>::forceNonCoherentSupported;
}
return false;
}
};
HWTEST2_F(ComputeModeRequirements, givenCoherencyWithoutSharedHandlesWhenComputeModeIsProgrammedThenCorrectCommandsAreAdded, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdsSize = sizeof(STATE_COMPUTE_MODE);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
char buff[1024] = {0};
LinearStream stream(buff, 1024);
auto expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
auto expectedBitsMask = FamilyType::stateComputeModeForceNonCoherentMask | FamilyType::stateComputeModeLargeGrfModeMask;
overrideComputeModeRequest<FamilyType>(true, false, false, false, true);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize, stream.getUsed());
auto scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(stream.getCpuBase());
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
auto startOffset = stream.getUsed();
overrideComputeModeRequest<FamilyType>(true, true, false, false, true);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize * 2, stream.getUsed());
expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_DISABLED);
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), startOffset));
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), startOffset + sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
}
HWTEST2_F(ComputeModeRequirements, givenCoherencyWithSharedHandlesWhenComputeModeIsProgrammedThenCorrectCommandsAreAdded, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdsSize = sizeof(STATE_COMPUTE_MODE) + sizeof(PIPE_CONTROL);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
char buff[1024] = {0};
LinearStream stream(buff, 1024);
auto expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
auto expectedBitsMask = FamilyType::stateComputeModeForceNonCoherentMask | FamilyType::stateComputeModeLargeGrfModeMask;
auto expectedPcCmd = FamilyType::cmdInitPipeControl;
overrideComputeModeRequest<FamilyType>(true, false, true, false, true);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize, stream.getUsed());
auto scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(stream.getCpuBase());
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
auto pcCmd = reinterpret_cast<PIPE_CONTROL *>(ptrOffset(stream.getCpuBase(), sizeof(STATE_COMPUTE_MODE)));
if (isBasicWARequired) {
pcCmd = reinterpret_cast<PIPE_CONTROL *>(ptrOffset(stream.getCpuBase(), sizeof(STATE_COMPUTE_MODE) + sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(memcmp(&expectedPcCmd, pcCmd, sizeof(PIPE_CONTROL)) == 0);
auto startOffset = stream.getUsed();
overrideComputeModeRequest<FamilyType>(true, true, true, false, true);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize * 2, stream.getUsed());
expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_DISABLED);
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), startOffset));
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), startOffset + sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
pcCmd = reinterpret_cast<PIPE_CONTROL *>(ptrOffset(stream.getCpuBase(), startOffset + sizeof(STATE_COMPUTE_MODE)));
if (isBasicWARequired) {
pcCmd = reinterpret_cast<PIPE_CONTROL *>(ptrOffset(stream.getCpuBase(), startOffset + sizeof(STATE_COMPUTE_MODE) + sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(memcmp(&expectedPcCmd, pcCmd, sizeof(PIPE_CONTROL)) == 0);
}
HWTEST2_F(ComputeModeRequirements, givenCoherencyRequirementWithoutSharedHandlesWhenFlushTaskCalledThenProgramCmdOnlyIfChanged, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
auto startOffset = getCsrHw<FamilyType>()->commandStream.getUsed();
auto graphicAlloc = csr->getMemoryManager()->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize});
IndirectHeap stream(graphicAlloc);
auto flushTask = [&](bool coherencyRequired) {
flags.requiresCoherency = coherencyRequired;
startOffset = getCsrHw<FamilyType>()->commandStream.getUsed();
csr->flushTask(stream, 0, stream, stream, stream, 0, flags, *device);
};
auto findCmd = [&](bool expectToBeProgrammed, bool expectCoherent) {
HardwareParse hwParser;
hwParser.parseCommands<FamilyType>(getCsrHw<FamilyType>()->commandStream, startOffset);
bool foundOne = false;
typename STATE_COMPUTE_MODE::FORCE_NON_COHERENT expectedCoherentValue = expectCoherent ? STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_DISABLED : STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT;
uint32_t expectedCoherentMask = FamilyType::stateComputeModeForceNonCoherentMask;
for (auto it = hwParser.cmdList.begin(); it != hwParser.cmdList.end(); it++) {
auto cmd = genCmdCast<STATE_COMPUTE_MODE *>(*it);
if (cmd) {
EXPECT_EQ(expectedCoherentValue, cmd->getForceNonCoherent());
EXPECT_TRUE(isValueSet(cmd->getMaskBits(), expectedCoherentMask));
EXPECT_FALSE(foundOne);
foundOne = true;
auto pc = genCmdCast<PIPE_CONTROL *>(*(++it));
EXPECT_EQ(nullptr, pc);
}
}
EXPECT_EQ(expectToBeProgrammed, foundOne);
};
flushTask(false);
findCmd(true, false); // first time
flushTask(false);
findCmd(false, false); // not changed
flushTask(true);
findCmd(true, true); // changed
flushTask(true);
findCmd(false, true); // not changed
flushTask(false);
findCmd(true, false); // changed
flushTask(false);
findCmd(false, false); // not changed
csr->getMemoryManager()->freeGraphicsMemory(graphicAlloc);
}
HWTEST2_F(ComputeModeRequirements, givenCoherencyRequirementWithSharedHandlesWhenFlushTaskCalledThenProgramCmdsWhenNeeded, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
auto startOffset = getCsrHw<FamilyType>()->commandStream.getUsed();
auto graphicsAlloc = csr->getMemoryManager()->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize});
IndirectHeap stream(graphicsAlloc);
auto flushTask = [&](bool coherencyRequired) {
flags.requiresCoherency = coherencyRequired;
makeResidentSharedAlloc();
startOffset = getCsrHw<FamilyType>()->commandStream.getUsed();
csr->flushTask(stream, 0, stream, stream, stream, 0, flags, *device);
};
auto flushTaskAndFindCmds = [&](bool expectCoherent, bool areCommandsProgrammed) {
flushTask(expectCoherent);
HardwareParse hwParser;
hwParser.parseCommands<FamilyType>(getCsrHw<FamilyType>()->commandStream, startOffset);
bool foundOne = false;
typename STATE_COMPUTE_MODE::FORCE_NON_COHERENT expectedCoherentValue = expectCoherent ? STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_DISABLED : STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT;
uint32_t expectedCoherentMask = FamilyType::stateComputeModeForceNonCoherentMask;
for (auto it = hwParser.cmdList.begin(); it != hwParser.cmdList.end(); it++) {
auto cmd = genCmdCast<STATE_COMPUTE_MODE *>(*it);
if (cmd) {
EXPECT_EQ(expectedCoherentValue, cmd->getForceNonCoherent());
EXPECT_TRUE(isValueSet(cmd->getMaskBits(), expectedCoherentMask));
EXPECT_FALSE(foundOne);
foundOne = true;
auto pc = genCmdCast<PIPE_CONTROL *>(*(++it));
EXPECT_NE(nullptr, pc);
}
}
EXPECT_EQ(foundOne, areCommandsProgrammed);
};
flushTaskAndFindCmds(false, true); // first time
flushTaskAndFindCmds(false, false); // not changed
flushTaskAndFindCmds(true, true); // changed
flushTaskAndFindCmds(true, false); // not changed
flushTaskAndFindCmds(false, true); // changed
flushTaskAndFindCmds(false, false); // not changed
csr->getMemoryManager()->freeGraphicsMemory(graphicsAlloc);
}
HWTEST2_F(ComputeModeRequirements, givenFlushWithoutSharedHandlesWhenPreviouslyUsedThenPcAndSCMAreNotProgrammed, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
auto graphicAlloc = csr->getMemoryManager()->allocateGraphicsMemoryWithProperties(MockAllocationProperties{csr->getRootDeviceIndex(), MemoryConstants::pageSize});
IndirectHeap stream(graphicAlloc);
makeResidentSharedAlloc();
csr->flushTask(stream, 0, stream, stream, stream, 0, flags, *device);
EXPECT_TRUE(getCsrHw<FamilyType>()->getCsrRequestFlags()->hasSharedHandles);
auto startOffset = getCsrHw<FamilyType>()->commandStream.getUsed();
csr->flushTask(stream, 0, stream, stream, stream, 0, flags, *device);
EXPECT_TRUE(getCsrHw<FamilyType>()->getCsrRequestFlags()->hasSharedHandles);
HardwareParse hwParser;
hwParser.parseCommands<FamilyType>(getCsrHw<FamilyType>()->commandStream, startOffset);
EXPECT_EQ(0u, hwParser.cmdList.size());
csr->getMemoryManager()->freeGraphicsMemory(graphicAlloc);
}
HWCMDTEST_F(IGFX_XE_HP_CORE, ComputeModeRequirements, givenComputeModeCmdSizeWhenLargeGrfModeChangeIsRequiredThenSCMCommandSizeIsCalculated) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
overrideComputeModeRequest<FamilyType>(false, false, false, false, 128u);
EXPECT_FALSE(getCsrHw<FamilyType>()->isComputeModeNeeded());
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdSize = sizeof(STATE_COMPUTE_MODE);
if (isBasicWARequired) {
cmdSize += +sizeof(PIPE_CONTROL);
}
overrideComputeModeRequest<FamilyType>(false, false, false, true, 256u);
auto retSize = getCsrHw<FamilyType>()->getCmdSizeForComputeMode();
EXPECT_TRUE(getCsrHw<FamilyType>()->isComputeModeNeeded());
EXPECT_EQ(cmdSize, retSize);
overrideComputeModeRequest<FamilyType>(true, false, false, true, 256u);
retSize = getCsrHw<FamilyType>()->getCmdSizeForComputeMode();
EXPECT_TRUE(getCsrHw<FamilyType>()->isComputeModeNeeded());
EXPECT_EQ(cmdSize, retSize);
}
HWTEST2_F(ComputeModeRequirements, givenComputeModeProgrammingWhenLargeGrfModeChangeIsRequiredThenCorrectCommandsAreAdded, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdsSize = sizeof(STATE_COMPUTE_MODE);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
char buff[1024];
LinearStream stream(buff, 1024);
auto expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
auto expectedBitsMask = FamilyType::stateComputeModeForceNonCoherentMask | FamilyType::stateComputeModeLargeGrfModeMask;
expectedScmCmd.setLargeGrfMode(true);
overrideComputeModeRequest<FamilyType>(true, false, false, true, 256u);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize, stream.getUsed());
auto scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(stream.getCpuBase());
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
auto startOffset = stream.getUsed();
overrideComputeModeRequest<FamilyType>(true, false, false, true, 128u);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize * 2, stream.getUsed());
expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setLargeGrfMode(false);
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), startOffset));
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), startOffset + sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
}
HWCMDTEST_F(IGFX_XE_HP_CORE, ComputeModeRequirements, givenComputeModeProgrammingWhenLargeGrfModeDoesntChangeThenSCMIsNotAdded) {
SetUpImpl<FamilyType>();
char buff[1024];
LinearStream stream(buff, 1024);
overrideComputeModeRequest<FamilyType>(false, false, false, false, 256u);
EXPECT_FALSE(getCsrHw<FamilyType>()->isComputeModeNeeded());
}
HWTEST2_F(ComputeModeRequirements, givenComputeModeProgrammingWhenRequiredGRFNumberIsLowerThan128ThenSmallGRFModeIsProgrammed, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdsSize = sizeof(STATE_COMPUTE_MODE);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
char buff[1024];
LinearStream stream(buff, 1024);
auto expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setLargeGrfMode(false);
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
auto expectedBitsMask = FamilyType::stateComputeModeForceNonCoherentMask | FamilyType::stateComputeModeLargeGrfModeMask;
overrideComputeModeRequest<FamilyType>(true, false, false, true, 127u);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize, stream.getUsed());
auto scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(stream.getCpuBase());
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
}
HWTEST2_F(ComputeModeRequirements, givenComputeModeProgrammingWhenRequiredGRFNumberIsGreaterThan128ThenLargeGRFModeIsProgrammed, ForceNonCoherentSupportedMatcher) {
SetUpImpl<FamilyType>();
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL;
const auto &hwInfoConfig = *HwInfoConfig::get(productFamily);
const auto &[isBasicWARequired, isExtendedWARequired] = hwInfoConfig.isPipeControlPriorToNonPipelinedStateCommandsWARequired(*defaultHwInfo, csr->isRcs());
std::ignore = isExtendedWARequired;
auto cmdsSize = sizeof(STATE_COMPUTE_MODE);
if (isBasicWARequired) {
cmdsSize += +sizeof(PIPE_CONTROL);
}
char buff[1024];
LinearStream stream(buff, 1024);
auto expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(STATE_COMPUTE_MODE::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
expectedScmCmd.setLargeGrfMode(true);
auto expectedBitsMask = FamilyType::stateComputeModeForceNonCoherentMask | FamilyType::stateComputeModeLargeGrfModeMask;
overrideComputeModeRequest<FamilyType>(true, false, false, true, 256u);
getCsrHw<FamilyType>()->programComputeMode(stream, flags, *defaultHwInfo);
EXPECT_EQ(cmdsSize, stream.getUsed());
auto scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(stream.getCpuBase());
if (isBasicWARequired) {
scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(stream.getCpuBase(), sizeof(PIPE_CONTROL)));
}
EXPECT_TRUE(isValueSet(scmCmd->getMaskBits(), expectedBitsMask));
expectedScmCmd.setMaskBits(scmCmd->getMaskBits());
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
}
|
db 0 ; species ID placeholder
db 80, 105, 65, 130, 60, 75
; hp atk def spd sat sdf
db ROCK, FLYING ; type
db 45 ; catch rate
db 202 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F12_5 ; gender ratio
db 35 ; step cycles to hatch
INCBIN "gfx/pokemon/aerodactyl/front.dimensions"
db GROWTH_SLOW ; growth rate
dn EGG_FLYING, EGG_FLYING ; egg groups
db 70 ; happiness
; tm/hm learnset
tmhm DRAGON_CLAW, ROAR, TOXIC, HIDDEN_POWER, SUNNY_DAY, TAUNT, HYPER_BEAM, PROTECT, RAIN_DANCE, FRUSTRATION, IRON_TAIL, EARTHQUAKE, RETURN, DOUBLE_TEAM, FLAMETHROWER, SANDSTORM, FIRE_BLAST, ROCK_TOMB, AERIAL_ACE, TORMENT, FACADE, SECRET_POWER, REST, ATTRACT, THIEF, STEEL_WING, ROOST, ENDURE, DRAGON_PULSE, PAYBACK, GIGA_IMPACT, ROCK_POLISH, STONE_EDGE, STEALTH_ROCK, CAPTIVATE, ROCK_SLIDE, SLEEP_TALK, NATURAL_GIFT, SWAGGER, SUBSTITUTE, FLY, STRENGTH, DEFOG, ROCK_SMASH, AIR_CUTTER, ANCIENTPOWER, AQUA_TAIL, EARTH_POWER, HEAT_WAVE, IRON_HEAD, OMINOUS_WIND, SNORE, SWIFT, TWISTER
; end
|
global main
extern printf
extern scanf
extern getchar
section .text
main:
Entry_main:
push ebp ;Store base pointer
mov ebp, esp ;Create new base pointer
sub esp, 0
push 3 ;Push int literal to stack
push intFrmt ;Push format string for printf
call printf
add esp, 8
push NewLine ;Push newline to stack for printf
call printf
add esp, 4 ;Clean up stack after printf
Exit_main:
mov esp, ebp
pop ebp
ret ;Return control to calling function
section .data
realFrmt: db "%f", 0 ;Print real without \n
intFrmt: db "%d", 0 ;Print int without \n
stringFrmt: db "%s", 0 ;Print string without \n
realFrmtIn: db "%lf", 0 ;Read real
intFrmtIn: db "%i", 0 ;Read int
stringFrmtIn: db "%s", 0 ;Read string
NewLine: db 0xA, 0 ;Print NewLine
randIn: db "/dev/urandom" ;File for random bytes
negone: dq -1.0 ;Negative one
section .bss
|
; local.asm
; Test of LOCAL, PROC and ENDP under CP/M.
bdos equ 5
conout equ 2
org 100h
jp hola
exit db "Hello, local world\r\n", 0
showtext proc
local hola, exit
hola ld a, (hl)
cp 0
jp z, exit
push hl
ld e, a
ld c, conout
call bdos
pop hl
inc hl
jp hola
exit ret
endp
hola ld hl, exit
call showtext
jp 0
end
|
; CALLER LINKAGE FOR FUNCTION POINTERS
SECTION code_clib
PUBLIC vz_line
PUBLIC _vz_line
EXTERN vz_line_callee
EXTERN ASMDISP_VZ_LINE_CALLEE
.vz_line
._vz_line
pop af
pop bc
pop de
pop hl
ld d,e
ld e,l
pop hl
ex af,af
ld a,l
pop hl
ld h,a
push hl
push hl
push hl
push de
push bc
ex af,af
push af
jp vz_line_callee + ASMDISP_VZ_LINE_CALLEE
|
;==============================================================================
; Contents of this file are copyright Phillip Stevens
;
; You have permission to use this for NON COMMERCIAL USE ONLY
; If you wish to use it elsewhere, please include an acknowledgement to myself.
;
; https://github.com/feilipu/
;
; https://feilipu.me/
;
;
; This work was authored in Marrakech, Morocco during May/June 2017.
INCLUDE "config_private.inc"
SECTION data_driver
PUBLIC __i2c1RxBuffer, __i2c1TxBuffer
__i2c1RxBuffer: DEFS __IO_I2C_RX_SIZE
__i2c1TxBuffer: DEFS __IO_I2C_TX_SIZE
PUBLIC __i2c1RxInPtr, __i2c1RxOutPtr, __i2c1RxBufUsed
PUBLIC __i2c1TxInPtr, __i2c1TxOutPtr, __i2c1TxBufUsed
PUBLIC __i2c1ControlEcho, __i2c1SlaveAddr, __i2c1SentenceLgth
__i2c1RxInPtr: DEFW __i2c1RxBuffer
__i2c1RxOutPtr: DEFW __i2c1RxBuffer
__i2c1TxInPtr: DEFW __i2c1TxBuffer
__i2c1TxOutPtr: DEFW __i2c1TxBuffer
__i2c1RxBufUsed: DEFB 0
__i2c1TxBufUsed: DEFB 0
__i2c1ControlEcho: DEFB 0
__i2c1SlaveAddr: DEFB 0
__i2c1SentenceLgth: DEFB 0
|
<%
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)}
|
//===-- alignment.cc --------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "gwp_asan/tests/harness.h"
TEST_F(DefaultGuardedPoolAllocator, BasicAllocation) {
std::vector<std::pair<int, int>> AllocSizeToAlignment = {
{1, 1}, {2, 2}, {3, 4}, {4, 4}, {5, 8}, {7, 8},
{8, 8}, {9, 16}, {15, 16}, {16, 16}, {17, 16}, {31, 16},
{32, 16}, {33, 16}, {4095, 4096}, {4096, 4096},
};
for (const auto &KV : AllocSizeToAlignment) {
void *Ptr = GPA.allocate(KV.first);
EXPECT_NE(nullptr, Ptr);
// Check the alignment of the pointer is as expected.
EXPECT_EQ(0u, reinterpret_cast<uintptr_t>(Ptr) % KV.second);
GPA.deallocate(Ptr);
}
}
|
/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "condor_fix_assert.h"
#include "condor_io.h"
#include "condor_constants.h"
#include "condor_classad.h"
#include "condor_attributes.h"
#include "condor_daemon_core.h"
#include "condor_config.h"
#include "condor_query.h"
#include "util_lib_proto.h"
#include "dc_startd.h"
#include "get_daemon_name.h"
#include <algorithm>
#include <iterator>
#include "defrag.h"
#include <list>
#include <tuple>
#define LOG_LENGTH 10
class DefragLog {
public:
void record_drain( const std::string & name, const std::string & schedule );
void record_cancel( const std::string & name );
void write_to_ad( ClassAd * ad ) const;
private:
std::list< std::tuple< time_t, std::string, std::string > > drains;
std::list< std::tuple< time_t, std::string > > cancels;
};
void
DefragLog::record_drain( const std::string & name, const std::string & schedule ) {
drains.emplace_back( time(NULL), name, schedule );
if( drains.size() > LOG_LENGTH ) { drains.pop_front(); }
}
void
DefragLog::record_cancel( const std::string & name ) {
cancels.emplace_back( time(NULL), name );
if( cancels.size() > LOG_LENGTH ) { cancels.pop_front(); }
}
void
DefragLog::write_to_ad(ClassAd * ad) const {
std::string buffer;
std::string list = "{ ";
for( auto i = drains.crbegin(); i != drains.crend(); ++i ) {
formatstr( buffer, "[ when = %ld; who = \"%s\"; what = \"%s\" ],",
std::get<0>(*i), std::get<1>(*i).c_str(), std::get<2>(*i).c_str() );
list += buffer;
}
list[list.length() - 1] = '}';
ad->AssignExpr( ATTR_RECENT_DRAINS_LIST, list.c_str() );
list = "{ ";
for( auto i = cancels.crbegin(); i != cancels.crend(); ++i ) {
formatstr( buffer, "[ when = %ld; who = \"%s\" ],",
std::get<0>(*i), std::get<1>(*i).c_str() );
list += buffer;
}
list[list.length() - 1] = '}';
ad->AssignExpr( ATTR_RECENT_CANCELS_LIST, list.c_str() );
}
DefragLog defrag_log;
// This constraint clause ignores machines that were drained by others
#define DEFRAG_DRAIN_REASON_CONSTRAINT "(" ATTR_DRAIN_REASON " is undefined || " ATTR_DRAIN_REASON " == \"Defrag\")"
static char const * const ATTR_LAST_POLL = "LastPoll";
static char const * const DRAINING_CONSTRAINT = "PartitionableSlot && Offline=!=True && Draining && " DEFRAG_DRAIN_REASON_CONSTRAINT;
Defrag::Defrag():
m_polling_interval(-1),
m_polling_timer(-1),
m_draining_per_hour(0),
m_draining_per_poll(0),
m_draining_per_poll_hour(0),
m_draining_per_poll_day(0),
m_max_draining(-1),
m_max_whole_machines(-1),
m_draining_schedule(DRAIN_GRACEFUL),
m_last_poll(0),
m_public_ad_update_interval(-1),
m_public_ad_update_timer(-1),
m_whole_machines_arrived(0),
m_last_whole_machine_arrival(0),
m_whole_machine_arrival_sum(0),
m_whole_machine_arrival_mean_squared(0)
{
}
Defrag::~Defrag()
{
stop();
}
void Defrag::init()
{
m_stats.Init();
config();
}
void Defrag::config()
{
ASSERT( param(m_state_file,"DEFRAG_STATE_FILE") );
if( m_last_poll==0 ) {
loadState();
}
int old_polling_interval = m_polling_interval;
m_polling_interval = param_integer("DEFRAG_INTERVAL",60);
if( m_polling_interval <= 0 ) {
dprintf(D_ALWAYS,
"DEFRAG_INTERVAL=%d, so no pool defragmentation "
"will be done.\n", m_polling_interval);
if( m_polling_timer != -1 ) {
daemonCore->Cancel_Timer(m_polling_timer);
m_polling_timer = -1;
}
}
else if( m_polling_timer >= 0 ) {
if( old_polling_interval != m_polling_interval ) {
daemonCore->Reset_Timer_Period(
m_polling_timer,
m_polling_interval);
}
}
else {
time_t now = time(NULL);
int first_time = 0;
if( m_last_poll != 0 && now-m_last_poll < m_polling_interval && m_last_poll <= now ) {
first_time = m_polling_interval - (now-m_last_poll);
}
m_polling_timer = daemonCore->Register_Timer(
first_time,
m_polling_interval,
(TimerHandlercpp)&Defrag::poll,
"Defrag::poll",
this );
}
if( old_polling_interval != m_polling_interval && m_polling_interval > 0 )
{
dprintf(D_ALWAYS,
"Will evaluate defragmentation policy every DEFRAG_INTERVAL="
"%d seconds.\n", m_polling_interval);
}
m_draining_per_hour = param_double("DEFRAG_DRAINING_MACHINES_PER_HOUR",0,0);
double rate = m_draining_per_hour/3600.0*m_polling_interval;
m_draining_per_poll = (int)floor(rate + 0.00001);
if( m_draining_per_poll < 0 ) m_draining_per_poll = 0;
double error_per_hour = (rate - m_draining_per_poll)/m_polling_interval*3600.0;
m_draining_per_poll_hour = (int)floor(error_per_hour + 0.00001);
if( m_draining_per_hour < 0 || m_polling_interval > 3600 ) {
m_draining_per_hour = 0;
}
double error_per_day = (error_per_hour - m_draining_per_poll_hour)*24.0;
m_draining_per_poll_day = (int)floor(error_per_day + 0.5);
if( m_draining_per_poll_day < 0 || m_polling_interval > 3600*24 ) {
m_draining_per_poll_day = 0;
}
dprintf(D_ALWAYS,"polling interval %ds, DEFRAG_DRAINING_MACHINES_PER_HOUR = %f/hour = %d/interval + %d/hour + %d/day\n",
m_polling_interval,m_draining_per_hour,m_draining_per_poll,
m_draining_per_poll_hour,m_draining_per_poll_day);
m_max_draining = param_integer("DEFRAG_MAX_CONCURRENT_DRAINING",-1,-1);
m_max_whole_machines = param_integer("DEFRAG_MAX_WHOLE_MACHINES",-1,-1);
param(m_defrag_requirements,"DEFRAG_REQUIREMENTS");
if ( ! m_defrag_requirements.empty()) {
validateExpr(m_defrag_requirements.c_str(), "DEFRAG_REQUIREMENTS");
}
ASSERT( param( m_draining_start_expr, "DEFRAG_DRAINING_START_EXPR" ) );
validateExpr( m_draining_start_expr.c_str(), "DEFRAG_DRAINING_START_EXPR" );
ASSERT( param(m_whole_machine_expr,"DEFRAG_WHOLE_MACHINE_EXPR") );
validateExpr( m_whole_machine_expr.c_str(), "DEFRAG_WHOLE_MACHINE_EXPR" );
m_whole_machine_expr += " && Offline =!= True && PartitionableSlot && " DEFRAG_DRAIN_REASON_CONSTRAINT;
ASSERT( param(m_draining_schedule_str,"DEFRAG_DRAINING_SCHEDULE") );
if( m_draining_schedule_str.empty() ) {
m_draining_schedule = DRAIN_GRACEFUL;
m_draining_schedule_str = "graceful";
}
else {
m_draining_schedule = getDrainingScheduleNum(m_draining_schedule_str.c_str());
if( m_draining_schedule < 0 ) {
EXCEPT("Invalid draining schedule: %s",m_draining_schedule_str.c_str());
}
}
m_drain_attrs.clear();
// we always need the attributes of a location lookup to send drain or cancel commands
m_drain_attrs.insert(ATTR_NAME);
m_drain_attrs.insert(ATTR_MACHINE);
m_drain_attrs.insert(ATTR_VERSION);
m_drain_attrs.insert(ATTR_PLATFORM); // TODO: get rid if this after Daemon object is fixed to work without it.
m_drain_attrs.insert(ATTR_MY_ADDRESS);
m_drain_attrs.insert(ATTR_ADDRESS_V1);
// also these special attributes to choose draining candidates
m_drain_attrs.insert(ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_COMPLETION);
m_drain_attrs.insert(ATTR_EXPECTED_MACHINE_QUICK_DRAINING_COMPLETION);
m_drain_attrs.insert(ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_BADPUT);
m_drain_attrs.insert(ATTR_EXPECTED_MACHINE_QUICK_DRAINING_BADPUT);
m_drain_attrs.insert(ATTR_DRAIN_REASON);
auto_free_ptr rank(param("DEFRAG_RANK"));
m_rank_ad.Delete(ATTR_RANK);
if (rank) {
if( !m_rank_ad.AssignExpr(ATTR_RANK,rank) ) {
EXCEPT("Invalid expression for DEFRAG_RANK: %s", rank.ptr());
}
// add rank references to the projection
GetExprReferences(m_rank_ad.Lookup(ATTR_RANK), m_rank_ad, NULL, &m_drain_attrs);
}
int update_interval = param_integer("DEFRAG_UPDATE_INTERVAL", 300);
if(m_public_ad_update_interval != update_interval) {
m_public_ad_update_interval = update_interval;
dprintf(D_FULLDEBUG, "Setting update interval to %d\n",
m_public_ad_update_interval);
if(m_public_ad_update_timer >= 0) {
daemonCore->Reset_Timer_Period(
m_public_ad_update_timer,
m_public_ad_update_interval);
}
else {
m_public_ad_update_timer = daemonCore->Register_Timer(
0,
m_public_ad_update_interval,
(TimerHandlercpp)&Defrag::updateCollector,
"Defrag::updateCollector",
this);
}
}
if (param(m_cancel_requirements, "DEFRAG_CANCEL_REQUIREMENTS")) {
validateExpr( m_cancel_requirements.c_str(), "DEFRAG_CANCEL_REQUIREMENTS" );
} else {
m_cancel_requirements = "";
}
param(m_defrag_name,"DEFRAG_NAME");
int stats_quantum = m_polling_interval;
int stats_window = 10*stats_quantum;
m_stats.SetWindowSize(stats_window,stats_quantum);
}
void Defrag::stop()
{
if( m_polling_timer != -1 ) {
daemonCore->Cancel_Timer(m_polling_timer);
m_polling_timer = -1;
}
}
static int StartdSortFunc(ClassAd *ad1,ClassAd *ad2,void *data)
{
ClassAd *rank_ad = (ClassAd *)data;
float rank1 = 0;
float rank2 = 0;
EvalFloat(ATTR_RANK,rank_ad,ad1,rank1);
EvalFloat(ATTR_RANK,rank_ad,ad2,rank2);
return rank1 > rank2;
}
void Defrag::validateExpr(char const *constraint,char const *constraint_source)
{
ExprTree *requirements = NULL;
if( ParseClassAdRvalExpr( constraint, requirements )!=0 || requirements==NULL )
{
EXCEPT("Invalid expression for %s: %s",
constraint_source,constraint);
}
delete requirements;
}
bool Defrag::queryMachines(char const *constraint,char const *constraint_source,ClassAdList &startdAds, classad::References * projection)
{
CondorQuery startdQuery(STARTD_AD);
validateExpr(constraint,constraint_source);
startdQuery.addANDConstraint(constraint);
if (projection) {
startdQuery.setDesiredAttrs(*projection);
} else {
// if no projection supplied, just get the Name attribute
startdQuery.setDesiredAttrs("Name");
}
CollectorList* collects = daemonCore->getCollectorList();
ASSERT( collects );
QueryResult result;
result = collects->query(startdQuery,startdAds);
if( result != Q_OK ) {
dprintf(D_ALWAYS,
"Couldn't fetch startd ads using constraint "
"%s=%s: %s\n",
constraint_source,constraint, getStrQueryResult(result));
return false;
}
dprintf(D_FULLDEBUG,"Got %d startd ads matching %s=%s\n",
startdAds.MyLength(), constraint_source, constraint);
return true;
}
void
Defrag::queryDrainingCost()
{
ClassAdList startdAds;
CondorQuery startdQuery(STARTD_AD);
char const *desired_attrs[6];
desired_attrs[0] = ATTR_TOTAL_MACHINE_DRAINING_UNCLAIMED_TIME;
desired_attrs[1] = ATTR_TOTAL_MACHINE_DRAINING_BADPUT;
desired_attrs[2] = ATTR_DAEMON_START_TIME;
desired_attrs[3] = ATTR_TOTAL_CPUS;
desired_attrs[4] = ATTR_LAST_HEARD_FROM;
desired_attrs[5] = NULL;
startdQuery.setDesiredAttrs(desired_attrs);
std::string query;
// only want one ad per machine
formatstr(query,"%s==1 && (%s =!= undefined || %s =!= undefined)",
ATTR_SLOT_ID,
ATTR_TOTAL_MACHINE_DRAINING_UNCLAIMED_TIME,
ATTR_TOTAL_MACHINE_DRAINING_BADPUT);
startdQuery.addANDConstraint(query.c_str());
CollectorList* collects = daemonCore->getCollectorList();
ASSERT( collects );
QueryResult result;
result = collects->query(startdQuery,startdAds);
if( result != Q_OK ) {
dprintf(D_ALWAYS,
"Couldn't fetch startd ads: %s\n",
getStrQueryResult(result));
return;
}
double avg_badput = 0.0;
double avg_unclaimed = 0.0;
int total_cpus = 0;
startdAds.Open();
ClassAd *startd_ad;
while( (startd_ad=startdAds.Next()) ) {
int unclaimed = 0;
int badput = 0;
int start_time = 0;
int cpus = 0;
int last_heard_from = 0;
startd_ad->LookupInteger(ATTR_TOTAL_MACHINE_DRAINING_UNCLAIMED_TIME,unclaimed);
startd_ad->LookupInteger(ATTR_TOTAL_MACHINE_DRAINING_BADPUT,badput);
startd_ad->LookupInteger(ATTR_DAEMON_START_TIME,start_time);
startd_ad->LookupInteger(ATTR_LAST_HEARD_FROM,last_heard_from);
startd_ad->LookupInteger(ATTR_TOTAL_CPUS,cpus);
int age = last_heard_from - start_time;
if( last_heard_from == 0 || start_time == 0 || age <= 0 ) {
continue;
}
avg_badput += ((double)badput)/age;
avg_unclaimed += ((double)unclaimed)/age;
total_cpus += cpus;
}
startdAds.Close();
if( total_cpus > 0 ) {
avg_badput = avg_badput/total_cpus;
avg_unclaimed = avg_unclaimed/total_cpus;
}
dprintf(D_ALWAYS,"Average pool draining badput = %.2f%%\n",
avg_badput*100);
dprintf(D_ALWAYS,"Average pool draining unclaimed = %.2f%%\n",
avg_unclaimed*100);
m_stats.AvgDrainingBadput = avg_badput;
m_stats.AvgDrainingUnclaimed = avg_unclaimed;
}
int Defrag::countMachines(char const *constraint,char const *constraint_source, MachineSet *machines)
{
ClassAdList startdAds;
int count = 0;
if( !queryMachines(constraint,constraint_source,startdAds,NULL) ) {
return -1;
}
MachineSet my_machines;
if( !machines ) {
machines = &my_machines;
}
startdAds.Open();
ClassAd *startd_ad;
while( (startd_ad=startdAds.Next()) ) {
std::string machine;
std::string name;
startd_ad->LookupString(ATTR_NAME,name);
slotNameToDaemonName(name,machine);
if( machines->count(machine) ) {
continue;
}
machines->insert(machine);
count++;
}
startdAds.Close();
dprintf(D_FULLDEBUG,"Counted %d machines matching %s=%s\n",
count,constraint_source,constraint);
return count;
}
void Defrag::saveState()
{
ClassAd ad;
ad.Assign(ATTR_LAST_POLL,(int)m_last_poll);
std::string new_state_file;
formatstr(new_state_file,"%s.new",m_state_file.c_str());
FILE *fp;
if( !(fp = safe_fopen_wrapper_follow(new_state_file.c_str(), "w")) ) {
EXCEPT("failed to save state to %s",new_state_file.c_str());
}
else {
fPrintAd(fp, ad);
fclose( fp );
if( rotate_file(new_state_file.c_str(),m_state_file.c_str())!=0 ) {
EXCEPT("failed to save state to %s",m_state_file.c_str());
}
}
}
void Defrag::loadState()
{
FILE *fp;
if( !(fp = safe_fopen_wrapper_follow(m_state_file.c_str(), "r")) ) {
if( errno == ENOENT ) {
dprintf(D_ALWAYS,"State file %s does not yet exist.\n",m_state_file.c_str());
}
else {
EXCEPT("failed to load state from %s",m_state_file.c_str());
}
}
else {
int isEOF=0, errorReadingAd=0, adEmpty=0;
ClassAd *ad = new ClassAd;
InsertFromFile(fp, *ad, "...", isEOF, errorReadingAd, adEmpty);
fclose( fp );
if( errorReadingAd ) {
dprintf(D_ALWAYS,"WARNING: failed to parse state from %s\n",m_state_file.c_str());
}
int timestamp = (int)m_last_poll;
ad->LookupInteger(ATTR_LAST_POLL,timestamp);
m_last_poll = (time_t)timestamp;
dprintf(D_ALWAYS,"Last poll: %d\n",(int)m_last_poll);
delete ad;
}
}
void Defrag::slotNameToDaemonName(std::string const &name,std::string &machine)
{
size_t pos = name.find('@');
if( pos == std::string::npos ) {
machine = name;
}
else {
machine.append(name,pos+1,name.size()-pos-1);
}
}
// n is a number per period. If we are partly through
// the interval, make n be in proportion to how much
// is left.
static int prorate(int n,int period_elapsed,int period,int granularity)
{
int time_remaining = period-period_elapsed;
double frac = ((double)time_remaining)/period;
// Add in maximum time in this interval that could have been
// missed due to polling interval (granularity).
frac += ((double)granularity)/period;
int answer = (int)floor(n*frac + 0.5);
if( (n > 0 && answer > n) || (n < 0 && answer < n) ) {
return n; // never exceed magnitude of n
}
if( answer*n < 0 ) { // never flip sign
return 0;
}
return answer;
}
void Defrag::poll_cancel(MachineSet &cancelled_machines)
{
if (!m_cancel_requirements.size())
{
return;
}
MachineSet draining_whole_machines;
std::string draining_whole_machines_ex(DRAINING_CONSTRAINT);
if ( ! m_cancel_requirements.empty()) {
formatstr_cat(draining_whole_machines_ex, " && (%s)", m_cancel_requirements.c_str());
}
int num_draining_whole_machines = countMachines(draining_whole_machines_ex.c_str(),
"<DEFRAG_CANCEL_REQUIREMENTS>", &draining_whole_machines);
if (num_draining_whole_machines)
{
dprintf(D_ALWAYS, "Of the whole machines, %d are in the draining state.\n", num_draining_whole_machines);
}
else
{ // Early exit: nothing to do.
return;
}
ClassAdList startdAds;
if (!queryMachines(DRAINING_CONSTRAINT, "DRAINING_CONSTRAINT <all draining slots>",startdAds,&m_drain_attrs))
{
return;
}
startdAds.Shuffle();
startdAds.Sort(StartdSortFunc,&m_rank_ad);
startdAds.Open();
unsigned int cancel_count = 0;
ClassAd *startd_ad_ptr;
while ( (startd_ad_ptr=startdAds.Next()) )
{
ClassAd &startd_ad = *startd_ad_ptr;
std::string machine;
std::string name;
startd_ad.LookupString(ATTR_NAME,name);
slotNameToDaemonName(name,machine);
if( !cancelled_machines.count(machine) && draining_whole_machines.count(machine) ) {
cancel_this_drain(startd_ad);
cancelled_machines.insert(machine);
cancel_count ++;
}
}
startdAds.Close();
dprintf(D_ALWAYS, "Cancelled draining of %u whole machines.\n", cancel_count);
}
void
Defrag::dprintf_set(const char *message, Defrag::MachineSet *m) const {
dprintf(D_ALWAYS, "%s\n", message);
for (Defrag::MachineSet::iterator it = m->begin(); it != m->end(); it++) {
dprintf(D_ALWAYS, "\t %s\n", (*it).c_str());
}
if (m->size() == 0) {
dprintf(D_ALWAYS, "(no machines)\n");
}
}
void Defrag::poll()
{
dprintf(D_FULLDEBUG,"Evaluating defragmentation policy.\n");
// If we crash during this polling cycle, we will have saved
// the time of the last poll, so the next cycle will be
// scheduled on the false assumption that a cycle ran now. In
// this way, we error on the side of draining too little
// rather than too much.
time_t now = time(NULL);
time_t prev = m_last_poll;
m_last_poll = now;
saveState();
m_stats.Tick();
int num_to_drain = m_draining_per_poll;
time_t last_hour = (prev / 3600)*3600;
time_t current_hour = (now / 3600)*3600;
time_t last_day = (prev / (3600*24))*3600*24;
time_t current_day = (now / (3600*24))*3600*24;
if( current_hour != last_hour ) {
num_to_drain += prorate(m_draining_per_poll_hour,now-current_hour,3600,m_polling_interval);
}
if( current_day != last_day ) {
num_to_drain += prorate(m_draining_per_poll_day,now-current_day,3600*24,m_polling_interval);
}
MachineSet draining_machines;
int num_draining = countMachines(DRAINING_CONSTRAINT,"<InternalDrainingConstraint>", &draining_machines);
m_stats.MachinesDraining = num_draining;
MachineSet whole_machines;
int num_whole_machines = countMachines(m_whole_machine_expr.c_str(),"DEFRAG_WHOLE_MACHINE_EXPR",&whole_machines);
m_stats.WholeMachines = num_whole_machines;
dprintf(D_ALWAYS,"There are currently %d draining and %d whole machines.\n",
num_draining,num_whole_machines);
// Calculate arrival rate of fully drained machines. This is a bit tricky because we poll.
// We count by finding the newly-arrived
// fully drained machines, and add to that count machines which are no-longer draining.
// This allows us to find machines that have fully drained, but were then claimed between
// polling cycles.
MachineSet new_machines;
MachineSet no_longer_whole_machines;
// Find newly-arrived machines
std::set_difference(whole_machines.begin(), whole_machines.end(),
m_prev_whole_machines.begin(), m_prev_whole_machines.end(),
std::inserter(new_machines, new_machines.begin()));
// Now, newly-departed machines
std::set_difference(m_prev_draining_machines.begin(), m_prev_draining_machines.end(),
draining_machines.begin(), draining_machines.end(),
std::inserter(no_longer_whole_machines, no_longer_whole_machines.begin()));
dprintf_set("Set of current whole machines is ", &whole_machines);
dprintf_set("Set of current draining machine is ", &draining_machines);
dprintf_set("Newly Arrived whole machines is ", &new_machines);
dprintf_set("Newly departed draining machines is ", &no_longer_whole_machines);
m_prev_draining_machines = draining_machines;
m_prev_whole_machines = whole_machines;
int newly_drained = new_machines.size() + no_longer_whole_machines.size();
double arrival_rate = 0.0;
// If there is an arrival...
if (newly_drained > 0) {
time_t current = time(0);
// And it isn't the first one since defrag boot...
if (m_last_whole_machine_arrival > 0) {
m_whole_machines_arrived += newly_drained;
time_t arrival_time = current - m_last_whole_machine_arrival;
if (arrival_time < 1) arrival_time = 1; // very unlikely, but just in case
m_whole_machine_arrival_sum += newly_drained * arrival_time;
arrival_rate = newly_drained / ((double)arrival_time);
dprintf(D_ALWAYS, "Arrival rate is %g machines/hour\n", arrival_rate * 3600.0);
}
m_last_whole_machine_arrival = current;
}
dprintf(D_ALWAYS, "Lifetime whole machines arrived: %d\n", m_whole_machines_arrived);
if (m_whole_machine_arrival_sum > 0) {
double lifetime_mean = m_whole_machines_arrived / m_whole_machine_arrival_sum;
dprintf(D_ALWAYS, "Lifetime mean arrival rate: %g machines / hour\n", 3600.0 * lifetime_mean);
if (newly_drained > 0) {
double diff = arrival_rate - lifetime_mean;
m_whole_machine_arrival_mean_squared += diff * diff;
}
double sd = sqrt(m_whole_machine_arrival_mean_squared / m_whole_machines_arrived);
dprintf(D_ALWAYS, "Lifetime mean arrival rate sd: %g\n", sd * 3600);
m_stats.MeanDrainedArrival = lifetime_mean;
m_stats.MeanDrainedArrivalSD = sd;
m_stats.DrainedMachines = m_whole_machines_arrived;
}
queryDrainingCost();
// If possible, cancel some drains.
MachineSet cancelled_machines;
poll_cancel(cancelled_machines);
if( num_to_drain <= 0 ) {
dprintf(D_ALWAYS,"Doing nothing, because number to drain in next %ds is calculated to be 0.\n",
m_polling_interval);
return;
}
if( (int)ceil(m_draining_per_hour) <= 0 ) {
dprintf(D_ALWAYS,"Doing nothing, because DEFRAG_DRAINING_MACHINES_PER_HOUR=%f\n",
m_draining_per_hour);
return;
}
if( m_max_draining == 0 ) {
dprintf(D_ALWAYS,"Doing nothing, because DEFRAG_MAX_CONCURRENT_DRAINING=0\n");
return;
}
if( m_max_whole_machines == 0 ) {
dprintf(D_ALWAYS,"Doing nothing, because DEFRAG_MAX_WHOLE_MACHINES=0\n");
return;
}
if( m_max_draining >= 0 ) {
if( num_draining >= m_max_draining ) {
dprintf(D_ALWAYS,"Doing nothing, because DEFRAG_MAX_CONCURRENT_DRAINING=%d and there are %d draining machines.\n",
m_max_draining, num_draining);
return;
}
else if( num_draining < 0 ) {
dprintf(D_ALWAYS,"Doing nothing, because DEFRAG_MAX_CONCURRENT_DRAINING=%d and the query to count draining machines failed.\n",
m_max_draining);
return;
}
}
if( m_max_whole_machines >= 0 ) {
if( num_whole_machines >= m_max_whole_machines ) {
dprintf(D_ALWAYS,"Doing nothing, because DEFRAG_MAX_WHOLE_MACHINES=%d and there are %d whole machines.\n",
m_max_whole_machines, num_whole_machines);
return;
}
}
// Even if m_max_whole_machines is -1 (infinite), we still need
// the list of whole machines in order to filter them out in
// the draining selection algorithm, so abort now if the
// whole machine query failed.
if( num_whole_machines < 0 ) {
dprintf(D_ALWAYS,"Doing nothing, because the query to find whole machines failed.\n");
return;
}
dprintf(D_ALWAYS,"Looking for %d machines to drain.\n",num_to_drain);
ClassAdList startdAds;
std::string requirements = "PartitionableSlot && Offline =!= true && Draining =!= true";
if ( ! m_defrag_requirements.empty()) {
formatstr_cat(requirements, " && (%s)", m_defrag_requirements.c_str());
}
if( !queryMachines(requirements.c_str(),"DEFRAG_REQUIREMENTS",startdAds,&m_drain_attrs) ) {
dprintf(D_ALWAYS,"Doing nothing, because the query to select machines matching DEFRAG_REQUIREMENTS failed.\n");
return;
}
startdAds.Shuffle();
startdAds.Sort(StartdSortFunc,&m_rank_ad);
startdAds.Open();
int num_drained = 0;
ClassAd *startd_ad_ptr;
MachineSet machines_done;
while( (startd_ad_ptr=startdAds.Next()) ) {
ClassAd &startd_ad = *startd_ad_ptr;
std::string machine;
std::string name;
startd_ad.LookupString(ATTR_NAME,name);
slotNameToDaemonName(name,machine);
// If we have already cancelled draining on this machine, ignore it for this cycle.
if( cancelled_machines.count(machine) ) {
dprintf(D_FULLDEBUG,
"Skipping %s: already cancelled draining of %s in this cycle.\n",
name.c_str(),machine.c_str());
continue;
}
if( machines_done.count(machine) ) {
dprintf(D_FULLDEBUG,
"Skipping %s: already attempted to drain %s in this cycle.\n",
name.c_str(),machine.c_str());
continue;
}
if( whole_machines.count(machine) ) {
dprintf(D_FULLDEBUG,
"Skipping %s: because it is already running as a whole machine.\n",
name.c_str());
continue;
}
if( drain_this(startd_ad) ) {
machines_done.insert(machine);
if( ++num_drained >= num_to_drain ) {
dprintf(D_ALWAYS,
"Drained maximum number of machines allowed in this cycle (%d).\n",
num_to_drain);
break;
}
}
}
startdAds.Close();
dprintf(D_ALWAYS,"Drained %d machines (wanted to drain %d machines).\n",
num_drained,num_to_drain);
dprintf(D_FULLDEBUG,"Done evaluating defragmentation policy.\n");
}
bool
Defrag::drain_this(const ClassAd &startd_ad)
{
std::string name;
startd_ad.LookupString(ATTR_NAME,name);
dprintf(D_ALWAYS,"Initiating %s draining of %s.\n",
m_draining_schedule_str.c_str(),name.c_str());
DCStartd startd( &startd_ad );
int graceful_completion = 0;
startd_ad.LookupInteger(ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_COMPLETION,graceful_completion);
int quick_completion = 0;
startd_ad.LookupInteger(ATTR_EXPECTED_MACHINE_QUICK_DRAINING_COMPLETION,quick_completion);
int graceful_badput = 0;
startd_ad.LookupInteger(ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_BADPUT,graceful_badput);
int quick_badput = 0;
startd_ad.LookupInteger(ATTR_EXPECTED_MACHINE_QUICK_DRAINING_BADPUT,quick_badput);
time_t now = time(NULL);
std::string draining_check_expr;
double badput_growth_tolerance = 1.25; // for now, this is hard-coded
int negligible_badput = 1200;
int negligible_deadline_slippage = 1200;
if( m_draining_schedule <= DRAIN_GRACEFUL ) {
dprintf(D_ALWAYS,"Expected draining completion time is %ds; expected draining badput is %d cpu-seconds\n",
(int)(graceful_completion-now),graceful_badput);
formatstr(draining_check_expr,"%s <= %d && %s <= %d",
ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_COMPLETION,
graceful_completion + negligible_deadline_slippage,
ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_BADPUT,
(int)(badput_growth_tolerance*graceful_badput) + negligible_badput);
}
else { // DRAIN_FAST and DRAIN_QUICK are effectively equivalent here
dprintf(D_ALWAYS,"Expected draining completion time is %ds; expected draining badput is %d cpu-seconds\n",
(int)(quick_completion-now),quick_badput);
formatstr(draining_check_expr,"%s <= %d && %s <= %d",
ATTR_EXPECTED_MACHINE_QUICK_DRAINING_COMPLETION,
quick_completion + negligible_deadline_slippage,
ATTR_EXPECTED_MACHINE_QUICK_DRAINING_BADPUT,
(int)(badput_growth_tolerance*quick_badput) + negligible_badput);
}
std::string request_id;
bool rval = startd.drainJobs( m_draining_schedule, "Defrag", DRAIN_RESUME_ON_COMPLETION,
draining_check_expr.c_str(), m_draining_start_expr.c_str(), request_id );
if( !rval ) {
dprintf(D_ALWAYS,"Failed to send request to drain %s: %s\n",startd.name(),startd.error());
m_stats.DrainFailures += 1;
} else {
m_stats.DrainSuccesses += 1;
}
defrag_log.record_drain( name, m_draining_schedule_str );
return rval ? true : false;
}
bool
Defrag::cancel_this_drain(const ClassAd &startd_ad)
{
std::string name;
startd_ad.LookupString(ATTR_NAME,name);
dprintf(D_ALWAYS, "Cancel draining of %s.\n", name.c_str());
DCStartd startd( &startd_ad );
bool rval = startd.cancelDrainJobs( NULL );
if ( rval ) {
dprintf(D_FULLDEBUG, "Sent request to cancel draining on %s\n", startd.name());
} else {
dprintf(D_ALWAYS, "Unable to cancel draining on %s: %s\n", startd.name(), startd.error());
}
defrag_log.record_cancel( startd.name() );
return rval;
}
void
Defrag::publish(ClassAd *ad)
{
char *valid_name = build_valid_daemon_name(m_defrag_name.c_str());
ASSERT( valid_name );
m_daemon_name = valid_name;
free(valid_name);
SetMyTypeName(*ad, "Defrag");
SetTargetTypeName(*ad, "");
ad->Assign(ATTR_NAME,m_daemon_name);
defrag_log.write_to_ad(ad);
m_stats.Tick();
m_stats.Publish(*ad);
daemonCore->publish(ad);
}
void
Defrag::updateCollector() {
publish(&m_public_ad);
daemonCore->sendUpdates(UPDATE_AD_GENERIC, &m_public_ad);
}
void
Defrag::invalidatePublicAd() {
ClassAd invalidate_ad;
std::string line;
SetMyTypeName(invalidate_ad, QUERY_ADTYPE);
SetTargetTypeName(invalidate_ad, "Defrag");
formatstr(line,"%s == \"%s\"", ATTR_NAME, m_daemon_name.c_str());
invalidate_ad.AssignExpr(ATTR_REQUIREMENTS, line.c_str());
invalidate_ad.Assign(ATTR_NAME, m_daemon_name);
daemonCore->sendUpdates(INVALIDATE_ADS_GENERIC, &invalidate_ad, NULL, false);
}
|
.586
.model flat, stdcall
.data
my_byte db 01110111b
one db 1b
.code
start:
mov al, my_byte
shl al, 1
jnc final
not al
rcr al, 1
ret
final:
rcr al, 1
ret
end start
|
; A098011: 10^a(n) + 1 = A088773(n).
; 1,1,2,3,6,12,24,48,96,192,384,768,1536,3072,6144,12288,24576,49152,98304,196608,393216,786432,1572864,3145728,6291456,12582912,25165824,50331648,100663296,201326592,402653184,805306368,1610612736,3221225472,6442450944,12884901888,25769803776,51539607552,103079215104,206158430208,412316860416,824633720832,1649267441664,3298534883328,6597069766656,13194139533312,26388279066624,52776558133248,105553116266496,211106232532992,422212465065984,844424930131968,1688849860263936,3377699720527872,6755399441055744,13510798882111488,27021597764222976,54043195528445952,108086391056891904,216172782113783808,432345564227567616,864691128455135232,1729382256910270464,3458764513820540928,6917529027641081856,13835058055282163712,27670116110564327424,55340232221128654848,110680464442257309696,221360928884514619392,442721857769029238784,885443715538058477568,1770887431076116955136,3541774862152233910272,7083549724304467820544,14167099448608935641088,28334198897217871282176,56668397794435742564352,113336795588871485128704,226673591177742970257408,453347182355485940514816,906694364710971881029632,1813388729421943762059264,3626777458843887524118528,7253554917687775048237056,14507109835375550096474112,29014219670751100192948224,58028439341502200385896448,116056878683004400771792896,232113757366008801543585792,464227514732017603087171584,928455029464035206174343168,1856910058928070412348686336,3713820117856140824697372672,7427640235712281649394745344,14855280471424563298789490688,29710560942849126597578981376,59421121885698253195157962752,118842243771396506390315925504,237684487542793012780631851008
mov $1,2
pow $1,$0
mul $1,3
sub $1,4
div $1,8
add $1,1
mov $0,$1
|
; Block of random data used by Oidos.
; Can also be useful as a 3D noise texture.
%include "platform.inc"
global PUBLIC_SYM(Oidos_FillRandomData)
global PUBLIC_SYM(Oidos_RandomData)
global ID3D11Texture2D_ID
global ?ID3D11Texture2D_ID@@3U_GUID@@A
%define NOISESIZE 64
SECTION_DATA(d3dtex2d) align=4
; Effectively random seed for the pseudo-random number generation.
; If you are using D3D11, you can re-use this GUID.
ID3D11Texture2D_ID:
?ID3D11Texture2D_ID@@3U_GUID@@A:
db 0xF2,0xAA,0x15,0x6F, 0x08,0xD2,0x89,0x4E, 0x9A,0xB4,0x48,0x95, 0x35,0xD3,0x4F,0x9C
SECTION_BSS(randdata) align=4
PUBLIC_SYM(Oidos_RandomData):
.align16:
resd NOISESIZE*NOISESIZE*NOISESIZE
SECTION_TEXT(fillrand) align=1
PUBLIC_SYM(Oidos_FillRandomData):
mov eax, PUBLIC_SYM(Oidos_RandomData)
.loop:
mov edx, ID3D11Texture2D_ID
mov ecx, [edx]
ror ecx, cl
add ecx, [edx+4]
mov [edx], ecx
xor [eax], ecx
add edx, byte 4
mov ecx, [edx]
ror ecx, cl
add ecx, [edx+4]
mov [edx], ecx
xor [eax], ecx
add edx, byte 4
mov ecx, [edx]
ror ecx, cl
add ecx, [edx+4]
mov [edx], ecx
xor [eax], ecx
add eax, byte 4
cmp eax, PUBLIC_SYM(Oidos_RandomData)+NOISESIZE*NOISESIZE*NOISESIZE*4
jb .loop
ret
|
; unsigned char zx_tape_verify_block(void *dst, unsigned int len, unsigned char type)
SECTION code_clib
SECTION code_arch
PUBLIC _zx_tape_verify_block_callee
EXTERN asm_zx_tape_verify_block
_zx_tape_verify_block_callee:
pop hl
pop bc
pop de
dec sp
ex (sp),hl
ld a,h
l_zx_tape_verify_block_callee:
push bc
ex (sp),iy
call asm_zx_tape_verify_block
pop iy
ret
|
0x0000 (0x000000) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x0001 (0x000002) 0x2922- f:00024 d: 290 | OR[290] = A
0x0002 (0x000004) 0x0400- f:00002 d: 0 | I = 0
0x0003 (0x000006) 0x0000- f:00000 d: 0 | PASS
0x0004 (0x000008) 0x2118- f:00020 d: 280 | A = OR[280]
0x0005 (0x00000A) 0x1409- f:00012 d: 9 | A = A + 9 (0x0009)
0x0006 (0x00000C) 0x289D- f:00024 d: 157 | OR[157] = A
0x0007 (0x00000E) 0x7E00-0x1FFD f:00077 d: 0 | R = OR[0]+8189 (0x1FFD)
0x0009 (0x000012) 0x209C- f:00020 d: 156 | A = OR[156]
0x000A (0x000014) 0x8402- f:00102 d: 2 | P = P + 2 (0x000C), A = 0
0x000B (0x000016) 0x701E- f:00070 d: 30 | P = P + 30 (0x0029)
0x000C (0x000018) 0x3118- f:00030 d: 280 | A = (OR[280])
0x000D (0x00001A) 0x1601- f:00013 d: 1 | A = A - 1 (0x0001)
0x000E (0x00001C) 0x8402- f:00102 d: 2 | P = P + 2 (0x0010), A = 0
0x000F (0x00001E) 0x7007- f:00070 d: 7 | P = P + 7 (0x0016)
0x0010 (0x000020) 0x102A- f:00010 d: 42 | A = 42 (0x002A)
0x0011 (0x000022) 0x2925- f:00024 d: 293 | OR[293] = A
0x0012 (0x000024) 0x1125- f:00010 d: 293 | A = 293 (0x0125)
0x0013 (0x000026) 0x5800- f:00054 d: 0 | B = A
0x0014 (0x000028) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x0015 (0x00002A) 0x7C09- f:00076 d: 9 | R = OR[9]
0x0016 (0x00002C) 0x2118- f:00020 d: 280 | A = OR[280]
0x0017 (0x00002E) 0x140C- f:00012 d: 12 | A = A + 12 (0x000C)
0x0018 (0x000030) 0x2913- f:00024 d: 275 | OR[275] = A
0x0019 (0x000032) 0x1001- f:00010 d: 1 | A = 1 (0x0001)
0x001A (0x000034) 0x2925- f:00024 d: 293 | OR[293] = A
0x001B (0x000036) 0x2113- f:00020 d: 275 | A = OR[275]
0x001C (0x000038) 0x2926- f:00024 d: 294 | OR[294] = A
0x001D (0x00003A) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x001E (0x00003C) 0x2927- f:00024 d: 295 | OR[295] = A
0x001F (0x00003E) 0x1125- f:00010 d: 293 | A = 293 (0x0125)
0x0020 (0x000040) 0x5800- f:00054 d: 0 | B = A
0x0021 (0x000042) 0x1800-0x1B18 f:00014 d: 0 | A = 6936 (0x1B18)
0x0023 (0x000046) 0x7C09- f:00076 d: 9 | R = OR[9]
0x0024 (0x000048) 0x2006- f:00020 d: 6 | A = OR[6]
0x0025 (0x00004A) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x0026 (0x00004C) 0x2908- f:00024 d: 264 | OR[264] = A
0x0027 (0x00004E) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0028 (0x000050) 0x7226- f:00071 d: 38 | P = P - 38 (0x0002)
0x0029 (0x000052) 0x209C- f:00020 d: 156 | A = OR[156]
0x002A (0x000054) 0x291C- f:00024 d: 284 | OR[284] = A
0x002B (0x000056) 0x0600- f:00003 d: 0 | I = 1
0x002C (0x000058) 0x211C- f:00020 d: 284 | A = OR[284]
0x002D (0x00005A) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x002E (0x00005C) 0x2908- f:00024 d: 264 | OR[264] = A
0x002F (0x00005E) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0030 (0x000060) 0x080C- f:00004 d: 12 | A = A > 12 (0x000C)
0x0031 (0x000062) 0x291D- f:00024 d: 285 | OR[285] = A
0x0032 (0x000064) 0x211D- f:00020 d: 285 | A = OR[285]
0x0033 (0x000066) 0x1601- f:00013 d: 1 | A = A - 1 (0x0001)
0x0034 (0x000068) 0x8405- f:00102 d: 5 | P = P + 5 (0x0039), A = 0
0x0035 (0x00006A) 0x211D- f:00020 d: 285 | A = OR[285]
0x0036 (0x00006C) 0x1602- f:00013 d: 2 | A = A - 2 (0x0002)
0x0037 (0x00006E) 0x8402- f:00102 d: 2 | P = P + 2 (0x0039), A = 0
0x0038 (0x000070) 0x702D- f:00070 d: 45 | P = P + 45 (0x0065)
0x0039 (0x000072) 0x211C- f:00020 d: 284 | A = OR[284]
0x003A (0x000074) 0x140C- f:00012 d: 12 | A = A + 12 (0x000C)
0x003B (0x000076) 0x291E- f:00024 d: 286 | OR[286] = A
0x003C (0x000078) 0x211C- f:00020 d: 284 | A = OR[284]
0x003D (0x00007A) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x003E (0x00007C) 0x2908- f:00024 d: 264 | OR[264] = A
0x003F (0x00007E) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0040 (0x000080) 0x12FF- f:00011 d: 255 | A = A & 255 (0x00FF)
0x0041 (0x000082) 0x291F- f:00024 d: 287 | OR[287] = A
0x0042 (0x000084) 0x2118- f:00020 d: 280 | A = OR[280]
0x0043 (0x000086) 0x1405- f:00012 d: 5 | A = A + 5 (0x0005)
0x0044 (0x000088) 0x2908- f:00024 d: 264 | OR[264] = A
0x0045 (0x00008A) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0046 (0x00008C) 0x1202- f:00011 d: 2 | A = A & 2 (0x0002)
0x0047 (0x00008E) 0x2908- f:00024 d: 264 | OR[264] = A
0x0048 (0x000090) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x0049 (0x000092) 0x2708- f:00023 d: 264 | A = A - OR[264]
0x004A (0x000094) 0x8602- f:00103 d: 2 | P = P + 2 (0x004C), A # 0
0x004B (0x000096) 0x7003- f:00070 d: 3 | P = P + 3 (0x004E)
0x004C (0x000098) 0x746F- f:00072 d: 111 | R = P + 111 (0x00BB)
0x004D (0x00009A) 0x7017- f:00070 d: 23 | P = P + 23 (0x0064)
0x004E (0x00009C) 0x211F- f:00020 d: 287 | A = OR[287]
0x004F (0x00009E) 0x8602- f:00103 d: 2 | P = P + 2 (0x0051), A # 0
0x0050 (0x0000A0) 0x7014- f:00070 d: 20 | P = P + 20 (0x0064)
0x0051 (0x0000A2) 0x1012- f:00010 d: 18 | A = 18 (0x0012)
0x0052 (0x0000A4) 0x2925- f:00024 d: 293 | OR[293] = A
0x0053 (0x0000A6) 0x211B- f:00020 d: 283 | A = OR[283]
0x0054 (0x0000A8) 0x2926- f:00024 d: 294 | OR[294] = A
0x0055 (0x0000AA) 0x211E- f:00020 d: 286 | A = OR[286]
0x0056 (0x0000AC) 0x2927- f:00024 d: 295 | OR[295] = A
0x0057 (0x0000AE) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x0058 (0x0000B0) 0x2928- f:00024 d: 296 | OR[296] = A
0x0059 (0x0000B2) 0x211F- f:00020 d: 287 | A = OR[287]
0x005A (0x0000B4) 0x2929- f:00024 d: 297 | OR[297] = A
0x005B (0x0000B6) 0x1125- f:00010 d: 293 | A = 293 (0x0125)
0x005C (0x0000B8) 0x5800- f:00054 d: 0 | B = A
0x005D (0x0000BA) 0x1800-0x1B18 f:00014 d: 0 | A = 6936 (0x1B18)
0x005F (0x0000BE) 0x7C09- f:00076 d: 9 | R = OR[9]
0x0060 (0x0000C0) 0x2006- f:00020 d: 6 | A = OR[6]
0x0061 (0x0000C2) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x0062 (0x0000C4) 0x2908- f:00024 d: 264 | OR[264] = A
0x0063 (0x0000C6) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0064 (0x0000C8) 0x702D- f:00070 d: 45 | P = P + 45 (0x0091)
0x0065 (0x0000CA) 0x211D- f:00020 d: 285 | A = OR[285]
0x0066 (0x0000CC) 0x1605- f:00013 d: 5 | A = A - 5 (0x0005)
0x0067 (0x0000CE) 0x8402- f:00102 d: 2 | P = P + 2 (0x0069), A = 0
0x0068 (0x0000D0) 0x7029- f:00070 d: 41 | P = P + 41 (0x0091)
0x0069 (0x0000D2) 0x211C- f:00020 d: 284 | A = OR[284]
0x006A (0x0000D4) 0x140C- f:00012 d: 12 | A = A + 12 (0x000C)
0x006B (0x0000D6) 0x2908- f:00024 d: 264 | OR[264] = A
0x006C (0x0000D8) 0x3108- f:00030 d: 264 | A = (OR[264])
0x006D (0x0000DA) 0x2913- f:00024 d: 275 | OR[275] = A
0x006E (0x0000DC) 0x2118- f:00020 d: 280 | A = OR[280]
0x006F (0x0000DE) 0x1402- f:00012 d: 2 | A = A + 2 (0x0002)
0x0070 (0x0000E0) 0x2908- f:00024 d: 264 | OR[264] = A
0x0071 (0x0000E2) 0x2113- f:00020 d: 275 | A = OR[275]
0x0072 (0x0000E4) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x0073 (0x0000E6) 0x211C- f:00020 d: 284 | A = OR[284]
0x0074 (0x0000E8) 0x140D- f:00012 d: 13 | A = A + 13 (0x000D)
0x0075 (0x0000EA) 0x2908- f:00024 d: 264 | OR[264] = A
0x0076 (0x0000EC) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0077 (0x0000EE) 0x2913- f:00024 d: 275 | OR[275] = A
0x0078 (0x0000F0) 0x2118- f:00020 d: 280 | A = OR[280]
0x0079 (0x0000F2) 0x1403- f:00012 d: 3 | A = A + 3 (0x0003)
0x007A (0x0000F4) 0x2908- f:00024 d: 264 | OR[264] = A
0x007B (0x0000F6) 0x2113- f:00020 d: 275 | A = OR[275]
0x007C (0x0000F8) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x007D (0x0000FA) 0x211C- f:00020 d: 284 | A = OR[284]
0x007E (0x0000FC) 0x140E- f:00012 d: 14 | A = A + 14 (0x000E)
0x007F (0x0000FE) 0x2908- f:00024 d: 264 | OR[264] = A
0x0080 (0x000100) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0081 (0x000102) 0x2913- f:00024 d: 275 | OR[275] = A
0x0082 (0x000104) 0x2118- f:00020 d: 280 | A = OR[280]
0x0083 (0x000106) 0x1404- f:00012 d: 4 | A = A + 4 (0x0004)
0x0084 (0x000108) 0x2908- f:00024 d: 264 | OR[264] = A
0x0085 (0x00010A) 0x2113- f:00020 d: 275 | A = OR[275]
0x0086 (0x00010C) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x0087 (0x00010E) 0x211C- f:00020 d: 284 | A = OR[284]
0x0088 (0x000110) 0x140F- f:00012 d: 15 | A = A + 15 (0x000F)
0x0089 (0x000112) 0x2908- f:00024 d: 264 | OR[264] = A
0x008A (0x000114) 0x3108- f:00030 d: 264 | A = (OR[264])
0x008B (0x000116) 0x2913- f:00024 d: 275 | OR[275] = A
0x008C (0x000118) 0x2118- f:00020 d: 280 | A = OR[280]
0x008D (0x00011A) 0x1405- f:00012 d: 5 | A = A + 5 (0x0005)
0x008E (0x00011C) 0x2908- f:00024 d: 264 | OR[264] = A
0x008F (0x00011E) 0x2113- f:00020 d: 275 | A = OR[275]
0x0090 (0x000120) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x0091 (0x000122) 0x211C- f:00020 d: 284 | A = OR[284]
0x0092 (0x000124) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x0093 (0x000126) 0x2908- f:00024 d: 264 | OR[264] = A
0x0094 (0x000128) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0095 (0x00012A) 0x0E05- f:00007 d: 5 | A = A << 5 (0x0005)
0x0096 (0x00012C) 0x0A04- f:00005 d: 4 | A = A < 4 (0x0004)
0x0097 (0x00012E) 0x1401- f:00012 d: 1 | A = A + 1 (0x0001)
0x0098 (0x000130) 0x0C09- f:00006 d: 9 | A = A >> 9 (0x0009)
0x0099 (0x000132) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x009A (0x000134) 0x211C- f:00020 d: 284 | A = OR[284]
0x009B (0x000136) 0x1409- f:00012 d: 9 | A = A + 9 (0x0009)
0x009C (0x000138) 0x2908- f:00024 d: 264 | OR[264] = A
0x009D (0x00013A) 0x3108- f:00030 d: 264 | A = (OR[264])
0x009E (0x00013C) 0x2913- f:00024 d: 275 | OR[275] = A
0x009F (0x00013E) 0x211C- f:00020 d: 284 | A = OR[284]
0x00A0 (0x000140) 0x1408- f:00012 d: 8 | A = A + 8 (0x0008)
0x00A1 (0x000142) 0x2908- f:00024 d: 264 | OR[264] = A
0x00A2 (0x000144) 0x2113- f:00020 d: 275 | A = OR[275]
0x00A3 (0x000146) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x00A4 (0x000148) 0x1800-0x38ED f:00014 d: 0 | A = 14573 (0x38ED)
0x00A6 (0x00014C) 0x2908- f:00024 d: 264 | OR[264] = A
0x00A7 (0x00014E) 0x3108- f:00030 d: 264 | A = (OR[264])
0x00A8 (0x000150) 0x2913- f:00024 d: 275 | OR[275] = A
0x00A9 (0x000152) 0x211C- f:00020 d: 284 | A = OR[284]
0x00AA (0x000154) 0x1409- f:00012 d: 9 | A = A + 9 (0x0009)
0x00AB (0x000156) 0x2908- f:00024 d: 264 | OR[264] = A
0x00AC (0x000158) 0x2113- f:00020 d: 275 | A = OR[275]
0x00AD (0x00015A) 0x3908- f:00034 d: 264 | (OR[264]) = A
0x00AE (0x00015C) 0x101C- f:00010 d: 28 | A = 28 (0x001C)
0x00AF (0x00015E) 0x2925- f:00024 d: 293 | OR[293] = A
0x00B0 (0x000160) 0x211C- f:00020 d: 284 | A = OR[284]
0x00B1 (0x000162) 0x2926- f:00024 d: 294 | OR[294] = A
0x00B2 (0x000164) 0x1125- f:00010 d: 293 | A = 293 (0x0125)
0x00B3 (0x000166) 0x5800- f:00054 d: 0 | B = A
0x00B4 (0x000168) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x00B5 (0x00016A) 0x7C09- f:00076 d: 9 | R = OR[9]
0x00B6 (0x00016C) 0x2006- f:00020 d: 6 | A = OR[6]
0x00B7 (0x00016E) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x00B8 (0x000170) 0x2908- f:00024 d: 264 | OR[264] = A
0x00B9 (0x000172) 0x3108- f:00030 d: 264 | A = (OR[264])
0x00BA (0x000174) 0x72B8- f:00071 d: 184 | P = P - 184 (0x0002)
0x00BB (0x000176) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x00BC (0x000178) 0x2920- f:00024 d: 288 | OR[288] = A
0x00BD (0x00017A) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x00BE (0x00017C) 0x2921- f:00024 d: 289 | OR[289] = A
0x00BF (0x00017E) 0x211F- f:00020 d: 287 | A = OR[287]
0x00C0 (0x000180) 0x8433- f:00102 d: 51 | P = P + 51 (0x00F3), A = 0
0x00C1 (0x000182) 0x2120- f:00020 d: 288 | A = OR[288]
0x00C2 (0x000184) 0x0801- f:00004 d: 1 | A = A > 1 (0x0001)
0x00C3 (0x000186) 0x251E- f:00022 d: 286 | A = A + OR[286]
0x00C4 (0x000188) 0x290D- f:00024 d: 269 | OR[269] = A
0x00C5 (0x00018A) 0x310D- f:00030 d: 269 | A = (OR[269])
0x00C6 (0x00018C) 0x290D- f:00024 d: 269 | OR[269] = A
0x00C7 (0x00018E) 0x2120- f:00020 d: 288 | A = OR[288]
0x00C8 (0x000190) 0x1201- f:00011 d: 1 | A = A & 1 (0x0001)
0x00C9 (0x000192) 0x2908- f:00024 d: 264 | OR[264] = A
0x00CA (0x000194) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x00CB (0x000196) 0x2708- f:00023 d: 264 | A = A - OR[264]
0x00CC (0x000198) 0x8604- f:00103 d: 4 | P = P + 4 (0x00D0), A # 0
0x00CD (0x00019A) 0x210D- f:00020 d: 269 | A = OR[269]
0x00CE (0x00019C) 0x0808- f:00004 d: 8 | A = A > 8 (0x0008)
0x00CF (0x00019E) 0x290D- f:00024 d: 269 | OR[269] = A
0x00D0 (0x0001A0) 0x210D- f:00020 d: 269 | A = OR[269]
0x00D1 (0x0001A2) 0x12FF- f:00011 d: 255 | A = A & 255 (0x00FF)
0x00D2 (0x0001A4) 0x2924- f:00024 d: 292 | OR[292] = A
0x00D3 (0x0001A6) 0x2D20- f:00026 d: 288 | OR[288] = OR[288] + 1
0x00D4 (0x0001A8) 0x2F1F- f:00027 d: 287 | OR[287] = OR[287] - 1
0x00D5 (0x0001AA) 0x2124- f:00020 d: 292 | A = OR[292]
0x00D6 (0x0001AC) 0x1609- f:00013 d: 9 | A = A - 9 (0x0009)
0x00D7 (0x0001AE) 0x8402- f:00102 d: 2 | P = P + 2 (0x00D9), A = 0
0x00D8 (0x0001B0) 0x7013- f:00070 d: 19 | P = P + 19 (0x00EB)
0x00D9 (0x0001B2) 0x2122- f:00020 d: 290 | A = OR[290]
0x00DA (0x0001B4) 0x1408- f:00012 d: 8 | A = A + 8 (0x0008)
0x00DB (0x0001B6) 0x1A00-0xFFF8 f:00015 d: 0 | A = A & 65528 (0xFFF8)
0x00DD (0x0001BA) 0x2722- f:00023 d: 290 | A = A - OR[290]
0x00DE (0x0001BC) 0x2923- f:00024 d: 291 | OR[291] = A
0x00DF (0x0001BE) 0x2123- f:00020 d: 291 | A = OR[291]
0x00E0 (0x0001C0) 0x8603- f:00103 d: 3 | P = P + 3 (0x00E3), A # 0
0x00E1 (0x0001C2) 0x1008- f:00010 d: 8 | A = 8 (0x0008)
0x00E2 (0x0001C4) 0x2923- f:00024 d: 291 | OR[291] = A
0x00E3 (0x0001C6) 0x1020- f:00010 d: 32 | A = 32 (0x0020)
0x00E4 (0x0001C8) 0x2924- f:00024 d: 292 | OR[292] = A
0x00E5 (0x0001CA) 0x2123- f:00020 d: 291 | A = OR[291]
0x00E6 (0x0001CC) 0x8404- f:00102 d: 4 | P = P + 4 (0x00EA), A = 0
0x00E7 (0x0001CE) 0x741A- f:00072 d: 26 | R = P + 26 (0x0101)
0x00E8 (0x0001D0) 0x2F23- f:00027 d: 291 | OR[291] = OR[291] - 1
0x00E9 (0x0001D2) 0x7204- f:00071 d: 4 | P = P - 4 (0x00E5)
0x00EA (0x0001D4) 0x7008- f:00070 d: 8 | P = P + 8 (0x00F2)
0x00EB (0x0001D6) 0x2124- f:00020 d: 292 | A = OR[292]
0x00EC (0x0001D8) 0x160A- f:00013 d: 10 | A = A - 10 (0x000A)
0x00ED (0x0001DA) 0x8402- f:00102 d: 2 | P = P + 2 (0x00EF), A = 0
0x00EE (0x0001DC) 0x7003- f:00070 d: 3 | P = P + 3 (0x00F1)
0x00EF (0x0001DE) 0x7409- f:00072 d: 9 | R = P + 9 (0x00F8)
0x00F0 (0x0001E0) 0x7002- f:00070 d: 2 | P = P + 2 (0x00F2)
0x00F1 (0x0001E2) 0x7410- f:00072 d: 16 | R = P + 16 (0x0101)
0x00F2 (0x0001E4) 0x7233- f:00071 d: 51 | P = P - 51 (0x00BF)
0x00F3 (0x0001E6) 0x211D- f:00020 d: 285 | A = OR[285]
0x00F4 (0x0001E8) 0x1602- f:00013 d: 2 | A = A - 2 (0x0002)
0x00F5 (0x0001EA) 0x9403- f:00112 d: 3 | R = P + 3 (0x00F8), A = 0
0x00F6 (0x0001EC) 0x7429- f:00072 d: 41 | R = P + 41 (0x011F)
0x00F7 (0x0001EE) 0x0200- f:00001 d: 0 | EXIT
0x00F8 (0x0001F0) 0x100A- f:00010 d: 10 | A = 10 (0x000A)
0x00F9 (0x0001F2) 0x2924- f:00024 d: 292 | OR[292] = A
0x00FA (0x0001F4) 0x7407- f:00072 d: 7 | R = P + 7 (0x0101)
0x00FB (0x0001F6) 0x100D- f:00010 d: 13 | A = 13 (0x000D)
0x00FC (0x0001F8) 0x2924- f:00024 d: 292 | OR[292] = A
0x00FD (0x0001FA) 0x7404- f:00072 d: 4 | R = P + 4 (0x0101)
0x00FE (0x0001FC) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x00FF (0x0001FE) 0x2922- f:00024 d: 290 | OR[290] = A
0x0100 (0x000200) 0x0200- f:00001 d: 0 | EXIT
0x0101 (0x000202) 0x2D22- f:00026 d: 290 | OR[290] = OR[290] + 1
0x0102 (0x000204) 0x2124- f:00020 d: 292 | A = OR[292]
0x0103 (0x000206) 0x12FF- f:00011 d: 255 | A = A & 255 (0x00FF)
0x0104 (0x000208) 0x290D- f:00024 d: 269 | OR[269] = A
0x0105 (0x00020A) 0x2121- f:00020 d: 289 | A = OR[289]
0x0106 (0x00020C) 0x0801- f:00004 d: 1 | A = A > 1 (0x0001)
0x0107 (0x00020E) 0x2519- f:00022 d: 281 | A = A + OR[281]
0x0108 (0x000210) 0x290E- f:00024 d: 270 | OR[270] = A
0x0109 (0x000212) 0x2121- f:00020 d: 289 | A = OR[289]
0x010A (0x000214) 0x1201- f:00011 d: 1 | A = A & 1 (0x0001)
0x010B (0x000216) 0x2908- f:00024 d: 264 | OR[264] = A
0x010C (0x000218) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x010D (0x00021A) 0x2708- f:00023 d: 264 | A = A - OR[264]
0x010E (0x00021C) 0x8607- f:00103 d: 7 | P = P + 7 (0x0115), A # 0
0x010F (0x00021E) 0x310E- f:00030 d: 270 | A = (OR[270])
0x0110 (0x000220) 0x0A09- f:00005 d: 9 | A = A < 9 (0x0009)
0x0111 (0x000222) 0x250D- f:00022 d: 269 | A = A + OR[269]
0x0112 (0x000224) 0x0C09- f:00006 d: 9 | A = A >> 9 (0x0009)
0x0113 (0x000226) 0x390E- f:00034 d: 270 | (OR[270]) = A
0x0114 (0x000228) 0x7006- f:00070 d: 6 | P = P + 6 (0x011A)
0x0115 (0x00022A) 0x310E- f:00030 d: 270 | A = (OR[270])
0x0116 (0x00022C) 0x1A00-0xFF00 f:00015 d: 0 | A = A & 65280 (0xFF00)
0x0118 (0x000230) 0x250D- f:00022 d: 269 | A = A + OR[269]
0x0119 (0x000232) 0x390E- f:00034 d: 270 | (OR[270]) = A
0x011A (0x000234) 0x2D21- f:00026 d: 289 | OR[289] = OR[289] + 1
0x011B (0x000236) 0x2121- f:00020 d: 289 | A = OR[289]
0x011C (0x000238) 0x271A- f:00023 d: 282 | A = A - OR[282]
0x011D (0x00023A) 0x9402- f:00112 d: 2 | R = P + 2 (0x011F), A = 0
0x011E (0x00023C) 0x0200- f:00001 d: 0 | EXIT
0x011F (0x00023E) 0x2121- f:00020 d: 289 | A = OR[289]
0x0120 (0x000240) 0x8602- f:00103 d: 2 | P = P + 2 (0x0122), A # 0
0x0121 (0x000242) 0x0200- f:00001 d: 0 | EXIT
0x0122 (0x000244) 0x1012- f:00010 d: 18 | A = 18 (0x0012)
0x0123 (0x000246) 0x2925- f:00024 d: 293 | OR[293] = A
0x0124 (0x000248) 0x211B- f:00020 d: 283 | A = OR[283]
0x0125 (0x00024A) 0x2926- f:00024 d: 294 | OR[294] = A
0x0126 (0x00024C) 0x2119- f:00020 d: 281 | A = OR[281]
0x0127 (0x00024E) 0x2927- f:00024 d: 295 | OR[295] = A
0x0128 (0x000250) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x0129 (0x000252) 0x2928- f:00024 d: 296 | OR[296] = A
0x012A (0x000254) 0x2121- f:00020 d: 289 | A = OR[289]
0x012B (0x000256) 0x2929- f:00024 d: 297 | OR[297] = A
0x012C (0x000258) 0x1125- f:00010 d: 293 | A = 293 (0x0125)
0x012D (0x00025A) 0x5800- f:00054 d: 0 | B = A
0x012E (0x00025C) 0x1800-0x1B18 f:00014 d: 0 | A = 6936 (0x1B18)
0x0130 (0x000260) 0x7C09- f:00076 d: 9 | R = OR[9]
0x0131 (0x000262) 0x2006- f:00020 d: 6 | A = OR[6]
0x0132 (0x000264) 0x140B- f:00012 d: 11 | A = A + 11 (0x000B)
0x0133 (0x000266) 0x2908- f:00024 d: 264 | OR[264] = A
0x0134 (0x000268) 0x3108- f:00030 d: 264 | A = (OR[264])
0x0135 (0x00026A) 0x1000- f:00010 d: 0 | A = 0 (0x0000)
0x0136 (0x00026C) 0x2921- f:00024 d: 289 | OR[289] = A
0x0137 (0x00026E) 0x0200- f:00001 d: 0 | EXIT
0x0138 (0x000270) 0x0000- f:00000 d: 0 | PASS
0x0139 (0x000272) 0x0000- f:00000 d: 0 | PASS
0x013A (0x000274) 0x0000- f:00000 d: 0 | PASS
0x013B (0x000276) 0x0000- f:00000 d: 0 | PASS
|
; Luis Maya
; CS 218 Section #1002
; Assignment #10
; Support Functions.
; Provided Template
; -----
; Function getIterations()
; Gets, checks, converts, and returns iteration
; count and rotation speed from the command line.
; Function drawChaos()
; Calculates and plots Chaos algorithm
; ---------------------------------------------------------
; MACROS (if any) GO HERE
; *****************************************************************************
; Macro, ternary2int, to convert an ASCII string (STR_SIZE characters,
; byte-size, leading sign, right justified, blank filled, NULL terminated)
; representing the signed ternary value into a signed base-10 integer.
; Assumes valid/correct data. As such, no error checking is performed.
; NOTE, addresses are passed. For example:
; mov rbx, %1 -> copies 1st argument address to rbx
; mov dword [%2], eax -> sets 2nd argument.
%macro ternary2int 2
push rbp
mov rbp, rsp
sub rsp, 8
push rcx
push rdx
mov dword [%2], 0 ; Clear ans value
mov dword [rbp - 4], 0 ; tempInt; Move 0 into temp [rbp - 4]
mov dword [rbp - 8], 3 ; numThree; Move 3 into [rbp - 8]
mov rax, 0 ; Clear rax
mov rdx, 0
mov rcx, 0
mov r10, 0 ; Clear r10, will be used as counter
%%spaceCheck:
movzx eax, byte [%1 + r10] ; Move current character of string[i] into eax
cmp eax, " " ; Compare current character with " "
jne %%controlLoop ; If current character is not " " jump to controlLoop
inc r10 ; Increase counter
jmp %%spaceCheck ; Jump to spaceCheck and check next character
%%controlLoop:
cmp eax, "-" ; Check if number is negative
je %%rmNegSign ; Jump to rmNegSign if number is negative
cmp eax, "0" ; Check if current charcter is a number
jae %%positiveLoop ; If charcter is number, jump to positiveLoop
inc r10 ; Update counter to access first digit if identified as postive
%%positiveLoop:
movzx eax, byte [%1 + r10] ; Move first digit into eax
cmp eax, NULL ; Check if at end of string
je %%controlDone ; Jump to controlDone if current character is equal to NULL
cmp eax, "0" ; Check if current character is number
jae %%postiveSum ; If character is 0 or above, jump to convert character to number
%%rmNegSign:
inc r10 ; Update counter to access first digit in string
%%negativeLoop:
movzx eax, byte [%1 + r10] ; Move first digit into eax
cmp eax, NULL ; Check if at end of string
je %%negativeDone ; Jump to negativeDone if current character is equal to NULL
cmp eax, "0" ; Check if current character is number
jae %%negativeSum ; If character is 0 or above, jump to convert character to number
%%postiveSum:
sub eax, "0" ; "Curr number" - "0" to get number as is
mov dword [rbp - 4], eax ; Move number to temp storage location
mov eax, dword [%2] ; Move current decimal number to eax
mul dword [rbp - 8] ; Mul current number by three to convert into decimal
add eax, dword [rbp - 4] ; ans += intDigit
mov dword [%2], eax ; Move current value of eax to ans
inc r10 ; Update string counter
jmp %%positiveLoop ; Jump to positiveLoop to continue
%%negativeSum:
sub eax, "0" ; "Curr number" - "0" to get number as is
mov dword [rbp - 4], eax ; Move number to temp storage location
mov eax, dword [%2] ; Move current decimal number to eax
mul dword [rbp - 8] ; Mul current number by three to convert into decimal
add eax, dword [rbp - 4] ; ans += intDigit
mov dword [%2], eax ; Move current value of eax to ans
inc r10 ; Update string counter
jmp %%negativeLoop ; Jump to negativeLoop to continue
%%negativeDone:
mov eax, dword [%2] ; Move decimal number to eax
neg eax ; Negate decimal number to get negative
mov dword [%2], eax ; Move negative number to ans
%%controlDone:
pop rdx
pop rcx
mov rsp, rbp
pop rbp
%endmacro
; ---------------------------------------------------------
section .data
; -----
; Define standard constants.
TRUE equ 1
FALSE equ 0
SUCCESS equ 0 ; successful operation
NOSUCCESS equ 1
STDIN equ 0 ; standard input
STDOUT equ 1 ; standard output
STDERR equ 2 ; standard error
SYS_read equ 0 ; code for read
SYS_write equ 1 ; code for write
SYS_open equ 2 ; code for file open
SYS_close equ 3 ; code for file close
SYS_fork equ 57 ; code for fork
SYS_exit equ 60 ; code for terminate
SYS_creat equ 85 ; code for file open/create
SYS_time equ 201 ; code for get time
LF equ 10
SPACE equ " "
NULL equ 0
ESC equ 27
; -----
; OpenGL constants
GL_COLOR_BUFFER_BIT equ 16384
GL_POINTS equ 0
GL_POLYGON equ 9
GL_PROJECTION equ 5889
GLUT_RGB equ 0
GLUT_SINGLE equ 0
; -----
; Define program constants.
IT_MIN equ 255
IT_MAX equ 65535
RS_MAX equ 32768
; -----
; Local variables for getArguments function.
STR_LENGTH equ 12
ddThree dd 3
errUsage db "Usage: chaos -it <ternaryNumber> -rs <ternaryNumber>"
db LF, NULL
errBadCL db "Error, invalid or incomplete command line argument."
db LF, NULL
errITsp db "Error, iterations specifier incorrect."
db LF, NULL
errITvalue db "Error, invalid iterations value."
db LF, NULL
errITrange db "Error, iterations value must be between "
db "100110 (3) and 10022220020 (3)."
db LF, NULL
errRSsp db "Error, rotation speed specifier incorrect."
db LF, NULL
errRSvalue db "Error, invalid rotation speed value."
db LF, NULL
errRSrange db "Error, rotation speed value must be between "
db "0 (3) and 1122221122 (3)."
db LF, NULL
; -----
; Local variables for plotChaos funcction.
red dd 0 ; 0-255
green dd 0 ; 0-255
blue dd 0 ; 0-255
pi dq 3.14159265358979 ; constant
oneEighty dq 180.0
tmp dq 0.0
dStep dq 120.0 ; t step
scale dq 500.0 ; scale factor
rScale dq 100.0 ; rotation speed scale factor
rStep dq 0.1 ; rotation step value
rSpeed dq 0.0 ; scaled rotation speed
initX dq 0.0, 0.0, 0.0 ; array of x values
initY dq 0.0, 0.0, 0.0 ; array of y values
x dq 0.0
y dq 0.0
seed dq 987123
qThree dq 3
fTwo dq 2.0
A_VALUE equ 9421 ; must be prime
B_VALUE equ 1
n dd 0
; ------------------------------------------------------------
section .text
; -----
; Open GL routines.
extern glutInit, glutInitDisplayMode, glutInitWindowSize
extern glutInitWindowPosition
extern glutCreateWindow, glutMainLoop
extern glutDisplayFunc, glutIdleFunc, glutReshapeFunc, glutKeyboardFunc
extern glutSwapBuffers
extern gluPerspective
extern glClearColor, glClearDepth, glDepthFunc, glEnable, glShadeModel
extern glClear, glLoadIdentity, glMatrixMode, glViewport
extern glTranslatef, glRotatef, glBegin, glEnd, glVertex3f, glColor3f
extern glVertex2f, glVertex2i, glColor3ub, glOrtho, glFlush, glVertex2d
extern glutPostRedisplay
; -----
; c math library funcitons
extern cos, sin
; ******************************************************************
; Generic function to display a string to the screen.
; String must be NULL terminated.
; Algorithm:
; Count characters in string (excluding NULL)
; Use syscall to output characters
; Arguments:
; 1) address, string
; Returns:
; nothing
global printString
printString:
push rbx
push rsi
push rdi
push rdx
; -----
; Count characters in string.
mov rbx, rdi ; str addr
mov rdx, 0
strCountLoop:
cmp byte [rbx], NULL
je strCountDone
inc rbx
inc rdx
jmp strCountLoop
strCountDone:
cmp rdx, 0
je prtDone
; -----
; Call OS to output string.
mov rax, SYS_write ; system code for write()
mov rsi, rdi ; address of characters to write
mov rdi, STDOUT ; file descriptor for standard in
; EDX=count to write, set above
syscall ; system call
; -----
; String printed, return to calling routine.
prtDone:
pop rdx
pop rdi
pop rsi
pop rbx
ret
; ******************************************************************
; Function getIterations()
; Performs error checking, converts ASCII/ternary to integer.
; Command line format (fixed order):
; "-it <ternaryNumber> -rs <ternaryNumber>"
; -----
; Arguments:
; 1) ARGC, double-word, value, rdi
; 2) ARGV, double-word, address, rsi
; 3) iterations count, double-word, address, rdx
; 4) rotate speed, double-word address, rcx
; YOUR CODE GOES HERE
global getIterations
getIterations:
push rbx
push rcx
push r8
push r12
push r13
cmp rdi, 1 ; Compare argc to 1
je usageMessage ; If argc = 1, then jump usageMessage
cmp rdi, 5 ; Compare argc to 5
jne lackofArguments ; If argc != 5, jump to lackofArguments
mov rbx, qword[rsi + 8] ; Move address of argv[1] into rbx
mov r10, 0 ; Set counter to traverse argv[1] to 0, i = 0
itSpecifier:
mov rax, 0 ; Clear rax
mov al, byte[rbx + r10] ; Move character of argv[1][i] into al
cmp r10, 0 ; Compare counter to 0
jne firstITDone ; If counter != 0, jump to firstITDone
cmp al, "-" ; Compare argv[1][0] to "-"
jne itSpecifierWrong ; If argv[1][0] != "-", jump to itSpecifierWrong
firstITDone:
cmp r10, 1 ; Compare counter to 1
jne secondITDone ; If counter != 1, jump to secondITDone
cmp al, 'i' ; Compare argv[1][1] to "i"
jne itSpecifierWrong ; If argv[1][1] != "i", jump to itSpecifierWrong
secondITDone:
cmp r10, 2 ; Compare counter to 2
jne thirdITDone ; If counter != 2, jump to thirdITDone
cmp al, 't' ; Compare argv[1][2] to "t"
jne itSpecifierWrong ; If argv[1][2] != "t", jump to thirdITDone
thirdITDone:
cmp r10, 3 ; Compare counter to 3
jne fourthITDone ; If counter != 3, jump to fourthITDone
cmp al, NULL ; Compare argv[1][3] to NULL
jne itSpecifierWrong ; If argv[1][3] != NULL, jump to fourthITDone
fourthITDone:
inc r10 ; Update counter, i++
cmp al, NULL ; Compare current character to NULL
jne itSpecifier ; If current character != NULL, jump to itSpecifier
mov rbx, qword[rsi + 16] ; Move address of argv[2]
mov r10, 0 ; Clear r10, will be used as counter to check string
itTernaryCheck:
mov rax, 0 ; Clear rax
mov al, byte [rbx + r10] ; Move ternaryString[i] into al
cmp al, NULL ; Check if at end of ternaryString[i]
je convertITString ; If at end of ternaryString[i], jump to convertString
cmp al, "3" ; Compare ternaryString[i] with "3"
jae itNotTernary ; If ternaryString[i] >= "3" jump to notTernary
cmp al, "0" ; Compare ternaryString[i] with "0"
jb itNotTernary ; If ternaryString[i] < "0", jump to notTernary
inc r10 ; Update counter to traverse ternaryString[i]
jmp itTernaryCheck ; If counter < value of total characters, jump to ternaryCheck
convertITString:
push rdi
push rsi
mov rdi, rbx
mov rsi, rdx
ternary2int rdi, rsi ; Invoke ternary2int macro
pop rsi
pop rdi
mov rbx, qword[rsi + 24] ; Move address of argv[3] into rbx
mov r10, 0 ; Set counter to traverse argv[3] to 0, i = 0
rsSpecifier:
mov rax, 0 ; Clear rax
mov al, byte[rbx + r10] ; Move character of argv[3][i] into al
cmp r10, 0 ; Compare counter to 0
jne firstRSDone ; If counter != 0, jump to firstRSDone
cmp al, "-" ; Compare argv[3][0] to "-"
jne rsSpecifierWrong ; If argv[3][0] != "-", jump to rsSpecifierWrong
firstRSDone:
cmp r10, 1 ; Compare counter to 1
jne secondRSDone ; If counter != 1, jump to secondRSDone
cmp al, 'r' ; Compare argv[3][1] to "i"
jne rsSpecifierWrong ; If argv[3][1] != "r", jump to rsSpecifierWrong
secondRSDone:
cmp r10, 2 ; Compare counter to 2
jne thirdRSDone ; If counter != 2, jump to thirdRSDone
cmp al, 's' ; Compare argv[3][2] to "t"
jne rsSpecifierWrong ; If argv[3][2] != "s", jump to rsSpecifierWrong
thirdRSDone:
cmp r10, 3 ; Compare counter to 3
jne fourthRSDone ; If counter != 3, jump to fourthRSDone
cmp al, NULL ; Compare argv[3][3] to NULL
jne rsSpecifierWrong ; If argv[3][3] != NULL, jump to rsSpecifierWrong
fourthRSDone:
inc r10 ; Update counter, i++
cmp al, NULL ; Compare current character to NULL
jne rsSpecifier ; If current character != NULL, jump to itSpecifier
mov rbx, qword[rsi + 32] ; Move address of argv[4]
mov r10, 0 ; Clear r10, will be used as counter to check string
rsTernaryCheck:
mov rax, 0 ; Clear rax
mov al, byte [rbx + r10] ; Move ternaryString[i] into al
cmp al, NULL ; Check if at end of ternaryString[i]
je convertRSString ; If at end of ternaryString[i], jump to convertString
cmp al, "3" ; Compare ternaryString[i] with "3"
jae rsNotTernary ; If ternaryString[i] >= "3" jump to notTernary
cmp al, "0" ; Compare ternaryString[i] with "0"
jb rsNotTernary ; If ternaryString[i] < "0", jump to notTernary
inc r10 ; Update counter to traverse ternaryString[i]
jmp rsTernaryCheck ; If counter < value of total characters, jump to ternaryCheck
convertRSString:
push rdi
push rsi
mov rdi, rbx
mov rsi, rcx
ternary2int rdi, rsi ; Invoke ternary2int macro
pop rsi
pop rdi
checkRange:
mov rax, 0 ; Clear rax
movsxd rax, dword [rdx] ; Move iterations value into rax
cmp rax, IT_MIN ; Compare iterations to IT_MIN
jb itInvalidRange ; If iterations < IT_MIN, jump to itInvalidRange
cmp rax, IT_MAX ; Compare iterations to IT_MAX
ja itInvalidRange ; If iterations > IT_MAX, jump to itInvalidRange
movsxd rax, dword [rcx] ; Move rotateSpeed value into rax
cmp rax, 1 ; Compare rotateSpeed to 1
jb rsInvalidRange ; If rotateSpeed < 1, jump to rsInvalidRange
cmp rax, RS_MAX ; Compare rotateSpeed to RS_MAX
ja rsInvalidRange ; If rotateSpeed > RS_MAX, jumpt to rsInvalidRange
successful:
mov rax, TRUE
jmp done
usageMessage:
lea rdi, [errUsage]
call printString
mov rax, FALSE
jmp done
lackofArguments:
lea rdi, [errBadCL]
call printString
mov rax, FALSE
jmp done
itSpecifierWrong:
lea rdi, [errITsp]
call printString
mov rax, FALSE
jmp done
rsSpecifierWrong:
lea rdi, [errRSsp]
call printString
mov rax, FALSE
jmp done
itNotTernary:
lea rdi, [errITvalue]
call printString
mov rax, FALSE
jmp done
rsNotTernary:
lea rdi, [errRSvalue]
call printString
mov rax, FALSE
jmp done
itInvalidRange:
lea rdi, [errITrange]
call printString
mov rax, FALSE
jmp done
rsInvalidRange:
lea rdi, [errRSrange]
call printString
mov rax, FALSE
done:
pop r13
pop r12
pop r8
pop rcx
pop rbx
ret
; ******************************************************************
; Function to draw chaos algorithm.
; Chaos point calculation algorithm:
; seed = 7 * 100th of seconds (from current time)
; for i := 1 to iterations do
; s = rand(seed)
; n = s mod 3
; x = x + ( (init_x(n) - x) / 2 )
; y = y + ( (init_y(n) - y) / 2 )
; color = n
; plot (x, y, color)
; seed = s
; end_for
; -----
; Global variables (form main) accessed.
common drawColor 1:4 ; draw color
common degree 1:4 ; initial degrees
common iterations 1:4 ; iteration count
common rotateSpeed 1:4 ; rotation speed
; -----
global drawChaos
drawChaos:
; -----
; Save registers...
push r12
; -----
; Prepare for drawing
; glClear(GL_COLOR_BUFFER_BIT);
mov rdi, GL_COLOR_BUFFER_BIT
call glClear
; -----
; Set rotation speed step value.
; rStep = rotateSpeed / rScale
cvtsi2sd xmm0, dword [rotateSpeed] ; Move rotateSpeed into xmm0
divsd xmm0, qword [rScale] ; rotateSpeed/rScale stored in xmm0
movsd qword [rStep], xmm0 ; Move rotateSpeed/rScale result into rStep
; -----
; Plot initial points.
; glBegin();
mov rdi, GL_POINTS
call glBegin
; -----
; Calculate and plot initial points.
mov r12, 0 ; Set counter to 0, i = 0
calcLoop:
;----------------
; initX[i]
cvtsi2sd xmm0, r12d ; Move i counter value into xmm0
mulsd xmm0, qword [dStep] ; (i * dStep) stored in xmm0
addsd xmm0, qword [rSpeed] ; (rSpeed + (i * dStep)) stored in xmm0
movsd xmm1, qword [pi] ; Move pi value into xmm1
divsd xmm1, qword [oneEighty] ; (pi/180.0), stored in xmm1
mulsd xmm0, xmm1 ; (rSpeed + (i * dStep)) * (pi/180.0) stored in xmm0
call sin
mulsd xmm0, qword [scale] ; sin((rSpeed + (i * dStep)) * (pi/180.0)) * scale, stored in xmm0
movsd qword [initX + (r12 * 8)], xmm0 ; Store initX[i]
;----------------
; initY[i]
cvtsi2sd xmm0, r12d ; Move i counter value into xmm0
mulsd xmm0, qword [dStep] ; (i * dStep) stored in xmm0
addsd xmm0, qword [rSpeed] ; (rSpeed + (i * dStep)) stored in xmm0
movsd xmm1, qword [pi] ; Move pi value into xmm1
divsd xmm1, qword [oneEighty] ; (pi/180.0), stored in xmm1
mulsd xmm0, xmm1 ; (rSpeed + (i * dStep)) * (pi/180.0) stored in xmm0
call cos
mulsd xmm0, qword [scale] ; cos((rSpeed + (i * dStep)) * (pi/180.0)) * scale, stored in xmm0
movsd qword [initY + (r12 * 8)], xmm0 ; Store initY[i]
;--------------
; Update counter and check condition
inc r12
cmp r12, 3
jb calcLoop
; -----
; set and plot x[0], y[0]
mov r12, 0
movsd xmm1, qword [initY + (r12 * 8)] ; Move y value into xmm1, 2nd argument
movsd xmm0, qword [initX + (r12 * 8)] ; Move x value into xmm0, 1st argument
call glVertex2d
; -----
; set and plot x[1], y[1]
mov r12, 1
movsd xmm1, qword [initY + (r12 * 8)] ; Move y value into xmm1, 2nd argument
movsd xmm0, qword [initX + (r12 * 8)] ; Move x value into xmm0, 1st argument
call glVertex2d
; -----
; set and plot x[2], y[2]
mov r12, 2
movsd xmm1, qword [initY + (r12 * 8)] ; Move y value into xmm1, 2nd argument
movsd xmm0, qword [initX + (r12 * 8)] ; Move x value into xmm0, 1st argument
call glVertex2d
; -----
; Main plot loop.
mov r12, 0 ; Reset counter, i = 0
mainPlotLoop:
cmp r12d, dword [iterations] ; Compare counter, with iterations
jae mainPlotDone ; If counter => iterations, jump to mainPlotDone
; -----
; Generate pseudo random number, via linear congruential generator
; s = R(n+1) = (A × seed + B) mod 2^16
; n = s mod 3
; Note, A and B are constants.
mov r10, 65536 ; Move 2^16 into r10
;----------------
; s = R(n+1) = (A × seed + B) mod 2^16
mov rax, A_VALUE ; Move A_VALUE into rax
mul qword [seed] ; (A * seed) stored in rax
add rax, B_VALUE ; (A * seed + B) stored in rax
mov rdx, 0
div r10 ; ((A * seed + B) mod 2^16) stored in rdx
mov qword [seed], rdx ; Move new seed value in
;----------------
; n = s mod 3
mov rax, qword [seed] ; Move seed (s) value into rax
mov rdx, 0
div qword [qThree] ; (s mod 3) stored in rdx
mov dword [n], edx ; Move n value into r12
; -----
; Generate next (x,y) point.
; x = x + ( (initX[n] - x) / 2 )
; y = y + ( (initY[n] - y) / 2 )
;----------------
; x
mov r8, 0 ; Clear r8
mov r8d, dword [n] ; Move value of n into r8d
movsd xmm0, qword [initX + (r8 * 8)] ; Move value of initX[n] into xmm0
subsd xmm0, qword [x] ; (initX[n] - x) stored in xmm0
divsd xmm0, qword [fTwo] ; ((initX[n] - x) / 2.0) stored in xmm0
addsd xmm0, qword [x] ; (x + ((initX[n] - x) / 2 )) stored in xmm0
movsd qword [x], xmm0 ; Move new x value into x
;----------------
; y
mov r8, 0 ; Clear r8
mov r8d, dword [n] ; Move value of n into r8d
movsd xmm0, qword [initY + (r8 * 8)] ; Move value of initY[n] into xmm0
subsd xmm0, qword [y] ; (initY[n] - x) stored in xmm0
divsd xmm0, qword [fTwo] ; ((initY[n] - x) / 2.0) stored in xmm0
addsd xmm0, qword [y] ; (y + ((initY[n] - y) / 2 )) stored in xmm0
movsd qword [y], xmm0 ; Move new y value into y
; -----
; Set draw color
cmp dword [n], 0 ; Compare n to 0
jne notZero ; If n != 0, jump to notZero
mov dword [blue], 0
mov dword [green], 0
mov dword [red], 255 ; Move 255 into red
notZero:
cmp dword [n], 1 ; Compare n to 1
jne notOne ; If n != 1, jump to notOne
mov dword [blue], 0
mov dword [green], 255 ; Move 255 into green
mov dword [red], 0
notOne:
cmp dword [n], 2 ; Compare n to 2
jne notTwo ; If n != 2, jump to notTwo
mov dword [blue], 255 ; Move 255 into blue
mov dword [green], 0
mov dword [red], 0
notTwo:
mov rdi, 0 ; Clear rdi
mov rsi, 0 ; Clear rsi
mov rdx, 0 ; Clear rdx
mov edx, dword[blue] ; Move blue value into edx, 3rd argument
mov esi, dword[green] ; Move green value into esi, 2nd argument
mov edi, dword[red] ; Move red value into edi, 1st argument
call glColor3ub
; -----
; Plot (x,y)
movsd xmm1, qword [y] ; Move y value into xmm1, 2nd argument
movsd xmm0, qword [x] ; Move x value into xmm0, 1st argument
call glVertex2d
inc r12 ; Update counter, i++
jmp mainPlotLoop ; Jump to mainPlotLoop
mainPlotDone:
; -----
call glEnd
call glFlush
; -----
; Update rotation speed.
; Then tell OpenGL to re-draw with new rSpeed value.
movsd xmm0, qword [rSpeed] ; Move rSpeed into xmm0
addsd xmm0, qword [rStep] ; rSpeed + rStep
movsd qword [rSpeed], xmm0 ; Move updated value into rSpeed
call glutPostRedisplay
pop r12
ret
; ******************************************************************
|
; void dzx2_nano(void *src, void *dst)
SECTION code_clib
SECTION code_compress_zx2
PUBLIC _dzx2_nano
EXTERN asm_dzx2_nano
_dzx2_nano:
pop af
pop hl
pop de
push de
push hl
push af
jp asm_dzx2_nano
|
; A282548: Expansion of phi_{12, 1}(x) where phi_{r, s}(x) = Sum_{n, m>0} m^r * n^s * x^{m*n}.
; 0,1,4098,531444,16785412,244140630,2177857512,13841287208,68753047560,282431130813,1000488301740,3138428376732,8920506494928,23298085122494,56721594978384,129747072969720,281612482805776,582622237229778,1157402774071674,2213314919066180,4098001060489560,7355869038968352,12861279487847736,21914624432020344,36538394607476640,59604645996093775,95475552831980412,150095482590391560,232331708396609696,353814783205469070,531703505029912560,787662783788549792,1153484729572458528,1667898930243961008
mov $2,$0
lpb $0
mov $3,$2
mov $4,$0
cmp $4,0
add $0,$4
dif $3,$0
cmp $3,$2
cmp $3,0
mul $3,$0
sub $0,1
pow $3,11
add $1,$3
lpe
add $1,1
mul $2,$1
mov $0,$2
|
; A240331: Inverse of 47th cyclotomic polynomial.
; 1,-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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0
mod $0,47
mov $2,$0
mov $0,4
sub $0,$2
lpb $0,1
mul $0,2
sub $0,7
mov $1,$0
lpe
|
; A212344: Sequence of coefficients of x^(n-3) in marked mesh pattern generating function Q_{n,132}^(0,3,0,0)(x).
; Submitted by Christian Krause
; 5,5,10,25,70,210,660,2145,7150,24310,83980,293930,1040060,3714500,13372200,48474225,176788350,648223950,2388193500,8836315950,32820602100,122331335100,457412818200,1715298068250,6449520736620,24309732007260,91836765360760
seq $0,108 ; Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
mul $0,5
|
#include "hoverbutton.h"
HoverButton::HoverButton(QWidget *parent) : QPushButton(parent), ban_enter(false)
{
}
HoverButton::HoverButton(QString text, QWidget *parent) : QPushButton(text, parent), ban_enter(false)
{
}
void HoverButton::banEnter(bool ban)
{
ban_enter = ban;
}
void HoverButton::enterEvent(QEvent *event)
{
emit signalEntered(mapFromGlobal(QCursor::pos()));
return QPushButton::enterEvent(event);
}
void HoverButton::leaveEvent(QEvent *event)
{
emit signalLeaved(mapFromGlobal(QCursor::pos()));
return QPushButton::leaveEvent(event);
}
void HoverButton::mousePressEvent(QMouseEvent *event)
{
emit signalMousePressed(mapFromGlobal(QCursor::pos()));
return QPushButton::mousePressEvent(event);
}
void HoverButton::mouseReleaseEvent(QMouseEvent *event)
{
emit signalMouseReleased(mapFromGlobal(QCursor::pos()));
return QPushButton::mouseReleaseEvent(event);
}
void HoverButton::keyPressEvent(QKeyEvent *event)
{
emit signalKeyPressed(event);
if (ban_enter && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)) // 是 Key_Return
return ;
return QPushButton::keyPressEvent(event);
}
void HoverButton::keyReleaseEvent(QKeyEvent *event)
{
emit signalKeyReleased(event);
if (ban_enter && (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter))
return ;
return QPushButton::keyReleaseEvent(event);
}
|
; $Id: bit_fx2.asm,v 1.5 2016-04-23 21:06:32 dom Exp $
;
; Generic platform sound effects module.
; Alternate sound library by Stefano Bodrato
;
SECTION code_clib
PUBLIC bit_fx2
PUBLIC _bit_fx2
INCLUDE "games/games.inc"
EXTERN bit_open
EXTERN bit_open_di
EXTERN bit_close
EXTERN bit_close_ei
.bit_fx2
._bit_fx2
pop bc
pop de
push de
push bc
IF sndbit_port >= 256
exx
ld bc,sndbit_port
exx
ENDIF
ld a,e
cp 8
ret nc
add a,a
ld e,a
ld d,0
ld hl,table
add hl,de
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
jp (hl)
.table defw DeepSpace ; effect #0
defw SSpace2
defw TSpace
defw Clackson2
defw TSpace2
defw TSpace3 ; effect #5
defw Squoink
defw explosion
;Space sound
.DeepSpace
call bit_open_di
.DS_LENGHT
ld b,100
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.ds_loop
dec h
jr nz,ds_jump
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
push bc
ld b,250
.loosetime1
djnz loosetime1
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.ds_FR_1
;ld h,230
ld h,254
.ds_jump
dec l
jr nz,ds_loop
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
push bc
ld b,200
.loosetime2
djnz loosetime2
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.ds_FR_2
ld l,255
djnz ds_loop
call bit_close_ei
ret
;Dual note with fuzzy addedd
.SSpace2
call bit_open_di
.SS_LENGHT
ld b,100
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.ss_loop
dec h
jr nz,ss_jump
push hl
push af
ld a,sndbit_mask
ld h,0
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
pop hl
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.ss_FR_1
ld h,230
.ss_jump
dec l
jr nz,ss_loop
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.ss_FR_2
ld l,255
djnz ss_loop
call bit_close_ei
ret
;Dual note with LOT of fuzzy addedd
.TSpace
call bit_open_di
.TS_LENGHT
ld b,100
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.ts_loop
dec h
jr nz,ts_jump
push hl
push af
ld a,sndbit_mask
ld h,0
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
pop hl
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.ts_FR_1
ld h,130
.ts_jump
dec l
jr nz,ts_loop
push hl
push af
ld a,sndbit_mask
ld l,h
ld h,0
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
pop hl
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.ts_FR_2
ld l,155
djnz ts_loop
call bit_close_ei
ret
.Clackson2
call bit_open_di
.CS_LENGHT
ld b,200
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.cs_loop
dec h
jr nz,cs_jump
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
push bc
ld b,250
.cswait1
djnz cswait1
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.cs_FR_1
ld h,230
.cs_jump
inc l
jr nz,cs_loop
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
push bc
ld b,200
.cswait2
djnz cswait2
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.cs_FR_2
ld l,0
djnz cs_loop
call bit_close_ei
ret
.TSpace2
ld a,230
ld (t2_FR_1+1),a
xor a
ld (t2_FR_2+1),a
call bit_open_di
.T2_LENGHT
ld b,200
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.t2_loop
dec h
jr nz,t2_jump
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
push bc
ld b,250
.wait1
djnz wait1
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.t2_FR_1
ld h,230
.t2_jump
inc l
jr nz,t2_loop
push af
ld a,(t2_FR_2+1)
inc a
ld (t2_FR_2+1),a
pop af
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
push bc
ld b,200
.wait2
djnz wait2
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.t2_FR_2
ld l,0
djnz t2_loop
call bit_close_ei
ret
.TSpace3
ld a,230
ld (u2_FR_1+1),a
xor a
ld (u2_FR_2+1),a
call bit_open_di
.U2_LENGHT
ld b,200
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.u2_loop
dec h
jr nz,u2_jump
push af
ld a,(u2_FR_1+1)
inc a
ld (u2_FR_1+1),a
pop af
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.u2_FR_1
ld h,50
.u2_jump
inc l
jr nz,u2_loop
push af
ld a,(u2_FR_2+1)
inc a
ld (u2_FR_2+1),a
pop af
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.u2_FR_2
ld l,0
djnz u2_loop
call bit_close_ei
ret
.Squoink
ld a,230
ld (qi_FR_1+1),a
xor a
ld (qi_FR_2+1),a
call bit_open_di
.qi_LENGHT
ld b,200
IF sndbit_port <= 255
ld c,sndbit_port
ENDIF
.qi_loop
dec h
jr nz,qi_jump
push af
ld a,(qi_FR_1+1)
dec a
ld (qi_FR_1+1),a
pop af
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.qi_FR_1
ld h,50
.qi_jump
inc l
jr nz,qi_loop
push af
ld a,(qi_FR_2+1)
inc a
ld (qi_FR_2+1),a
pop af
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;8 T slower
exx
ELSE
out (c),a
ENDIF
.qi_FR_2
ld l,0
djnz qi_loop
call bit_close_ei
ret
.explosion
call bit_open_di
ld hl,1
.expl
push hl
push af
ld a,sndbit_mask
ld h,0
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
pop hl
push af
ld b,h
ld c,l
.dly dec bc
ld a,b
or c
jr nz,dly
pop af
inc hl
bit 1,h
jr z,expl
call bit_close_ei
ret
|
; A213283: Number of 4-length words w over n-ary alphabet such that for every prefix z of w we have #(z,a_i) = 0 or #(z,a_i) >= #(z,a_j) for all j>i and #(z,a_i) counts the occurrences of the i-th letter in z.
; 0,1,9,36,118,315,711,1414,2556,4293,6805,10296,14994,21151,29043,38970,51256,66249,84321,105868,131310,161091,195679,235566,281268,333325,392301,458784,533386,616743,709515,812386,926064,1051281,1188793,1339380,1503846,1683019,1877751,2088918,2317420,2564181,2830149,3116296,3423618,3753135,4105891,4482954,4885416,5314393,5771025,6256476,6771934,7318611,7897743,8510590,9158436,9842589,10564381,11325168,12126330,12969271,13855419,14786226,15763168,16787745,17861481,18985924,20162646,21393243,22679335,24022566,25424604,26887141,28411893,30000600,31655026,33376959,35168211,37030618,38966040,40976361,43063489,45229356,47475918,49805155,52219071,54719694,57309076,59989293,62762445,65630656,68596074,71660871,74827243,78097410,81473616,84958129,88553241,92261268,96084550,100025451,104086359,108269686,112577868,117013365,121578661,126276264,131108706,136078543,141188355,146440746,151838344,157383801,163079793,168929020,174934206,181098099,187423471,193913118,200569860,207396541,214396029,221571216,228925018,236460375,244180251,252087634,260185536,268476993,276965065,285652836,294543414,303639931,312945543,322463430,332196796,342148869,352322901,362722168,373349970,384209631,395304499,406637946,418213368,430034185,442103841,454425804,467003566,479840643,492940575,506306926,519943284,533853261,548040493,562508640,577261386,592302439,607635531,623264418,639192880,655424721,671963769,688813876,705978918,723462795,741269431,759402774,777866796,796665493,815802885,835283016,855109954,875287791,895820643,916712650,937967976,959590809,981585361,1003955868,1026706590,1049841811,1073365839,1097283006,1121597668,1146314205,1171437021,1196970544,1222919226,1249287543,1276079995,1303301106,1330955424,1359047521,1387581993,1416563460,1445996566,1475885979,1506236391,1537052518,1568339100,1600100901,1632342709,1665069336,1698285618,1731996415,1766206611,1800921114,1836144856,1871882793,1908139905,1944921196,1982231694,2020076451,2058460543,2097389070,2136867156,2176899949,2217492621,2258650368,2300378410,2342681991,2385566379,2429036866,2473098768,2517757425,2563018201,2608886484,2655367686,2702467243,2750190615,2798543286,2847530764,2897158581,2947432293,2998357480,3049939746,3102184719,3155098051,3208685418,3262952520,3317905081,3373548849,3429889596,3486933118,3544685235,3603151791,3662338654,3722251716,3782896893
mov $12,$0
mov $14,$0
lpb $14
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
lpb $11
mov $0,$9
sub $11,1
sub $0,$11
mov $5,$0
lpb $0
sub $0,2
mov $2,$0
mul $2,6
mul $2,$0
mov $0,1
mul $2,2
mov $5,5
add $7,8
add $7,$2
add $5,$7
sub $5,6
mov $7,0
lpe
add $10,$5
lpe
add $13,$10
lpe
mov $1,$13
|
copyright zengfr site:http://github.com/zengfr/romhack
001268 bne $1278 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, etc+25, item+25]
0012B8 bne $12c8 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, item+25]
00605C rts [123p+ BF]
006072 bne $60e0
00607C bne $60e0
006084 ble $60e0
0141C0 move.w ($c,A0), D5 [enemy+ 8, enemy+28, enemy+48, enemy+68, enemy+A8]
0141C4 add.w ($10,A0), D5 [enemy+ C, enemy+2C, enemy+4C, enemy+6C, enemy+AC]
0141C8 btst #$7, ($25,A0) [enemy+10, enemy+30, enemy+50, enemy+70, enemy+B0]
0141CE bne $141da
0141EE move.w (-$711e,A5), D0 [enemy+ C, enemy+2C, enemy+4C, enemy+6C, enemy+8C, enemy+AC]
0141FE bne $14226 [123p+ 5, enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, etc+ 5, item+ 5]
014208 bne $14226 [123p+ 2E, enemy+ E, enemy+2E, enemy+4E, enemy+6E, enemy+8E, item+2E]
01421E bne $14226 [enemy+2E, enemy+6E]
01422C bne $14136 [123p+ 25, enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, etc+25, item+25]
014234 btst #$6, ($25,A0) [123p+ 28, 123p+ 2A, enemy+ 8, enemy+ A, enemy+48, enemy+4A, enemy+68, enemy+6A, enemy+88, enemy+8A, enemy+A8, enemy+AA, etc+28, etc+2A, item+28, item+2A]
01423A bne $147fe [123p+ 25, enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, etc+25, item+25]
01425C move.w ($c,A0), D5 [123p+ 8, enemy+ 8, enemy+28, enemy+48, enemy+68, enemy+88, enemy+A8, etc+ 8, item+ 8]
014260 add.w ($10,A0), D5 [123p+ C, enemy+ C, enemy+2C, enemy+4C, enemy+6C, enemy+8C, enemy+AC, etc+ C, item+ C]
014264 btst #$7, ($25,A0) [123p+ 10, enemy+10, enemy+30, enemy+50, enemy+70, enemy+90, enemy+B0, etc+10, item+10]
01426A bne $14276 [123p+ 25, enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, etc+25, item+25]
014EDC bne $14f92 [123p+ 25, enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5, etc+25, item+25]
014EE4 add.w ($56,A0), D1
02B498 rts [enemy+1A, enemy+3A, enemy+5A, enemy+7A, enemy+9A, enemy+BA]
02B49E move.w ($84,A6), D1
02B4A2 movea.l #$2e68c, A0 [enemy+ 4, enemy+24, enemy+44, enemy+64, enemy+84, enemy+A4]
033854 move.w ($6,PC,D0.w), D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+A5]
033866 jsr $939b6.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
033946 move.b #$b4, ($72,A6)
03394C move.b D0, ($a4,A6) [enemy+12, enemy+32, enemy+52, enemy+72, enemy+92, enemy+B2]
033950 move.w D0, ($a2,A6)
033954 move.b #$ff, ($a5,A6)
03395A move.b #$14, ($a9,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
033960 move.b #$5a, ($ac,A6) [enemy+ 9, enemy+29, enemy+49, enemy+69, enemy+89, enemy+A9]
033966 move.b D0, ($ba,A6) [enemy+ C, enemy+2C, enemy+4C, enemy+6C, enemy+8C, enemy+AC]
033A0E addi.w #$80, D0 [enemy+14, enemy+54]
033A1C jsr $1862.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
033AAE addi.w #$80, D0 [enemy+14, enemy+34, enemy+94, enemy+B4]
033ABC jsr $1862.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
033C30 rts [enemy+25, enemy+45, enemy+65, enemy+85]
033C84 bsr $33c9e [enemy+1B, enemy+5B, enemy+7B, enemy+9B, enemy+BB]
033C98 clr.b ($23,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
033C9C rts
033E46 rts [enemy+25, enemy+45, enemy+85, enemy+A5]
03486A addq.b #2, ($5,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
03486E move.w ($80,A6), D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
034872 subq.w #1, D0 [enemy+ 0, enemy+20, enemy+60, enemy+80, enemy+A0]
035424 bne $3542a [enemy+ 5, enemy+85, enemy+A5]
03542E jsr $119c.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
03543E move.b ($a5,A6), D0 [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
035442 bne $3547a [enemy+ 5, enemy+85, enemy+A5]
036830 jsr $3293c.l
03683A jsr $119c.l [enemy+ 5, enemy+25, enemy+45, enemy+85, enemy+A5]
03B854 moveq #$0, D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
03B9A8 jsr $1862.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
03B9DA move.b #$1, ($51,A6) [enemy+2C, enemy+4C, enemy+6C, enemy+8C, enemy+AC]
03B9E0 move.b ($5b,A6), ($24,A6) [enemy+11, enemy+31, enemy+71, enemy+91, enemy+B1]
03B9E6 addq.b #2, ($5,A6)
03B9EA rts [enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
03BB68 rts [enemy+ 5, enemy+25, enemy+45, enemy+85]
03CB4E addq.b #2, ($5,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
03CB52 move.w ($80,A6), D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
04006E move.b D0, ($bc,A6)
040072 move.b D0, ($af,A6)
040076 jsr $3293c.l
040080 move.b ($6,A6), ($a0,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
040086 jsr $119c.l [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
04016A move.b #$0, ($bc,A6)
040170 jsr $3293c.l
04017A jsr $119c.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85]
0401E4 jsr $325e6.l [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
0401EE move.w ($80,A6), D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
040292 move.w ($10,A6), ($10,A1)
040298 move.w A0, ($a8,A1) [enemy+10, enemy+30, enemy+50, enemy+70, enemy+90, enemy+B0]
04029C move.w A2, ($aa,A1) [enemy+ 8, enemy+28, enemy+48, enemy+68, enemy+88, enemy+A8]
0402A0 move.b #$2, ($5,A1) [enemy+ A, enemy+2A, enemy+4A, enemy+6A, enemy+8A, enemy+AA]
0402A6 move.b #$1, ($0,A0) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
0402AC move.w #$f0, ($20,A0) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
0402B2 move.w #$0, ($26,A0) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
041BF6 move.b #$0, ($ba,A6)
041BFC jsr $3293c.l
041C06 jsr $119c.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
041CDC clr.b ($ba,A6)
041CE0 jsr $3293c.l
041CEA bsr $41c46 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
041E6C jsr $325e6.l [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
041E76 move.w ($80,A6), D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
041F1E move.w ($6,PC,D0.w), D1 [enemy+ 4, enemy+44, enemy+64, enemy+84]
041F36 move.b #$10, ($25,A6) [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+40, enemy+42, enemy+60, enemy+62, enemy+80, enemy+82, enemy+A0, enemy+A2]
041F3C move.b #$ff, ($7d,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
041F42 clr.b ($59,A6) [enemy+1D, enemy+3D, enemy+5D, enemy+7D, enemy+9D, enemy+BD]
041F46 move.b #$ff, ($63,A6)
042690 tst.b ($26,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85]
042878 clr.b ($5,A6) [enemy+ 4, enemy+24, enemy+44, enemy+64, enemy+84]
04287C clr.w ($6,A6)
042880 bra $42b96
0438AE move.b #$78, ($80,A6) [enemy+ 5, enemy+45, enemy+65, enemy+85]
0438B4 tst.b ($26,A6) [enemy+ 0, enemy+20, enemy+40, enemy+80]
0457DC tst.b ($26,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
045848 move.b D0, ($87,A6)
04584C move.b D0, ($63,A6)
045850 move.b #$3c, ($72,A6)
045856 move.b D0, ($a5,A6) [enemy+12, enemy+32, enemy+52, enemy+72, enemy+92, enemy+B2]
04585A move.b D0, ($b6,A6)
04585E move.b D0, ($b7,A6)
045862 move.b D0, ($b8,A6)
04599C rts [enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
045AB0 jsr $1862.l [enemy+ 5, enemy+25, enemy+65, enemy+85, enemy+A5]
045B4E jsr $1862.l [enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
045EEA clr.b ($a5,A6)
045EEE move.b #$1, ($a6,A6)
045EF4 moveq #$1, D0 [enemy+ 6, enemy+26, enemy+46, enemy+66, enemy+86, enemy+A6]
045F3C move.b ($7,A6), D0 [enemy+ 2, enemy+22, enemy+42, enemy+62, enemy+82, enemy+A2]
045F68 jsr $119c.l
0460D8 move.b #$1, ($a6,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
0460DE tst.b ($a6,A6) [enemy+ 6, enemy+26, enemy+46, enemy+66, enemy+86, enemy+A6]
046A4A addq.b #2, ($5,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
046A4E move.w ($80,A6), D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
048BF0 move.b #$4, ($5,A6) [enemy+76]
048BF6 clr.w ($6,A6) [enemy+85]
048BFA jmp $a0cc.l
048E12 move.b #$a, ($78,A6) [enemy+22, enemy+A2]
048E18 move.w ($8,A6), ($ae,A6) [enemy+38, enemy+78]
048E1E move.b ($bd,A6), ($23,A6) [enemy+6E, enemy+AE]
048E24 clr.b ($5,A6) [enemy+23, enemy+A3]
048E28 clr.w ($6,A6)
048E2C tst.w ($6c,A6)
0512DC move.b #$ff, ($7d,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
0512E2 moveq #$0, D0 [enemy+1D, enemy+3D, enemy+5D, enemy+7D, enemy+9D, enemy+BD]
0512EC move.b #$10, ($25,A6) [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+40, enemy+42, enemy+60, enemy+62, enemy+80, enemy+82]
0512F2 move.b D0, ($a5,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
0512F6 jsr $12cb4.l
053906 move.b #$8, ($a6,A6) [enemy+ 5, enemy+45, enemy+85]
05390C move.b ($a4,A6), ($a7,A6) [enemy+ 6, enemy+46, enemy+86]
053912 rts
05394A subq.b #1, ($a5,A6) [enemy+ 3, enemy+43, enemy+83]
05394E bpl $53954 [enemy+ 5, enemy+45, enemy+85]
055A02 moveq #$20, D0
055A16 rts [enemy+ 5, enemy+25, enemy+45, enemy+85, enemy+A5]
055B72 tst.b ($5,A6) [enemy+24, enemy+44, enemy+84, enemy+A4]
055B7C moveq #$1, D0 [enemy+25, enemy+45, enemy+85, enemy+A5]
056586 move.b #$ff, ($7d,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
05658C move.b #$0, ($5,A6) [enemy+1D, enemy+3D, enemy+5D, enemy+7D, enemy+9D, enemy+BD]
056592 move.b #$10, ($25,A6)
056598 move.l #$5674e, ($40,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
0565A0 clr.w ($a0,A6) [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+40, enemy+42, enemy+60, enemy+62, enemy+80, enemy+82, enemy+A0, enemy+A2]
0565A4 move.w #$64, ($a2,A6)
056620 move.l #$0, ($b0,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
056628 jsr $119c.l
05693E move.b #$0, ($5,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+80, enemy+A0]
056944 move.b #$ff, ($7d,A6)
05694A move.l #$56a56, ($40,A6) [enemy+1D, enemy+3D, enemy+5D, enemy+7D, enemy+9D, enemy+BD]
056952 move.b #$83, ($23,A6) [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+40, enemy+42, enemy+60, enemy+62, enemy+80, enemy+82, enemy+A0, enemy+A2]
056958 move.b #$10, ($25,A6) [enemy+ 3, enemy+23, enemy+43, enemy+63, enemy+83, enemy+A3]
05695E clr.w ($a0,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
056962 move.w #$64, ($a2,A6)
056968 move.w #$10, ($a6,A6) [enemy+ 2, enemy+22, enemy+42, enemy+62, enemy+82, enemy+A2]
0569A6 move.w #$0, ($ac,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
0569AC jsr $119c.l
056CA2 move.b #$9d, ($23,A6) [enemy+ 0, enemy+ 2, enemy+40, enemy+42, enemy+60, enemy+62, enemy+80, enemy+82, enemy+A0, enemy+A2]
056CA8 move.b #$ff, ($7d,A6) [enemy+23, enemy+43, enemy+63, enemy+83, enemy+A3]
056CAE clr.w ($a0,A6) [enemy+1D, enemy+3D, enemy+7D, enemy+9D, enemy+BD]
056CB2 move.b #$10, ($25,A6) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+A0]
056CB8 moveq #$0, D0 [enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
056CBE move.w ($12,PC,D0.w), D1 [enemy+66, enemy+86]
057944 addq.b #2, ($4,A6) [enemy+3D, enemy+5D, enemy+7D, enemy+9D, enemy+BD]
057948 rts [enemy+ 4, enemy+24, enemy+44, enemy+84, enemy+A4]
057968 add.w D0, D0 [enemy+ 5, enemy+25, enemy+45, enemy+85, enemy+A5]
057DAE move.l #$57e0e, ($40,A6) [enemy+60]
057DB6 clr.w ($80,A6) [enemy+A0, enemy+A2]
057DBA clr.b ($83,A6)
057DBE move.b #$10, ($25,A6)
057DC4 jsr $12cb4.l [enemy+85]
057DCE beq $57dde
057FE8 addq.b #1, ($67be,A5) [enemy+1E, enemy+3E, enemy+7E, enemy+BE]
057FF2 move.l #$6fb1a, ($40,A6) [enemy+20, enemy+60, enemy+80, enemy+A0]
057FFA move.b #$10, ($25,A6) [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+60, enemy+62, enemy+A0, enemy+A2]
058000 move.b #$ff, ($7d,A6) [enemy+ 5, enemy+45, enemy+85, enemy+A5]
058006 move.b #$ff, ($63,A6) [enemy+1D, enemy+3D, enemy+5D, enemy+9D]
05800C move.b $0.w, ($59,A6) [enemy+ 3, enemy+23, enemy+43, enemy+83]
05810A move.b #$ff, ($63,A6) [enemy+1D, enemy+3D, enemy+5D, enemy+7D, enemy+9D, enemy+BD]
058110 move.l #$6fb6a, ($40,A6) [enemy+ 3, enemy+23, enemy+43, enemy+63, enemy+83, enemy+A3]
058118 moveq #$0, D0 [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+40, enemy+42, enemy+60, enemy+62, enemy+80, enemy+82, enemy+A0, enemy+A2]
058120 move.b D0, ($a5,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
058124 move.b D0, ($59,A6)
058128 moveq #$22, D0
05A4A2 moveq #$0, D0 [enemy+23, enemy+43, enemy+63, enemy+A3]
05A4AC move.b #$10, ($25,A6) [enemy+ 0, enemy+ 2, enemy+20, enemy+22, enemy+40, enemy+42, enemy+80, enemy+82]
05A4B2 move.b D0, ($a5,A6) [enemy+ 5, enemy+25, enemy+65, enemy+A5]
05A4B6 move.b D0, ($b2,A6)
05A4BA move.w D0, ($a6,A6)
05A4BE move.b D0, ($a4,A6)
05A5E2 moveq #$0, D0
05A622 moveq #$1, D0 [enemy+25, enemy+65, enemy+85, enemy+A5]
05B024 move.w ($10,A6), ($10,A0)
05B02A move.w A1, ($a8,A0) [enemy+10, enemy+30, enemy+50, enemy+70, enemy+90, enemy+B0]
05B02E move.b ($96,A6), ($96,A0) [enemy+ 8, enemy+28, enemy+48, enemy+68, enemy+88, enemy+A8]
05B034 move.b #$2, ($5,A0) [enemy+16, enemy+36, enemy+56, enemy+76, enemy+96, enemy+B6]
05B03A move.b #$1, ($0,A1) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
05B040 move.w #$134, ($20,A1) [enemy+ 0, enemy+20, enemy+40, enemy+80, enemy+A0]
05B046 move.w A0, ($a0,A1) [enemy+ 0, enemy+20, enemy+40, enemy+60, enemy+A0]
05B04A move.w ($26,A0), ($26,A1) [enemy+ 0, enemy+20, enemy+60, enemy+80, enemy+A0]
05B050 rts [enemy+ 6, enemy+26, enemy+46, enemy+66, enemy+A6]
05B056 tst.b ($26,A6) [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
05B242 jsr $1862.l [enemy+45, enemy+65, enemy+85, enemy+A5]
05B252 clr.b ($5,A6) [enemy+ 4, enemy+24, enemy+44, enemy+64, enemy+84, enemy+A4]
05B256 clr.w ($6,A6)
05B25A jsr $326f8.l
05C38A move.b D0, ($a5,A6) [enemy+ 4, enemy+24, enemy+44, enemy+64, enemy+84, enemy+A4]
05C38E jsr $3140c.l [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
05C39A clr.b ($a7,A6) [enemy+ 6, enemy+26, enemy+46, enemy+66, enemy+86, enemy+A6]
05C43A addq.b #1, ($67be,A5) [enemy+1E, enemy+3E, enemy+5E, enemy+7E, enemy+9E, enemy+BE]
05C448 addq.b #2, ($5,A6)
05C44C moveq #$0, D0 [enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
05C452 bmi $5c46e [enemy+ 6, enemy+26, enemy+46, enemy+66, enemy+86, enemy+A6]
05C474 clr.b ($5,A6) [enemy+ 6, enemy+26, enemy+46, enemy+66, enemy+A6]
05C478 move.b #$2, ($4,A6)
05C47E move.b ($5,A6), D0 [enemy+ 4, enemy+24, enemy+44, enemy+64, enemy+84]
05EFEC clr.b ($a2,A6) [enemy+ 5, enemy+25, enemy+45, enemy+85]
05EFF0 clr.b ($25,A6)
05EFF4 move.b #$1, ($51,A6)
092A66 move.b ($4e,A0), D0 [123p+ 25, enemy+ 5, enemy+25, enemy+45, enemy+65, enemy+85, enemy+A5]
092ABA jmp $4964.l
copyright zengfr site:http://github.com/zengfr/romhack
|
%ifdef CONFIG
{
"RegData": {
"XMM0": ["0x4142434445464748", "0x5152535455565758"],
"XMM1": ["0x4142434445464748", "0x5152535455565758"]
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0x4142434445464748
mov [rdx + 8 * 0], rax
mov rax, 0x5152535455565758
mov [rdx + 8 * 1], rax
mov rax, 0x0
mov [rdx + 8 * 2], rax
mov [rdx + 8 * 3], rax
movaps xmm0, [rdx + 8 * 0]
movntpd [rdx + 8 * 2], xmm0
movaps xmm1, [rdx + 8 * 2]
hlt
|
/*
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2019 Google LLC.
* Copyright (c) 2013-2017 Nest Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* Implementation of network interface abstraction layer.
*
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
#include "InetInterface.h"
#include "InetLayer.h"
#include "InetLayerEvents.h"
#include <support/CodeUtils.h>
#include <support/DLLUtil.h>
#if CHIP_SYSTEM_CONFIG_USE_LWIP
#include <lwip/netif.h>
#include <lwip/sys.h>
#include <lwip/tcpip.h>
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <unistd.h>
#ifdef HAVE_SYS_SOCKIO_H
#include <sys/sockio.h>
#endif /* HAVE_SYS_SOCKIO_H */
#include <net/if.h>
#include <sys/ioctl.h>
#ifdef __ANDROID__
#include "ifaddrs-android.h"
#else // !defined(__ANDROID__)
#include <ifaddrs.h>
#endif // !defined(__ANDROID__)
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#include <stdio.h>
#include <string.h>
namespace chip {
namespace Inet {
/**
* @brief Get the name of a network interface
*
* @param[in] intfId a network interface
* @param[in] nameBuf region of memory to write the interface name
* @param[in] nameBufSize size of the region denoted by \c nameBuf
*
* @retval INET_NO_ERROR successful result, interface name written
* @retval INET_ERROR_NO_MEMORY name is too large to be written in buffer
* @retval other another system or platform error
*
* @details
* Writes the name of the network interface as \c NUL terminated text string
* at \c nameBuf. The name of the unspecified network interface is the empty
* string.
*/
DLL_EXPORT INET_ERROR GetInterfaceName(InterfaceId intfId, char * nameBuf, size_t nameBufSize)
{
if (intfId != INET_NULL_INTERFACEID)
{
#if CHIP_SYSTEM_CONFIG_USE_LWIP
int status = snprintf(nameBuf, nameBufSize, "%c%c%d", intfId->name[0], intfId->name[1], intfId->num);
if (status >= static_cast<int>(nameBufSize))
return INET_ERROR_NO_MEMORY;
return INET_NO_ERROR;
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
char intfName[IF_NAMESIZE];
if (if_indextoname(intfId, intfName) == NULL)
return chip::System::MapErrorPOSIX(errno);
if (strlen(intfName) >= nameBufSize)
return INET_ERROR_NO_MEMORY;
strcpy(nameBuf, intfName);
return INET_NO_ERROR;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
}
else
{
if (nameBufSize < 1)
return INET_ERROR_NO_MEMORY;
nameBuf[0] = 0;
return INET_NO_ERROR;
}
}
/**
* @brief Search the list of network interfaces for the indicated name.
*
* @param[in] intfName name of the network interface to find
* @param[out] intfId indicator of the network interface to assign
*
* @retval INET_NO_ERROR success, network interface indicated
* @retval INET_ERROR_UNKNOWN_INTERFACE no network interface found
* @retval other another system or platform error
*
* @details
* On LwIP, this function must be called with the LwIP stack lock acquired.
*
* The \c intfId parameter is not updated unless the value returned is
* \c INET_NO_ERROR. It should be initialized with \c INET_NULL_INTERFACEID
* before calling this function.
*/
DLL_EXPORT INET_ERROR InterfaceNameToId(const char * intfName, InterfaceId & intfId)
{
#if CHIP_SYSTEM_CONFIG_USE_LWIP
if (strlen(intfName) < 3)
return INET_ERROR_UNKNOWN_INTERFACE;
char * parseEnd;
unsigned long intfNum = strtoul(intfName + 2, &parseEnd, 10);
if (*parseEnd != 0 || intfNum > UINT8_MAX)
return INET_ERROR_UNKNOWN_INTERFACE;
struct netif * intf;
#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 0 && defined(NETIF_FOREACH)
NETIF_FOREACH(intf)
#else
for (intf = netif_list; intf != NULL; intf = intf->next)
#endif
{
if (intf->name[0] == intfName[0] && intf->name[1] == intfName[1] && intf->num == (uint8_t) intfNum)
{
intfId = intf;
return INET_NO_ERROR;
}
}
intfId = INET_NULL_INTERFACEID;
return INET_ERROR_UNKNOWN_INTERFACE;
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
intfId = if_nametoindex(intfName);
if (intfId == 0)
return (errno == ENXIO) ? INET_ERROR_UNKNOWN_INTERFACE : chip::System::MapErrorPOSIX(errno);
return INET_NO_ERROR;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
}
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
static int sIOCTLSocket = -1;
/**
* @brief Returns a global general purpose socket useful for invoking certain network IOCTLs.
*
* This function is thread-safe on all platforms.
*/
int GetIOCTLSocket(void)
{
if (sIOCTLSocket == -1)
{
int s;
#ifdef SOCK_CLOEXEC
s = socket(AF_INET, SOCK_STREAM, SOCK_CLOEXEC);
if (s < 0)
#endif
{
s = socket(AF_INET, SOCK_STREAM, 0);
fcntl(s, O_CLOEXEC);
}
if (!__sync_bool_compare_and_swap(&sIOCTLSocket, -1, s))
{
close(s);
}
}
return sIOCTLSocket;
}
/**
* @brief Close the global socket created by \c GetIOCTLSocket.
*
* @details
* This function is provided for cases were leaving the global IOCTL socket
* open would register as a leak.
*
* NB: This function is NOT thread-safe with respect to \c GetIOCTLSocket.
*/
void CloseIOCTLSocket(void)
{
if (sIOCTLSocket == -1)
{
close(sIOCTLSocket);
sIOCTLSocket = -1;
}
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
/**
* @fn InterfaceIterator::InterfaceIterator(void)
*
* @brief Constructs an InterfaceIterator object.
*
* @details
* Starts the iterator at the first network interface. On some platforms,
* this constructor may allocate resources recycled by the destructor.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if __ANDROID__ && __ANDROID_API__ < 24
static struct if_nameindex * backport_if_nameindex(void);
static void backport_if_freenameindex(struct if_nameindex *);
static void backport_if_freenameindex(struct if_nameindex * inArray)
{
if (inArray == NULL)
{
return;
}
for (size_t i = 0; inArray[i].if_index != 0; i++)
{
if (inArray[i].if_name != NULL)
{
free(inArray[i].if_name);
}
}
free(inArray);
}
static struct if_nameindex * backport_if_nameindex(void)
{
int err;
unsigned index;
size_t intfIter = 0;
size_t maxIntfNum = 0;
size_t numIntf = 0;
size_t numAddrs = 0;
struct if_nameindex * retval = NULL;
struct if_nameindex * tmpval = NULL;
struct ifaddrs * addrList = NULL;
struct ifaddrs * addrIter = NULL;
const char * lastIntfName = "";
err = getifaddrs(&addrList);
VerifyOrExit(err >= 0, );
// coalesce on consecutive interface names
for (addrIter = addrList; addrIter != NULL; addrIter = addrIter->ifa_next)
{
numAddrs++;
if (strcmp(addrIter->ifa_name, lastIntfName) == 0)
{
continue;
}
numIntf++;
lastIntfName = addrIter->ifa_name;
}
tmpval = (struct if_nameindex *) malloc((numIntf + 1) * sizeof(struct if_nameindex));
VerifyOrExit(tmpval != NULL, );
memset(tmpval, 0, (numIntf + 1) * sizeof(struct if_nameindex));
lastIntfName = "";
for (addrIter = addrList; addrIter != NULL; addrIter = addrIter->ifa_next)
{
if (strcmp(addrIter->ifa_name, lastIntfName) == 0)
{
continue;
}
index = if_nametoindex(addrIter->ifa_name);
if (index != 0)
{
tmpval[intfIter].if_index = index;
tmpval[intfIter].if_name = strdup(addrIter->ifa_name);
intfIter++;
}
lastIntfName = addrIter->ifa_name;
}
// coalesce on interface index
maxIntfNum = 0;
for (size_t i = 0; tmpval[i].if_index != 0; i++)
{
if (maxIntfNum < tmpval[i].if_index)
{
maxIntfNum = tmpval[i].if_index;
}
}
retval = (struct if_nameindex *) malloc((maxIntfNum + 1) * sizeof(struct if_nameindex));
VerifyOrExit(retval != NULL, );
memset(retval, 0, (maxIntfNum + 1) * sizeof(struct if_nameindex));
for (size_t i = 0; tmpval[i].if_index != 0; i++)
{
struct if_nameindex * intf = &tmpval[i];
if (retval[intf->if_index - 1].if_index == 0)
{
retval[intf->if_index - 1] = *intf;
}
else
{
free(intf->if_name);
intf->if_index = 0;
intf->if_name = 0;
}
}
intfIter = 0;
// coalesce potential gaps between indeces
for (size_t i = 0; i < maxIntfNum; i++)
{
if (retval[i].if_index != 0)
{
retval[intfIter] = retval[i];
intfIter++;
}
}
for (size_t i = intfIter; i < maxIntfNum; i++)
{
retval[i].if_index = 0;
retval[i].if_name = NULL;
}
exit:
if (tmpval != NULL)
{
free(tmpval);
}
if (addrList != NULL)
{
freeifaddrs(addrList);
}
return retval;
}
#endif // __ANDROID__ && __ANDROID_API__ < 24
InterfaceIterator::InterfaceIterator(void)
{
mIntfArray = NULL;
mCurIntf = 0;
mIntfFlags = 0;
mIntfFlagsCached = 0;
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
/**
* @fn InterfaceIterator::~InterfaceIterator(void)
*
* @brief Destroys an InterfaceIterator object.
*
* @details
* Recycles any resources allocated by the constructor.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
InterfaceIterator::~InterfaceIterator(void)
{
if (mIntfArray != NULL)
{
#if __ANDROID__ && __ANDROID_API__ < 24
backport_if_freenameindex(mIntfArray);
#else
if_freenameindex(mIntfArray);
#endif
mIntfArray = NULL;
}
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
/**
* @fn bool InterfaceIterator::HasCurrent(void)
*
* @brief Test whether the iterator is positioned on an interface
*
* @return \c true if the iterator is positioned on an interface;
* \c false if positioned beyond the end of the interface list.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
bool InterfaceIterator::HasCurrent(void)
{
return (mIntfArray != NULL) ? mIntfArray[mCurIntf].if_index != 0 : Next();
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
/**
* @fn bool InterfaceIterator::Next(void)
*
* @brief Advance the iterator to the next network interface.
*
* @return \c false if advanced beyond the end, else \c true.
*
* @details
* Advances the internal iterator to the next network interface or to a position
* beyond the end of the interface list.
*
* On multi-threaded LwIP systems, this method is thread-safe relative to other
* threads accessing the global LwIP state provided that: 1) the other threads
* hold the LwIP core lock while mutating the list of netifs; and 2) netif objects
* themselves are never destroyed.
*
* Iteration is stable in the face of changes to the underlying system's
* interfaces, *except* in the case of LwIP systems when the currently selected
* interface is removed from the list, which causes iteration to end immediately.
*/
bool InterfaceIterator::Next(void)
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
if (mIntfArray == NULL)
{
#if __ANDROID__ && __ANDROID_API__ < 24
mIntfArray = backport_if_nameindex();
#else
mIntfArray = if_nameindex();
#endif
}
else if (mIntfArray[mCurIntf].if_index != 0)
{
mCurIntf++;
mIntfFlags = 0;
mIntfFlagsCached = false;
}
return (mIntfArray != NULL && mIntfArray[mCurIntf].if_index != 0);
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
// Lock LwIP stack
LOCK_TCPIP_CORE();
// Verify the previous netif is still on the list if netifs. If so,
// advance to the next nextif.
struct netif * prevNetif = mCurNetif;
#if LWIP_VERSION_MAJOR >= 2 && LWIP_VERSION_MINOR >= 0 && defined(NETIF_FOREACH)
NETIF_FOREACH(mCurNetif)
#else
for (mCurNetif = netif_list; mCurNetif != NULL; mCurNetif = mCurNetif->next)
#endif
{
if (mCurNetif == prevNetif)
{
mCurNetif = mCurNetif->next;
break;
}
}
// Unlock LwIP stack
UNLOCK_TCPIP_CORE();
return mCurNetif != NULL;
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
/**
* @fn InterfaceId InterfaceIterator::GetInterfaceId(void)
*
* @brief Returns the network interface id at the current iterator position.
*
* @retval INET_NULL_INTERFACEID if advanced beyond the end of the list.
* @retval id the current network interface id.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
InterfaceId InterfaceIterator::GetInterfaceId(void)
{
return (HasCurrent()) ? mIntfArray[mCurIntf].if_index : INET_NULL_INTERFACEID;
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
/**
* @brief Get the name of the current network interface
*
* @param[in] nameBuf region of memory to write the interface name
* @param[in] nameBufSize size of the region denoted by \c nameBuf
*
* @retval INET_NO_ERROR successful result, interface name written
* @retval INET_ERROR_INCORRECT_STATE
* iterator is positioned beyond the end of
* the list
* @retval INET_ERROR_NO_MEMORY name is too large to be written in buffer
* @retval other another system or platform error
*
* @details
* Writes the name of the network interface as \c NUL terminated text string
* at \c nameBuf.
*/
INET_ERROR InterfaceIterator::GetInterfaceName(char * nameBuf, size_t nameBufSize)
{
INET_ERROR err = INET_ERROR_NOT_IMPLEMENTED;
VerifyOrExit(HasCurrent(), err = INET_ERROR_INCORRECT_STATE);
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
VerifyOrExit(strlen(mIntfArray[mCurIntf].if_name) < nameBufSize, err = INET_ERROR_NO_MEMORY);
strncpy(nameBuf, mIntfArray[mCurIntf].if_name, nameBufSize);
err = INET_NO_ERROR;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
err = ::chip::Inet::GetInterfaceName(mCurNetif, nameBuf, nameBufSize);
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
exit:
return err;
}
/**
* @brief Returns whether the current network interface is up.
*
* @return \c true if current network interface is up, \c false if not
* or if the iterator is positioned beyond the end of the list.
*/
bool InterfaceIterator::IsUp(void)
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return (GetFlags() & IFF_UP) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return HasCurrent() && netif_is_up(mCurNetif);
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
/**
* @brief Returns whether the current network interface supports multicast.
*
* @return \c true if current network interface supports multicast, \c false
* if not, or if the iterator is positioned beyond the end of the list.
*/
bool InterfaceIterator::SupportsMulticast(void)
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return (GetFlags() & IFF_MULTICAST) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return HasCurrent() &&
#if LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
(mCurNetif->flags & (NETIF_FLAG_IGMP | NETIF_FLAG_MLD6 | NETIF_FLAG_BROADCAST)) != 0;
#else
(mCurNetif->flags & NETIF_FLAG_POINTTOPOINT) == 0;
#endif // LWIP_VERSION_MAJOR > 1 || LWIP_VERSION_MINOR >= 5
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
/**
* @brief Returns whether the current network interface has a broadcast address.
*
* @return \c true if current network interface has a broadcast address, \c false
* if not, or if the iterator is positioned beyond the end of the list.
*/
bool InterfaceIterator::HasBroadcastAddress(void)
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return (GetFlags() & IFF_BROADCAST) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return HasCurrent() && (mCurNetif->flags & NETIF_FLAG_BROADCAST) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
/**
* @fn short InterfaceIterator::GetFlags(void)
*
* @brief Returns the ifr_flags value for the current interface.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
short InterfaceIterator::GetFlags(void)
{
struct ifreq intfData;
if (!mIntfFlagsCached && HasCurrent())
{
strncpy(intfData.ifr_name, mIntfArray[mCurIntf].if_name, IFNAMSIZ);
intfData.ifr_name[IFNAMSIZ - 1] = '\0';
int res = ioctl(GetIOCTLSocket(), SIOCGIFFLAGS, &intfData);
if (res == 0)
{
mIntfFlags = intfData.ifr_flags;
mIntfFlagsCached = true;
}
}
return mIntfFlags;
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
/**
* @fn InterfaceAddressIterator::InterfaceAddressIterator(void)
*
* @brief Constructs an InterfaceAddressIterator object.
*
* @details
* Starts the iterator at the first network address. On some platforms,
* this constructor may allocate resources recycled by the destructor.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
InterfaceAddressIterator::InterfaceAddressIterator(void)
{
mAddrsList = NULL;
mCurAddr = NULL;
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
/**
* @fn InterfaceAddressIterator::~InterfaceAddressIterator(void)
*
* @brief Destroys an InterfaceAddressIterator object.
*
* @details
* Recycles any resources allocated by the constructor.
*/
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
InterfaceAddressIterator::~InterfaceAddressIterator(void)
{
if (mAddrsList != NULL)
{
freeifaddrs(mAddrsList);
mAddrsList = mCurAddr = NULL;
}
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
/**
* @fn bool InterfaceIterator::HasCurrent(void)
*
* @brief Test whether the iterator is positioned on an interface address
*
* @return \c true if the iterator is positioned on an interface address;
* \c false if positioned beyond the end of the address list.
*/
bool InterfaceAddressIterator::HasCurrent(void)
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
return (mAddrsList != NULL) ? (mCurAddr != NULL) : Next();
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS || CHIP_SYSTEM_CONFIG_USE_NETWORK_FRAMEWORK
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return mIntfIter.HasCurrent() && ((mCurAddrIndex != kBeforeStartIndex) || Next());
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
/**
* @fn bool InterfaceAddressIterator::Next(void)
*
* @brief Advance the iterator to the next interface address.
*
* @return \c false if advanced beyond the end, else \c true.
*
* @details
* Advances the iterator to the next interface address or to a position
* beyond the end of the address list.
*
* On LwIP, this method is thread-safe provided that: 1) other threads hold
* the LwIP core lock while mutating the netif list; and 2) netif objects
* themselves are never destroyed. Additionally, iteration on LwIP systems
* will terminate early if the current interface is removed from the list.
*/
bool InterfaceAddressIterator::Next(void)
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
while (true)
{
if (mAddrsList == NULL)
{
int res = getifaddrs(&mAddrsList);
if (res < 0)
{
return false;
}
mCurAddr = mAddrsList;
}
else if (mCurAddr != NULL)
{
mCurAddr = mCurAddr->ifa_next;
}
if (mCurAddr == NULL)
{
return false;
}
if (mCurAddr->ifa_addr != NULL &&
(mCurAddr->ifa_addr->sa_family == AF_INET6
#if INET_CONFIG_ENABLE_IPV4
|| mCurAddr->ifa_addr->sa_family == AF_INET
#endif // INET_CONFIG_ENABLE_IPV4
))
{
return true;
}
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
mCurAddrIndex++;
while (mIntfIter.HasCurrent())
{
struct netif * curIntf = mIntfIter.GetInterfaceId();
while (mCurAddrIndex < LWIP_IPV6_NUM_ADDRESSES)
{
if (ip6_addr_isvalid(netif_ip6_addr_state(curIntf, mCurAddrIndex)))
{
return true;
}
mCurAddrIndex++;
}
#if INET_CONFIG_ENABLE_IPV4 && LWIP_IPV4
if (mCurAddrIndex == LWIP_IPV6_NUM_ADDRESSES)
{
if (!ip4_addr_isany(netif_ip4_addr(curIntf)))
{
return true;
}
}
#endif // INET_CONFIG_ENABLE_IPV4 && LWIP_IPV4
mIntfIter.Next();
mCurAddrIndex = 0;
}
return false;
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
/**
* @fn IPAddress InterfaceAddressIterator::GetAddress(void)
*
* @brief Get the current interface address.
*
* @return the current interface address or \c IPAddress::Any if the iterator
* is positioned beyond the end of the address list.
*/
IPAddress InterfaceAddressIterator::GetAddress(void)
{
if (HasCurrent())
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return IPAddress::FromSockAddr(*mCurAddr->ifa_addr);
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
struct netif * curIntf = mIntfIter.GetInterfaceId();
if (mCurAddrIndex < LWIP_IPV6_NUM_ADDRESSES)
{
return IPAddress::FromIPv6(*netif_ip6_addr(curIntf, mCurAddrIndex));
}
#if INET_CONFIG_ENABLE_IPV4 && LWIP_IPV4
else
{
return IPAddress::FromIPv4(*netif_ip4_addr(curIntf));
}
#endif // INET_CONFIG_ENABLE_IPV4 && LWIP_IPV4
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
return IPAddress::Any;
}
/**
* @fn uint8_t InterfaceAddressIterator::GetPrefixLength(void)
*
* @brief Gets the network prefix associated with the current interface address.
*
* @return the network prefix (in bits) or 0 if the iterator is positioned beyond
* the end of the address list.
*
* @details
* On LwIP, this method simply returns the hard-coded constant 64.
*
* Note Well: the standard subnet prefix on all links other than PPP
* links is 64 bits. On PPP links and some non-broadcast multipoint access
* links, the convention is either 127 bits or 128 bits, but it might be
* something else. On most platforms, the system's interface address
* structure can represent arbitrary prefix lengths between 0 and 128.
*/
uint8_t InterfaceAddressIterator::GetPrefixLength(void)
{
if (HasCurrent())
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
if (mCurAddr->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6 & netmask = *(struct sockaddr_in6 *) (mCurAddr->ifa_netmask);
return NetmaskToPrefixLength(netmask.sin6_addr.s6_addr, 16);
}
if (mCurAddr->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in & netmask = *(struct sockaddr_in *) (mCurAddr->ifa_netmask);
return NetmaskToPrefixLength((const uint8_t *) &netmask.sin_addr.s_addr, 4);
}
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
if (mCurAddrIndex < LWIP_IPV6_NUM_ADDRESSES)
{
return 64;
}
#if INET_CONFIG_ENABLE_IPV4 && LWIP_IPV4
else
{
struct netif * curIntf = mIntfIter.GetInterfaceId();
return NetmaskToPrefixLength((const uint8_t *) netif_ip4_netmask(curIntf), 4);
}
#endif // INET_CONFIG_ENABLE_IPV4 && LWIP_IPV4
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
return 0;
}
/**
* @fn InterfaceId InterfaceAddressIterator::GetInterfaceId(void)
*
* @brief Returns the network interface id associated with the current
* interface address.
*
* @return the interface id or \c INET_NULL_INTERFACEID if the iterator
* is positioned beyond the end of the address list.
*/
InterfaceId InterfaceAddressIterator::GetInterfaceId(void)
{
if (HasCurrent())
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return if_nametoindex(mCurAddr->ifa_name);
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return mIntfIter.GetInterfaceId();
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
return INET_NULL_INTERFACEID;
}
/**
* @fn INET_ERROR InterfaceAddressIterator::GetInterfaceName(char * nameBuf, size_t nameBufSize)
*
* @brief Get the name of the network interface associated with the
* current interface address.
*
* @param[in] nameBuf region of memory to write the interface name
* @param[in] nameBufSize size of the region denoted by \c nameBuf
*
* @retval INET_NO_ERROR successful result, interface name written
* @retval INET_ERROR_NO_MEMORY name is too large to be written in buffer
* @retval INET_ERROR_INCORRECT_STATE
* the iterator is not currently positioned on an
* interface address
* @retval other another system or platform error
*
* @details
* Writes the name of the network interface as \c NUL terminated text string
* at \c nameBuf.
*/
INET_ERROR InterfaceAddressIterator::GetInterfaceName(char * nameBuf, size_t nameBufSize)
{
INET_ERROR err = INET_ERROR_NOT_IMPLEMENTED;
VerifyOrExit(HasCurrent(), err = INET_ERROR_INCORRECT_STATE);
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
VerifyOrExit(strlen(mCurAddr->ifa_name) < nameBufSize, err = INET_ERROR_NO_MEMORY);
strncpy(nameBuf, mCurAddr->ifa_name, nameBufSize);
err = INET_NO_ERROR;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
err = mIntfIter.GetInterfaceName(nameBuf, nameBufSize);
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
exit:
return err;
}
/**
* @fn bool InterfaceAddressIterator::IsUp(void)
*
* @brief Returns whether the network interface associated with the current
* interface address is up.
*
* @return \c true if current network interface is up, \c false if not, or
* if the iterator is not positioned on an interface address.
*/
bool InterfaceAddressIterator::IsUp(void)
{
if (HasCurrent())
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return (mCurAddr->ifa_flags & IFF_UP) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return mIntfIter.IsUp();
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
return false;
}
/**
* @fn bool InterfaceAddressIterator::SupportsMulticast(void)
*
* @brief Returns whether the network interface associated with the current
* interface address supports multicast.
*
* @return \c true if multicast is supported, \c false if not, or
* if the iterator is not positioned on an interface address.
*/
bool InterfaceAddressIterator::SupportsMulticast(void)
{
if (HasCurrent())
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return (mCurAddr->ifa_flags & IFF_MULTICAST) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return mIntfIter.SupportsMulticast();
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
return false;
}
/**
* @fn bool InterfaceAddressIterator::HasBroadcastAddress(void)
*
* @brief Returns whether the network interface associated with the current
* interface address has an IPv4 broadcast address.
*
* @return \c true if the interface has a broadcast address, \c false if not, or
* if the iterator is not positioned on an interface address.
*/
bool InterfaceAddressIterator::HasBroadcastAddress(void)
{
if (HasCurrent())
{
#if CHIP_SYSTEM_CONFIG_USE_SOCKETS
return (mCurAddr->ifa_flags & IFF_BROADCAST) != 0;
#endif // CHIP_SYSTEM_CONFIG_USE_SOCKETS
#if CHIP_SYSTEM_CONFIG_USE_LWIP
return mIntfIter.HasBroadcastAddress();
#endif // CHIP_SYSTEM_CONFIG_USE_LWIP
}
return false;
}
/**
* @fn void InterfaceAddressIterator::GetAddressWithPrefix(IPPrefix & addrWithPrefix)
*
* @brief Returns an IPPrefix containing the address and prefix length
* for the current address.
*/
void InterfaceAddressIterator::GetAddressWithPrefix(IPPrefix & addrWithPrefix)
{
if (HasCurrent())
{
addrWithPrefix.IPAddr = GetAddress();
addrWithPrefix.Length = GetPrefixLength();
}
else
{
addrWithPrefix = IPPrefix::Zero;
}
}
/**
* @fn uint8_t NetmaskToPrefixLength(const uint8_t * netmask, uint16_t netmaskLen)
*
* @brief Compute a prefix length from a variable-length netmask.
*/
uint8_t NetmaskToPrefixLength(const uint8_t * netmask, uint16_t netmaskLen)
{
uint8_t prefixLen = 0;
for (uint8_t i = 0; i < netmaskLen; i++, prefixLen += 8)
{
uint8_t b = netmask[i];
if (b != 0xFF)
{
if ((b & 0xF0) == 0xF0)
prefixLen += 4;
else
b = b >> 4;
if ((b & 0x0C) == 0x0C)
prefixLen += 2;
else
b = b >> 2;
if ((b & 0x02) == 0x02)
prefixLen++;
break;
}
}
return prefixLen;
}
} // namespace Inet
} // namespace chip
|
; void *zx_saddrpleft(void *saddr, uchar bitmask)
SECTION code_clib
SECTION code_arch
PUBLIC zx_saddrpleft
EXTERN asm_zx_saddrpleft
zx_saddrpleft:
pop af
pop de
pop hl
push hl
push de
push af
jp asm_zx_saddrpleft
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _zx_saddrpleft
defc _zx_saddrpleft = zx_saddrpleft
ENDIF
|
; ===============================================================
; Dec 2013
; ===============================================================
;
; void *memalign_unlocked(size_t alignment, size_t size)
;
; Allocate size bytes from the thread's default heap at an
; address that is an integer multiple of alignment.
; Returns 0 with carry set on failure.
;
; If alignment is not an exact power of 2, it will be rounded up
; to the next power of 2.
;
; Returns 0 if size == 0 without indicating error.
;
; ===============================================================
SECTION code_alloc_malloc
PUBLIC asm_memalign_unlocked
EXTERN asm_aligned_alloc_unlocked
defc asm_memalign_unlocked = asm_aligned_alloc_unlocked
; Attempt to allocate memory at an address that is aligned to a power of 2
; from the thread's default heap without locking
;
; enter : hl = size
; bc = alignment (promoted to next higher power of two if necessary)
;
; exit : success
;
; hl = void *p_aligned could be zero if size == 0
; carry reset
;
; fail on alignment = $10000
;
; hl = 0
; carry set, errno = EINVAL
;
; fail on memory not found
;
; hl = 0
; carry set, errno = ENOMEM
;
; uses : af, bc, de, hl
|
SFX_Cry08_1_Ch4:
dutycycle 240
squarenote 15, 15, 6, 1381
squarenote 10, 14, 4, 1404
squarenote 3, 12, 2, 1372
squarenote 15, 11, 2, 1340
endchannel
SFX_Cry08_1_Ch5:
dutycycle 90
squarenote 14, 13, 6, 1283
squarenote 9, 11, 4, 1307
squarenote 4, 9, 2, 1274
squarenote 15, 10, 2, 1243
endchannel
SFX_Cry08_1_Ch7:
noisenote 12, 14, 6, 76
noisenote 11, 13, 7, 92
noisenote 15, 12, 2, 76
endchannel
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r14
push %r15
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x1c65e, %r8
nop
nop
nop
and %r10, %r10
mov $0x6162636465666768, %rax
movq %rax, %xmm6
movups %xmm6, (%r8)
nop
nop
inc %r15
lea addresses_UC_ht+0x6c0e, %rbx
nop
nop
nop
nop
sub %r10, %r10
movb $0x61, (%rbx)
nop
nop
nop
and $55842, %r15
lea addresses_UC_ht+0xb01e, %r14
nop
nop
nop
sub %r10, %r10
movl $0x61626364, (%r14)
nop
nop
nop
nop
nop
add $13641, %r15
lea addresses_UC_ht+0x543e, %rax
nop
nop
and %rcx, %rcx
movb $0x61, (%rax)
nop
cmp $42918, %rax
lea addresses_WT_ht+0x1cc1e, %r8
cmp %r15, %r15
mov (%r8), %r10w
nop
nop
nop
nop
nop
sub %r15, %r15
lea addresses_normal_ht+0xba22, %rsi
lea addresses_D_ht+0xa5e, %rdi
sub $25470, %r10
mov $126, %rcx
rep movsq
nop
add $41954, %rdi
lea addresses_A_ht+0x625e, %rdi
add $24246, %r15
mov (%rdi), %bx
nop
and $15070, %r14
lea addresses_UC_ht+0xd95e, %rdi
nop
nop
nop
nop
nop
cmp $40265, %rsi
movb $0x61, (%rdi)
nop
nop
sub $32520, %r15
lea addresses_WC_ht+0x625e, %r10
nop
nop
nop
nop
nop
and %rsi, %rsi
movb (%r10), %cl
nop
cmp %r14, %r14
lea addresses_A_ht+0x53de, %rcx
nop
nop
nop
xor $38214, %r8
mov $0x6162636465666768, %r10
movq %r10, %xmm4
vmovups %ymm4, (%rcx)
nop
nop
add %rax, %rax
lea addresses_normal_ht+0x1247e, %r15
nop
nop
nop
nop
add $17696, %rbx
mov $0x6162636465666768, %rdi
movq %rdi, %xmm3
movups %xmm3, (%r15)
nop
nop
nop
nop
sub %r10, %r10
lea addresses_WT_ht+0x12a4a, %rsi
lea addresses_D_ht+0x1dafe, %rdi
cmp %r8, %r8
mov $50, %rcx
rep movsl
dec %rsi
lea addresses_A_ht+0xd70e, %r15
nop
nop
nop
nop
add $1056, %rcx
movw $0x6162, (%r15)
nop
nop
cmp %rax, %rax
lea addresses_UC_ht+0xa1b2, %rsi
lea addresses_UC_ht+0x5c5e, %rdi
nop
nop
cmp $8337, %r15
mov $50, %rcx
rep movsl
nop
nop
nop
nop
xor %r8, %r8
lea addresses_WC_ht+0x1619e, %rbx
nop
nop
sub %rcx, %rcx
movb (%rbx), %r14b
nop
nop
xor $59194, %r15
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r15
pop %r14
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r9
push %rax
push %rbx
push %rdx
push %rsi
// Store
lea addresses_WC+0x1b355, %r9
nop
nop
nop
nop
nop
inc %rsi
mov $0x5152535455565758, %r10
movq %r10, %xmm7
vmovups %ymm7, (%r9)
nop
nop
xor %r15, %r15
// Store
lea addresses_A+0x10e5e, %rax
nop
nop
nop
nop
nop
xor %rdx, %rdx
movb $0x51, (%rax)
nop
cmp $24663, %rdx
// Store
lea addresses_WT+0x1cd9e, %r15
nop
nop
nop
dec %rdx
mov $0x5152535455565758, %rbx
movq %rbx, (%r15)
nop
nop
add $41815, %rax
// Store
lea addresses_A+0xfa5e, %rax
clflush (%rax)
nop
xor %r15, %r15
movb $0x51, (%rax)
nop
nop
nop
xor $37583, %rdx
// Load
lea addresses_PSE+0x6b42, %r10
nop
nop
sub $50311, %rax
mov (%r10), %edx
nop
nop
cmp $2182, %r15
// Store
mov $0x690c62000000005e, %rdx
clflush (%rdx)
nop
nop
nop
nop
add $12159, %r9
mov $0x5152535455565758, %r15
movq %r15, %xmm2
movaps %xmm2, (%rdx)
nop
nop
nop
nop
inc %rax
// Store
lea addresses_normal+0x1d29e, %r10
nop
nop
nop
nop
nop
add %rbx, %rbx
movw $0x5152, (%r10)
nop
xor $11339, %rdx
// Faulty Load
lea addresses_A+0xfa5e, %rax
nop
nop
nop
add $17552, %rsi
mov (%rax), %r9w
lea oracles, %rsi
and $0xff, %r9
shlq $12, %r9
mov (%rsi,%r9,1), %r9
pop %rsi
pop %rdx
pop %rbx
pop %rax
pop %r9
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WC', 'size': 32, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_A', 'size': 1, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_WT', 'size': 8, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 1, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_PSE', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_NC', 'size': 16, 'AVXalign': True}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_normal', 'size': 2, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_A', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': True, 'congruent': 5, 'NT': False, 'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': True}}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}}
{'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}}
{'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}}
{'src': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'51': 4}
51 51 51 51
*/
|
; A037852: Number of normal subgroups of dihedral group with 2n elements.
; 2,5,3,6,3,7,3,7,4,7,3,9,3,7,5,8,3,9,3,9,5,7,3,11,4,7,5,9,3,11,3,9,5,7,5,12,3,7,5,11,3,11,3,9,7,7,3,13,4,9,5,9,3,11,5,11,5,7,3,15,3,7,7,10,5,11,3,9,5,11,3,15,3,7,7,9,5,11,3,13,6,7,3,15,5,7,5,11,3,15,5,9,5,7,5,15,3,9,7,12,3,11,3,11,9,7,3,15,3,11,5,13,3,11,5,9,7,7,5,19,4,7,5,9,5,15,3,11,5,11,3,15,5,7,9,11,3,11,3,15,5,7,5,18,5,7,7,9,3,15,3,11,7,11,5,15,3,7,5,15,5,13,3,9,9,7,3,19,4,11,7,9,3,11,7,13,5,7,3,21,3,11,5,11,5,11,5,9,9,11,3,17,3,7,9,12,3,15,3,15,5,7,5,15,5,7,7,13,5,19,3,9,5,7,5,19,5,7,5,15,5,11,3,15,10,7,3,15,3,11,9,11,3,15,5,9,5,11,3,23,3,9,7,9,7,11,5,11,5,11
mov $1,$0
cal $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n.
mod $1,2
add $1,18
mul $1,2
sub $1,2
add $1,$0
sub $1,33
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r14
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x51d6, %rsi
nop
nop
nop
nop
nop
dec %r13
mov $0x6162636465666768, %r10
movq %r10, %xmm3
movups %xmm3, (%rsi)
nop
nop
nop
nop
cmp $12630, %rax
lea addresses_WT_ht+0x1337e, %r9
nop
nop
nop
inc %rdi
vmovups (%r9), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $0, %xmm6, %r14
nop
nop
nop
nop
nop
dec %rsi
lea addresses_A_ht+0x117e, %rax
nop
nop
nop
nop
nop
add $6967, %r9
mov $0x6162636465666768, %r10
movq %r10, %xmm7
and $0xffffffffffffffc0, %rax
movntdq %xmm7, (%rax)
nop
xor $4274, %r9
lea addresses_WT_ht+0xb19e, %r10
clflush (%r10)
nop
add $20845, %rsi
mov $0x6162636465666768, %rdi
movq %rdi, %xmm3
vmovups %ymm3, (%r10)
nop
nop
xor %r14, %r14
lea addresses_normal_ht+0x1839e, %r13
nop
nop
nop
dec %r14
movups (%r13), %xmm1
vpextrq $1, %xmm1, %rsi
nop
add $26291, %r13
lea addresses_A_ht+0x1999e, %r10
and %r13, %r13
mov (%r10), %edi
nop
lfence
lea addresses_D_ht+0x18b9e, %rsi
lea addresses_normal_ht+0x139e, %rdi
clflush (%rsi)
nop
and %r14, %r14
mov $74, %rcx
rep movsb
cmp %rax, %rax
lea addresses_A_ht+0x1c79e, %r14
nop
nop
sub $55739, %r9
movl $0x61626364, (%r14)
nop
nop
nop
nop
nop
add $20710, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r14
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WC+0x1b6a3, %r13
nop
add %r10, %r10
movb $0x51, (%r13)
nop
nop
nop
nop
sub $43873, %r14
// REPMOV
lea addresses_US+0x1541e, %rsi
lea addresses_US+0x25fe, %rdi
nop
add %rdx, %rdx
mov $54, %rcx
rep movsb
nop
nop
add $41684, %rdx
// Load
mov $0x3a20900000000f1e, %rdi
nop
dec %r10
vmovaps (%rdi), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $1, %xmm4, %rdx
nop
nop
inc %rdx
// Store
mov $0x6be, %r10
nop
nop
nop
add $62540, %rdx
mov $0x5152535455565758, %r14
movq %r14, %xmm6
movups %xmm6, (%r10)
nop
dec %r14
// Store
lea addresses_RW+0x1819e, %r13
nop
sub %rdx, %rdx
movl $0x51525354, (%r13)
nop
sub $38800, %rsi
// Faulty Load
mov $0xa74000000019e, %rsi
nop
add %r10, %r10
movups (%rsi), %xmm0
vpextrq $0, %xmm0, %rdx
lea oracles, %r10
and $0xff, %rdx
shlq $12, %rdx
mov (%r10,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_US', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_US', 'congruent': 4, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_NC', 'same': False, 'size': 32, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_P', 'same': False, 'size': 16, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_RW', 'same': False, 'size': 4, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'same': True, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 16, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 16, 'congruent': 5, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal_ht', 'same': True, 'size': 16, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'54': 11396, '00': 10433}
54 54 00 54 54 00 54 54 54 54 00 00 54 00 54 54 00 54 54 54 54 00 00 00 00 54 54 00 00 54 00 54 54 54 54 00 00 54 00 54 54 54 00 00 54 00 00 00 00 54 00 54 54 54 54 54 54 00 00 54 00 00 00 54 54 54 00 00 54 00 54 00 54 00 54 00 00 00 00 54 00 54 54 54 54 54 00 54 54 54 00 00 00 00 00 54 00 00 00 54 00 00 00 54 00 00 00 54 00 00 54 00 54 54 00 00 00 00 00 00 00 00 54 00 00 00 54 54 54 54 00 00 00 54 00 00 00 54 00 00 00 54 54 54 00 00 00 54 54 00 54 54 54 00 54 00 54 54 00 54 00 00 00 00 00 00 00 54 54 00 00 00 00 54 54 00 00 54 54 54 54 54 54 00 54 00 54 54 54 00 00 00 00 54 00 00 00 00 00 54 54 00 54 00 54 00 00 54 00 00 54 00 54 54 00 54 00 54 00 54 54 00 00 00 00 00 00 54 54 00 00 54 00 54 00 00 00 00 54 00 00 00 54 00 54 00 54 00 54 54 54 00 00 00 54 00 54 54 54 54 54 00 54 54 00 54 00 54 54 54 00 54 00 00 00 00 00 54 54 54 54 00 00 00 00 54 54 54 00 54 54 00 00 00 54 54 00 00 00 54 00 54 00 54 00 00 00 00 54 54 54 54 00 00 54 54 00 00 54 00 00 54 54 00 00 00 00 54 00 54 00 54 00 00 54 00 54 54 00 00 54 54 54 54 00 00 00 54 54 00 54 00 00 54 00 00 54 54 54 00 00 00 54 54 00 54 54 54 00 00 54 00 00 00 00 00 00 54 54 00 00 54 00 54 54 00 54 54 00 00 00 00 54 54 54 54 00 54 00 00 00 54 54 54 54 54 00 54 00 00 00 00 54 00 00 54 54 54 00 00 54 00 54 00 54 00 54 00 00 00 00 54 54 00 00 54 00 00 00 54 00 54 00 00 54 00 00 00 00 00 54 00 54 54 00 54 00 54 00 00 00 54 54 00 00 54 00 00 00 54 00 00 00 00 00 00 00 54 54 00 54 00 00 00 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 00 54 54 54 00 00 54 54 54 54 54 00 54 54 54 54 54 00 00 00 00 54 54 00 54 54 54 54 00 00 00 54 00 00 54 00 00 00 54 00 00 00 00 00 00 54 54 54 54 54 00 54 00 54 54 00 00 54 00 00 54 00 54 00 54 00 54 00 54 54 00 54 54 00 00 54 54 00 54 54 54 00 54 54 00 00 00 54 54 54 54 54 00 00 54 54 00 00 00 54 00 00 00 54 54 54 54 00 54 54 54 54 00 54 54 54 54 00 54 54 54 00 54 54 54 00 54 54 54 00 00 54 00 54 54 00 54 00 54 00 00 00 00 54 54 54 54 54 54 54 00 54 54 00 00 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 54 54 00 54 54 54 54 54 00 54 00 54 00 54 54 00 00 00 00 54 54 54 54 00 54 54 00 00 54 54 00 54 00 00 00 00 00 00 00 00 54 00 00 00 54 00 00 54 54 54 00 00 00 00 00 00 54 00 54 54 00 00 00 00 00 54 00 54 00 54 54 00 00 54 54 00 54 00 54 54 54 00 00 54 00 54 54 00 54 00 00 54 54 54 00 54 54 00 00 54 00 00 54 54 54 00 00 00 00 00 00 00 54 00 00 54 54 54 54 00 54 00 00 00 00 00 54 54 54 00 54 00 54 00 00 00 54 54 54 54 54 00 54 00 00 00 00 54 00 54 00 00 54 54 00 54 54 54 00 00 54 54 54 54 54 54 00 54 00 54 54 54 00 00 00 54 00 54 00 54 00 54 00 54 54 00 00 54 54 54 54 54 00 00 00 54 00 54 54 54 00 54 00 54 54 54 00 54 00 00 00 54 54 00 54 00 54 00 54 00 54 54 00 00 54 54 54 54 00 54 00 00 54 54 00 54 00 00 00 00 54 00 54 54 54 00 54 54 00 00 00 54 00 00 54 54 54 00 00 54 54 00 54 54 00 54 00 00 54 00 54 54 54 54 54 00 00 00 54 00 54 54 00 00 54 54 54 00 00 00 54 00 54 00 54 54 54 54 00 54 00 54 00 00 54 54 54 00 00 54 54 00 54 00 54 00 00 54 00 54 00 54 54 00 00 00 54 54
*/
|
ldy {c1}
sty $fe
ldy {c1}+1
sty $ff
ldy #0
and ($fe),y
|
; A126324: a(2n) = Cat(n), a(2n+1) = 3*Cat(n), where Cat(n) = binomial(2n,n)/(n+1) are the Catalan numbers (A000108).
; Submitted by Jon Maiga
; 1,3,1,3,2,6,5,15,14,42,42,126,132,396,429,1287,1430,4290,4862,14586,16796,50388,58786,176358,208012,624036,742900,2228700,2674440,8023320,9694845,29084535,35357670,106073010,129644790,388934370,477638700,1432916100,1767263190,5301789570,6564120420,19692361260,24466267020,73398801060,91482563640,274447690920,343059613650,1029178840950,1289904147324,3869712441972,4861946401452,14585839204356,18367353072152,55102059216456,69533550916004,208600652748012,263747951750360,791243855251080
mov $2,$0
div $0,2
seq $0,108 ; Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
mod $2,2
seq $2,168604 ; a(n) = 2^(n-2) - 1.
mul $0,$2
|
/*
* Copyright 2009 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkFontLCDConfig.h"
#ifdef SK_LEGACY_SURFACE_PROPS
static SkFontLCDConfig::LCDOrientation gLCDOrientation = SkFontLCDConfig::kHorizontal_LCDOrientation;
static SkFontLCDConfig::LCDOrder gLCDOrder = SkFontLCDConfig::kRGB_LCDOrder;
SkFontLCDConfig::LCDOrientation SkFontLCDConfig::GetSubpixelOrientation() {
return gLCDOrientation;
}
void SkFontLCDConfig::SetSubpixelOrientation(LCDOrientation orientation) {
gLCDOrientation = orientation;
}
SkFontLCDConfig::LCDOrder SkFontLCDConfig::GetSubpixelOrder() {
return gLCDOrder;
}
void SkFontLCDConfig::SetSubpixelOrder(LCDOrder order) {
gLCDOrder = order;
}
#endif
|
/* UTEuropeanOptionSABR.cpp
*
* Copyright (c) 2016
* Diva Analytics
*/
#include "UTMathFunctions.h"
#include "UTEuropeanOptionSABR.h"
#include "UTEuropeanOptionLogNormal.h"
#include "UTEuropeanOptionNormal.h"
using namespace std;
///////////////////////////////////////////////////////////////////////////////
// Destructor
UTEuropeanOptionSABR::~UTEuropeanOptionSABR()
{
}
///////////////////////////////////////////////////////////////////////////////
// Default constructor
UTEuropeanOptionSABR::UTEuropeanOptionSABR()
: UTEuropeanOptionBase()
{
}
///////////////////////////////////////////////////////////////////////////////
// Constructor
UTEuropeanOptionSABR::UTEuropeanOptionSABR(
double dForward,
double dStrike,
double dTimeToExpiry,
double dSigma, // This is a CEV Volatility !!!
double dBeta, // CEV coefficient
double dAlpha, // volatility of volatility
double dRho, // correlation
UT_ExpansionType expansiontype)
: UTEuropeanOptionBase(dForward, dStrike, dTimeToExpiry, dSigma),
myAlpha(dAlpha),
myBeta(dBeta),
myRho(dRho),
myExpansionType(expansiontype)
{
// Make sure the Forward is STRICTLY positive when expansion type is lognormal
if (myExpansionType && forward() <= 0.0)
{
throw runtime_error("UTEuropeanOptionSABR :: cannot have a negative Forward with lognormal expansion");
}
// Make sure that the absolute value of rho is less than 1.
if (!(fabs(myRho) < 1.0))
throw runtime_error("UTEuropeanOptionSABR :: absolut value of correlation must be less than one");
// Calculates (IN SITU) the equivalent volatility and Derivatives
preliminaryCalculations();
}
///////////////////////////////////////////////////////////////////////////////
// Overwrites the sigma in the Option Pricer -- updates all that has to be updated (called by the solvers)
void
UTEuropeanOptionSABR::overwriteSigma(double newSigma)
{
UTEuropeanOptionBase::overwriteSigma(newSigma);
preliminaryCalculations();
}
///////////////////////////////////////////////////////////////////////////////
// Calculates all the terms needed for equivalent volatility transformations, as well as derivatives !!!!
void
UTEuropeanOptionSABR::preliminaryCalculations()
{
// First, treat the case when the volatility or time to expiry are zero
if (stdDev() < ourEpsilon)
{
myEquivalentVolatility = 0.0;
// Re-Builds the associated underlying option pricer, using the equivalent volatility that has just been calculated
if (myExpansionType == UT_LOGNORMAL)
{
myUnderlyingOption = unique_ptr<UTEuropeanOptionBase>(new UTEuropeanOptionLogNormal(forward(), strike(), timeToExpiry(), myEquivalentVolatility));
}
else
{
myUnderlyingOption = unique_ptr<UTEuropeanOptionBase>(new UTEuropeanOptionNormal(forward(), strike(), timeToExpiry(), myEquivalentVolatility));
}
return;
}
// Re-Builds the associated underlying option pricer, using the equivalent volatility that has just been calculated
if (myExpansionType == UT_LOGNORMAL)
{
//These are homeworks.
myEquivalentVolatility = 0.3;
myDEquivalentVolatilityDForward = 0.0;
myDEquivalentVolatilityDSigma = 0.0;
myDEquivalentVolatilityDTime = 0.0;
myUnderlyingOption = unique_ptr<UTEuropeanOptionBase>(new UTEuropeanOptionLogNormal(forward(), strike(), timeToExpiry(), myEquivalentVolatility));
}
else
{
//These are homeworks.
myEquivalentVolatility = 0.3 * 0.01; //This is a homework.
myDEquivalentVolatilityDForward = 0.0; //This is a homework.
myDEquivalentVolatilityDSigma = 0.0; //This is a homework.
myDEquivalentVolatilityDTime = 0.0; //This is a homework.
myUnderlyingOption = unique_ptr<UTEuropeanOptionBase>(new UTEuropeanOptionNormal(forward(), strike(), timeToExpiry(), myEquivalentVolatility));
}
}
///////////////////////////////////////////////////////////////////////////////
// The Option Premium
double
UTEuropeanOptionSABR::premium(UT_CallPut callPut) const
{
// Delegates
double premiumRtn = underlyingOption().premium(callPut);
// Returns the Premium
return UTMathFunctions::max(premiumRtn, intrinsic(callPut));
}
///////////////////////////////////////////////////////////////////////////////
// The Option Delta : dPremium/dForward
double
UTEuropeanOptionSABR::delta(UT_CallPut callPut) const
{
// Get the underlying delta : dUndP / dF;
double underlyingDelta = underlyingOption().delta(callPut);
// Get the underlying vega : dUndP / dEqSig;
double underlyingVega = underlyingOption().vega(callPut);
// Constructs the 'real' delta : dP/dF = dUndP/dF + dUndP/dEqSig * dEqSig/dF
double deltaRtn = underlyingDelta + underlyingVega * DEquivalentVolatilityDForward();
// Returns the Full Delta
return deltaRtn;
}
///////////////////////////////////////////////////////////////////////////////
// The Option Vega : dPremium/dSigma
double
UTEuropeanOptionSABR::vega(UT_CallPut callPut) const
{
// Get the underlying vega : dUndP / dEqSig;
double underlyingVega = underlyingOption().vega(callPut);
// Renormalises the Vega to get it wrt to the Real Volatility: dP/dSig = dUndP/dEqSig * dEqSig/dSig
double vegaRtn = underlyingVega * DEquivalentVolatilityDSigma();
// Return the Final Vega
return vegaRtn;
}
///////////////////////////////////////////////////////////////////////////////
// The Option Theta : -dPremium/dTimeToExpiry
double
UTEuropeanOptionSABR::theta(UT_CallPut callPut) const
{
// Get the underlying theta : -dUndP / dT;
double underlyingTheta = underlyingOption().theta(callPut);
// Get the underlying vega : dUndP / dEqSig;
double underlyingVega = underlyingOption().vega(callPut);
// Constructs the 'real' theta : -dP/dT = -dUndP/dT - dUndP/dEqSig * dEqSig/dT
double thetaRtn = underlyingTheta - underlyingVega * DEquivalentVolatilityDTime();
// Returns the Full Theta
return thetaRtn;
}
///////////////////////////////////////////////////////////////////////////////
// The Option Gamma (for this Forward, Strike, Volatility type...) : dDelta/dForward
double
UTEuropeanOptionSABR::gamma(UT_CallPut callPut) const
{
return 0.0; //Please implement
}
///////////////////////////////////////////////////////////////////////////////
|
;
; CPC Maths Routines
;
; August 2003 **_|warp6|_** <kbaccam /at/ free.fr>
;
; $Id: dgt.asm,v 1.3 2015/01/21 10:56:29 stefano Exp $
;
INCLUDE "cpcfirm.def"
INCLUDE "cpcfp.def"
PUBLIC dgt
PUBLIC dgtc
EXTERN fsetup
EXTERN stkequcmp
EXTERN cmpfin
.dgt call fsetup
call firmware
.dgtc defw CPCFP_FLO_CMP ; comp (hl)?(de)
cp $1 ;(hl) > (de)
jp z,cmpfin
xor a
jp stkequcmp
|
; A195027: a(n) = 2*n*(7*n + 5).
; 0,24,76,156,264,400,564,756,976,1224,1500,1804,2136,2496,2884,3300,3744,4216,4716,5244,5800,6384,6996,7636,8304,9000,9724,10476,11256,12064,12900,13764,14656,15576,16524,17500,18504,19536,20596,21684,22800,23944,25116,26316,27544,28800,30084,31396,32736,34104,35500,36924,38376,39856,41364,42900,44464,46056,47676,49324,51000,52704,54436,56196,57984,59800,61644,63516,65416,67344,69300,71284,73296,75336,77404,79500,81624,83776,85956,88164,90400,92664,94956,97276,99624,102000,104404,106836,109296
mov $1,14
mul $1,$0
add $1,10
mul $1,$0
mov $0,$1
|
;/** @file
;
; This code provides low level routines that support the Virtual Machine
; for option ROMs.
;
; Copyright (c) 2006 - 2011, 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.
;
;**/
page ,132
title VM ASSEMBLY LANGUAGE ROUTINES
;---------------------------------------------------------------------------
; Equate files needed.
;---------------------------------------------------------------------------
.XLIST
.LIST
;---------------------------------------------------------------------------
; Assembler options
;---------------------------------------------------------------------------
.686p
.model flat, C
.code
CopyMem PROTO Destination:PTR DWORD, Source:PTR DWORD, Count:DWORD
EbcInterpret PROTO
ExecuteEbcImageEntryPoint PROTO
;****************************************************************************
; EbcLLCALLEXNative
;
; This function is called to execute an EBC CALLEX instruction
; to native code.
; This instruction requires that we thunk out to external native
; code. For IA32, we simply switch stacks and jump to the
; specified function. On return, we restore the stack pointer
; to its original location.
;
; Destroys no working registers.
;****************************************************************************
; INT64 EbcLLCALLEXNative(UINTN FuncAddr, UINTN NewStackPointer, VOID *FramePtr)
EbcLLCALLEXNative PROC PUBLIC
push ebp
push ebx
mov ebp, esp ; standard function prolog
; Get function address in a register
; mov ecx, FuncAddr => mov ecx, dword ptr [FuncAddr]
mov ecx, dword ptr [esp]+0Ch
; Set stack pointer to new value
; mov eax, NewStackPointer => mov eax, dword ptr [NewSp]
mov eax, dword ptr [esp] + 14h
mov edx, dword ptr [esp] + 10h
sub eax, edx
sub esp, eax
mov ebx, esp
push ecx
push eax
push edx
push ebx
call CopyMem
pop eax
pop eax
pop eax
pop ecx
; Now call the external routine
call ecx
; ebp is preserved by the callee. In this function it
; equals the original esp, so set them equal
mov esp, ebp
; Standard function epilog
mov esp, ebp
pop ebx
pop ebp
ret
EbcLLCALLEXNative ENDP
;****************************************************************************
; EbcLLEbcInterpret
;
; Begin executing an EBC image.
;****************************************************************************
; UINT64 EbcLLEbcInterpret(VOID)
EbcLLEbcInterpret PROC PUBLIC
;
;; mov eax, 0xca112ebc
;; mov eax, EbcEntryPoint
;; mov ecx, EbcLLEbcInterpret
;; jmp ecx
;
; Caller uses above instruction to jump here
; The stack is below:
; +-----------+
; | RetAddr |
; +-----------+
; |EntryPoint | (EAX)
; +-----------+
; | Arg1 | <- EDI
; +-----------+
; | Arg2 |
; +-----------+
; | ... |
; +-----------+
; | Arg16 |
; +-----------+
; | EDI |
; +-----------+
; | ESI |
; +-----------+
; | EBP | <- EBP
; +-----------+
; | RetAddr | <- ESP is here
; +-----------+
; | Arg1 | <- ESI
; +-----------+
; | Arg2 |
; +-----------+
; | ... |
; +-----------+
; | Arg16 |
; +-----------+
;
; Construct new stack
push ebp
mov ebp, esp
push esi
push edi
sub esp, 40h
push eax
mov esi, ebp
add esi, 8
mov edi, esp
add edi, 4
mov ecx, 16
rep movsd
; call C-code
call EbcInterpret
add esp, 44h
pop edi
pop esi
pop ebp
ret
EbcLLEbcInterpret ENDP
;****************************************************************************
; EbcLLExecuteEbcImageEntryPoint
;
; Begin executing an EBC image.
;****************************************************************************
; UINT64 EbcLLExecuteEbcImageEntryPoint(VOID)
EbcLLExecuteEbcImageEntryPoint PROC PUBLIC
;
;; mov eax, 0xca112ebc
;; mov eax, EbcEntryPoint
;; mov ecx, EbcLLExecuteEbcImageEntryPoint
;; jmp ecx
;
; Caller uses above instruction to jump here
; The stack is below:
; +-----------+
; | RetAddr |
; +-----------+
; |EntryPoint | (EAX)
; +-----------+
; |ImageHandle|
; +-----------+
; |SystemTable|
; +-----------+
; | RetAddr | <- ESP is here
; +-----------+
; |ImageHandle|
; +-----------+
; |SystemTable|
; +-----------+
;
; Construct new stack
mov [esp - 0Ch], eax
mov eax, [esp + 04h]
mov [esp - 08h], eax
mov eax, [esp + 08h]
mov [esp - 04h], eax
; call C-code
sub esp, 0Ch
call ExecuteEbcImageEntryPoint
add esp, 0Ch
ret
EbcLLExecuteEbcImageEntryPoint ENDP
END
|
[bits 16]
; Switch to protected mode
switch_to_pm :
cli ; We must switch of interrupts until we have
; set - up the protected mode interrupt vector
; otherwise interrupts will run riot.
lgdt [gdt_descriptor] ; Load our global descriptor table , which defines
; the protected mode segments ( e.g. for code and data )
mov eax , cr0 ; To make the switch to protected mode , we set
or eax , 0x1 ; the first bit of CR0 , a control register
mov cr0 , eax
jmp CODE_SEG : init_pm ; Make a far jump ( i.e. to a new segment ) to our 32 - bit
; code. This also forces the CPU to flush its cache of
; pre - fetched and real - mode decoded instructions , which can
; cause problems.
[bits 32]
; Initialise registers and the stack once in PM.
init_pm :
mov ax,DATA_SEG ; Now in PM , our old segments are meaningless ,
mov ds,ax ; so we point our segment registers to the
mov ss,ax ; data selector we defined in our GDT
mov es,ax
mov fs,ax
mov gs,ax
mov ebp , 0x90000 ; Update our stack position so it is right
mov esp , ebp ; at the top of the free space.
call BEGIN_PM ; Finally , call some well-known label
|
; --COPYRIGHT--,BSD_EX
; Copyright (c) 2012, Texas Instruments Incorporated
; 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 Texas Instruments Incorporated 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.
;
; ******************************************************************************
;
; MSP430 CODE EXAMPLE DISCLAIMER
;
; MSP430 code examples are self-contained low-level programs that typically
; demonstrate a single peripheral function or device feature in a highly
; concise manner. For this the code may rely on the device's power-on default
; register values and settings such as the clock configuration and care must
; be taken when combining code from several examples to avoid potential side
; effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware
; for an API functional library-approach to peripheral configuration.
;
; --/COPYRIGHT--
;******************************************************************************
; MSP430F543xA Demo - Timer_A3, Toggle P1.0, Overflow ISR, DCO SMCLK
;
; Description: Toggle P1.0 using software and Timer1_A overflow ISR.
; In this example an ISR triggers when TA overflows. Inside the TA
; overflow ISR P1.0 is toggled. Toggle rate is approximatlely 16.8Hz.
; Proper use of the TAIV interrupt vector generator is demonstrated.
; ACLK = n/a, MCLK = SMCLK = TACLK = default DCO ~1.05MHz
;
; MSP430F5438A
; ---------------
; /|\| |
; | | |
; --|RST |
; | |
; | P1.0|-->LED
;
; D. Dang
; Texas Instruments Inc.
; December 2009
; Built with CCS Version: 4.0.2
;******************************************************************************
.cdecls C,LIST,"msp430.h"
;-------------------------------------------------------------------------------
.def RESET ; Export program entry-point to
; make it known to linker.
;-------------------------------------------------------------------------------
.global _main
.text ; Assemble to Flash memory
;-------------------------------------------------------------------------------
_main
RESET mov.w #0x5C00,SP ; Initialize stackpointer
mov.w #WDTPW + WDTHOLD,&WDTCTL; Stop WDT
bis.b #BIT0,&P1DIR ; P1.0 output
mov.w #TASSEL_2 + MC_2 + TACLR + TAIE,&TA1CTL
; SMCLK, contmode, clear TAR
; enable interrupt
bis.w #LPM0 + GIE,SR ; Enter LPM0, enable interrupts
nop ; For debugger
;-------------------------------------------------------------------------------
TIMER1_A1_ISR ; Timer_A3 Interrupt Vector (TAIV) handler
;-------------------------------------------------------------------------------
add.w &TA1IV,PC ; Vector to ISR handler
reti ; No interrupt
reti ; CCR1 not used
reti ; CCR2 not used
reti ; Reserved
reti ; Reserved
reti ; Reserved
reti ; Reserved
TA1IFG_HND xor.b #BIT0,&P1OUT ; Timer overflow handler
reti ; Return from interrupt
;-------------------------------------------------------------------------------
; Interrupt Vectors
;-------------------------------------------------------------------------------
.sect ".int48"
.short TIMER1_A1_ISR
.sect ".reset" ; POR, ext. Reset
.short RESET
.end
|
add a, a
|
;
;==================================================================================================
; ROMWBW 2.X CONFIGURATION FOR MARK IV
;==================================================================================================
;
; THIS FILE CONTAINS THE FULL SET OF DEFAULT CONFIGURATION SETTINGS FOR THE PLATFORM
; INDICATED ABOVE. THIS FILE SHOULD *NOT* NORMALLY BE CHANGED. INSTEAD, YOU SHOULD
; OVERRIDE ANY SETTINGS YOU WANT USING A CONFIGURATION FILE IN THE CONFIG DIRECTORY
; UNDER THIS DIRECTORY.
;
; THIS FILE CAN BE CONSIDERED A REFERENCE THAT LISTS ALL POSSIBLE CONFIGURATION SETTINGS
; FOR THE PLATFORM.
;
#DEFINE PLATFORM_NAME "MARK IV"
;
PLATFORM .EQU PLT_MK4 ; PLT_[SBC|ZETA|ZETA2|N8|MK4|UNA|RCZ80|RCZ180|EZZ80|SCZ180|DYNO]
CPUFAM .EQU CPU_Z180 ; CPU FAMILY: CPU_[Z80|Z180]
BIOS .EQU BIOS_WBW ; HARDWARE BIOS: BIOS_[WBW|UNA]
BATCOND .EQU FALSE ; ENABLE LOW BATTERY WARNING MESSAGE
HBIOS_MUTEX .EQU FALSE ; ENABLE REENTRANT CALLS TO HBIOS (ADDS OVERHEAD)
USELZSA2 .EQU TRUE ; ENABLE FONT COMPRESSION
;
BOOTTYPE .EQU BT_MENU ; BT_[MENU|AUTO], IF AUTO, BOOT DEFAULT AFTER TIMEOUT
BOOT_TIMEOUT .EQU 20 ; AUTO BOOT TIMEOUT IN SECONDS, 0 FOR IMMEDIATE BOOT
BOOT_DEFAULT .EQU 'Z' ; AUTO BOOT SELECTION TO INVOKE AT TIMEOUT
;
CPUOSC .EQU 18432000 ; CPU OSC FREQ IN MHZ
INTMODE .EQU 2 ; INTERRUPTS: 0=NONE, 1=MODE 1, 2=MODE 2
DEFSERCFG .EQU SER_38400_8N1 ; DEFAULT SERIAL LINE CONFIG (SEE STD.ASM)
;
RAMSIZE .EQU 512 ; SIZE OF RAM IN KB (MUST MATCH YOUR HARDWARE!!!)
MEMMGR .EQU MM_Z180 ; MEMORY MANAGER: MM_[SBC|Z2|N8|Z180]
RAMBIAS .EQU 512 ; OFFSET OF START OF RAM IN PHYSICAL ADDRESS SPACE
;
Z180_BASE .EQU $40 ; Z180: I/O BASE ADDRESS FOR INTERNAL REGISTERS
Z180_CLKDIV .EQU 1 ; Z180: CHK DIV: 0=OSC/2, 1=OSC, 2=OSC*2
Z180_MEMWAIT .EQU 0 ; Z180: MEMORY WAIT STATES (0-3)
Z180_IOWAIT .EQU 1 ; Z180: I/O WAIT STATES TO ADD ABOVE 1 W/S BUILT-IN (0-3)
;
MK4_IDE .EQU $80 ; MK4: IDE REGISTERS BASE ADR
MK4_XAR .EQU $88 ; MK4: EXTERNAL ADDRESS REGISTER (XAR) ADR
MK4_SD .EQU $89 ; MK4: SD CARD CONTROL REGISTER ADR
MK4_RTC .EQU $8A ; MK4: RTC LATCH REGISTER ADR
;
RTCIO .EQU MK4_RTC ; RTC LATCH REGISTER ADR
;
KIOENABLE .EQU FALSE ; ENABLE ZILOG KIO SUPPORT
KIOBASE .EQU $80 ; KIO BASE I/O ADDRESS
;
CTCENABLE .EQU FALSE ; ENABLE ZILOG CTC SUPPORT
;
DIAGENABLE .EQU FALSE ; ENABLES OUTPUT TO 8 BIT LED DIAGNOSTIC PORT
DIAGPORT .EQU $00 ; DIAGNOSTIC PORT ADDRESS
DIAGDISKIO .EQU TRUE ; ENABLES DISK I/O ACTIVITY ON DIAGNOSTIC LEDS
;
LEDENABLE .EQU FALSE ; ENABLES STATUS LED (SINGLE LED)
LEDPORT .EQU $0E ; STATUS LED PORT ADDRESS
LEDDISKIO .EQU TRUE ; ENABLES DISK I/O ACTIVITY ON STATUS LED
;
DSKYENABLE .EQU FALSE ; ENABLES DSKY (DO NOT COMBINE WITH PPIDE)
;
CRTACT .EQU FALSE ; ACTIVATE CRT (VDU,CVDU,PROPIO,ETC) AT STARTUP
VDAEMU .EQU EMUTYP_ANSI ; VDA EMULATION: EMUTYP_[TTY|ANSI]
ANSITRACE .EQU 1 ; ANSI DRIVER TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
PPKTRACE .EQU 1 ; PPK DRIVER TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
KBDTRACE .EQU 1 ; KBD DRIVER TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
PPKKBLOUT .EQU KBD_US ; PPK KEYBOARD LANGUAGE: KBD_[US|DE]
KBDKBLOUT .EQU KBD_US ; KBD KEYBOARD LANGUAGE: KBD_[US|DE]
;
HTIMENABLE .EQU FALSE ; ENABLE SIMH TIMER SUPPORT
SIMRTCENABLE .EQU FALSE ; ENABLE SIMH CLOCK DRIVER (SIMRTC.ASM)
;
DSRTCENABLE .EQU TRUE ; DSRTC: ENABLE DS-1302 CLOCK DRIVER (DSRTC.ASM)
DSRTCMODE .EQU DSRTCMODE_STD ; DSRTC: OPERATING MODE: DSRTC_[STD|MFPIC]
DSRTCCHG .EQU FALSE ; DSRTC: FORCE BATTERY CHARGE ON (USE WITH CAUTION!!!)
;
BQRTCENABLE .EQU FALSE ; BQRTC: ENABLE BQ4845 CLOCK DRIVER (BQRTC.ASM)
BQRTC_BASE .EQU $50 ; BQRTC: I/O BASE ADDRESS
;
UARTENABLE .EQU TRUE ; UART: ENABLE 8250/16550-LIKE SERIAL DRIVER (UART.ASM)
UARTOSC .EQU 1843200 ; UART: OSC FREQUENCY IN MHZ
UARTCFG .EQU DEFSERCFG ; UART: LINE CONFIG FOR UART PORTS
UARTCASSPD .EQU SER_300_8N1 ; UART: ECB CASSETTE UART DEFAULT SPEED
UARTSBC .EQU FALSE ; UART: AUTO-DETECT SBC/ZETA ONBOARD UART
UARTCAS .EQU TRUE ; UART: AUTO-DETECT ECB CASSETTE UART
UARTMFP .EQU FALSE ; UART: AUTO-DETECT MF/PIC UART
UART4 .EQU TRUE ; UART: AUTO-DETECT 4UART UART
;
ASCIENABLE .EQU TRUE ; ASCI: ENABLE Z180 ASCI SERIAL DRIVER (ASCI.ASM)
ASCI0CFG .EQU DEFSERCFG ; ASCI 0: SERIAL LINE CONFIG
ASCI1CFG .EQU DEFSERCFG ; ASCI 1: SERIAL LINE CONFIG
;
ACIAENABLE .EQU FALSE ; ACIA: ENABLE MOTOROLA 6850 ACIA DRIVER (ACIA.ASM)
;
SIOENABLE .EQU FALSE ; SIO: ENABLE ZILOG SIO SERIAL DRIVER (SIO.ASM)
;
XIOCFG .EQU DEFSERCFG ; XIO: SERIAL LINE CONFIG
;
VDUENABLE .EQU FALSE ; VDU: ENABLE VDU VIDEO/KBD DRIVER (VDU.ASM)
VDUSIZ .EQU V80X25 ; VDU: DISPLAY FORMAT [V80X24|V80X25|V80X30]
CVDUENABLE .EQU FALSE ; CVDU: ENABLE CVDU VIDEO/KBD DRIVER (CVDU.ASM)
NECENABLE .EQU FALSE ; NEC: ENABLE NEC UPD7220 VIDEO/KBD DRIVER (NEC.ASM)
TMSENABLE .EQU FALSE ; TMS: ENABLE TMS9918 VIDEO/KBD DRIVER (TMS.ASM)
TMSMODE .EQU TMSMODE_SCG ; TMS: DRIVER MODE: TMSMODE_[SCG/N8]
VGAENABLE .EQU FALSE ; VGA: ENABLE VGA VIDEO/KBD DRIVER (VGA.ASM)
VGASIZ .EQU V80X25 ; VGA: DISPLAY FORMAT [V80X25|V80X30|V80X43]
;
SPKENABLE .EQU FALSE ; SPK: ENABLE RTC LATCH IOBIT SOUND DRIVER (SPK.ASM)
;
AYENABLE .EQU FALSE ; AY: ENABLE AY PSG SOUND DRIVER
AYMODE .EQU AYMODE_SCG ; AY: DRIVER MODE: AYMODE_[SCG/N8/RCZ80/RCZ180]
;
MDENABLE .EQU TRUE ; MD: ENABLE MEMORY (ROM/RAM) DISK DRIVER (MD.ASM)
MDTRACE .EQU 1 ; MD: TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
;
FDENABLE .EQU FALSE ; FD: ENABLE FLOPPY DISK DRIVER (FD.ASM)
FDMODE .EQU FDMODE_N8 ; FD: DRIVER MODE: FDMODE_[DIO|ZETA|DIDE|N8|DIO3|DYNO]
FDTRACE .EQU 1 ; FD: TRACE LEVEL (0=NO,1=FATAL,2=ERRORS,3=ALL)
FDMEDIA .EQU FDM144 ; FD: DEFAULT MEDIA FORMAT FDM[720|144|360|120|111]
FDMEDIAALT .EQU FDM720 ; FD: ALTERNATE MEDIA FORMAT FDM[720|144|360|120|111]
FDMAUTO .EQU TRUE ; FD: AUTO SELECT DEFAULT/ALTERNATE MEDIA FORMATS
;
RFENABLE .EQU FALSE ; RF: ENABLE RAM FLOPPY DRIVER
RFCNT .EQU 1 ; RF: NUMBER OF RAM FLOPPY UNITS (1-4)
;
IDEENABLE .EQU TRUE ; IDE: ENABLE IDE DISK DRIVER (IDE.ASM)
IDETRACE .EQU 1 ; IDE: TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
IDECNT .EQU 1 ; IDE: NUMBER OF IDE INTERFACES TO DETECT (1-3), 2 DRIVES EACH
IDE0MODE .EQU IDEMODE_MK4 ; IDE 0: DRIVER MODE: IDEMODE_[DIO|DIDE|MK4|RC]
IDE0BASE .EQU $80 ; IDE 0: IO BASE ADDRESS
IDE0DATLO .EQU $00 ; IDE 0: DATA LO PORT FOR 16-BIT I/O
IDE0DATHI .EQU $00 ; IDE 0: DATA HI PORT FOR 16-BIT I/O
IDE0A8BIT .EQU TRUE ; IDE 0A (MASTER): 8 BIT XFER
IDE0B8BIT .EQU TRUE ; IDE 0B (MASTER): 8 BIT XFER
IDE1MODE .EQU IDEMODE_DIDE ; IDE 1: DRIVER MODE: IDEMODE_[DIO|DIDE|MK4|RC]
IDE1BASE .EQU $20 ; IDE 1: IO BASE ADDRESS
IDE1DATLO .EQU $28 ; IDE 1: DATA LO PORT FOR 16-BIT I/O
IDE1DATHI .EQU $28 ; IDE 1: DATA HI PORT FOR 16-BIT I/O
IDE1A8BIT .EQU FALSE ; IDE 1A (MASTER): 8 BIT XFER
IDE1B8BIT .EQU FALSE ; IDE 1B (MASTER): 8 BIT XFER
IDE2MODE .EQU IDEMODE_DIDE ; IDE 2: DRIVER MODE: IDEMODE_[DIO|DIDE|MK4|RC]
IDE2BASE .EQU $30 ; IDE 2: IO BASE ADDRESS
IDE2DATLO .EQU $38 ; IDE 2: DATA LO PORT FOR 16-BIT I/O
IDE2DATHI .EQU $38 ; IDE 2: DATA HI PORT FOR 16-BIT I/O
IDE2A8BIT .EQU FALSE ; IDE 2A (MASTER): 8 BIT XFER
IDE2B8BIT .EQU FALSE ; IDE 2B (MASTER): 8 BIT XFER
;
PPIDEENABLE .EQU FALSE ; PPIDE: ENABLE PARALLEL PORT IDE DISK DRIVER (PPIDE.ASM)
PPIDETRACE .EQU 1 ; PPIDE: TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
PPIDECNT .EQU 2 ; PPIDE: NUMBER OF PPI CHIPS TO DETECT (1-3), 2 DRIVES PER CHIP
PPIDE0BASE .EQU $44 ; PPIDE 0: PPI REGISTERS BASE ADR
PPIDE0A8BIT .EQU FALSE ; PPIDE 0A (MASTER): 8 BIT XFER
PPIDE0B8BIT .EQU FALSE ; PPIDE 0B (SLAVE): 8 BIT XFER
PPIDE1BASE .EQU $20 ; PPIDE 1: PPI REGISTERS BASE ADR
PPIDE1A8BIT .EQU FALSE ; PPIDE 1A (MASTER): 8 BIT XFER
PPIDE1B8BIT .EQU FALSE ; PPIDE 0B (SLAVE): 8 BIT XFER
PPIDE2BASE .EQU $00 ; PPIDE 2: PPI REGISTERS BASE ADR
PPIDE2A8BIT .EQU FALSE ; PPIDE 2A (MASTER): 8 BIT XFER
PPIDE2B8BIT .EQU FALSE ; PPIDE 0B (SLAVE): 8 BIT XFER
;
SDENABLE .EQU TRUE ; SD: ENABLE SD CARD DISK DRIVER (SD.ASM)
SDMODE .EQU SDMODE_MK4 ; SD: DRIVER MODE: SDMODE_[JUHA|N8|CSIO|PPI|UART|DSD|MK4|SC|MT]
SDCNT .EQU 1 ; SD: NUMBER OF SD CARD DEVICES (1-2), FOR DSD & SC ONLY
SDTRACE .EQU 1 ; SD: TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
SDCSIOFAST .EQU TRUE ; SD: ENABLE TABLE-DRIVEN BIT INVERTER IN CSIO MODE
;
PRPENABLE .EQU FALSE ; PRP: ENABLE ECB PROPELLER IO BOARD DRIVER (PRP.ASM)
PRPSDENABLE .EQU TRUE ; PRP: ENABLE PROPIO DRIVER SD CARD SUPPORT
PRPSDTRACE .EQU 1 ; PRP: SD CARD TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
PRPCONENABLE .EQU TRUE ; PRP: ENABLE PROPIO DRIVER VIDEO/KBD SUPPORT
;
PPPENABLE .EQU FALSE ; PPP: ENABLE ZETA PARALLEL PORT PROPELLER BOARD DRIVER (PPP.ASM)
PPPSDENABLE .EQU TRUE ; PPP: ENABLE PPP DRIVER SD CARD SUPPORT
PPPSDTRACE .EQU 1 ; PPP: SD CARD TRACE LEVEL (0=NO,1=ERRORS,2=ALL)
PPPCONENABLE .EQU TRUE ; PPP: ENABLE PPP DRIVER VIDEO/KBD SUPPORT
;
HDSKENABLE .EQU FALSE ; HDSK: ENABLE SIMH HDSK DISK DRIVER (HDSK.ASM)
;
PIO_4P .EQU FALSE ; PIO: ENABLE PARALLEL PORT DRIVER FOR ECB 4P BOARD
PIO4BASE .EQU $90 ; PIO: PIO REGISTERS BASE ADR FOR ECB 4P BOARD
PIO_ZP .EQU FALSE ; PIO: ENABLE PARALLEL PORT DRIVER FOR ECB ZILOG PERIPHERALS BOARD (PIO.ASM)
PIOZBASE .EQU $88 ; PIO: PIO REGISTERS BASE ADR FOR ECB ZP BOARD
PPI_SBC .EQU FALSE ; PIO: ENABLE PARALLEL PORT DRIVER FOR 8255 CHIP
;
UFENABLE .EQU FALSE ; UF: ENABLE ECB USB FIFO DRIVER (UF.ASM)
UFBASE .EQU $0C ; UF: REGISTERS BASE ADR
;
EIPCENABLE .EQU FALSE ; EIPC: ENABLE Z80 EIPC (Z84C15) INITIALIZATION
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r14
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0x1360, %rsi
lea addresses_WC_ht+0xd992, %rdi
nop
nop
nop
nop
nop
cmp %r10, %r10
mov $3, %rcx
rep movsw
nop
cmp $9158, %rax
lea addresses_A_ht+0x6b9e, %rdx
nop
nop
and %r14, %r14
movups (%rdx), %xmm6
vpextrq $1, %xmm6, %rsi
nop
add $56088, %rdx
lea addresses_A_ht+0x11b7a, %rsi
nop
nop
nop
inc %rdx
mov $0x6162636465666768, %rcx
movq %rcx, %xmm3
vmovups %ymm3, (%rsi)
nop
nop
nop
nop
sub %rsi, %rsi
lea addresses_A_ht+0xf6a2, %rsi
lea addresses_normal_ht+0x15422, %rdi
clflush (%rsi)
clflush (%rdi)
nop
nop
nop
nop
add %rdx, %rdx
mov $67, %rcx
rep movsw
lfence
lea addresses_WC_ht+0x970d, %rsi
lea addresses_A_ht+0x6aa2, %rdi
nop
nop
sub %r11, %r11
mov $10, %rcx
rep movsq
nop
nop
nop
nop
nop
cmp $23908, %rax
lea addresses_WC_ht+0x1cca2, %rdx
nop
nop
nop
add $61593, %r14
movups (%rdx), %xmm1
vpextrq $0, %xmm1, %rdi
nop
nop
nop
nop
nop
inc %r14
lea addresses_WT_ht+0xf6a2, %rsi
lea addresses_D_ht+0x195a2, %rdi
nop
nop
sub $12858, %r10
mov $11, %rcx
rep movsb
xor $65014, %rax
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r14
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r15
push %r9
push %rbp
push %rcx
push %rdi
// Load
lea addresses_normal+0x12e42, %rbp
nop
nop
nop
nop
nop
cmp %r10, %r10
vmovups (%rbp), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $0, %xmm6, %rdi
nop
nop
nop
nop
sub $51982, %rbp
// Store
lea addresses_RW+0x6ea2, %r10
nop
nop
add $14286, %r9
mov $0x5152535455565758, %rbp
movq %rbp, %xmm2
movups %xmm2, (%r10)
nop
nop
and $37863, %rdi
// Store
lea addresses_US+0x12a2, %r10
cmp $45741, %rcx
mov $0x5152535455565758, %r15
movq %r15, (%r10)
// Exception!!!
nop
nop
nop
nop
nop
mov (0), %r15
nop
nop
nop
add %rbp, %rbp
// Store
lea addresses_UC+0xdda2, %r15
nop
nop
nop
nop
nop
add $53516, %rcx
mov $0x5152535455565758, %rdi
movq %rdi, %xmm1
vmovaps %ymm1, (%r15)
nop
nop
nop
add $36619, %r9
// Load
mov $0x87a, %r10
nop
nop
nop
cmp %r9, %r9
mov (%r10), %edi
nop
nop
nop
add %rcx, %rcx
// Faulty Load
lea addresses_US+0x12a2, %r12
nop
nop
nop
nop
add $65034, %rcx
movb (%r12), %r10b
lea oracles, %rdi
and $0xff, %r10
shlq $12, %r10
mov (%rdi,%r10,1), %r10
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 4}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': True, 'size': 32, 'NT': True, 'same': False, 'congruent': 2}}
{'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 3}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_US', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 2}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}}
{'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}}
{'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': True}}
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': True}}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; A075876: Values of n for which A075825(n)=1.
; Submitted by Jon Maiga
; 0,2,4,12,52,212,852,3412,13652,54612,218452,873812,3495252,13981012
mov $1,4
pow $1,$0
mul $1,5
div $1,48
max $1,$0
mov $0,$1
mul $0,2
|
#include "Dog.h"
#include <iostream>
#include <string>
Dog::Dog(std::string aName) : cuteness(0), isFluffy(true), name()
{
name = aName;
std::cout << "Dog::Dog() constructor for " << aName << "\n";
}
Dog::~Dog(){
std::cout << "DESTRUCT!!" << "\n";
}
// copy constructor
Dog::Dog(const Dog *dref){ // expects a pointer as argument
std::cout << "Dog::Dog() copy constructor: " << dref << "\n";
cuteness = dref->cuteness;
isFluffy = dref->isFluffy;
name = dref->name;
}
// assignment operator
// does NOT get called by main if '*doper' instead of '&doper'
// needs to be reference to a Dog NOT a pointer
Dog& Dog::operator = (const Dog &doper){
std::cout << "Dog::Dog() operator" << "\n";
return *this;
}
void Dog::setName(std::string aName){
name = aName;
}
std::string Dog::getName(){
return name;
}
void Dog::setCuteness(int cute){
cuteness = cute;
}
int Dog::getCuteness(){
return cuteness;
} |
; int adt_ListAdd(struct adt_List *list, void *item)
; 02.2003, 06.2005 aralbrec
; CALLER linkage for function pointers
SECTION code_clib
PUBLIC adt_ListAdd
PUBLIC _adt_ListAdd
EXTERN asm_adt_ListAdd
.adt_ListAdd
._adt_ListAdd
pop hl
pop bc
pop de
push de
push bc
push hl
jp asm_adt_ListAdd
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r9
push %rax
push %rbp
push %rbx
push %rdi
// Faulty Load
lea addresses_US+0x144aa, %rax
nop
nop
nop
nop
inc %rbp
mov (%rax), %ebx
lea oracles, %r10
and $0xff, %rbx
shlq $12, %rbx
mov (%r10,%rbx,1), %rbx
pop %rdi
pop %rbx
pop %rbp
pop %rax
pop %r9
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_US', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r14
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0xc020, %rsi
lea addresses_WC_ht+0x12b0, %rdi
clflush (%rdi)
sub %rax, %rax
mov $93, %rcx
rep movsq
nop
sub $1016, %r13
lea addresses_normal_ht+0x93c7, %r9
sub %r14, %r14
movb (%r9), %cl
nop
and %rsi, %rsi
lea addresses_A_ht+0x30, %rsi
lea addresses_D_ht+0x10d30, %rdi
and $62167, %r13
mov $122, %rcx
rep movsb
dec %r14
lea addresses_UC_ht+0x1d468, %rsi
lea addresses_D_ht+0x101ec, %rdi
nop
nop
nop
sub $30650, %r11
mov $9, %rcx
rep movsl
nop
nop
nop
inc %rsi
lea addresses_WC_ht+0x1b8f0, %rsi
lea addresses_A_ht+0x1d630, %rdi
clflush (%rdi)
nop
add %r9, %r9
mov $51, %rcx
rep movsq
and %rax, %rax
lea addresses_WC_ht+0x18e30, %r9
nop
nop
nop
nop
dec %rax
movups (%r9), %xmm5
vpextrq $1, %xmm5, %r11
nop
nop
nop
nop
nop
xor %r11, %r11
lea addresses_A_ht+0xe630, %r11
nop
nop
and $18267, %r14
movw $0x6162, (%r11)
nop
nop
nop
nop
lfence
lea addresses_D_ht+0x4960, %r11
nop
nop
add %r14, %r14
mov $0x6162636465666768, %rax
movq %rax, %xmm4
movups %xmm4, (%r11)
cmp %rdi, %rdi
lea addresses_UC_ht+0xbb30, %r11
nop
nop
and $30538, %rdi
mov $0x6162636465666768, %rsi
movq %rsi, %xmm5
and $0xffffffffffffffc0, %r11
vmovaps %ymm5, (%r11)
nop
nop
xor $48388, %r13
lea addresses_WC_ht+0x119d0, %rax
nop
cmp %rsi, %rsi
movb $0x61, (%rax)
nop
nop
and %rax, %rax
lea addresses_A_ht+0x11c50, %r9
clflush (%r9)
inc %r14
movb (%r9), %r11b
nop
nop
nop
nop
add $6138, %rdi
lea addresses_D_ht+0x14fe0, %rcx
add $43132, %r11
mov $0x6162636465666768, %r9
movq %r9, %xmm5
vmovups %ymm5, (%rcx)
nop
nop
nop
nop
sub %rax, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r14
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r14
push %rax
push %rdi
push %rsi
// Store
lea addresses_WC+0x12a30, %rax
xor $30432, %r11
mov $0x5152535455565758, %rsi
movq %rsi, (%rax)
nop
sub %rsi, %rsi
// Store
mov $0x230, %r13
nop
nop
nop
nop
nop
dec %r10
mov $0x5152535455565758, %rsi
movq %rsi, %xmm2
movups %xmm2, (%r13)
nop
nop
sub %rsi, %rsi
// Store
lea addresses_PSE+0x6830, %r10
and %rax, %rax
movb $0x51, (%r10)
// Exception!!!
nop
mov (0), %rax
nop
nop
add %r11, %r11
// Store
lea addresses_US+0x51a5, %r13
and $52093, %rdi
movb $0x51, (%r13)
nop
nop
add $42363, %r11
// Load
lea addresses_WC+0x1ee30, %r10
nop
nop
add %rax, %rax
movb (%r10), %r13b
nop
nop
sub %rsi, %rsi
// Faulty Load
lea addresses_UC+0x12e30, %r11
nop
nop
nop
nop
sub %rax, %rax
mov (%r11), %si
lea oracles, %r10
and $0xff, %rsi
shlq $12, %rsi
mov (%r10,%rsi,1), %rsi
pop %rsi
pop %rdi
pop %rax
pop %r14
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_P', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 10}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_UC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_normal_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 6}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': True, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 8}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 7}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 2}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 0}}
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_WC_ht', 'congruent': 4}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_A_ht', 'same': True, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A153153: Permutation of natural numbers: A059893-conjugate of A003188.
; Submitted by Simon Strandgaard
; 0,1,3,2,5,6,7,4,9,10,15,12,13,14,11,8,17,18,23,20,29,30,27,24,25,26,31,28,21,22,19,16,33,34,39,36,45,46,43,40,57,58,63,60,53,54,51,48,49,50,55,52,61,62,59,56,41,42,47,44,37,38,35,32,65,66,71,68,77,78,75,72,89,90,95,92,85,86,83,80,113,114,119,116,125,126,123,120,105,106,111,108,101,102,99,96,97,98,103,100
mov $1,$0
trn $0,1
seq $0,59893 ; Reverse the order of all but the most significant bit in binary expansion of n: if n = 1ab..yz then a(n) = 1zy..ba.
seq $0,3188 ; Decimal equivalent of Gray code for n.
sub $0,1
seq $0,59893 ; Reverse the order of all but the most significant bit in binary expansion of n: if n = 1ab..yz then a(n) = 1zy..ba.
cmp $1,0
cmp $1,0
mul $0,$1
|
/** Task
* Написать чат-сервер.
* Каждое сообщение, посланное одним клиентом,
* передается всем остальным.
* К началу каждого сообщения присоединяется IP-адрес клиента.
* Всем клиентам приходят сообщения о подключении
* новых участников и об отключении существующих.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <cstring>
#include <sstream>
#include <unordered_map>
#define RECV_BUFFER_SIZE 1024
#define LISTENING_PORT 2017
#define MAX_EVENTS 1024
int set_nonblock(int fd)
{
int flags;
#ifdef O_NONBLOCK
//printf("O_NONBLOCK defined\n");
if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
#else
//printf("O_NONBLOCK undefined\n");
flags = 1;
return ioctl(fd, FIOBIO, &flags);
#endif
}
void send_message_to(unsigned sender_descriptor,
std::unordered_map<unsigned, struct sockaddr_in>& clients,
const char* buffer,
size_t length)
{
char ip_address[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &clients[sender_descriptor].sin_addr, ip_address, INET_ADDRSTRLEN);
std::uint16_t port = clients[sender_descriptor].sin_port;
std::stringstream result_msg;
result_msg << ip_address << ":" << port << ": " << buffer;
for (auto &client : clients)
if (client.first != sender_descriptor)
send(client.first,
result_msg.str().c_str(),
result_msg.str().length(),
MSG_NOSIGNAL);
}
int main(int argc, char **argv)
{
int master_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in sock_addr;
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(LISTENING_PORT);
sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(master_socket, (struct sockaddr *)(&sock_addr), sizeof(sockaddr));
set_nonblock(master_socket);
listen(master_socket, SOMAXCONN);
int epoll_descriptor = epoll_create1(0);
struct epoll_event event;
event.data.fd = master_socket;
event.events = EPOLLIN;
epoll_ctl(epoll_descriptor, EPOLL_CTL_ADD, master_socket, &event);
std::unordered_map<unsigned, struct sockaddr_in> slave_sockets;
while (true) {
struct epoll_event events[MAX_EVENTS];
int n = epoll_wait(epoll_descriptor, events, MAX_EVENTS, -1);
for (int i = 0; i < n; ++i) {
if (events[i].data.fd == master_socket) {
struct sockaddr_in client_addr;
socklen_t client_addr_size = sizeof(client_addr);
int slave_socket = accept(master_socket,
(struct sockaddr *)&client_addr,
&client_addr_size);
set_nonblock(slave_socket);
struct epoll_event tmp_event;
tmp_event.data.fd = slave_socket;
tmp_event.events = EPOLLIN;
epoll_ctl(epoll_descriptor, EPOLL_CTL_ADD, slave_socket, &tmp_event);
slave_sockets[slave_socket] = client_addr;
const char connect_msg[] = "[New client connected]\n";
send_message_to(slave_socket, slave_sockets, connect_msg, strlen(connect_msg));
} else {
static char buffer[RECV_BUFFER_SIZE];
memset(buffer, 0, RECV_BUFFER_SIZE);
int recv_n = recv(events[i].data.fd, buffer, RECV_BUFFER_SIZE, MSG_NOSIGNAL);
if (recv_n == 0 && errno != EAGAIN) {
shutdown(events[i].data.fd, SHUT_RDWR);
close(events[i].data.fd);
const char disconnect_msg[] = "[Client disconnected]\n";
send_message_to(events[i].data.fd,
slave_sockets,
disconnect_msg,
strlen(disconnect_msg));
slave_sockets.erase(events[i].data.fd);
} else if (recv_n > 0) {
send_message_to(events[i].data.fd, slave_sockets, buffer, recv_n);
}
}
}
}
return 0;
}
|
// // Copyright (c) 2014-2017 The Dash Core developers
// // Copyright (c) 2017-2018 The BroFist Core developers
// // Distributed under the MIT/X11 software license, see the accompanying
// // file COPYING or http://www.opensource.org/licenses/mit-license.php.
// #ifndef GOVERNANCE_KEYS_H
// #define GOVERNANCE_KEYS_H
// #include <string>
// #include <vector>
// #include <map>
// #include <univalue.h>
// #include "support/allocators/secure.h"
// #include ""
// vector<CGovernanceKey> vGovernanceKeys;
// CCriticalSection cs_vGovernanceKeys;
// bool CGovernanceKeyManager::InitGovernanceKeys(std::string strError)
// {
// {
// LOCK(cs_vGovernanceKeys);
// vGovernanceKeys = mapMultiArgs["-addgovkey"];
// }
// BOOST_FOREACH(SecureString& strSecure, vGovernanceKeys)
// {
// std::vector<std::string> vecTokenized = SplitBy(strSubCommand, ":");
// if(vecTokenized.size() == 2) continue;
// CBitcoinSecret vchSecret;
// bool fGood = vchSecret.SetString(vecTokenized[0]);
// if(!fGood) {
// strError = "Invalid Governance Key : " + vecTokenized[0];
// return false;
// }
// CGovernanceKey key(vecTokenized[0], vecTokenized[1]);
// vGovernanceKeys.push_back(key);
// }
// }
|
; A275796: One half of the y members of the positive proper solutions (x = x2(n), y = y2(n)) of the second class for the Pell equation x^2 - 2*y^2 = +7^2.
; 3,20,117,682,3975,23168,135033,787030,4587147,26735852,155827965,908231938,5293563663,30853150040,179825336577,1048098869422,6108767879955,35604508410308,207518282581893,1209505187081050,7049512839904407,41087571852345392,239475918274167945,1395767937792662278,8135131708481805723,47415022313098172060,276355002170107226637,1610714990707545187762,9387934942075163899935,54716894661743438211848,318913433028385465371153,1858763703508569354015070,10833668788023030658719267,63143249024629614598300532
mov $1,6
mov $2,11
lpb $0
sub $0,1
add $2,$1
add $1,$2
add $1,$2
add $2,$1
lpe
div $1,2
mov $0,$1
|
; A321175: a(n) = -a(n-1) + 2*a(n-2) + a(n-3), a(0) = -1, a(1) = -2, a(2) = 3.
; Submitted by Christian Krause
; -1,-2,3,-8,12,-25,41,-79,136,-253,446,-816,1455,-2641,4735,-8562,15391,-27780,50000,-90169,162389,-292727,527336,-950401,1712346,-3085812,5560103,-10019381,18053775,-32532434,58620603,-105631696,190340468,-342983257,618032497,-1113658543,2006740280,-3616024869,6515846886,-11741156344,21156825247,-38123291049,68695785199,-123785542050,223053821399,-401929120300,724251221048,-1305055640249,2351628962045,-4237489021495,7635691305336,-13759040386281,24792933975458,-44675323442684,80502151007319
mov $3,2
mov $4,-1
lpb $0
sub $0,1
add $2,$1
add $4,1
add $3,$4
add $1,$3
add $4,$2
cmp $2,1
add $3,$4
sub $4,$3
add $3,$4
add $3,$4
lpe
mov $0,$4
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r15
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x1e024, %rsi
lea addresses_WT_ht+0x1e08c, %rdi
nop
nop
nop
xor %rbx, %rbx
mov $101, %rcx
rep movsw
add %r11, %r11
lea addresses_WC_ht+0x1a1d4, %rbx
nop
nop
nop
nop
cmp %rax, %rax
mov $0x6162636465666768, %r11
movq %r11, %xmm4
vmovups %ymm4, (%rbx)
nop
nop
nop
nop
nop
add %rbx, %rbx
lea addresses_A_ht+0x1ab3c, %rsi
lea addresses_WT_ht+0x1521c, %rdi
add $54535, %r10
mov $28, %rcx
rep movsl
sub %rdi, %rdi
lea addresses_WT_ht+0x73c, %rcx
nop
nop
nop
xor %rax, %rax
mov (%rcx), %r10d
nop
nop
nop
nop
nop
inc %rdi
lea addresses_normal_ht+0x1ce48, %rsi
lea addresses_A_ht+0x8f3c, %rdi
cmp $10632, %r15
mov $26, %rcx
rep movsl
nop
nop
nop
nop
nop
sub $49084, %rax
lea addresses_UC_ht+0x1193c, %rsi
lea addresses_D_ht+0x1ed74, %rdi
nop
nop
nop
cmp %r10, %r10
mov $83, %rcx
rep movsw
add $35008, %rcx
lea addresses_WC_ht+0x55fc, %r11
cmp %rsi, %rsi
mov $0x6162636465666768, %r15
movq %r15, %xmm2
vmovups %ymm2, (%r11)
nop
nop
nop
inc %r10
lea addresses_D_ht+0x13d3c, %rsi
nop
sub $916, %r11
mov (%rsi), %ecx
nop
nop
sub %r15, %r15
lea addresses_D_ht+0x6a3c, %rdi
nop
nop
nop
nop
cmp %r15, %r15
movb $0x61, (%rdi)
nop
cmp %rbx, %rbx
lea addresses_UC_ht+0x1c128, %rsi
lea addresses_WC_ht+0x1637c, %rdi
clflush (%rdi)
nop
nop
nop
dec %rax
mov $51, %rcx
rep movsb
and $8001, %rsi
lea addresses_WT_ht+0x1647c, %rax
nop
nop
nop
sub %r15, %r15
mov (%rax), %r11
nop
nop
nop
and %rdi, %rdi
lea addresses_WC_ht+0x174ea, %rsi
nop
nop
nop
dec %r10
movups (%rsi), %xmm6
vpextrq $1, %xmm6, %r11
nop
nop
dec %r11
lea addresses_WT_ht+0xd31c, %rsi
lea addresses_UC_ht+0x19cbc, %rdi
nop
and %r10, %r10
mov $123, %rcx
rep movsq
nop
and $16436, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r15
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
// REPMOV
lea addresses_A+0x43bc, %rsi
lea addresses_PSE+0xb9a4, %rdi
nop
inc %rax
mov $12, %rcx
rep movsl
nop
nop
nop
and %rsi, %rsi
// Store
lea addresses_A+0x11abc, %r8
nop
cmp %r12, %r12
movw $0x5152, (%r8)
// Exception!!!
nop
nop
nop
nop
mov (0), %rcx
nop
nop
nop
dec %rdi
// Faulty Load
lea addresses_RW+0x1bf3c, %rax
nop
nop
sub $28380, %rsi
mov (%rax), %rcx
lea oracles, %rbx
and $0xff, %rcx
shlq $12, %rcx
mov (%rbx,%rcx,1), %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_A'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'REPM'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 5, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': True, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 3, 'same': True, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
INCLUDE "hardware.inc"
INCLUDE "header.inc"
;--------------------------------------------------------------------------
;- RESTART VECTORS -
;--------------------------------------------------------------------------
SECTION "RST_00",HOME[$0000]
ret
SECTION "RST_08",HOME[$0008]
ret
SECTION "RST_10",HOME[$0010]
ret
SECTION "RST_18",HOME[$0018]
ret
SECTION "RST_20",HOME[$0020]
ret
SECTION "RST_28",HOME[$0028]
ret
SECTION "RST_30",HOME[$0030]
ret
SECTION "RST_38",HOME[$0038]
jp Reset
;--------------------------------------------------------------------------
;- INTERRUPT VECTORS -
;--------------------------------------------------------------------------
SECTION "Interrupt Vectors",HOME[$0040]
; SECTION "VBL Interrupt Vector",HOME[$0040]
push hl
ld hl,_is_vbl_flag
ld [hl],1
jr irq_VBlank
; SECTION "LCD Interrupt Vector",HOME[$0048]
push hl
ld hl,LCD_handler
jr irq_Common
nop
nop
; SECTION "TIM Interrupt Vector",HOME[$0050]
ret
ret
nop
nop
nop
nop
nop
nop
; SECTION "SIO Interrupt Vector",HOME[$0058]
reti
nop
nop
nop
nop
nop
nop
nop
; SECTION "JOY Interrupt Vector",HOME[$0060]
push hl
ld hl,JOY_handler
jr irq_Common
; nop
; nop
;--------------------------------------------------------------------------
;- IRQS HANDLER -
;--------------------------------------------------------------------------
irq_VBlank:
ld hl,VBL_handler
irq_Common:
push af
ld a,[hl+]
ld h,[hl]
ld l,a
; or a,h
; jr z,.no_irq
push bc
push de
call .goto_irq_handler
pop de
pop bc
;.no_irq:
pop af
pop hl
reti
.goto_irq_handler:
jp hl
;--------------------------------------------------------------------------
;- wait_vbl() -
;--------------------------------------------------------------------------
wait_vbl:
ld hl,_is_vbl_flag
ld [hl],0
._not_yet:
halt
bit 0,[hl]
jr z,._not_yet
ret
;--------------------------------------------------------------------------
;- CARTRIDGE HEADER -
;--------------------------------------------------------------------------
SECTION "Cartridge Header",HOME[$0100]
nop
jp StartPoint
DB $CE,$ED,$66,$66,$CC,$0D,$00,$0B,$03,$73,$00,$83,$00,$0C,$00,$0D
DB $00,$08,$11,$1F,$88,$89,$00,$0E,$DC,$CC,$6E,$E6,$DD,$DD,$D9,$99
DB $BB,$BB,$67,$63,$6E,$0E,$EC,$CC,$DD,$DC,$99,$9F,$BB,$B9,$33,$3E
; 0123456789ABC
DB "TESTING......"
DW $0000
DB $00 ;GBC flag
DB 0,0,0 ;SuperGameboy
DB $1B ;CARTTYPE (MBC5+RAM+BATTERY)
DB 0 ;ROMSIZE
DB 2 ;RAMSIZE (8KB)
DB $01 ;Destination (0 = Japan, 1 = Non Japan)
DB $00 ;Manufacturer
DB 0 ;Version
DB 0 ;Complement check
DW 0 ;Checksum
;--------------------------------------------------------------------------
;- INITIALIZE THE GAMEBOY -
;--------------------------------------------------------------------------
SECTION "Program Start",HOME[$0150]
StartPoint:
di
ld sp,$FFFE ; Use this as stack for a while
push af ; Save CPU type
push bc
xor a,a
ld [rNR52],a ; Switch off sound
ld hl,_RAM ; Clear RAM
ld bc,$2000
ld d,$00
call memset
pop bc ; Get CPU type
pop af
ld [Init_Reg_A],a ; Save CPU type into RAM
ld a,b
ld [Init_Reg_B],a
ld sp,StackTop ; Real stack
call screen_off
ld hl,_VRAM ; Clear VRAM
ld bc,$2000
ld d,$00
call memset
ld hl,_HRAM ; Clear high RAM (and rIE)
ld bc,$0080
ld d,$00
call memset
call init_OAM ; Copy OAM refresh function to high ram
call refresh_OAM ; We filled RAM with $00, so this will clear OAM
call rom_handler_init
; Real program starts here
call Main
;Should never reach this point
jp Reset
;--------------------------------------------------------------------------
;- Reset() -
;--------------------------------------------------------------------------
Reset::
ld a,[Init_Reg_B]
ld b,a
ld a,[Init_Reg_A]
jp $0100
;--------------------------------------------------------------------------
;- irq_set_VBL() bc = function pointer -
;- irq_set_LCD() bc = function pointer -
;- irq_set_TIM() bc = function pointer -
;- irq_set_SIO() bc = function pointer -
;- irq_set_JOY() bc = function pointer -
;--------------------------------------------------------------------------
irq_set_VBL::
ld hl,VBL_handler
jr irq_set_handler
irq_set_LCD::
ld hl,LCD_handler
jr irq_set_handler
irq_set_TIM::
ld hl,TIM_handler
jr irq_set_handler
irq_set_SIO::
ld hl,SIO_handler
jr irq_set_handler
irq_set_JOY::
ld hl,JOY_handler
; jr irq_set_handler
irq_set_handler: ; hl = dest handler bc = function pointer
ld [hl],c
inc hl
ld [hl],b
ret
;--------------------------------------------------------------------------
;- CPU_fast() -
;- CPU_slow() -
;--------------------------------------------------------------------------
CPU_fast::
ld a,[rKEY1]
bit 7,a
jr z,__CPU_switch
ret
CPU_slow::
ld a,[rKEY1]
bit 7,a
jr nz,__CPU_switch
ret
__CPU_switch:
ld a,[rIE]
ld b,a ; save IE
xor a,a
ld [rIE],a
ld a,$30
ld [rP1],a
ld a,$01
ld [rKEY1],a
stop
ld a,b
ld [rIE],a ; restore IE
ret
;--------------------------------------------------------------------------
;- Variables -
;--------------------------------------------------------------------------
SECTION "StartupVars",BSS
Init_Reg_A:: DS 1
Init_Reg_B:: DS 1
_is_vbl_flag: DS 1
VBL_handler: DS 2
LCD_handler: DS 2
TIM_handler: DS 2
SIO_handler: DS 2
JOY_handler: DS 2
SECTION "Stack",BSS[$CE00]
Stack: DS $200
StackTop: ; $D000
|
//===- FastISel.cpp - Implementation of the FastISel class ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the implementation of the FastISel class.
//
// "Fast" instruction selection is designed to emit very poor code quickly.
// Also, it is not designed to be able to do much lowering, so most illegal
// types (e.g. i64 on 32-bit targets) and operations are not supported. It is
// also not intended to be able to do much optimization, except in a few cases
// where doing optimizations reduces overall compile time. For example, folding
// constants into immediate fields is often done, because it's cheap and it
// reduces the number of instructions later phases have to examine.
//
// "Fast" instruction selection is able to fail gracefully and transfer
// control to the SelectionDAG selector for operations that it doesn't
// support. In many cases, this allows us to avoid duplicating a lot of
// the complicated lowering logic that SelectionDAG currently has.
//
// The intended use for "fast" instruction selection is "-O0" mode
// compilation, where the quality of the generated code is irrelevant when
// weighed against the speed at which the code can be generated. Also,
// at -O0, the LLVM optimizers are not running, and this makes the
// compile time of codegen a much higher portion of the overall compile
// time. Despite its limitations, "fast" instruction selection is able to
// handle enough code on its own to provide noticeable overall speedups
// in -O0 compiles.
//
// Basic operations are supported in a target-independent way, by reading
// the same instruction descriptions that the SelectionDAG selector reads,
// and identifying simple arithmetic operations that can be directly selected
// from simple operators. More complicated operations currently require
// target-specific code.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/FastISel.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/CodeGen/Analysis.h"
#include "llvm/CodeGen/FunctionLoweringInfo.h"
#include "llvm/CodeGen/ISDOpcodes.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MachineValueType.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <utility>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "isel"
STATISTIC(NumFastIselSuccessIndependent, "Number of insts selected by "
"target-independent selector");
STATISTIC(NumFastIselSuccessTarget, "Number of insts selected by "
"target-specific selector");
STATISTIC(NumFastIselDead, "Number of dead insts removed on failure");
/// Set the current block to which generated machine instructions will be
/// appended.
void FastISel::startNewBlock() {
assert(LocalValueMap.empty() &&
"local values should be cleared after finishing a BB");
// Instructions are appended to FuncInfo.MBB. If the basic block already
// contains labels or copies, use the last instruction as the last local
// value.
EmitStartPt = nullptr;
if (!FuncInfo.MBB->empty())
EmitStartPt = &FuncInfo.MBB->back();
LastLocalValue = EmitStartPt;
}
void FastISel::finishBasicBlock() { flushLocalValueMap(); }
bool FastISel::lowerArguments() {
if (!FuncInfo.CanLowerReturn)
// Fallback to SDISel argument lowering code to deal with sret pointer
// parameter.
return false;
if (!fastLowerArguments())
return false;
// Enter arguments into ValueMap for uses in non-entry BBs.
for (Function::const_arg_iterator I = FuncInfo.Fn->arg_begin(),
E = FuncInfo.Fn->arg_end();
I != E; ++I) {
DenseMap<const Value *, Register>::iterator VI = LocalValueMap.find(&*I);
assert(VI != LocalValueMap.end() && "Missed an argument?");
FuncInfo.ValueMap[&*I] = VI->second;
}
return true;
}
/// Return the defined register if this instruction defines exactly one
/// virtual register and uses no other virtual registers. Otherwise return 0.
static Register findLocalRegDef(MachineInstr &MI) {
Register RegDef;
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg())
continue;
if (MO.isDef()) {
if (RegDef)
return Register();
RegDef = MO.getReg();
} else if (MO.getReg().isVirtual()) {
// This is another use of a vreg. Don't delete it.
return Register();
}
}
return RegDef;
}
static bool isRegUsedByPhiNodes(Register DefReg,
FunctionLoweringInfo &FuncInfo) {
for (auto &P : FuncInfo.PHINodesToUpdate)
if (P.second == DefReg)
return true;
return false;
}
void FastISel::flushLocalValueMap() {
// If FastISel bails out, it could leave local value instructions behind
// that aren't used for anything. Detect and erase those.
if (LastLocalValue != EmitStartPt) {
// Save the first instruction after local values, for later.
MachineBasicBlock::iterator FirstNonValue(LastLocalValue);
++FirstNonValue;
MachineBasicBlock::reverse_iterator RE =
EmitStartPt ? MachineBasicBlock::reverse_iterator(EmitStartPt)
: FuncInfo.MBB->rend();
MachineBasicBlock::reverse_iterator RI(LastLocalValue);
for (; RI != RE;) {
MachineInstr &LocalMI = *RI;
// Increment before erasing what it points to.
++RI;
Register DefReg = findLocalRegDef(LocalMI);
if (!DefReg)
continue;
if (FuncInfo.RegsWithFixups.count(DefReg))
continue;
bool UsedByPHI = isRegUsedByPhiNodes(DefReg, FuncInfo);
if (!UsedByPHI && MRI.use_nodbg_empty(DefReg)) {
if (EmitStartPt == &LocalMI)
EmitStartPt = EmitStartPt->getPrevNode();
LLVM_DEBUG(dbgs() << "removing dead local value materialization"
<< LocalMI);
LocalMI.eraseFromParent();
}
}
if (FirstNonValue != FuncInfo.MBB->end()) {
// See if there are any local value instructions left. If so, we want to
// make sure the first one has a debug location; if it doesn't, use the
// first non-value instruction's debug location.
// If EmitStartPt is non-null, this block had copies at the top before
// FastISel started doing anything; it points to the last one, so the
// first local value instruction is the one after EmitStartPt.
// If EmitStartPt is null, the first local value instruction is at the
// top of the block.
MachineBasicBlock::iterator FirstLocalValue =
EmitStartPt ? ++MachineBasicBlock::iterator(EmitStartPt)
: FuncInfo.MBB->begin();
if (FirstLocalValue != FirstNonValue && !FirstLocalValue->getDebugLoc())
FirstLocalValue->setDebugLoc(FirstNonValue->getDebugLoc());
}
}
LocalValueMap.clear();
LastLocalValue = EmitStartPt;
recomputeInsertPt();
SavedInsertPt = FuncInfo.InsertPt;
}
Register FastISel::getRegForValue(const Value *V) {
EVT RealVT = TLI.getValueType(DL, V->getType(), /*AllowUnknown=*/true);
// Don't handle non-simple values in FastISel.
if (!RealVT.isSimple())
return Register();
// Ignore illegal types. We must do this before looking up the value
// in ValueMap because Arguments are given virtual registers regardless
// of whether FastISel can handle them.
MVT VT = RealVT.getSimpleVT();
if (!TLI.isTypeLegal(VT)) {
// Handle integer promotions, though, because they're common and easy.
if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
VT = TLI.getTypeToTransformTo(V->getContext(), VT).getSimpleVT();
else
return Register();
}
// Look up the value to see if we already have a register for it.
Register Reg = lookUpRegForValue(V);
if (Reg)
return Reg;
// In bottom-up mode, just create the virtual register which will be used
// to hold the value. It will be materialized later.
if (isa<Instruction>(V) &&
(!isa<AllocaInst>(V) ||
!FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(V))))
return FuncInfo.InitializeRegForValue(V);
SavePoint SaveInsertPt = enterLocalValueArea();
// Materialize the value in a register. Emit any instructions in the
// local value area.
Reg = materializeRegForValue(V, VT);
leaveLocalValueArea(SaveInsertPt);
return Reg;
}
Register FastISel::materializeConstant(const Value *V, MVT VT) {
Register Reg;
if (const auto *CI = dyn_cast<ConstantInt>(V)) {
if (CI->getValue().getActiveBits() <= 64)
Reg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
} else if (isa<AllocaInst>(V))
Reg = fastMaterializeAlloca(cast<AllocaInst>(V));
else if (isa<ConstantPointerNull>(V))
// Translate this as an integer zero so that it can be
// local-CSE'd with actual integer zeros.
Reg =
getRegForValue(Constant::getNullValue(DL.getIntPtrType(V->getType())));
else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
if (CF->isNullValue())
Reg = fastMaterializeFloatZero(CF);
else
// Try to emit the constant directly.
Reg = fastEmit_f(VT, VT, ISD::ConstantFP, CF);
if (!Reg) {
// Try to emit the constant by using an integer constant with a cast.
const APFloat &Flt = CF->getValueAPF();
EVT IntVT = TLI.getPointerTy(DL);
uint32_t IntBitWidth = IntVT.getSizeInBits();
APSInt SIntVal(IntBitWidth, /*isUnsigned=*/false);
bool isExact;
(void)Flt.convertToInteger(SIntVal, APFloat::rmTowardZero, &isExact);
if (isExact) {
Register IntegerReg =
getRegForValue(ConstantInt::get(V->getContext(), SIntVal));
if (IntegerReg)
Reg = fastEmit_r(IntVT.getSimpleVT(), VT, ISD::SINT_TO_FP,
IntegerReg);
}
}
} else if (const auto *Op = dyn_cast<Operator>(V)) {
if (!selectOperator(Op, Op->getOpcode()))
if (!isa<Instruction>(Op) ||
!fastSelectInstruction(cast<Instruction>(Op)))
return 0;
Reg = lookUpRegForValue(Op);
} else if (isa<UndefValue>(V)) {
Reg = createResultReg(TLI.getRegClassFor(VT));
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::IMPLICIT_DEF), Reg);
}
return Reg;
}
/// Helper for getRegForValue. This function is called when the value isn't
/// already available in a register and must be materialized with new
/// instructions.
Register FastISel::materializeRegForValue(const Value *V, MVT VT) {
Register Reg;
// Give the target-specific code a try first.
if (isa<Constant>(V))
Reg = fastMaterializeConstant(cast<Constant>(V));
// If target-specific code couldn't or didn't want to handle the value, then
// give target-independent code a try.
if (!Reg)
Reg = materializeConstant(V, VT);
// Don't cache constant materializations in the general ValueMap.
// To do so would require tracking what uses they dominate.
if (Reg) {
LocalValueMap[V] = Reg;
LastLocalValue = MRI.getVRegDef(Reg);
}
return Reg;
}
Register FastISel::lookUpRegForValue(const Value *V) {
// Look up the value to see if we already have a register for it. We
// cache values defined by Instructions across blocks, and other values
// only locally. This is because Instructions already have the SSA
// def-dominates-use requirement enforced.
DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(V);
if (I != FuncInfo.ValueMap.end())
return I->second;
return LocalValueMap[V];
}
void FastISel::updateValueMap(const Value *I, Register Reg, unsigned NumRegs) {
if (!isa<Instruction>(I)) {
LocalValueMap[I] = Reg;
return;
}
Register &AssignedReg = FuncInfo.ValueMap[I];
if (!AssignedReg)
// Use the new register.
AssignedReg = Reg;
else if (Reg != AssignedReg) {
// Arrange for uses of AssignedReg to be replaced by uses of Reg.
for (unsigned i = 0; i < NumRegs; i++) {
FuncInfo.RegFixups[AssignedReg + i] = Reg + i;
FuncInfo.RegsWithFixups.insert(Reg + i);
}
AssignedReg = Reg;
}
}
Register FastISel::getRegForGEPIndex(const Value *Idx) {
Register IdxN = getRegForValue(Idx);
if (!IdxN)
// Unhandled operand. Halt "fast" selection and bail.
return Register();
// If the index is smaller or larger than intptr_t, truncate or extend it.
MVT PtrVT = TLI.getPointerTy(DL);
EVT IdxVT = EVT::getEVT(Idx->getType(), /*HandleUnknown=*/false);
if (IdxVT.bitsLT(PtrVT)) {
IdxN = fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::SIGN_EXTEND, IdxN);
} else if (IdxVT.bitsGT(PtrVT)) {
IdxN =
fastEmit_r(IdxVT.getSimpleVT(), PtrVT, ISD::TRUNCATE, IdxN);
}
return IdxN;
}
void FastISel::recomputeInsertPt() {
if (getLastLocalValue()) {
FuncInfo.InsertPt = getLastLocalValue();
FuncInfo.MBB = FuncInfo.InsertPt->getParent();
++FuncInfo.InsertPt;
} else
FuncInfo.InsertPt = FuncInfo.MBB->getFirstNonPHI();
// Now skip past any EH_LABELs, which must remain at the beginning.
while (FuncInfo.InsertPt != FuncInfo.MBB->end() &&
FuncInfo.InsertPt->getOpcode() == TargetOpcode::EH_LABEL)
++FuncInfo.InsertPt;
}
void FastISel::removeDeadCode(MachineBasicBlock::iterator I,
MachineBasicBlock::iterator E) {
assert(I.isValid() && E.isValid() && std::distance(I, E) > 0 &&
"Invalid iterator!");
while (I != E) {
if (SavedInsertPt == I)
SavedInsertPt = E;
if (EmitStartPt == I)
EmitStartPt = E.isValid() ? &*E : nullptr;
if (LastLocalValue == I)
LastLocalValue = E.isValid() ? &*E : nullptr;
MachineInstr *Dead = &*I;
++I;
Dead->eraseFromParent();
++NumFastIselDead;
}
recomputeInsertPt();
}
FastISel::SavePoint FastISel::enterLocalValueArea() {
SavePoint OldInsertPt = FuncInfo.InsertPt;
recomputeInsertPt();
return OldInsertPt;
}
void FastISel::leaveLocalValueArea(SavePoint OldInsertPt) {
if (FuncInfo.InsertPt != FuncInfo.MBB->begin())
LastLocalValue = &*std::prev(FuncInfo.InsertPt);
// Restore the previous insert position.
FuncInfo.InsertPt = OldInsertPt;
}
bool FastISel::selectBinaryOp(const User *I, unsigned ISDOpcode) {
EVT VT = EVT::getEVT(I->getType(), /*HandleUnknown=*/true);
if (VT == MVT::Other || !VT.isSimple())
// Unhandled type. Halt "fast" selection and bail.
return false;
// We only handle legal types. For example, on x86-32 the instruction
// selector contains all of the 64-bit instructions from x86-64,
// under the assumption that i64 won't be used if the target doesn't
// support it.
if (!TLI.isTypeLegal(VT)) {
// MVT::i1 is special. Allow AND, OR, or XOR because they
// don't require additional zeroing, which makes them easy.
if (VT == MVT::i1 && (ISDOpcode == ISD::AND || ISDOpcode == ISD::OR ||
ISDOpcode == ISD::XOR))
VT = TLI.getTypeToTransformTo(I->getContext(), VT);
else
return false;
}
// Check if the first operand is a constant, and handle it as "ri". At -O0,
// we don't have anything that canonicalizes operand order.
if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(0)))
if (isa<Instruction>(I) && cast<Instruction>(I)->isCommutative()) {
Register Op1 = getRegForValue(I->getOperand(1));
if (!Op1)
return false;
Register ResultReg =
fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op1, CI->getZExtValue(),
VT.getSimpleVT());
if (!ResultReg)
return false;
// We successfully emitted code for the given LLVM Instruction.
updateValueMap(I, ResultReg);
return true;
}
Register Op0 = getRegForValue(I->getOperand(0));
if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
return false;
// Check if the second operand is a constant and handle it appropriately.
if (const auto *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
uint64_t Imm = CI->getSExtValue();
// Transform "sdiv exact X, 8" -> "sra X, 3".
if (ISDOpcode == ISD::SDIV && isa<BinaryOperator>(I) &&
cast<BinaryOperator>(I)->isExact() && isPowerOf2_64(Imm)) {
Imm = Log2_64(Imm);
ISDOpcode = ISD::SRA;
}
// Transform "urem x, pow2" -> "and x, pow2-1".
if (ISDOpcode == ISD::UREM && isa<BinaryOperator>(I) &&
isPowerOf2_64(Imm)) {
--Imm;
ISDOpcode = ISD::AND;
}
Register ResultReg = fastEmit_ri_(VT.getSimpleVT(), ISDOpcode, Op0, Imm,
VT.getSimpleVT());
if (!ResultReg)
return false;
// We successfully emitted code for the given LLVM Instruction.
updateValueMap(I, ResultReg);
return true;
}
Register Op1 = getRegForValue(I->getOperand(1));
if (!Op1) // Unhandled operand. Halt "fast" selection and bail.
return false;
// Now we have both operands in registers. Emit the instruction.
Register ResultReg = fastEmit_rr(VT.getSimpleVT(), VT.getSimpleVT(),
ISDOpcode, Op0, Op1);
if (!ResultReg)
// Target-specific code wasn't able to find a machine opcode for
// the given ISD opcode and type. Halt "fast" selection and bail.
return false;
// We successfully emitted code for the given LLVM Instruction.
updateValueMap(I, ResultReg);
return true;
}
bool FastISel::selectGetElementPtr(const User *I) {
Register N = getRegForValue(I->getOperand(0));
if (!N) // Unhandled operand. Halt "fast" selection and bail.
return false;
// FIXME: The code below does not handle vector GEPs. Halt "fast" selection
// and bail.
if (isa<VectorType>(I->getType()))
return false;
// Keep a running tab of the total offset to coalesce multiple N = N + Offset
// into a single N = N + TotalOffset.
uint64_t TotalOffs = 0;
// FIXME: What's a good SWAG number for MaxOffs?
uint64_t MaxOffs = 2048;
MVT VT = TLI.getPointerTy(DL);
for (gep_type_iterator GTI = gep_type_begin(I), E = gep_type_end(I);
GTI != E; ++GTI) {
const Value *Idx = GTI.getOperand();
if (StructType *StTy = GTI.getStructTypeOrNull()) {
uint64_t Field = cast<ConstantInt>(Idx)->getZExtValue();
if (Field) {
// N = N + Offset
TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
if (TotalOffs >= MaxOffs) {
N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
if (!N) // Unhandled operand. Halt "fast" selection and bail.
return false;
TotalOffs = 0;
}
}
} else {
Type *Ty = GTI.getIndexedType();
// If this is a constant subscript, handle it quickly.
if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
if (CI->isZero())
continue;
// N = N + Offset
uint64_t IdxN = CI->getValue().sextOrTrunc(64).getSExtValue();
TotalOffs += DL.getTypeAllocSize(Ty) * IdxN;
if (TotalOffs >= MaxOffs) {
N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
if (!N) // Unhandled operand. Halt "fast" selection and bail.
return false;
TotalOffs = 0;
}
continue;
}
if (TotalOffs) {
N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
if (!N) // Unhandled operand. Halt "fast" selection and bail.
return false;
TotalOffs = 0;
}
// N = N + Idx * ElementSize;
uint64_t ElementSize = DL.getTypeAllocSize(Ty);
Register IdxN = getRegForGEPIndex(Idx);
if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
return false;
if (ElementSize != 1) {
IdxN = fastEmit_ri_(VT, ISD::MUL, IdxN, ElementSize, VT);
if (!IdxN) // Unhandled operand. Halt "fast" selection and bail.
return false;
}
N = fastEmit_rr(VT, VT, ISD::ADD, N, IdxN);
if (!N) // Unhandled operand. Halt "fast" selection and bail.
return false;
}
}
if (TotalOffs) {
N = fastEmit_ri_(VT, ISD::ADD, N, TotalOffs, VT);
if (!N) // Unhandled operand. Halt "fast" selection and bail.
return false;
}
// We successfully emitted code for the given LLVM Instruction.
updateValueMap(I, N);
return true;
}
bool FastISel::addStackMapLiveVars(SmallVectorImpl<MachineOperand> &Ops,
const CallInst *CI, unsigned StartIdx) {
for (unsigned i = StartIdx, e = CI->getNumArgOperands(); i != e; ++i) {
Value *Val = CI->getArgOperand(i);
// Check for constants and encode them with a StackMaps::ConstantOp prefix.
if (const auto *C = dyn_cast<ConstantInt>(Val)) {
Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
Ops.push_back(MachineOperand::CreateImm(C->getSExtValue()));
} else if (isa<ConstantPointerNull>(Val)) {
Ops.push_back(MachineOperand::CreateImm(StackMaps::ConstantOp));
Ops.push_back(MachineOperand::CreateImm(0));
} else if (auto *AI = dyn_cast<AllocaInst>(Val)) {
// Values coming from a stack location also require a special encoding,
// but that is added later on by the target specific frame index
// elimination implementation.
auto SI = FuncInfo.StaticAllocaMap.find(AI);
if (SI != FuncInfo.StaticAllocaMap.end())
Ops.push_back(MachineOperand::CreateFI(SI->second));
else
return false;
} else {
Register Reg = getRegForValue(Val);
if (!Reg)
return false;
Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
}
}
return true;
}
bool FastISel::selectStackmap(const CallInst *I) {
// void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
// [live variables...])
assert(I->getCalledFunction()->getReturnType()->isVoidTy() &&
"Stackmap cannot return a value.");
// The stackmap intrinsic only records the live variables (the arguments
// passed to it) and emits NOPS (if requested). Unlike the patchpoint
// intrinsic, this won't be lowered to a function call. This means we don't
// have to worry about calling conventions and target-specific lowering code.
// Instead we perform the call lowering right here.
//
// CALLSEQ_START(0, 0...)
// STACKMAP(id, nbytes, ...)
// CALLSEQ_END(0, 0)
//
SmallVector<MachineOperand, 32> Ops;
// Add the <id> and <numBytes> constants.
assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
"Expected a constant integer.");
const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
"Expected a constant integer.");
const auto *NumBytes =
cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
// Push live variables for the stack map (skipping the first two arguments
// <id> and <numBytes>).
if (!addStackMapLiveVars(Ops, I, 2))
return false;
// We are not adding any register mask info here, because the stackmap doesn't
// clobber anything.
// Add scratch registers as implicit def and early clobber.
CallingConv::ID CC = I->getCallingConv();
const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
for (unsigned i = 0; ScratchRegs[i]; ++i)
Ops.push_back(MachineOperand::CreateReg(
ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
/*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
// Issue CALLSEQ_START
unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
auto Builder =
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown));
const MCInstrDesc &MCID = Builder.getInstr()->getDesc();
for (unsigned I = 0, E = MCID.getNumOperands(); I < E; ++I)
Builder.addImm(0);
// Issue STACKMAP.
MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::STACKMAP));
for (auto const &MO : Ops)
MIB.add(MO);
// Issue CALLSEQ_END
unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
.addImm(0)
.addImm(0);
// Inform the Frame Information that we have a stackmap in this function.
FuncInfo.MF->getFrameInfo().setHasStackMap();
return true;
}
/// Lower an argument list according to the target calling convention.
///
/// This is a helper for lowering intrinsics that follow a target calling
/// convention or require stack pointer adjustment. Only a subset of the
/// intrinsic's operands need to participate in the calling convention.
bool FastISel::lowerCallOperands(const CallInst *CI, unsigned ArgIdx,
unsigned NumArgs, const Value *Callee,
bool ForceRetVoidTy, CallLoweringInfo &CLI) {
ArgListTy Args;
Args.reserve(NumArgs);
// Populate the argument list.
for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs; ArgI != ArgE; ++ArgI) {
Value *V = CI->getOperand(ArgI);
assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
ArgListEntry Entry;
Entry.Val = V;
Entry.Ty = V->getType();
Entry.setAttributes(CI, ArgI);
Args.push_back(Entry);
}
Type *RetTy = ForceRetVoidTy ? Type::getVoidTy(CI->getType()->getContext())
: CI->getType();
CLI.setCallee(CI->getCallingConv(), RetTy, Callee, std::move(Args), NumArgs);
return lowerCallTo(CLI);
}
FastISel::CallLoweringInfo &FastISel::CallLoweringInfo::setCallee(
const DataLayout &DL, MCContext &Ctx, CallingConv::ID CC, Type *ResultTy,
StringRef Target, ArgListTy &&ArgsList, unsigned FixedArgs) {
SmallString<32> MangledName;
Mangler::getNameWithPrefix(MangledName, Target, DL);
MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
return setCallee(CC, ResultTy, Sym, std::move(ArgsList), FixedArgs);
}
bool FastISel::selectPatchpoint(const CallInst *I) {
// void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
// i32 <numBytes>,
// i8* <target>,
// i32 <numArgs>,
// [Args...],
// [live variables...])
CallingConv::ID CC = I->getCallingConv();
bool IsAnyRegCC = CC == CallingConv::AnyReg;
bool HasDef = !I->getType()->isVoidTy();
Value *Callee = I->getOperand(PatchPointOpers::TargetPos)->stripPointerCasts();
// Get the real number of arguments participating in the call <numArgs>
assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos)) &&
"Expected a constant integer.");
const auto *NumArgsVal =
cast<ConstantInt>(I->getOperand(PatchPointOpers::NArgPos));
unsigned NumArgs = NumArgsVal->getZExtValue();
// Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
// This includes all meta-operands up to but not including CC.
unsigned NumMetaOpers = PatchPointOpers::CCPos;
assert(I->getNumArgOperands() >= NumMetaOpers + NumArgs &&
"Not enough arguments provided to the patchpoint intrinsic");
// For AnyRegCC the arguments are lowered later on manually.
unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
CallLoweringInfo CLI;
CLI.setIsPatchPoint();
if (!lowerCallOperands(I, NumMetaOpers, NumCallArgs, Callee, IsAnyRegCC, CLI))
return false;
assert(CLI.Call && "No call instruction specified.");
SmallVector<MachineOperand, 32> Ops;
// Add an explicit result reg if we use the anyreg calling convention.
if (IsAnyRegCC && HasDef) {
assert(CLI.NumResultRegs == 0 && "Unexpected result register.");
CLI.ResultReg = createResultReg(TLI.getRegClassFor(MVT::i64));
CLI.NumResultRegs = 1;
Ops.push_back(MachineOperand::CreateReg(CLI.ResultReg, /*isDef=*/true));
}
// Add the <id> and <numBytes> constants.
assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::IDPos)) &&
"Expected a constant integer.");
const auto *ID = cast<ConstantInt>(I->getOperand(PatchPointOpers::IDPos));
Ops.push_back(MachineOperand::CreateImm(ID->getZExtValue()));
assert(isa<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos)) &&
"Expected a constant integer.");
const auto *NumBytes =
cast<ConstantInt>(I->getOperand(PatchPointOpers::NBytesPos));
Ops.push_back(MachineOperand::CreateImm(NumBytes->getZExtValue()));
// Add the call target.
if (const auto *C = dyn_cast<IntToPtrInst>(Callee)) {
uint64_t CalleeConstAddr =
cast<ConstantInt>(C->getOperand(0))->getZExtValue();
Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
} else if (const auto *C = dyn_cast<ConstantExpr>(Callee)) {
if (C->getOpcode() == Instruction::IntToPtr) {
uint64_t CalleeConstAddr =
cast<ConstantInt>(C->getOperand(0))->getZExtValue();
Ops.push_back(MachineOperand::CreateImm(CalleeConstAddr));
} else
llvm_unreachable("Unsupported ConstantExpr.");
} else if (const auto *GV = dyn_cast<GlobalValue>(Callee)) {
Ops.push_back(MachineOperand::CreateGA(GV, 0));
} else if (isa<ConstantPointerNull>(Callee))
Ops.push_back(MachineOperand::CreateImm(0));
else
llvm_unreachable("Unsupported callee address.");
// Adjust <numArgs> to account for any arguments that have been passed on
// the stack instead.
unsigned NumCallRegArgs = IsAnyRegCC ? NumArgs : CLI.OutRegs.size();
Ops.push_back(MachineOperand::CreateImm(NumCallRegArgs));
// Add the calling convention
Ops.push_back(MachineOperand::CreateImm((unsigned)CC));
// Add the arguments we omitted previously. The register allocator should
// place these in any free register.
if (IsAnyRegCC) {
for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i) {
Register Reg = getRegForValue(I->getArgOperand(i));
if (!Reg)
return false;
Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
}
}
// Push the arguments from the call instruction.
for (auto Reg : CLI.OutRegs)
Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/false));
// Push live variables for the stack map.
if (!addStackMapLiveVars(Ops, I, NumMetaOpers + NumArgs))
return false;
// Push the register mask info.
Ops.push_back(MachineOperand::CreateRegMask(
TRI.getCallPreservedMask(*FuncInfo.MF, CC)));
// Add scratch registers as implicit def and early clobber.
const MCPhysReg *ScratchRegs = TLI.getScratchRegisters(CC);
for (unsigned i = 0; ScratchRegs[i]; ++i)
Ops.push_back(MachineOperand::CreateReg(
ScratchRegs[i], /*isDef=*/true, /*isImp=*/true, /*isKill=*/false,
/*isDead=*/false, /*isUndef=*/false, /*isEarlyClobber=*/true));
// Add implicit defs (return values).
for (auto Reg : CLI.InRegs)
Ops.push_back(MachineOperand::CreateReg(Reg, /*isDef=*/true,
/*isImp=*/true));
// Insert the patchpoint instruction before the call generated by the target.
MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, CLI.Call, DbgLoc,
TII.get(TargetOpcode::PATCHPOINT));
for (auto &MO : Ops)
MIB.add(MO);
MIB->setPhysRegsDeadExcept(CLI.InRegs, TRI);
// Delete the original call instruction.
CLI.Call->eraseFromParent();
// Inform the Frame Information that we have a patchpoint in this function.
FuncInfo.MF->getFrameInfo().setHasPatchPoint();
if (CLI.NumResultRegs)
updateValueMap(I, CLI.ResultReg, CLI.NumResultRegs);
return true;
}
bool FastISel::selectXRayCustomEvent(const CallInst *I) {
const auto &Triple = TM.getTargetTriple();
if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
return true; // don't do anything to this instruction.
SmallVector<MachineOperand, 8> Ops;
Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
/*isDef=*/false));
Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
/*isDef=*/false));
MachineInstrBuilder MIB =
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::PATCHABLE_EVENT_CALL));
for (auto &MO : Ops)
MIB.add(MO);
// Insert the Patchable Event Call instruction, that gets lowered properly.
return true;
}
bool FastISel::selectXRayTypedEvent(const CallInst *I) {
const auto &Triple = TM.getTargetTriple();
if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
return true; // don't do anything to this instruction.
SmallVector<MachineOperand, 8> Ops;
Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(0)),
/*isDef=*/false));
Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(1)),
/*isDef=*/false));
Ops.push_back(MachineOperand::CreateReg(getRegForValue(I->getArgOperand(2)),
/*isDef=*/false));
MachineInstrBuilder MIB =
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::PATCHABLE_TYPED_EVENT_CALL));
for (auto &MO : Ops)
MIB.add(MO);
// Insert the Patchable Typed Event Call instruction, that gets lowered properly.
return true;
}
/// Returns an AttributeList representing the attributes applied to the return
/// value of the given call.
static AttributeList getReturnAttrs(FastISel::CallLoweringInfo &CLI) {
SmallVector<Attribute::AttrKind, 2> Attrs;
if (CLI.RetSExt)
Attrs.push_back(Attribute::SExt);
if (CLI.RetZExt)
Attrs.push_back(Attribute::ZExt);
if (CLI.IsInReg)
Attrs.push_back(Attribute::InReg);
return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
Attrs);
}
bool FastISel::lowerCallTo(const CallInst *CI, const char *SymName,
unsigned NumArgs) {
MCContext &Ctx = MF->getContext();
SmallString<32> MangledName;
Mangler::getNameWithPrefix(MangledName, SymName, DL);
MCSymbol *Sym = Ctx.getOrCreateSymbol(MangledName);
return lowerCallTo(CI, Sym, NumArgs);
}
bool FastISel::lowerCallTo(const CallInst *CI, MCSymbol *Symbol,
unsigned NumArgs) {
FunctionType *FTy = CI->getFunctionType();
Type *RetTy = CI->getType();
ArgListTy Args;
Args.reserve(NumArgs);
// Populate the argument list.
// Attributes for args start at offset 1, after the return attribute.
for (unsigned ArgI = 0; ArgI != NumArgs; ++ArgI) {
Value *V = CI->getOperand(ArgI);
assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
ArgListEntry Entry;
Entry.Val = V;
Entry.Ty = V->getType();
Entry.setAttributes(CI, ArgI);
Args.push_back(Entry);
}
TLI.markLibCallAttributes(MF, CI->getCallingConv(), Args);
CallLoweringInfo CLI;
CLI.setCallee(RetTy, FTy, Symbol, std::move(Args), *CI, NumArgs);
return lowerCallTo(CLI);
}
bool FastISel::lowerCallTo(CallLoweringInfo &CLI) {
// Handle the incoming return values from the call.
CLI.clearIns();
SmallVector<EVT, 4> RetTys;
ComputeValueVTs(TLI, DL, CLI.RetTy, RetTys);
SmallVector<ISD::OutputArg, 4> Outs;
GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, TLI, DL);
bool CanLowerReturn = TLI.CanLowerReturn(
CLI.CallConv, *FuncInfo.MF, CLI.IsVarArg, Outs, CLI.RetTy->getContext());
// FIXME: sret demotion isn't supported yet - bail out.
if (!CanLowerReturn)
return false;
for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
EVT VT = RetTys[I];
MVT RegisterVT = TLI.getRegisterType(CLI.RetTy->getContext(), VT);
unsigned NumRegs = TLI.getNumRegisters(CLI.RetTy->getContext(), VT);
for (unsigned i = 0; i != NumRegs; ++i) {
ISD::InputArg MyFlags;
MyFlags.VT = RegisterVT;
MyFlags.ArgVT = VT;
MyFlags.Used = CLI.IsReturnValueUsed;
if (CLI.RetSExt)
MyFlags.Flags.setSExt();
if (CLI.RetZExt)
MyFlags.Flags.setZExt();
if (CLI.IsInReg)
MyFlags.Flags.setInReg();
CLI.Ins.push_back(MyFlags);
}
}
// Handle all of the outgoing arguments.
CLI.clearOuts();
for (auto &Arg : CLI.getArgs()) {
Type *FinalType = Arg.Ty;
if (Arg.IsByVal)
FinalType = cast<PointerType>(Arg.Ty)->getElementType();
bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
FinalType, CLI.CallConv, CLI.IsVarArg, DL);
ISD::ArgFlagsTy Flags;
if (Arg.IsZExt)
Flags.setZExt();
if (Arg.IsSExt)
Flags.setSExt();
if (Arg.IsInReg)
Flags.setInReg();
if (Arg.IsSRet)
Flags.setSRet();
if (Arg.IsSwiftSelf)
Flags.setSwiftSelf();
if (Arg.IsSwiftAsync)
Flags.setSwiftAsync();
if (Arg.IsSwiftError)
Flags.setSwiftError();
if (Arg.IsCFGuardTarget)
Flags.setCFGuardTarget();
if (Arg.IsByVal)
Flags.setByVal();
if (Arg.IsInAlloca) {
Flags.setInAlloca();
// Set the byval flag for CCAssignFn callbacks that don't know about
// inalloca. This way we can know how many bytes we should've allocated
// and how many bytes a callee cleanup function will pop. If we port
// inalloca to more targets, we'll have to add custom inalloca handling in
// the various CC lowering callbacks.
Flags.setByVal();
}
if (Arg.IsPreallocated) {
Flags.setPreallocated();
// Set the byval flag for CCAssignFn callbacks that don't know about
// preallocated. This way we can know how many bytes we should've
// allocated and how many bytes a callee cleanup function will pop. If we
// port preallocated to more targets, we'll have to add custom
// preallocated handling in the various CC lowering callbacks.
Flags.setByVal();
}
MaybeAlign MemAlign = Arg.Alignment;
if (Arg.IsByVal || Arg.IsInAlloca || Arg.IsPreallocated) {
PointerType *Ty = cast<PointerType>(Arg.Ty);
Type *ElementTy = Ty->getElementType();
unsigned FrameSize =
DL.getTypeAllocSize(Arg.ByValType ? Arg.ByValType : ElementTy);
// For ByVal, alignment should come from FE. BE will guess if this info
// is not there, but there are cases it cannot get right.
if (!MemAlign)
MemAlign = Align(TLI.getByValTypeAlignment(ElementTy, DL));
Flags.setByValSize(FrameSize);
} else if (!MemAlign) {
MemAlign = DL.getABITypeAlign(Arg.Ty);
}
Flags.setMemAlign(*MemAlign);
if (Arg.IsNest)
Flags.setNest();
if (NeedsRegBlock)
Flags.setInConsecutiveRegs();
Flags.setOrigAlign(DL.getABITypeAlign(Arg.Ty));
CLI.OutVals.push_back(Arg.Val);
CLI.OutFlags.push_back(Flags);
}
if (!fastLowerCall(CLI))
return false;
// Set all unused physreg defs as dead.
assert(CLI.Call && "No call instruction specified.");
CLI.Call->setPhysRegsDeadExcept(CLI.InRegs, TRI);
if (CLI.NumResultRegs && CLI.CB)
updateValueMap(CLI.CB, CLI.ResultReg, CLI.NumResultRegs);
// Set labels for heapallocsite call.
if (CLI.CB)
if (MDNode *MD = CLI.CB->getMetadata("heapallocsite"))
CLI.Call->setHeapAllocMarker(*MF, MD);
return true;
}
bool FastISel::lowerCall(const CallInst *CI) {
FunctionType *FuncTy = CI->getFunctionType();
Type *RetTy = CI->getType();
ArgListTy Args;
ArgListEntry Entry;
Args.reserve(CI->arg_size());
for (auto i = CI->arg_begin(), e = CI->arg_end(); i != e; ++i) {
Value *V = *i;
// Skip empty types
if (V->getType()->isEmptyTy())
continue;
Entry.Val = V;
Entry.Ty = V->getType();
// Skip the first return-type Attribute to get to params.
Entry.setAttributes(CI, i - CI->arg_begin());
Args.push_back(Entry);
}
// Check if target-independent constraints permit a tail call here.
// Target-dependent constraints are checked within fastLowerCall.
bool IsTailCall = CI->isTailCall();
if (IsTailCall && !isInTailCallPosition(*CI, TM))
IsTailCall = false;
if (IsTailCall && MF->getFunction()
.getFnAttribute("disable-tail-calls")
.getValueAsBool())
IsTailCall = false;
CallLoweringInfo CLI;
CLI.setCallee(RetTy, FuncTy, CI->getCalledOperand(), std::move(Args), *CI)
.setTailCall(IsTailCall);
return lowerCallTo(CLI);
}
bool FastISel::selectCall(const User *I) {
const CallInst *Call = cast<CallInst>(I);
// Handle simple inline asms.
if (const InlineAsm *IA = dyn_cast<InlineAsm>(Call->getCalledOperand())) {
// Don't attempt to handle constraints.
if (!IA->getConstraintString().empty())
return false;
unsigned ExtraInfo = 0;
if (IA->hasSideEffects())
ExtraInfo |= InlineAsm::Extra_HasSideEffects;
if (IA->isAlignStack())
ExtraInfo |= InlineAsm::Extra_IsAlignStack;
if (Call->isConvergent())
ExtraInfo |= InlineAsm::Extra_IsConvergent;
ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::INLINEASM));
MIB.addExternalSymbol(IA->getAsmString().c_str());
MIB.addImm(ExtraInfo);
const MDNode *SrcLoc = Call->getMetadata("srcloc");
if (SrcLoc)
MIB.addMetadata(SrcLoc);
return true;
}
// Handle intrinsic function calls.
if (const auto *II = dyn_cast<IntrinsicInst>(Call))
return selectIntrinsicCall(II);
return lowerCall(Call);
}
bool FastISel::selectIntrinsicCall(const IntrinsicInst *II) {
switch (II->getIntrinsicID()) {
default:
break;
// At -O0 we don't care about the lifetime intrinsics.
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
// The donothing intrinsic does, well, nothing.
case Intrinsic::donothing:
// Neither does the sideeffect intrinsic.
case Intrinsic::sideeffect:
// Neither does the assume intrinsic; it's also OK not to codegen its operand.
case Intrinsic::assume:
// Neither does the llvm.experimental.noalias.scope.decl intrinsic
case Intrinsic::experimental_noalias_scope_decl:
return true;
case Intrinsic::dbg_declare: {
const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
assert(DI->getVariable() && "Missing variable");
if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
<< " (!hasDebugInfo)\n");
return true;
}
const Value *Address = DI->getAddress();
if (!Address || isa<UndefValue>(Address)) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
<< " (bad/undef address)\n");
return true;
}
// Byval arguments with frame indices were already handled after argument
// lowering and before isel.
const auto *Arg =
dyn_cast<Argument>(Address->stripInBoundsConstantOffsets());
if (Arg && FuncInfo.getArgumentFrameIndex(Arg) != INT_MAX)
return true;
Optional<MachineOperand> Op;
if (Register Reg = lookUpRegForValue(Address))
Op = MachineOperand::CreateReg(Reg, false);
// If we have a VLA that has a "use" in a metadata node that's then used
// here but it has no other uses, then we have a problem. E.g.,
//
// int foo (const int *x) {
// char a[*x];
// return 0;
// }
//
// If we assign 'a' a vreg and fast isel later on has to use the selection
// DAG isel, it will want to copy the value to the vreg. However, there are
// no uses, which goes counter to what selection DAG isel expects.
if (!Op && !Address->use_empty() && isa<Instruction>(Address) &&
(!isa<AllocaInst>(Address) ||
!FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(Address))))
Op = MachineOperand::CreateReg(FuncInfo.InitializeRegForValue(Address),
false);
if (Op) {
assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
"Expected inlined-at fields to agree");
// A dbg.declare describes the address of a source variable, so lower it
// into an indirect DBG_VALUE.
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::DBG_VALUE), /*IsIndirect*/ true,
*Op, DI->getVariable(), DI->getExpression());
} else {
// We can't yet handle anything else here because it would require
// generating code, thus altering codegen because of debug info.
LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI
<< " (no materialized reg for address)\n");
}
return true;
}
case Intrinsic::dbg_value: {
// This form of DBG_VALUE is target-independent.
const DbgValueInst *DI = cast<DbgValueInst>(II);
const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
const Value *V = DI->getValue();
assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
"Expected inlined-at fields to agree");
if (!V || isa<UndefValue>(V) || DI->hasArgList()) {
// DI is either undef or cannot produce a valid DBG_VALUE, so produce an
// undef DBG_VALUE to terminate any prior location.
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, false, 0U,
DI->getVariable(), DI->getExpression());
} else if (const auto *CI = dyn_cast<ConstantInt>(V)) {
if (CI->getBitWidth() > 64)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addCImm(CI)
.addImm(0U)
.addMetadata(DI->getVariable())
.addMetadata(DI->getExpression());
else
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addImm(CI->getZExtValue())
.addImm(0U)
.addMetadata(DI->getVariable())
.addMetadata(DI->getExpression());
} else if (const auto *CF = dyn_cast<ConstantFP>(V)) {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addFPImm(CF)
.addImm(0U)
.addMetadata(DI->getVariable())
.addMetadata(DI->getExpression());
} else if (Register Reg = lookUpRegForValue(V)) {
// FIXME: This does not handle register-indirect values at offset 0.
bool IsIndirect = false;
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, IsIndirect, Reg,
DI->getVariable(), DI->getExpression());
} else {
// We don't know how to handle other cases, so we drop.
LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
}
return true;
}
case Intrinsic::dbg_label: {
const DbgLabelInst *DI = cast<DbgLabelInst>(II);
assert(DI->getLabel() && "Missing label");
if (!FuncInfo.MF->getMMI().hasDebugInfo()) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
return true;
}
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::DBG_LABEL)).addMetadata(DI->getLabel());
return true;
}
case Intrinsic::objectsize:
llvm_unreachable("llvm.objectsize.* should have been lowered already");
case Intrinsic::is_constant:
llvm_unreachable("llvm.is.constant.* should have been lowered already");
case Intrinsic::launder_invariant_group:
case Intrinsic::strip_invariant_group:
case Intrinsic::expect: {
Register ResultReg = getRegForValue(II->getArgOperand(0));
if (!ResultReg)
return false;
updateValueMap(II, ResultReg);
return true;
}
case Intrinsic::experimental_stackmap:
return selectStackmap(II);
case Intrinsic::experimental_patchpoint_void:
case Intrinsic::experimental_patchpoint_i64:
return selectPatchpoint(II);
case Intrinsic::xray_customevent:
return selectXRayCustomEvent(II);
case Intrinsic::xray_typedevent:
return selectXRayTypedEvent(II);
}
return fastLowerIntrinsicCall(II);
}
bool FastISel::selectCast(const User *I, unsigned Opcode) {
EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
EVT DstVT = TLI.getValueType(DL, I->getType());
if (SrcVT == MVT::Other || !SrcVT.isSimple() || DstVT == MVT::Other ||
!DstVT.isSimple())
// Unhandled type. Halt "fast" selection and bail.
return false;
// Check if the destination type is legal.
if (!TLI.isTypeLegal(DstVT))
return false;
// Check if the source operand is legal.
if (!TLI.isTypeLegal(SrcVT))
return false;
Register InputReg = getRegForValue(I->getOperand(0));
if (!InputReg)
// Unhandled operand. Halt "fast" selection and bail.
return false;
Register ResultReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(),
Opcode, InputReg);
if (!ResultReg)
return false;
updateValueMap(I, ResultReg);
return true;
}
bool FastISel::selectBitCast(const User *I) {
// If the bitcast doesn't change the type, just use the operand value.
if (I->getType() == I->getOperand(0)->getType()) {
Register Reg = getRegForValue(I->getOperand(0));
if (!Reg)
return false;
updateValueMap(I, Reg);
return true;
}
// Bitcasts of other values become reg-reg copies or BITCAST operators.
EVT SrcEVT = TLI.getValueType(DL, I->getOperand(0)->getType());
EVT DstEVT = TLI.getValueType(DL, I->getType());
if (SrcEVT == MVT::Other || DstEVT == MVT::Other ||
!TLI.isTypeLegal(SrcEVT) || !TLI.isTypeLegal(DstEVT))
// Unhandled type. Halt "fast" selection and bail.
return false;
MVT SrcVT = SrcEVT.getSimpleVT();
MVT DstVT = DstEVT.getSimpleVT();
Register Op0 = getRegForValue(I->getOperand(0));
if (!Op0) // Unhandled operand. Halt "fast" selection and bail.
return false;
// First, try to perform the bitcast by inserting a reg-reg copy.
Register ResultReg;
if (SrcVT == DstVT) {
const TargetRegisterClass *SrcClass = TLI.getRegClassFor(SrcVT);
const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
// Don't attempt a cross-class copy. It will likely fail.
if (SrcClass == DstClass) {
ResultReg = createResultReg(DstClass);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(Op0);
}
}
// If the reg-reg copy failed, select a BITCAST opcode.
if (!ResultReg)
ResultReg = fastEmit_r(SrcVT, DstVT, ISD::BITCAST, Op0);
if (!ResultReg)
return false;
updateValueMap(I, ResultReg);
return true;
}
bool FastISel::selectFreeze(const User *I) {
Register Reg = getRegForValue(I->getOperand(0));
if (!Reg)
// Unhandled operand.
return false;
EVT ETy = TLI.getValueType(DL, I->getOperand(0)->getType());
if (ETy == MVT::Other || !TLI.isTypeLegal(ETy))
// Unhandled type, bail out.
return false;
MVT Ty = ETy.getSimpleVT();
const TargetRegisterClass *TyRegClass = TLI.getRegClassFor(Ty);
Register ResultReg = createResultReg(TyRegClass);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg);
updateValueMap(I, ResultReg);
return true;
}
// Remove local value instructions starting from the instruction after
// SavedLastLocalValue to the current function insert point.
void FastISel::removeDeadLocalValueCode(MachineInstr *SavedLastLocalValue)
{
MachineInstr *CurLastLocalValue = getLastLocalValue();
if (CurLastLocalValue != SavedLastLocalValue) {
// Find the first local value instruction to be deleted.
// This is the instruction after SavedLastLocalValue if it is non-NULL.
// Otherwise it's the first instruction in the block.
MachineBasicBlock::iterator FirstDeadInst(SavedLastLocalValue);
if (SavedLastLocalValue)
++FirstDeadInst;
else
FirstDeadInst = FuncInfo.MBB->getFirstNonPHI();
setLastLocalValue(SavedLastLocalValue);
removeDeadCode(FirstDeadInst, FuncInfo.InsertPt);
}
}
bool FastISel::selectInstruction(const Instruction *I) {
// Flush the local value map before starting each instruction.
// This improves locality and debugging, and can reduce spills.
// Reuse of values across IR instructions is relatively uncommon.
flushLocalValueMap();
MachineInstr *SavedLastLocalValue = getLastLocalValue();
// Just before the terminator instruction, insert instructions to
// feed PHI nodes in successor blocks.
if (I->isTerminator()) {
if (!handlePHINodesInSuccessorBlocks(I->getParent())) {
// PHI node handling may have generated local value instructions,
// even though it failed to handle all PHI nodes.
// We remove these instructions because SelectionDAGISel will generate
// them again.
removeDeadLocalValueCode(SavedLastLocalValue);
return false;
}
}
// FastISel does not handle any operand bundles except OB_funclet.
if (auto *Call = dyn_cast<CallBase>(I))
for (unsigned i = 0, e = Call->getNumOperandBundles(); i != e; ++i)
if (Call->getOperandBundleAt(i).getTagID() != LLVMContext::OB_funclet)
return false;
DbgLoc = I->getDebugLoc();
SavedInsertPt = FuncInfo.InsertPt;
if (const auto *Call = dyn_cast<CallInst>(I)) {
const Function *F = Call->getCalledFunction();
LibFunc Func;
// As a special case, don't handle calls to builtin library functions that
// may be translated directly to target instructions.
if (F && !F->hasLocalLinkage() && F->hasName() &&
LibInfo->getLibFunc(F->getName(), Func) &&
LibInfo->hasOptimizedCodeGen(Func))
return false;
// Don't handle Intrinsic::trap if a trap function is specified.
if (F && F->getIntrinsicID() == Intrinsic::trap &&
Call->hasFnAttr("trap-func-name"))
return false;
}
// First, try doing target-independent selection.
if (!SkipTargetIndependentISel) {
if (selectOperator(I, I->getOpcode())) {
++NumFastIselSuccessIndependent;
DbgLoc = DebugLoc();
return true;
}
// Remove dead code.
recomputeInsertPt();
if (SavedInsertPt != FuncInfo.InsertPt)
removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
SavedInsertPt = FuncInfo.InsertPt;
}
// Next, try calling the target to attempt to handle the instruction.
if (fastSelectInstruction(I)) {
++NumFastIselSuccessTarget;
DbgLoc = DebugLoc();
return true;
}
// Remove dead code.
recomputeInsertPt();
if (SavedInsertPt != FuncInfo.InsertPt)
removeDeadCode(FuncInfo.InsertPt, SavedInsertPt);
DbgLoc = DebugLoc();
// Undo phi node updates, because they will be added again by SelectionDAG.
if (I->isTerminator()) {
// PHI node handling may have generated local value instructions.
// We remove them because SelectionDAGISel will generate them again.
removeDeadLocalValueCode(SavedLastLocalValue);
FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
}
return false;
}
/// Emit an unconditional branch to the given block, unless it is the immediate
/// (fall-through) successor, and update the CFG.
void FastISel::fastEmitBranch(MachineBasicBlock *MSucc,
const DebugLoc &DbgLoc) {
if (FuncInfo.MBB->getBasicBlock()->sizeWithoutDebug() > 1 &&
FuncInfo.MBB->isLayoutSuccessor(MSucc)) {
// For more accurate line information if this is the only non-debug
// instruction in the block then emit it, otherwise we have the
// unconditional fall-through case, which needs no instructions.
} else {
// The unconditional branch case.
TII.insertBranch(*FuncInfo.MBB, MSucc, nullptr,
SmallVector<MachineOperand, 0>(), DbgLoc);
}
if (FuncInfo.BPI) {
auto BranchProbability = FuncInfo.BPI->getEdgeProbability(
FuncInfo.MBB->getBasicBlock(), MSucc->getBasicBlock());
FuncInfo.MBB->addSuccessor(MSucc, BranchProbability);
} else
FuncInfo.MBB->addSuccessorWithoutProb(MSucc);
}
void FastISel::finishCondBranch(const BasicBlock *BranchBB,
MachineBasicBlock *TrueMBB,
MachineBasicBlock *FalseMBB) {
// Add TrueMBB as successor unless it is equal to the FalseMBB: This can
// happen in degenerate IR and MachineIR forbids to have a block twice in the
// successor/predecessor lists.
if (TrueMBB != FalseMBB) {
if (FuncInfo.BPI) {
auto BranchProbability =
FuncInfo.BPI->getEdgeProbability(BranchBB, TrueMBB->getBasicBlock());
FuncInfo.MBB->addSuccessor(TrueMBB, BranchProbability);
} else
FuncInfo.MBB->addSuccessorWithoutProb(TrueMBB);
}
fastEmitBranch(FalseMBB, DbgLoc);
}
/// Emit an FNeg operation.
bool FastISel::selectFNeg(const User *I, const Value *In) {
Register OpReg = getRegForValue(In);
if (!OpReg)
return false;
// If the target has ISD::FNEG, use it.
EVT VT = TLI.getValueType(DL, I->getType());
Register ResultReg = fastEmit_r(VT.getSimpleVT(), VT.getSimpleVT(), ISD::FNEG,
OpReg);
if (ResultReg) {
updateValueMap(I, ResultReg);
return true;
}
// Bitcast the value to integer, twiddle the sign bit with xor,
// and then bitcast it back to floating-point.
if (VT.getSizeInBits() > 64)
return false;
EVT IntVT = EVT::getIntegerVT(I->getContext(), VT.getSizeInBits());
if (!TLI.isTypeLegal(IntVT))
return false;
Register IntReg = fastEmit_r(VT.getSimpleVT(), IntVT.getSimpleVT(),
ISD::BITCAST, OpReg);
if (!IntReg)
return false;
Register IntResultReg = fastEmit_ri_(
IntVT.getSimpleVT(), ISD::XOR, IntReg,
UINT64_C(1) << (VT.getSizeInBits() - 1), IntVT.getSimpleVT());
if (!IntResultReg)
return false;
ResultReg = fastEmit_r(IntVT.getSimpleVT(), VT.getSimpleVT(), ISD::BITCAST,
IntResultReg);
if (!ResultReg)
return false;
updateValueMap(I, ResultReg);
return true;
}
bool FastISel::selectExtractValue(const User *U) {
const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U);
if (!EVI)
return false;
// Make sure we only try to handle extracts with a legal result. But also
// allow i1 because it's easy.
EVT RealVT = TLI.getValueType(DL, EVI->getType(), /*AllowUnknown=*/true);
if (!RealVT.isSimple())
return false;
MVT VT = RealVT.getSimpleVT();
if (!TLI.isTypeLegal(VT) && VT != MVT::i1)
return false;
const Value *Op0 = EVI->getOperand(0);
Type *AggTy = Op0->getType();
// Get the base result register.
unsigned ResultReg;
DenseMap<const Value *, Register>::iterator I = FuncInfo.ValueMap.find(Op0);
if (I != FuncInfo.ValueMap.end())
ResultReg = I->second;
else if (isa<Instruction>(Op0))
ResultReg = FuncInfo.InitializeRegForValue(Op0);
else
return false; // fast-isel can't handle aggregate constants at the moment
// Get the actual result register, which is an offset from the base register.
unsigned VTIndex = ComputeLinearIndex(AggTy, EVI->getIndices());
SmallVector<EVT, 4> AggValueVTs;
ComputeValueVTs(TLI, DL, AggTy, AggValueVTs);
for (unsigned i = 0; i < VTIndex; i++)
ResultReg += TLI.getNumRegisters(FuncInfo.Fn->getContext(), AggValueVTs[i]);
updateValueMap(EVI, ResultReg);
return true;
}
bool FastISel::selectOperator(const User *I, unsigned Opcode) {
switch (Opcode) {
case Instruction::Add:
return selectBinaryOp(I, ISD::ADD);
case Instruction::FAdd:
return selectBinaryOp(I, ISD::FADD);
case Instruction::Sub:
return selectBinaryOp(I, ISD::SUB);
case Instruction::FSub:
return selectBinaryOp(I, ISD::FSUB);
case Instruction::Mul:
return selectBinaryOp(I, ISD::MUL);
case Instruction::FMul:
return selectBinaryOp(I, ISD::FMUL);
case Instruction::SDiv:
return selectBinaryOp(I, ISD::SDIV);
case Instruction::UDiv:
return selectBinaryOp(I, ISD::UDIV);
case Instruction::FDiv:
return selectBinaryOp(I, ISD::FDIV);
case Instruction::SRem:
return selectBinaryOp(I, ISD::SREM);
case Instruction::URem:
return selectBinaryOp(I, ISD::UREM);
case Instruction::FRem:
return selectBinaryOp(I, ISD::FREM);
case Instruction::Shl:
return selectBinaryOp(I, ISD::SHL);
case Instruction::LShr:
return selectBinaryOp(I, ISD::SRL);
case Instruction::AShr:
return selectBinaryOp(I, ISD::SRA);
case Instruction::And:
return selectBinaryOp(I, ISD::AND);
case Instruction::Or:
return selectBinaryOp(I, ISD::OR);
case Instruction::Xor:
return selectBinaryOp(I, ISD::XOR);
case Instruction::FNeg:
return selectFNeg(I, I->getOperand(0));
case Instruction::GetElementPtr:
return selectGetElementPtr(I);
case Instruction::Br: {
const BranchInst *BI = cast<BranchInst>(I);
if (BI->isUnconditional()) {
const BasicBlock *LLVMSucc = BI->getSuccessor(0);
MachineBasicBlock *MSucc = FuncInfo.MBBMap[LLVMSucc];
fastEmitBranch(MSucc, BI->getDebugLoc());
return true;
}
// Conditional branches are not handed yet.
// Halt "fast" selection and bail.
return false;
}
case Instruction::Unreachable:
if (TM.Options.TrapUnreachable)
return fastEmit_(MVT::Other, MVT::Other, ISD::TRAP) != 0;
else
return true;
case Instruction::Alloca:
// FunctionLowering has the static-sized case covered.
if (FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(I)))
return true;
// Dynamic-sized alloca is not handled yet.
return false;
case Instruction::Call:
// On AIX, call lowering uses the DAG-ISEL path currently so that the
// callee of the direct function call instruction will be mapped to the
// symbol for the function's entry point, which is distinct from the
// function descriptor symbol. The latter is the symbol whose XCOFF symbol
// name is the C-linkage name of the source level function.
if (TM.getTargetTriple().isOSAIX())
return false;
return selectCall(I);
case Instruction::BitCast:
return selectBitCast(I);
case Instruction::FPToSI:
return selectCast(I, ISD::FP_TO_SINT);
case Instruction::ZExt:
return selectCast(I, ISD::ZERO_EXTEND);
case Instruction::SExt:
return selectCast(I, ISD::SIGN_EXTEND);
case Instruction::Trunc:
return selectCast(I, ISD::TRUNCATE);
case Instruction::SIToFP:
return selectCast(I, ISD::SINT_TO_FP);
case Instruction::IntToPtr: // Deliberate fall-through.
case Instruction::PtrToInt: {
EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
EVT DstVT = TLI.getValueType(DL, I->getType());
if (DstVT.bitsGT(SrcVT))
return selectCast(I, ISD::ZERO_EXTEND);
if (DstVT.bitsLT(SrcVT))
return selectCast(I, ISD::TRUNCATE);
Register Reg = getRegForValue(I->getOperand(0));
if (!Reg)
return false;
updateValueMap(I, Reg);
return true;
}
case Instruction::ExtractValue:
return selectExtractValue(I);
case Instruction::Freeze:
return selectFreeze(I);
case Instruction::PHI:
llvm_unreachable("FastISel shouldn't visit PHI nodes!");
default:
// Unhandled instruction. Halt "fast" selection and bail.
return false;
}
}
FastISel::FastISel(FunctionLoweringInfo &FuncInfo,
const TargetLibraryInfo *LibInfo,
bool SkipTargetIndependentISel)
: FuncInfo(FuncInfo), MF(FuncInfo.MF), MRI(FuncInfo.MF->getRegInfo()),
MFI(FuncInfo.MF->getFrameInfo()), MCP(*FuncInfo.MF->getConstantPool()),
TM(FuncInfo.MF->getTarget()), DL(MF->getDataLayout()),
TII(*MF->getSubtarget().getInstrInfo()),
TLI(*MF->getSubtarget().getTargetLowering()),
TRI(*MF->getSubtarget().getRegisterInfo()), LibInfo(LibInfo),
SkipTargetIndependentISel(SkipTargetIndependentISel),
LastLocalValue(nullptr), EmitStartPt(nullptr) {}
FastISel::~FastISel() = default;
bool FastISel::fastLowerArguments() { return false; }
bool FastISel::fastLowerCall(CallLoweringInfo & /*CLI*/) { return false; }
bool FastISel::fastLowerIntrinsicCall(const IntrinsicInst * /*II*/) {
return false;
}
unsigned FastISel::fastEmit_(MVT, MVT, unsigned) { return 0; }
unsigned FastISel::fastEmit_r(MVT, MVT, unsigned, unsigned /*Op0*/) {
return 0;
}
unsigned FastISel::fastEmit_rr(MVT, MVT, unsigned, unsigned /*Op0*/,
unsigned /*Op1*/) {
return 0;
}
unsigned FastISel::fastEmit_i(MVT, MVT, unsigned, uint64_t /*Imm*/) {
return 0;
}
unsigned FastISel::fastEmit_f(MVT, MVT, unsigned,
const ConstantFP * /*FPImm*/) {
return 0;
}
unsigned FastISel::fastEmit_ri(MVT, MVT, unsigned, unsigned /*Op0*/,
uint64_t /*Imm*/) {
return 0;
}
/// This method is a wrapper of fastEmit_ri. It first tries to emit an
/// instruction with an immediate operand using fastEmit_ri.
/// If that fails, it materializes the immediate into a register and try
/// fastEmit_rr instead.
Register FastISel::fastEmit_ri_(MVT VT, unsigned Opcode, unsigned Op0,
uint64_t Imm, MVT ImmType) {
// If this is a multiply by a power of two, emit this as a shift left.
if (Opcode == ISD::MUL && isPowerOf2_64(Imm)) {
Opcode = ISD::SHL;
Imm = Log2_64(Imm);
} else if (Opcode == ISD::UDIV && isPowerOf2_64(Imm)) {
// div x, 8 -> srl x, 3
Opcode = ISD::SRL;
Imm = Log2_64(Imm);
}
// Horrible hack (to be removed), check to make sure shift amounts are
// in-range.
if ((Opcode == ISD::SHL || Opcode == ISD::SRA || Opcode == ISD::SRL) &&
Imm >= VT.getSizeInBits())
return 0;
// First check if immediate type is legal. If not, we can't use the ri form.
Register ResultReg = fastEmit_ri(VT, VT, Opcode, Op0, Imm);
if (ResultReg)
return ResultReg;
Register MaterialReg = fastEmit_i(ImmType, ImmType, ISD::Constant, Imm);
if (!MaterialReg) {
// This is a bit ugly/slow, but failing here means falling out of
// fast-isel, which would be very slow.
IntegerType *ITy =
IntegerType::get(FuncInfo.Fn->getContext(), VT.getSizeInBits());
MaterialReg = getRegForValue(ConstantInt::get(ITy, Imm));
if (!MaterialReg)
return 0;
}
return fastEmit_rr(VT, VT, Opcode, Op0, MaterialReg);
}
Register FastISel::createResultReg(const TargetRegisterClass *RC) {
return MRI.createVirtualRegister(RC);
}
Register FastISel::constrainOperandRegClass(const MCInstrDesc &II, Register Op,
unsigned OpNum) {
if (Op.isVirtual()) {
const TargetRegisterClass *RegClass =
TII.getRegClass(II, OpNum, &TRI, *FuncInfo.MF);
if (!MRI.constrainRegClass(Op, RegClass)) {
// If it's not legal to COPY between the register classes, something
// has gone very wrong before we got here.
Register NewOp = createResultReg(RegClass);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), NewOp).addReg(Op);
return NewOp;
}
}
return Op;
}
Register FastISel::fastEmitInst_(unsigned MachineInstOpcode,
const TargetRegisterClass *RC) {
Register ResultReg = createResultReg(RC);
const MCInstrDesc &II = TII.get(MachineInstOpcode);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg);
return ResultReg;
}
Register FastISel::fastEmitInst_r(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, unsigned Op0) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addReg(Op0);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addReg(Op0);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, unsigned Op0,
unsigned Op1) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addReg(Op0)
.addReg(Op1);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addReg(Op0)
.addReg(Op1);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_rrr(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, unsigned Op0,
unsigned Op1, unsigned Op2) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addReg(Op0)
.addReg(Op1)
.addReg(Op2);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addReg(Op0)
.addReg(Op1)
.addReg(Op2);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, unsigned Op0,
uint64_t Imm) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addReg(Op0)
.addImm(Imm);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addReg(Op0)
.addImm(Imm);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_rii(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, unsigned Op0,
uint64_t Imm1, uint64_t Imm2) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addReg(Op0)
.addImm(Imm1)
.addImm(Imm2);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addReg(Op0)
.addImm(Imm1)
.addImm(Imm2);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_f(unsigned MachineInstOpcode,
const TargetRegisterClass *RC,
const ConstantFP *FPImm) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addFPImm(FPImm);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addFPImm(FPImm);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, unsigned Op0,
unsigned Op1, uint64_t Imm) {
const MCInstrDesc &II = TII.get(MachineInstOpcode);
Register ResultReg = createResultReg(RC);
Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addReg(Op0)
.addReg(Op1)
.addImm(Imm);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
.addReg(Op0)
.addReg(Op1)
.addImm(Imm);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_i(unsigned MachineInstOpcode,
const TargetRegisterClass *RC, uint64_t Imm) {
Register ResultReg = createResultReg(RC);
const MCInstrDesc &II = TII.get(MachineInstOpcode);
if (II.getNumDefs() >= 1)
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
.addImm(Imm);
else {
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addImm(Imm);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
}
return ResultReg;
}
Register FastISel::fastEmitInst_extractsubreg(MVT RetVT, unsigned Op0,
uint32_t Idx) {
Register ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
assert(Register::isVirtualRegister(Op0) &&
"Cannot yet extract from physregs");
const TargetRegisterClass *RC = MRI.getRegClass(Op0);
MRI.constrainRegClass(Op0, TRI.getSubClassWithSubReg(RC, Idx));
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
ResultReg).addReg(Op0, 0, Idx);
return ResultReg;
}
/// Emit MachineInstrs to compute the value of Op with all but the least
/// significant bit set to zero.
Register FastISel::fastEmitZExtFromI1(MVT VT, unsigned Op0) {
return fastEmit_ri(VT, VT, ISD::AND, Op0, 1);
}
/// HandlePHINodesInSuccessorBlocks - Handle PHI nodes in successor blocks.
/// Emit code to ensure constants are copied into registers when needed.
/// Remember the virtual registers that need to be added to the Machine PHI
/// nodes as input. We cannot just directly add them, because expansion
/// might result in multiple MBB's for one BB. As such, the start of the
/// BB might correspond to a different MBB than the end.
bool FastISel::handlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
const Instruction *TI = LLVMBB->getTerminator();
SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
FuncInfo.OrigNumPHINodesToUpdate = FuncInfo.PHINodesToUpdate.size();
// Check successor nodes' PHI nodes that expect a constant to be available
// from this block.
for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
const BasicBlock *SuccBB = TI->getSuccessor(succ);
if (!isa<PHINode>(SuccBB->begin()))
continue;
MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
// If this terminator has multiple identical successors (common for
// switches), only handle each succ once.
if (!SuccsHandled.insert(SuccMBB).second)
continue;
MachineBasicBlock::iterator MBBI = SuccMBB->begin();
// At this point we know that there is a 1-1 correspondence between LLVM PHI
// nodes and Machine PHI nodes, but the incoming operands have not been
// emitted yet.
for (const PHINode &PN : SuccBB->phis()) {
// Ignore dead phi's.
if (PN.use_empty())
continue;
// Only handle legal types. Two interesting things to note here. First,
// by bailing out early, we may leave behind some dead instructions,
// since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
// own moves. Second, this check is necessary because FastISel doesn't
// use CreateRegs to create registers, so it always creates
// exactly one register for each non-void instruction.
EVT VT = TLI.getValueType(DL, PN.getType(), /*AllowUnknown=*/true);
if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
// Handle integer promotions, though, because they're common and easy.
if (!(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)) {
FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
return false;
}
}
const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
// Set the DebugLoc for the copy. Use the location of the operand if
// there is one; otherwise no location, flushLocalValueMap will fix it.
DbgLoc = DebugLoc();
if (const auto *Inst = dyn_cast<Instruction>(PHIOp))
DbgLoc = Inst->getDebugLoc();
Register Reg = getRegForValue(PHIOp);
if (!Reg) {
FuncInfo.PHINodesToUpdate.resize(FuncInfo.OrigNumPHINodesToUpdate);
return false;
}
FuncInfo.PHINodesToUpdate.push_back(std::make_pair(&*MBBI++, Reg));
DbgLoc = DebugLoc();
}
}
return true;
}
bool FastISel::tryToFoldLoad(const LoadInst *LI, const Instruction *FoldInst) {
assert(LI->hasOneUse() &&
"tryToFoldLoad expected a LoadInst with a single use");
// We know that the load has a single use, but don't know what it is. If it
// isn't one of the folded instructions, then we can't succeed here. Handle
// this by scanning the single-use users of the load until we get to FoldInst.
unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
const Instruction *TheUser = LI->user_back();
while (TheUser != FoldInst && // Scan up until we find FoldInst.
// Stay in the right block.
TheUser->getParent() == FoldInst->getParent() &&
--MaxUsers) { // Don't scan too far.
// If there are multiple or no uses of this instruction, then bail out.
if (!TheUser->hasOneUse())
return false;
TheUser = TheUser->user_back();
}
// If we didn't find the fold instruction, then we failed to collapse the
// sequence.
if (TheUser != FoldInst)
return false;
// Don't try to fold volatile loads. Target has to deal with alignment
// constraints.
if (LI->isVolatile())
return false;
// Figure out which vreg this is going into. If there is no assigned vreg yet
// then there actually was no reference to it. Perhaps the load is referenced
// by a dead instruction.
Register LoadReg = getRegForValue(LI);
if (!LoadReg)
return false;
// We can't fold if this vreg has no uses or more than one use. Multiple uses
// may mean that the instruction got lowered to multiple MIs, or the use of
// the loaded value ended up being multiple operands of the result.
if (!MRI.hasOneUse(LoadReg))
return false;
MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(LoadReg);
MachineInstr *User = RI->getParent();
// Set the insertion point properly. Folding the load can cause generation of
// other random instructions (like sign extends) for addressing modes; make
// sure they get inserted in a logical place before the new instruction.
FuncInfo.InsertPt = User;
FuncInfo.MBB = User->getParent();
// Ask the target to try folding the load.
return tryToFoldLoadIntoMI(User, RI.getOperandNo(), LI);
}
bool FastISel::canFoldAddIntoGEP(const User *GEP, const Value *Add) {
// Must be an add.
if (!isa<AddOperator>(Add))
return false;
// Type size needs to match.
if (DL.getTypeSizeInBits(GEP->getType()) !=
DL.getTypeSizeInBits(Add->getType()))
return false;
// Must be in the same basic block.
if (isa<Instruction>(Add) &&
FuncInfo.MBBMap[cast<Instruction>(Add)->getParent()] != FuncInfo.MBB)
return false;
// Must have a constant operand.
return isa<ConstantInt>(cast<AddOperator>(Add)->getOperand(1));
}
MachineMemOperand *
FastISel::createMachineMemOperandFor(const Instruction *I) const {
const Value *Ptr;
Type *ValTy;
MaybeAlign Alignment;
MachineMemOperand::Flags Flags;
bool IsVolatile;
if (const auto *LI = dyn_cast<LoadInst>(I)) {
Alignment = LI->getAlign();
IsVolatile = LI->isVolatile();
Flags = MachineMemOperand::MOLoad;
Ptr = LI->getPointerOperand();
ValTy = LI->getType();
} else if (const auto *SI = dyn_cast<StoreInst>(I)) {
Alignment = SI->getAlign();
IsVolatile = SI->isVolatile();
Flags = MachineMemOperand::MOStore;
Ptr = SI->getPointerOperand();
ValTy = SI->getValueOperand()->getType();
} else
return nullptr;
bool IsNonTemporal = I->hasMetadata(LLVMContext::MD_nontemporal);
bool IsInvariant = I->hasMetadata(LLVMContext::MD_invariant_load);
bool IsDereferenceable = I->hasMetadata(LLVMContext::MD_dereferenceable);
const MDNode *Ranges = I->getMetadata(LLVMContext::MD_range);
AAMDNodes AAInfo;
I->getAAMetadata(AAInfo);
if (!Alignment) // Ensure that codegen never sees alignment 0.
Alignment = DL.getABITypeAlign(ValTy);
unsigned Size = DL.getTypeStoreSize(ValTy);
if (IsVolatile)
Flags |= MachineMemOperand::MOVolatile;
if (IsNonTemporal)
Flags |= MachineMemOperand::MONonTemporal;
if (IsDereferenceable)
Flags |= MachineMemOperand::MODereferenceable;
if (IsInvariant)
Flags |= MachineMemOperand::MOInvariant;
return FuncInfo.MF->getMachineMemOperand(MachinePointerInfo(Ptr), Flags, Size,
*Alignment, AAInfo, Ranges);
}
CmpInst::Predicate FastISel::optimizeCmpPredicate(const CmpInst *CI) const {
// If both operands are the same, then try to optimize or fold the cmp.
CmpInst::Predicate Predicate = CI->getPredicate();
if (CI->getOperand(0) != CI->getOperand(1))
return Predicate;
switch (Predicate) {
default: llvm_unreachable("Invalid predicate!");
case CmpInst::FCMP_FALSE: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::FCMP_OEQ: Predicate = CmpInst::FCMP_ORD; break;
case CmpInst::FCMP_OGT: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::FCMP_OGE: Predicate = CmpInst::FCMP_ORD; break;
case CmpInst::FCMP_OLT: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::FCMP_OLE: Predicate = CmpInst::FCMP_ORD; break;
case CmpInst::FCMP_ONE: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::FCMP_ORD: Predicate = CmpInst::FCMP_ORD; break;
case CmpInst::FCMP_UNO: Predicate = CmpInst::FCMP_UNO; break;
case CmpInst::FCMP_UEQ: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::FCMP_UGT: Predicate = CmpInst::FCMP_UNO; break;
case CmpInst::FCMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::FCMP_ULT: Predicate = CmpInst::FCMP_UNO; break;
case CmpInst::FCMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::FCMP_UNE: Predicate = CmpInst::FCMP_UNO; break;
case CmpInst::FCMP_TRUE: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::ICMP_EQ: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::ICMP_NE: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::ICMP_UGT: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::ICMP_UGE: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::ICMP_ULT: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::ICMP_ULE: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::ICMP_SGT: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::ICMP_SGE: Predicate = CmpInst::FCMP_TRUE; break;
case CmpInst::ICMP_SLT: Predicate = CmpInst::FCMP_FALSE; break;
case CmpInst::ICMP_SLE: Predicate = CmpInst::FCMP_TRUE; break;
}
return Predicate;
}
|
; A078881: Size of the largest subset S of {1,2,3,...,n} with the property that if i and j are distinct elements of S then i XOR j is not in S, where XOR is the bitwise exclusive-OR operator.
; 1,2,2,3,4,4,4,5,6,7,8,8,8,8,8,9,10,11,12,13,14,15,16,16,16,16,16,16,16,16,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,33,34,35,36,37,38,39,40,41,42,43,44
mov $1,1
mov $2,$0
mov $3,1
lpb $2,1
lpb $3,1
mov $3,$0
lpe
add $3,$1
trn $0,$3
mov $1,$3
sub $2,1
lpe
|
;===============================================================================
; Copyright 2014-2021 Intel Corporation
;
; 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.
;===============================================================================
;
;
; Purpose: Cryptography Primitive.
; Message block processing according to SHA512
;
; Content:
; UpdateSHA512
;
;
%include "asmdefs.inc"
%include "ia_emm.inc"
%include "pcpvariant.inc"
%if (_ENABLE_ALG_SHA512_)
%if (_IPP >= _IPP_G9)
;;
;; ENDIANNESS
;;
%macro ENDIANNESS 2.nolist
%xdefine %%xmm %1
%xdefine %%masks %2
vpshufb %%xmm, %%xmm, %%masks
%endmacro
;;
;; Rotate Right
;;
%macro PRORQ 3.nolist
%xdefine %%mm %1
%xdefine %%nbits %2
%xdefine %%tmp %3
vpsllq %%tmp, %%mm, (64-%%nbits)
vpsrlq %%mm, %%mm, %%nbits
vpor %%mm, %%mm,%%tmp
%endmacro
;;
;; Init and Update W:
;;
;; j = 0-15
;; W[j] = ENDIANNESS(src)
;;
;; j = 16-79
;; W[j] = SIGMA1(W[j- 2]) + W[j- 7]
;; +SIGMA0(W[j-15]) + W[j-16]
;;
;; SIGMA0(x) = ROR64(x,1) ^ROR64(x,8) ^LSR64(x,7)
;; SIGMA1(x) = ROR64(x,19)^ROR64(x,61)^LSR64(x,6)
;;
%macro SIGMA0 4.nolist
%xdefine %%sigma %1
%xdefine %%x %2
%xdefine %%t1 %3
%xdefine %%t2 %4
vpsrlq %%sigma, %%x, 7
vmovdqa %%t1, %%x
PRORQ %%x, 1, %%t2
vpxor %%sigma, %%sigma, %%x
PRORQ %%t1,8, %%t2
vpxor %%sigma, %%sigma, %%t1
%endmacro
%macro SIGMA1 4.nolist
%xdefine %%sigma %1
%xdefine %%x %2
%xdefine %%t1 %3
%xdefine %%t2 %4
vpsrlq %%sigma, %%x, 6
vmovdqa %%t1, %%x
PRORQ %%x, 19, %%t2
vpxor %%sigma, %%sigma, %%x
PRORQ %%t1,61, %%t2
vpxor %%sigma, %%sigma, %%t1
%endmacro
;;
;; SHA512 step
;;
;; Ipp64u T1 = H + SUM1(E) + CHJ(E,F,G) + K_SHA512[t] + W[t];
;; Ipp64u T2 = SUM0(A) + MAJ(A,B,C);
;; D+= T1;
;; H = T1 + T2;
;;
;; where
;; SUM1(x) = ROR64(x,14) ^ ROR64(x,18) ^ ROR64(x,41)
;; SUM0(x) = ROR64(x,28) ^ ROR64(x,34) ^ ROR64(x,39)
;;
;; CHJ(x,y,z) = (x & y) ^ (~x & z) => x&(y^z) ^z
;; MAJ(x,y,z) = (x & y) ^ (x & z) ^ (y & z) = (x&y)^((x^y)&z)
;;
;; Input:
;; A,B,C,D,E,F,G,H - 8 digest's values
;; pW - pointer to the W array
;; pK512 - pointer to the constants
;; pBuffer - temporary buffer
;; Output:
;; A,B,C,D*,E,F,G,H* - 8 digest's values (D and H updated)
;; pW - pointer to the W array
;; pK512 - pointer to the constants
;; pBuffer - temporary buffer (changed)
;;
%macro CHJ 5.nolist
%xdefine %%R %1
%xdefine %%E %2
%xdefine %%F %3
%xdefine %%G %4
%xdefine %%T %5
vpxor %%R, %%F,%%G ; R=(f^g)
vpand %%R, %%R,%%E ; R=e & (f^g)
vpxor %%R, %%R,%%G ; R=e & (f^g) ^g
%endmacro
%macro MAJ 5.nolist
%xdefine %%R %1
%xdefine %%A %2
%xdefine %%B %3
%xdefine %%C %4
%xdefine %%T %5
vpxor %%T, %%A,%%B ; T=a^b
vpand %%R, %%A,%%B ; R=a&b
vpand %%T, %%T,%%C ; T=(a^b)&c
vpxor %%R, %%R,%%T ; R=(a&b)^((a^b)&c)
%endmacro
%macro SUM0 3.nolist
%xdefine %%R %1
%xdefine %%X %2
%xdefine %%tmp %3
vmovdqa %%R,%%X
PRORQ %%R,28,%%tmp ; R=ROR(X,28)
PRORQ %%X,34,%%tmp ; X=ROR(X,34)
vpxor %%R, %%R,%%X
PRORQ %%X,(39-34),%%tmp ; X=ROR(x,39)
vpxor %%R, %%R,%%X
%endmacro
%macro SUM1 3.nolist
%xdefine %%R %1
%xdefine %%X %2
%xdefine %%tmp %3
vmovdqa %%R,%%X
PRORQ %%R,14,%%tmp ; R=ROR(X,14)
PRORQ %%X,18,%%tmp ; X=ROR(X,18)
vpxor %%R, %%R,%%X
PRORQ %%X,(41-18),%%tmp ; X=ROR(x,41)
vpxor %%R, %%R,%%X
%endmacro
%macro SHA512_STEP 11.nolist
%xdefine %%A %1
%xdefine %%B %2
%xdefine %%C %3
%xdefine %%D %4
%xdefine %%E %5
%xdefine %%F %6
%xdefine %%G %7
%xdefine %%H %8
%xdefine %%pW %9
%xdefine %%pK512 %10
%xdefine %%pBuffer %11
vmovdqa oword [%%pBuffer+0*sizeof(oword)],%%E ; save E
vmovdqa oword [%%pBuffer+1*sizeof(oword)],%%A ; save A
vmovdqa oword [%%pBuffer+2*sizeof(oword)],%%D ; save D
vmovdqa oword [%%pBuffer+3*sizeof(oword)],%%H ; save H
CHJ %%D,%%E,%%F,%%G, %%H ; t1 = h+CHJ(e,f,g)+pW[]+pK512[]
vmovq %%H, qword [%%pW]
vpaddq %%D, %%D,%%H ; +[pW]
vmovq %%H, qword [%%pK512]
vpaddq %%D, %%D,%%H ; +[pK512]
vpaddq %%D, %%D,oword [%%pBuffer+3*sizeof(oword)]
vmovdqa oword [%%pBuffer+3*sizeof(oword)],%%D ; save t1
MAJ %%H,%%A,%%B,%%C, %%D ; t2 = MAJ(a,b,c)
vmovdqa oword [%%pBuffer+4*sizeof(oword)],%%H ; save t2
SUM1 %%D,%%E,%%H ; D = SUM1(e)
vpaddq %%D, %%D,oword [%%pBuffer+3*sizeof(oword)]; t1 = h+CHJ(e,f,g)+pW[]+pK512[] + SUM1(e)
SUM0 %%H,%%A,%%E ; H = SUM0(a)
vpaddq %%H, %%H,oword [%%pBuffer+4*sizeof(oword)]; t2 = MAJ(a,b,c)+SUM0(a)
vpaddq %%H, %%H,%%D ; h = t1+t2
vpaddq %%D, %%D,oword [%%pBuffer+2*sizeof(oword)]; d+= t1
vmovdqa %%E,oword [%%pBuffer+0*sizeof(oword)] ; restore E
vmovdqa %%A,oword [%%pBuffer+1*sizeof(oword)] ; restore A
%endmacro
segment .text align=IPP_ALIGN_FACTOR
%if (_IPP >= _IPP_V8)
align IPP_ALIGN_FACTOR
SWP_BYTE:
pByteSwp DB 7,6,5,4,3,2,1,0, 15,14,13,12,11,10,9,8
%endif
;*******************************************************************************************
;* Purpose: Update internal digest according to message block
;*
;* void UpdateSHA512(DigestSHA512 digest, const Ipp64u* mblk, int mlen, const void* pParam)
;*
;*******************************************************************************************
;;
;; Lib = W7, V8, P8
;;
;; Caller = ippsSHA512Update
;; Caller = ippsSHA512Final
;; Caller = ippsSHA512MessageDigest
;;
;; Caller = ippsSHA384Update
;; Caller = ippsSHA384Final
;; Caller = ippsSHA384MessageDigest
;;
;; Caller = ippsHMACSHA512Update
;; Caller = ippsHMACSHA512Final
;; Caller = ippsHMACSHA512MessageDigest
;;
;; Caller = ippsHMACSHA384Update
;; Caller = ippsHMACSHA384Final
;; Caller = ippsHMACSHA384MessageDigest
;;
align IPP_ALIGN_FACTOR
IPPASM UpdateSHA512,PUBLIC
USES_GPR esi,edi,ebp
mov ebp, esp ; save original esp to use it to reach parameters
%xdefine digest [ebp + ARG_1 + 0*sizeof(dword)] ; digest address
%xdefine mblk [ebp + ARG_1 + 1*sizeof(dword)] ; buffer address
%xdefine mlen [ebp + ARG_1 + 2*sizeof(dword)] ; buffer length
%xdefine pSHA512 [ebp + ARG_1 + 3*sizeof(dword)] ; address of SHA constants
%xdefine MBS_SHA512 (128) ; SHA512 block data size
%assign sSize 5 ; size of save area (oword)
%assign dSize 8 ; size of digest (oword)
%assign wSize 80 ; W values queue (qword)
%assign stackSize (sSize*sizeof(oword)+dSize*sizeof(oword)+wSize*sizeof(qword)+sizeof(dword)) ; stack size (bytes)
%assign sOffset 0 ; save area
%assign dOffset sOffset+sSize*sizeof(oword) ; digest offset
%assign wOffset dOffset+dSize*sizeof(oword) ; W values offset
%assign acualOffset wOffset+wSize*sizeof(qword) ; actual stack size offset
mov edi,digest ; digest address
mov esi,mblk ; source data address
mov eax,mlen ; source data length
mov edx, pSHA512 ; table constant address
sub esp,stackSize ; allocate local buffer (probably unaligned)
mov ecx,esp
and esp,-16 ; 16-byte aligned stack
sub ecx,esp
add ecx,stackSize ; acual stack size (bytes)
mov [esp+acualOffset],ecx
vmovq xmm0,qword [edi+sizeof(qword)*0] ; A = digest[0]
vmovq xmm1,qword [edi+sizeof(qword)*1] ; B = digest[1]
vmovq xmm2,qword [edi+sizeof(qword)*2] ; C = digest[2]
vmovq xmm3,qword [edi+sizeof(qword)*3] ; D = digest[3]
vmovq xmm4,qword [edi+sizeof(qword)*4] ; E = digest[4]
vmovq xmm5,qword [edi+sizeof(qword)*5] ; F = digest[5]
vmovq xmm6,qword [edi+sizeof(qword)*6] ; G = digest[6]
vmovq xmm7,qword [edi+sizeof(qword)*7] ; H = digest[7]
vmovdqa oword [esp+dOffset+sizeof(oword)*0], xmm0
vmovdqa oword [esp+dOffset+sizeof(oword)*1], xmm1
vmovdqa oword [esp+dOffset+sizeof(oword)*2], xmm2
vmovdqa oword [esp+dOffset+sizeof(oword)*3], xmm3
vmovdqa oword [esp+dOffset+sizeof(oword)*4], xmm4
vmovdqa oword [esp+dOffset+sizeof(oword)*5], xmm5
vmovdqa oword [esp+dOffset+sizeof(oword)*6], xmm6
vmovdqa oword [esp+dOffset+sizeof(oword)*7], xmm7
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; process next data block
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
.sha512_block_loop:
;;
;; initialize the first 16 qwords in the array W (remember about endian)
;;
;vmovdqa xmm1, oword pByteSwp ; load shuffle mask
LD_ADDR ecx, SWP_BYTE
movdqa xmm1, oword [ecx+(pByteSwp-SWP_BYTE)]
mov ecx,0
align IPP_ALIGN_FACTOR
.loop1:
vmovdqu xmm0, oword [esi+ecx*sizeof(qword)] ; swap input
ENDIANNESS xmm0, xmm1
vmovdqa oword [esp+wOffset+ecx*sizeof(qword)],xmm0
add ecx,sizeof(oword)/sizeof(qword)
cmp ecx,16
jl .loop1
;;
;; initialize another 80-16 qwords in the array W
;;
align IPP_ALIGN_FACTOR
.loop2:
vmovdqa xmm1,oword [esp+ecx*sizeof(qword)+wOffset- 2*sizeof(qword)] ; xmm1 = W[j-2]
SIGMA1 xmm0,xmm1,xmm2,xmm3
vmovdqu xmm5,oword [esp+ecx*sizeof(qword)+wOffset-15*sizeof(qword)] ; xmm5 = W[j-15]
SIGMA0 xmm4,xmm5,xmm6,xmm3
vmovdqu xmm7,oword [esp+ecx*sizeof(qword)+wOffset- 7*sizeof(qword)] ; W[j-7]
vpaddq xmm0, xmm0,xmm4
vpaddq xmm7, xmm7,oword [esp+ecx*sizeof(qword)+wOffset-16*sizeof(qword)] ; W[j-16]
vpaddq xmm0, xmm0,xmm7
vmovdqa oword [esp+ecx*sizeof(qword)+wOffset],xmm0
add ecx,sizeof(oword)/sizeof(qword)
cmp ecx,80
jl .loop2
;;
;; init A,B,C,D,E,F,G,H by the internal digest
;;
vmovdqa xmm0,oword [esp+dOffset+sizeof(oword)*0] ; A = digest[0]
vmovdqa xmm1,oword [esp+dOffset+sizeof(oword)*1] ; B = digest[1]
vmovdqa xmm2,oword [esp+dOffset+sizeof(oword)*2] ; C = digest[2]
vmovdqa xmm3,oword [esp+dOffset+sizeof(oword)*3] ; D = digest[3]
vmovdqa xmm4,oword [esp+dOffset+sizeof(oword)*4] ; E = digest[4]
vmovdqa xmm5,oword [esp+dOffset+sizeof(oword)*5] ; F = digest[5]
vmovdqa xmm6,oword [esp+dOffset+sizeof(oword)*6] ; G = digest[6]
vmovdqa xmm7,oword [esp+dOffset+sizeof(oword)*7] ; H = digest[7]
;;
;; perform 0-79 steps
;;
xor ecx,ecx
align IPP_ALIGN_FACTOR
.loop3:
;; A, B, C, D, E, F, G, H W[], K[], buffer
;; --------------------------------------------------------------------------------------------------------------------------------------
SHA512_STEP xmm0,xmm1,xmm2,xmm3,xmm4,xmm5,xmm6,xmm7, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*0},{edx+ecx*sizeof(qword)+sizeof(qword)*0}, {esp}
SHA512_STEP xmm7,xmm0,xmm1,xmm2,xmm3,xmm4,xmm5,xmm6, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*1},{edx+ecx*sizeof(qword)+sizeof(qword)*1}, {esp}
SHA512_STEP xmm6,xmm7,xmm0,xmm1,xmm2,xmm3,xmm4,xmm5, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*2},{edx+ecx*sizeof(qword)+sizeof(qword)*2}, {esp}
SHA512_STEP xmm5,xmm6,xmm7,xmm0,xmm1,xmm2,xmm3,xmm4, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*3},{edx+ecx*sizeof(qword)+sizeof(qword)*3}, {esp}
SHA512_STEP xmm4,xmm5,xmm6,xmm7,xmm0,xmm1,xmm2,xmm3, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*4},{edx+ecx*sizeof(qword)+sizeof(qword)*4}, {esp}
SHA512_STEP xmm3,xmm4,xmm5,xmm6,xmm7,xmm0,xmm1,xmm2, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*5},{edx+ecx*sizeof(qword)+sizeof(qword)*5}, {esp}
SHA512_STEP xmm2,xmm3,xmm4,xmm5,xmm6,xmm7,xmm0,xmm1, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*6},{edx+ecx*sizeof(qword)+sizeof(qword)*6}, {esp}
SHA512_STEP xmm1,xmm2,xmm3,xmm4,xmm5,xmm6,xmm7,xmm0, {esp+ecx*sizeof(qword)+wOffset+sizeof(qword)*7},{edx+ecx*sizeof(qword)+sizeof(qword)*7}, {esp}
add ecx,8
cmp ecx,80
jl .loop3
;;
;; update digest
;;
vpaddq xmm0, xmm0,oword [esp+dOffset+sizeof(oword)*0] ; A += digest[0]
vpaddq xmm1, xmm1,oword [esp+dOffset+sizeof(oword)*1] ; B += digest[1]
vpaddq xmm2, xmm2,oword [esp+dOffset+sizeof(oword)*2] ; C += digest[2]
vpaddq xmm3, xmm3,oword [esp+dOffset+sizeof(oword)*3] ; D += digest[3]
vpaddq xmm4, xmm4,oword [esp+dOffset+sizeof(oword)*4] ; E += digest[4]
vpaddq xmm5, xmm5,oword [esp+dOffset+sizeof(oword)*5] ; F += digest[5]
vpaddq xmm6, xmm6,oword [esp+dOffset+sizeof(oword)*6] ; G += digest[6]
vpaddq xmm7, xmm7,oword [esp+dOffset+sizeof(oword)*7] ; H += digest[7]
vmovdqa oword [esp+dOffset+sizeof(oword)*0],xmm0 ; digest[0] = A
vmovdqa oword [esp+dOffset+sizeof(oword)*1],xmm1 ; digest[1] = B
vmovdqa oword [esp+dOffset+sizeof(oword)*2],xmm2 ; digest[2] = C
vmovdqa oword [esp+dOffset+sizeof(oword)*3],xmm3 ; digest[3] = D
vmovdqa oword [esp+dOffset+sizeof(oword)*4],xmm4 ; digest[4] = E
vmovdqa oword [esp+dOffset+sizeof(oword)*5],xmm5 ; digest[5] = F
vmovdqa oword [esp+dOffset+sizeof(oword)*6],xmm6 ; digest[6] = G
vmovdqa oword [esp+dOffset+sizeof(oword)*7],xmm7 ; digest[7] = H
add esi, MBS_SHA512
sub eax, MBS_SHA512
jg .sha512_block_loop
vmovq qword [edi+sizeof(qword)*0], xmm0 ; A = digest[0]
vmovq qword [edi+sizeof(qword)*1], xmm1 ; B = digest[1]
vmovq qword [edi+sizeof(qword)*2], xmm2 ; C = digest[2]
vmovq qword [edi+sizeof(qword)*3], xmm3 ; D = digest[3]
vmovq qword [edi+sizeof(qword)*4], xmm4 ; E = digest[4]
vmovq qword [edi+sizeof(qword)*5], xmm5 ; F = digest[5]
vmovq qword [edi+sizeof(qword)*6], xmm6 ; G = digest[6]
vmovq qword [edi+sizeof(qword)*7], xmm7 ; H = digest[7]
add esp,[esp+acualOffset]
REST_GPR
ret
ENDFUNC UpdateSHA512
%endif ;; (_IPP >= _IPP_G9)
%endif ;; _ENABLE_ALG_SHA512_
|
/*! @file
@brief MessageBox用関数
@author Norio Nakatani
@date 2002/01/17 aroka 型の修正
@date 2013/03/03 Uchi Debug1.cppから分離
*/
/*
Copyright (C) 1998-2001, Norio Nakatani
Copyright (C) 2002, aroka
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "StdAfx.h"
#include <stdarg.h>
#include <tchar.h>
#include "MessageBoxF.h"
#include "window/CEditWnd.h"
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
// メッセージボックス:実装 //
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //
int Wrap_MessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
// 選択中の言語IDを取得する
LANGID wLangId = CSelectLang::getDefaultLangId();
// lpText, lpCaption をローカルバッファにコピーして MessageBox API を呼び出す
// ※ 使い回しのバッファが使用されていてそれが裏で書き換えられた場合でも
// メッセージボックス上の Ctrl+C が文字化けしないように
return ::MessageBoxEx(hWnd,
lpText ? std::tstring(lpText).c_str() : NULL,
lpCaption ? std::tstring(lpCaption).c_str() : NULL,
uType,
wLangId
);
}
HWND GetMessageBoxOwner(HWND hwndOwner)
{
if(hwndOwner==NULL && g_pcEditWnd){
return g_pcEditWnd->GetHwnd();
}
else{
return hwndOwner;
}
}
/*!
書式付きメッセージボックス
引数で与えられた情報をダイアログボックスで表示する.
デバッグ目的以外でも使用できる.
*/
int VMessageBoxF(
HWND hwndOwner, //!< [in] オーナーウィンドウのハンドル
UINT uType, //!< [in] メッセージボックスのスタイル (MessageBoxと同じ形式)
LPCTSTR lpCaption, //!< [in] メッセージボックスのタイトル
LPCTSTR lpText, //!< [in] 表示するテキスト。printf仕様の書式指定が可能。
va_list& v //!< [in,out] 引数リスト
)
{
hwndOwner=GetMessageBoxOwner(hwndOwner);
//整形
static TCHAR szBuf[16000];
tchar_vsnprintf_s(szBuf,_countof(szBuf),lpText,v);
//API呼び出し
return ::MessageBox( hwndOwner, szBuf, lpCaption, uType);
}
int MessageBoxF( HWND hwndOwner, UINT uType, LPCTSTR lpCaption, LPCTSTR lpText, ... )
{
va_list v;
va_start(v,lpText);
int nRet = VMessageBoxF(hwndOwner, uType, lpCaption, lpText, v);
va_end(v);
return nRet;
}
//エラー:赤丸に「×」[OK]
int ErrorMessage (HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONSTOP , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopErrorMessage(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONSTOP | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;} //(TOPMOST)
//警告:三角に「i」
int WarningMessage (HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONEXCLAMATION , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopWarningMessage(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;}
//情報:青丸に「i」
int InfoMessage (HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONINFORMATION , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopInfoMessage(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONINFORMATION | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;}
//確認:吹き出しの「?」 戻り値:ID_YES,ID_NO
int ConfirmMessage (HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_YESNO | MB_ICONQUESTION , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopConfirmMessage(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_YESNO | MB_ICONQUESTION | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;}
//三択:吹き出しの「?」 戻り値:ID_YES,ID_NO,ID_CANCEL
int Select3Message (HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_YESNOCANCEL | MB_ICONQUESTION , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopSelect3Message(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_YESNOCANCEL | MB_ICONQUESTION | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;}
//その他メッセージ表示用ボックス
int OkMessage (HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopOkMessage(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;} //(TOPMOST)
//タイプ指定メッセージ表示用ボックス
int CustomMessage (HWND hwnd, UINT uType, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, uType , GSTR_APPNAME, format, p);va_end(p);return n;}
int TopCustomMessage(HWND hwnd, UINT uType, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, uType | MB_TOPMOST , GSTR_APPNAME, format, p);va_end(p);return n;} //(TOPMOST)
//作者に教えて欲しいエラー
int PleaseReportToAuthor(HWND hwnd, LPCTSTR format, ...){ va_list p;va_start(p, format);int n=VMessageBoxF (hwnd, MB_OK | MB_ICONSTOP | MB_TOPMOST, LS(STR_ERR_DLGDOCLMN1), format, p);va_end(p);return n;}
|
;
; OZ-7xx DK emulation layer for Z88DK
; by Stefano Bodrato - Oct. 2003
;
; int isin(unsigned degrees);
; input must be between 0 and 360
; returns value from -16384 to +16384
;
; ------
; $Id: isin.asm,v 1.1 2003/10/29 11:37:11 stefano Exp $
;
XLIB isin
XDEF sin_start
isin:
pop de
pop hl
push hl
push de
sin_start:
ld c,l
ld b,h ;; save input
ld de,181
or a
sbc hl,de
jr c,DontFlip
ld hl,360
sbc hl,bc ;; no carry here
ld c,l
ld b,h
ld a,1
jr Norm_0_180
DontFlip:
ld l,c
ld h,b
xor a
Norm_0_180:
;; degrees normalized between 0 and 180 in hl and in bc
;; sign of output in a
ld de,90
or a
sbc hl,de
jr c,DontFlip2
ld hl,180
sbc hl,bc ;; carry is 0 here
jr Norm_0_90
DontFlip2:
ld l,c
ld h,b
Norm_0_90:
;; degrees normalized between 0 and 90 in hl and sign of answer is in a
add hl,hl
ld de,sin_table
add hl,de
ld e,(hl)
inc hl
ld d,(hl)
;; de=answer
or a
jr z,DontNegate
ld hl,0
sbc hl,de ;; carry is 0 here
ret
DontNegate:
ex de,hl
ret
sin_table:
;; generated by sintable.c
defw 0
defw 285
defw 571
defw 857
defw 1142
defw 1427
defw 1712
defw 1996
defw 2280
defw 2563
defw 2845
defw 3126
defw 3406
defw 3685
defw 3963
defw 4240
defw 4516
defw 4790
defw 5062
defw 5334
defw 5603
defw 5871
defw 6137
defw 6401
defw 6663
defw 6924
defw 7182
defw 7438
defw 7691
defw 7943
defw 8191
defw 8438
defw 8682
defw 8923
defw 9161
defw 9397
defw 9630
defw 9860
defw 10086
defw 10310
defw 10531
defw 10748
defw 10963
defw 11173
defw 11381
defw 11585
defw 11785
defw 11982
defw 12175
defw 12365
defw 12550
defw 12732
defw 12910
defw 13084
defw 13254
defw 13420
defw 13582
defw 13740
defw 13894
defw 14043
defw 14188
defw 14329
defw 14466
defw 14598
defw 14725
defw 14848
defw 14967
defw 15081
defw 15190
defw 15295
defw 15395
defw 15491
defw 15582
defw 15668
defw 15749
defw 15825
defw 15897
defw 15964
defw 16025
defw 16082
defw 16135
defw 16182
defw 16224
defw 16261
defw 16294
defw 16321
defw 16344
defw 16361
defw 16374
defw 16381
defw 16384
|
//===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This implements routines for translating from LLVM IR into SelectionDAG IR.
//
//===----------------------------------------------------------------------===//
#include "SelectionDAGBuilder.h"
#include "SDNodeDbgValue.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/BlockFrequencyInfo.h"
#include "llvm/Analysis/BranchProbabilityInfo.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/CodeGen/Analysis.h"
#include "llvm/CodeGen/FunctionLoweringInfo.h"
#include "llvm/CodeGen/GCMetadata.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/RuntimeLibcalls.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
#include "llvm/CodeGen/StackMaps.h"
#include "llvm/CodeGen/SwiftErrorValueTracking.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetOpcodes.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/CodeGen/WinEHFuncInfo.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/IntrinsicsAArch64.h"
#include "llvm/IR/IntrinsicsWebAssembly.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Statepoint.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetIntrinsicInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Utils/Local.h"
#include <cstddef>
#include <cstring>
#include <iterator>
#include <limits>
#include <numeric>
#include <tuple>
using namespace llvm;
using namespace PatternMatch;
using namespace SwitchCG;
#define DEBUG_TYPE "isel"
/// LimitFloatPrecision - Generate low-precision inline sequences for
/// some float libcalls (6, 8 or 12 bits).
static unsigned LimitFloatPrecision;
static cl::opt<bool>
InsertAssertAlign("insert-assert-align", cl::init(true),
cl::desc("Insert the experimental `assertalign` node."),
cl::ReallyHidden);
static cl::opt<unsigned, true>
LimitFPPrecision("limit-float-precision",
cl::desc("Generate low-precision inline sequences "
"for some float libcalls"),
cl::location(LimitFloatPrecision), cl::Hidden,
cl::init(0));
static cl::opt<unsigned> SwitchPeelThreshold(
"switch-peel-threshold", cl::Hidden, cl::init(66),
cl::desc("Set the case probability threshold for peeling the case from a "
"switch statement. A value greater than 100 will void this "
"optimization"));
// Limit the width of DAG chains. This is important in general to prevent
// DAG-based analysis from blowing up. For example, alias analysis and
// load clustering may not complete in reasonable time. It is difficult to
// recognize and avoid this situation within each individual analysis, and
// future analyses are likely to have the same behavior. Limiting DAG width is
// the safe approach and will be especially important with global DAGs.
//
// MaxParallelChains default is arbitrarily high to avoid affecting
// optimization, but could be lowered to improve compile time. Any ld-ld-st-st
// sequence over this should have been converted to llvm.memcpy by the
// frontend. It is easy to induce this behavior with .ll code such as:
// %buffer = alloca [4096 x i8]
// %data = load [4096 x i8]* %argPtr
// store [4096 x i8] %data, [4096 x i8]* %buffer
static const unsigned MaxParallelChains = 64;
static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
const SDValue *Parts, unsigned NumParts,
MVT PartVT, EVT ValueVT, const Value *V,
Optional<CallingConv::ID> CC);
/// getCopyFromParts - Create a value that contains the specified legal parts
/// combined into the value they represent. If the parts combine to a type
/// larger than ValueVT then AssertOp can be used to specify whether the extra
/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
/// (ISD::AssertSext).
static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
const SDValue *Parts, unsigned NumParts,
MVT PartVT, EVT ValueVT, const Value *V,
Optional<CallingConv::ID> CC = None,
Optional<ISD::NodeType> AssertOp = None) {
// Let the target assemble the parts if it wants to
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
PartVT, ValueVT, CC))
return Val;
if (ValueVT.isVector())
return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
CC);
assert(NumParts > 0 && "No parts to assemble!");
SDValue Val = Parts[0];
if (NumParts > 1) {
// Assemble the value from multiple parts.
if (ValueVT.isInteger()) {
unsigned PartBits = PartVT.getSizeInBits();
unsigned ValueBits = ValueVT.getSizeInBits();
// Assemble the power of 2 part.
unsigned RoundParts =
(NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
unsigned RoundBits = PartBits * RoundParts;
EVT RoundVT = RoundBits == ValueBits ?
ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
SDValue Lo, Hi;
EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
if (RoundParts > 2) {
Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
PartVT, HalfVT, V);
Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
RoundParts / 2, PartVT, HalfVT, V);
} else {
Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
}
if (DAG.getDataLayout().isBigEndian())
std::swap(Lo, Hi);
Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
if (RoundParts < NumParts) {
// Assemble the trailing non-power-of-2 part.
unsigned OddParts = NumParts - RoundParts;
EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
OddVT, V, CC);
// Combine the round and odd parts.
Lo = Val;
if (DAG.getDataLayout().isBigEndian())
std::swap(Lo, Hi);
EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
Hi =
DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
DAG.getConstant(Lo.getValueSizeInBits(), DL,
TLI.getPointerTy(DAG.getDataLayout())));
Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
}
} else if (PartVT.isFloatingPoint()) {
// FP split into multiple FP parts (for ppcf128)
assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
"Unexpected split");
SDValue Lo, Hi;
Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
std::swap(Lo, Hi);
Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
} else {
// FP split into integer parts (soft fp)
assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
!PartVT.isVector() && "Unexpected split");
EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
}
}
// There is now one part, held in Val. Correct it to match ValueVT.
// PartEVT is the type of the register class that holds the value.
// ValueVT is the type of the inline asm operation.
EVT PartEVT = Val.getValueType();
if (PartEVT == ValueVT)
return Val;
if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
ValueVT.bitsLT(PartEVT)) {
// For an FP value in an integer part, we need to truncate to the right
// width first.
PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
}
// Handle types that have the same size.
if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
// Handle types with different sizes.
if (PartEVT.isInteger() && ValueVT.isInteger()) {
if (ValueVT.bitsLT(PartEVT)) {
// For a truncate, see if we have any information to
// indicate whether the truncated bits will always be
// zero or sign-extension.
if (AssertOp.hasValue())
Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
DAG.getValueType(ValueVT));
return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
}
return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
}
if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
// FP_ROUND's are always exact here.
if (ValueVT.bitsLT(Val.getValueType()))
return DAG.getNode(
ISD::FP_ROUND, DL, ValueVT, Val,
DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
}
// Handle MMX to a narrower integer type by bitcasting MMX to integer and
// then truncating.
if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
ValueVT.bitsLT(PartEVT)) {
Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
}
report_fatal_error("Unknown mismatch in getCopyFromParts!");
}
static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
const Twine &ErrMsg) {
const Instruction *I = dyn_cast_or_null<Instruction>(V);
if (!V)
return Ctx.emitError(ErrMsg);
const char *AsmError = ", possible invalid constraint for vector type";
if (const CallInst *CI = dyn_cast<CallInst>(I))
if (CI->isInlineAsm())
return Ctx.emitError(I, ErrMsg + AsmError);
return Ctx.emitError(I, ErrMsg);
}
/// getCopyFromPartsVector - Create a value that contains the specified legal
/// parts combined into the value they represent. If the parts combine to a
/// type larger than ValueVT then AssertOp can be used to specify whether the
/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
/// ValueVT (ISD::AssertSext).
static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
const SDValue *Parts, unsigned NumParts,
MVT PartVT, EVT ValueVT, const Value *V,
Optional<CallingConv::ID> CallConv) {
assert(ValueVT.isVector() && "Not a vector value");
assert(NumParts > 0 && "No parts to assemble!");
const bool IsABIRegCopy = CallConv.hasValue();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SDValue Val = Parts[0];
// Handle a multi-element vector.
if (NumParts > 1) {
EVT IntermediateVT;
MVT RegisterVT;
unsigned NumIntermediates;
unsigned NumRegs;
if (IsABIRegCopy) {
NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
*DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
NumIntermediates, RegisterVT);
} else {
NumRegs =
TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
NumIntermediates, RegisterVT);
}
assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
NumParts = NumRegs; // Silence a compiler warning.
assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
assert(RegisterVT.getSizeInBits() ==
Parts[0].getSimpleValueType().getSizeInBits() &&
"Part type sizes don't match!");
// Assemble the parts into intermediate operands.
SmallVector<SDValue, 8> Ops(NumIntermediates);
if (NumIntermediates == NumParts) {
// If the register was not expanded, truncate or copy the value,
// as appropriate.
for (unsigned i = 0; i != NumParts; ++i)
Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
PartVT, IntermediateVT, V, CallConv);
} else if (NumParts > 0) {
// If the intermediate type was expanded, build the intermediate
// operands from the parts.
assert(NumParts % NumIntermediates == 0 &&
"Must expand into a divisible number of parts!");
unsigned Factor = NumParts / NumIntermediates;
for (unsigned i = 0; i != NumIntermediates; ++i)
Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
PartVT, IntermediateVT, V, CallConv);
}
// Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
// intermediate operands.
EVT BuiltVectorTy =
IntermediateVT.isVector()
? EVT::getVectorVT(
*DAG.getContext(), IntermediateVT.getScalarType(),
IntermediateVT.getVectorElementCount() * NumParts)
: EVT::getVectorVT(*DAG.getContext(),
IntermediateVT.getScalarType(),
NumIntermediates);
Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
: ISD::BUILD_VECTOR,
DL, BuiltVectorTy, Ops);
}
// There is now one part, held in Val. Correct it to match ValueVT.
EVT PartEVT = Val.getValueType();
if (PartEVT == ValueVT)
return Val;
if (PartEVT.isVector()) {
// If the element type of the source/dest vectors are the same, but the
// parts vector has more elements than the value vector, then we have a
// vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
// elements we want.
if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
assert((PartEVT.getVectorElementCount().getKnownMinValue() >
ValueVT.getVectorElementCount().getKnownMinValue()) &&
(PartEVT.getVectorElementCount().isScalable() ==
ValueVT.getVectorElementCount().isScalable()) &&
"Cannot narrow, it would be a lossy transformation");
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
DAG.getVectorIdxConstant(0, DL));
}
// Vector/Vector bitcast.
if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
"Cannot handle this kind of promotion");
// Promoted vector extract
return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
}
// Trivial bitcast if the types are the same size and the destination
// vector type is legal.
if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
TLI.isTypeLegal(ValueVT))
return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
if (ValueVT.getVectorNumElements() != 1) {
// Certain ABIs require that vectors are passed as integers. For vectors
// are the same size, this is an obvious bitcast.
if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
} else if (ValueVT.bitsLT(PartEVT)) {
const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
// Drop the extra bits.
Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
return DAG.getBitcast(ValueVT, Val);
}
diagnosePossiblyInvalidConstraint(
*DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
return DAG.getUNDEF(ValueVT);
}
// Handle cases such as i8 -> <1 x i1>
EVT ValueSVT = ValueVT.getVectorElementType();
if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
else
Val = ValueVT.isFloatingPoint()
? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
: DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
}
return DAG.getBuildVector(ValueVT, DL, Val);
}
static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
SDValue Val, SDValue *Parts, unsigned NumParts,
MVT PartVT, const Value *V,
Optional<CallingConv::ID> CallConv);
/// getCopyToParts - Create a series of nodes that contain the specified value
/// split into legal parts. If the parts contain more bits than Val, then, for
/// integers, ExtendKind can be used to specify how to generate the extra bits.
static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
SDValue *Parts, unsigned NumParts, MVT PartVT,
const Value *V,
Optional<CallingConv::ID> CallConv = None,
ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
// Let the target split the parts if it wants to
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
CallConv))
return;
EVT ValueVT = Val.getValueType();
// Handle the vector case separately.
if (ValueVT.isVector())
return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
CallConv);
unsigned PartBits = PartVT.getSizeInBits();
unsigned OrigNumParts = NumParts;
assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
"Copying to an illegal type!");
if (NumParts == 0)
return;
assert(!ValueVT.isVector() && "Vector case handled elsewhere");
EVT PartEVT = PartVT;
if (PartEVT == ValueVT) {
assert(NumParts == 1 && "No-op copy with multiple parts!");
Parts[0] = Val;
return;
}
if (NumParts * PartBits > ValueVT.getSizeInBits()) {
// If the parts cover more bits than the value has, promote the value.
if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
assert(NumParts == 1 && "Do not know what to promote to!");
Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
} else {
if (ValueVT.isFloatingPoint()) {
// FP values need to be bitcast, then extended if they are being put
// into a larger container.
ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
}
assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
ValueVT.isInteger() &&
"Unknown mismatch!");
ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
if (PartVT == MVT::x86mmx)
Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
}
} else if (PartBits == ValueVT.getSizeInBits()) {
// Different types of the same size.
assert(NumParts == 1 && PartEVT != ValueVT);
Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
} else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
// If the parts cover less bits than value has, truncate the value.
assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
ValueVT.isInteger() &&
"Unknown mismatch!");
ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
if (PartVT == MVT::x86mmx)
Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
}
// The value may have changed - recompute ValueVT.
ValueVT = Val.getValueType();
assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
"Failed to tile the value with PartVT!");
if (NumParts == 1) {
if (PartEVT != ValueVT) {
diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
"scalar-to-vector conversion failed");
Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
}
Parts[0] = Val;
return;
}
// Expand the value into multiple parts.
if (NumParts & (NumParts - 1)) {
// The number of parts is not a power of 2. Split off and copy the tail.
assert(PartVT.isInteger() && ValueVT.isInteger() &&
"Do not know what to expand to!");
unsigned RoundParts = 1 << Log2_32(NumParts);
unsigned RoundBits = RoundParts * PartBits;
unsigned OddParts = NumParts - RoundParts;
SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
CallConv);
if (DAG.getDataLayout().isBigEndian())
// The odd parts were reversed by getCopyToParts - unreverse them.
std::reverse(Parts + RoundParts, Parts + NumParts);
NumParts = RoundParts;
ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
}
// The number of parts is a power of 2. Repeatedly bisect the value using
// EXTRACT_ELEMENT.
Parts[0] = DAG.getNode(ISD::BITCAST, DL,
EVT::getIntegerVT(*DAG.getContext(),
ValueVT.getSizeInBits()),
Val);
for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
for (unsigned i = 0; i < NumParts; i += StepSize) {
unsigned ThisBits = StepSize * PartBits / 2;
EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
SDValue &Part0 = Parts[i];
SDValue &Part1 = Parts[i+StepSize/2];
Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
if (ThisBits == PartBits && ThisVT != PartVT) {
Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
}
}
}
if (DAG.getDataLayout().isBigEndian())
std::reverse(Parts, Parts + OrigNumParts);
}
static SDValue widenVectorToPartType(SelectionDAG &DAG,
SDValue Val, const SDLoc &DL, EVT PartVT) {
if (!PartVT.isFixedLengthVector())
return SDValue();
EVT ValueVT = Val.getValueType();
unsigned PartNumElts = PartVT.getVectorNumElements();
unsigned ValueNumElts = ValueVT.getVectorNumElements();
if (PartNumElts > ValueNumElts &&
PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
EVT ElementVT = PartVT.getVectorElementType();
// Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
// undef elements.
SmallVector<SDValue, 16> Ops;
DAG.ExtractVectorElements(Val, Ops);
SDValue EltUndef = DAG.getUNDEF(ElementVT);
for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
Ops.push_back(EltUndef);
// FIXME: Use CONCAT for 2x -> 4x.
return DAG.getBuildVector(PartVT, DL, Ops);
}
return SDValue();
}
/// getCopyToPartsVector - Create a series of nodes that contain the specified
/// value split into legal parts.
static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
SDValue Val, SDValue *Parts, unsigned NumParts,
MVT PartVT, const Value *V,
Optional<CallingConv::ID> CallConv) {
EVT ValueVT = Val.getValueType();
assert(ValueVT.isVector() && "Not a vector");
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const bool IsABIRegCopy = CallConv.hasValue();
if (NumParts == 1) {
EVT PartEVT = PartVT;
if (PartEVT == ValueVT) {
// Nothing to do.
} else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
// Bitconvert vector->vector case.
Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
} else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
Val = Widened;
} else if (PartVT.isVector() &&
PartEVT.getVectorElementType().bitsGE(
ValueVT.getVectorElementType()) &&
PartEVT.getVectorElementCount() ==
ValueVT.getVectorElementCount()) {
// Promoted vector extract
Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
} else {
if (ValueVT.getVectorElementCount().isScalar()) {
Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
DAG.getVectorIdxConstant(0, DL));
} else {
uint64_t ValueSize = ValueVT.getFixedSizeInBits();
assert(PartVT.getFixedSizeInBits() > ValueSize &&
"lossy conversion of vector to scalar type");
EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
Val = DAG.getBitcast(IntermediateType, Val);
Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
}
}
assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
Parts[0] = Val;
return;
}
// Handle a multi-element vector.
EVT IntermediateVT;
MVT RegisterVT;
unsigned NumIntermediates;
unsigned NumRegs;
if (IsABIRegCopy) {
NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
*DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
NumIntermediates, RegisterVT);
} else {
NumRegs =
TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
NumIntermediates, RegisterVT);
}
assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
NumParts = NumRegs; // Silence a compiler warning.
assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
"Mixing scalable and fixed vectors when copying in parts");
Optional<ElementCount> DestEltCnt;
if (IntermediateVT.isVector())
DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
else
DestEltCnt = ElementCount::getFixed(NumIntermediates);
EVT BuiltVectorTy = EVT::getVectorVT(
*DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
if (ValueVT == BuiltVectorTy) {
// Nothing to do.
} else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
// Bitconvert vector->vector case.
Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
} else if (SDValue Widened =
widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
Val = Widened;
} else if (BuiltVectorTy.getVectorElementType().bitsGE(
ValueVT.getVectorElementType()) &&
BuiltVectorTy.getVectorElementCount() ==
ValueVT.getVectorElementCount()) {
// Promoted vector extract
Val = DAG.getAnyExtOrTrunc(Val, DL, BuiltVectorTy);
}
assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
// Split the vector into intermediate operands.
SmallVector<SDValue, 8> Ops(NumIntermediates);
for (unsigned i = 0; i != NumIntermediates; ++i) {
if (IntermediateVT.isVector()) {
// This does something sensible for scalable vectors - see the
// definition of EXTRACT_SUBVECTOR for further details.
unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
Ops[i] =
DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
} else {
Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
DAG.getVectorIdxConstant(i, DL));
}
}
// Split the intermediate operands into legal parts.
if (NumParts == NumIntermediates) {
// If the register was not expanded, promote or copy the value,
// as appropriate.
for (unsigned i = 0; i != NumParts; ++i)
getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
} else if (NumParts > 0) {
// If the intermediate type was expanded, split each the value into
// legal parts.
assert(NumIntermediates != 0 && "division by zero");
assert(NumParts % NumIntermediates == 0 &&
"Must expand into a divisible number of parts!");
unsigned Factor = NumParts / NumIntermediates;
for (unsigned i = 0; i != NumIntermediates; ++i)
getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
CallConv);
}
}
RegsForValue::RegsForValue(const SmallVector<unsigned, 4> ®s, MVT regvt,
EVT valuevt, Optional<CallingConv::ID> CC)
: ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
RegCount(1, regs.size()), CallConv(CC) {}
RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
const DataLayout &DL, unsigned Reg, Type *Ty,
Optional<CallingConv::ID> CC) {
ComputeValueVTs(TLI, DL, Ty, ValueVTs);
CallConv = CC;
for (EVT ValueVT : ValueVTs) {
unsigned NumRegs =
isABIMangled()
? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
: TLI.getNumRegisters(Context, ValueVT);
MVT RegisterVT =
isABIMangled()
? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
: TLI.getRegisterType(Context, ValueVT);
for (unsigned i = 0; i != NumRegs; ++i)
Regs.push_back(Reg + i);
RegVTs.push_back(RegisterVT);
RegCount.push_back(NumRegs);
Reg += NumRegs;
}
}
SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
FunctionLoweringInfo &FuncInfo,
const SDLoc &dl, SDValue &Chain,
SDValue *Flag, const Value *V) const {
// A Value with type {} or [0 x %t] needs no registers.
if (ValueVTs.empty())
return SDValue();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
// Assemble the legal parts into the final values.
SmallVector<SDValue, 4> Values(ValueVTs.size());
SmallVector<SDValue, 8> Parts;
for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
// Copy the legal parts from the registers.
EVT ValueVT = ValueVTs[Value];
unsigned NumRegs = RegCount[Value];
MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
*DAG.getContext(),
CallConv.getValue(), RegVTs[Value])
: RegVTs[Value];
Parts.resize(NumRegs);
for (unsigned i = 0; i != NumRegs; ++i) {
SDValue P;
if (!Flag) {
P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
} else {
P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
*Flag = P.getValue(2);
}
Chain = P.getValue(1);
Parts[i] = P;
// If the source register was virtual and if we know something about it,
// add an assert node.
if (!Register::isVirtualRegister(Regs[Part + i]) ||
!RegisterVT.isInteger())
continue;
const FunctionLoweringInfo::LiveOutInfo *LOI =
FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
if (!LOI)
continue;
unsigned RegSize = RegisterVT.getScalarSizeInBits();
unsigned NumSignBits = LOI->NumSignBits;
unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
if (NumZeroBits == RegSize) {
// The current value is a zero.
// Explicitly express that as it would be easier for
// optimizations to kick in.
Parts[i] = DAG.getConstant(0, dl, RegisterVT);
continue;
}
// FIXME: We capture more information than the dag can represent. For
// now, just use the tightest assertzext/assertsext possible.
bool isSExt;
EVT FromVT(MVT::Other);
if (NumZeroBits) {
FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
isSExt = false;
} else if (NumSignBits > 1) {
FromVT =
EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
isSExt = true;
} else {
continue;
}
// Add an assertion node.
assert(FromVT != MVT::Other);
Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
RegisterVT, P, DAG.getValueType(FromVT));
}
Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
RegisterVT, ValueVT, V, CallConv);
Part += NumRegs;
Parts.clear();
}
return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
}
void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
const SDLoc &dl, SDValue &Chain, SDValue *Flag,
const Value *V,
ISD::NodeType PreferredExtendType) const {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
ISD::NodeType ExtendKind = PreferredExtendType;
// Get the list of the values's legal parts.
unsigned NumRegs = Regs.size();
SmallVector<SDValue, 8> Parts(NumRegs);
for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
unsigned NumParts = RegCount[Value];
MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
*DAG.getContext(),
CallConv.getValue(), RegVTs[Value])
: RegVTs[Value];
if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
ExtendKind = ISD::ZERO_EXTEND;
getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
NumParts, RegisterVT, V, CallConv, ExtendKind);
Part += NumParts;
}
// Copy the parts into the registers.
SmallVector<SDValue, 8> Chains(NumRegs);
for (unsigned i = 0; i != NumRegs; ++i) {
SDValue Part;
if (!Flag) {
Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
} else {
Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
*Flag = Part.getValue(1);
}
Chains[i] = Part.getValue(0);
}
if (NumRegs == 1 || Flag)
// If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
// flagged to it. That is the CopyToReg nodes and the user are considered
// a single scheduling unit. If we create a TokenFactor and return it as
// chain, then the TokenFactor is both a predecessor (operand) of the
// user as well as a successor (the TF operands are flagged to the user).
// c1, f1 = CopyToReg
// c2, f2 = CopyToReg
// c3 = TokenFactor c1, c2
// ...
// = op c3, ..., f2
Chain = Chains[NumRegs-1];
else
Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
}
void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
unsigned MatchingIdx, const SDLoc &dl,
SelectionDAG &DAG,
std::vector<SDValue> &Ops) const {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
if (HasMatching)
Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
// Put the register class of the virtual registers in the flag word. That
// way, later passes can recompute register class constraints for inline
// assembly as well as normal instructions.
// Don't do this for tied operands that can use the regclass information
// from the def.
const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
}
SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
Ops.push_back(Res);
if (Code == InlineAsm::Kind_Clobber) {
// Clobbers should always have a 1:1 mapping with registers, and may
// reference registers that have illegal (e.g. vector) types. Hence, we
// shouldn't try to apply any sort of splitting logic to them.
assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
"No 1:1 mapping from clobbers to regs?");
Register SP = TLI.getStackPointerRegisterToSaveRestore();
(void)SP;
for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
assert(
(Regs[I] != SP ||
DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
"If we clobbered the stack pointer, MFI should know about it.");
}
return;
}
for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
MVT RegisterVT = RegVTs[Value];
for (unsigned i = 0; i != NumRegs; ++i) {
assert(Reg < Regs.size() && "Mismatch in # registers expected");
unsigned TheReg = Regs[Reg++];
Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
}
}
}
SmallVector<std::pair<unsigned, TypeSize>, 4>
RegsForValue::getRegsAndSizes() const {
SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
unsigned I = 0;
for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
unsigned RegCount = std::get<0>(CountAndVT);
MVT RegisterVT = std::get<1>(CountAndVT);
TypeSize RegisterSize = RegisterVT.getSizeInBits();
for (unsigned E = I + RegCount; I != E; ++I)
OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
}
return OutVec;
}
void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
const TargetLibraryInfo *li) {
AA = aa;
GFI = gfi;
LibInfo = li;
DL = &DAG.getDataLayout();
Context = DAG.getContext();
LPadToCallSiteMap.clear();
SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
}
void SelectionDAGBuilder::clear() {
NodeMap.clear();
UnusedArgNodeMap.clear();
PendingLoads.clear();
PendingExports.clear();
PendingConstrainedFP.clear();
PendingConstrainedFPStrict.clear();
CurInst = nullptr;
HasTailCall = false;
SDNodeOrder = LowestSDNodeOrder;
StatepointLowering.clear();
}
void SelectionDAGBuilder::clearDanglingDebugInfo() {
DanglingDebugInfoMap.clear();
}
// Update DAG root to include dependencies on Pending chains.
SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
SDValue Root = DAG.getRoot();
if (Pending.empty())
return Root;
// Add current root to PendingChains, unless we already indirectly
// depend on it.
if (Root.getOpcode() != ISD::EntryToken) {
unsigned i = 0, e = Pending.size();
for (; i != e; ++i) {
assert(Pending[i].getNode()->getNumOperands() > 1);
if (Pending[i].getNode()->getOperand(0) == Root)
break; // Don't add the root if we already indirectly depend on it.
}
if (i == e)
Pending.push_back(Root);
}
if (Pending.size() == 1)
Root = Pending[0];
else
Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
DAG.setRoot(Root);
Pending.clear();
return Root;
}
SDValue SelectionDAGBuilder::getMemoryRoot() {
return updateRoot(PendingLoads);
}
SDValue SelectionDAGBuilder::getRoot() {
// Chain up all pending constrained intrinsics together with all
// pending loads, by simply appending them to PendingLoads and
// then calling getMemoryRoot().
PendingLoads.reserve(PendingLoads.size() +
PendingConstrainedFP.size() +
PendingConstrainedFPStrict.size());
PendingLoads.append(PendingConstrainedFP.begin(),
PendingConstrainedFP.end());
PendingLoads.append(PendingConstrainedFPStrict.begin(),
PendingConstrainedFPStrict.end());
PendingConstrainedFP.clear();
PendingConstrainedFPStrict.clear();
return getMemoryRoot();
}
SDValue SelectionDAGBuilder::getControlRoot() {
// We need to emit pending fpexcept.strict constrained intrinsics,
// so append them to the PendingExports list.
PendingExports.append(PendingConstrainedFPStrict.begin(),
PendingConstrainedFPStrict.end());
PendingConstrainedFPStrict.clear();
return updateRoot(PendingExports);
}
void SelectionDAGBuilder::visit(const Instruction &I) {
// Set up outgoing PHI node register values before emitting the terminator.
if (I.isTerminator()) {
HandlePHINodesInSuccessorBlocks(I.getParent());
}
// Increase the SDNodeOrder if dealing with a non-debug instruction.
if (!isa<DbgInfoIntrinsic>(I))
++SDNodeOrder;
CurInst = &I;
visit(I.getOpcode(), I);
if (!I.isTerminator() && !HasTailCall &&
!isa<GCStatepointInst>(I)) // statepoints handle their exports internally
CopyToExportRegsIfNeeded(&I);
CurInst = nullptr;
}
void SelectionDAGBuilder::visitPHI(const PHINode &) {
llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
}
void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
// Note: this doesn't use InstVisitor, because it has to work with
// ConstantExpr's in addition to instructions.
switch (Opcode) {
default: llvm_unreachable("Unknown instruction type encountered!");
// Build the switch statement using the Instruction.def file.
#define HANDLE_INST(NUM, OPCODE, CLASS) \
case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
#include "llvm/IR/Instruction.def"
}
}
void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
DebugLoc DL, unsigned Order) {
// We treat variadic dbg_values differently at this stage.
if (DI->hasArgList()) {
// For variadic dbg_values we will now insert an undef.
// FIXME: We can potentially recover these!
SmallVector<SDDbgOperand, 2> Locs;
for (const Value *V : DI->getValues()) {
auto Undef = UndefValue::get(V->getType());
Locs.push_back(SDDbgOperand::fromConst(Undef));
}
SDDbgValue *SDV = DAG.getDbgValueList(
DI->getVariable(), DI->getExpression(), Locs, {},
/*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
DAG.AddDbgValue(SDV, /*isParameter=*/false);
} else {
// TODO: Dangling debug info will eventually either be resolved or produce
// an Undef DBG_VALUE. However in the resolution case, a gap may appear
// between the original dbg.value location and its resolved DBG_VALUE,
// which we should ideally fill with an extra Undef DBG_VALUE.
assert(DI->getNumVariableLocationOps() == 1 &&
"DbgValueInst without an ArgList should have a single location "
"operand.");
DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
}
}
void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
const DIExpression *Expr) {
auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
const DbgValueInst *DI = DDI.getDI();
DIVariable *DanglingVariable = DI->getVariable();
DIExpression *DanglingExpr = DI->getExpression();
if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
return true;
}
return false;
};
for (auto &DDIMI : DanglingDebugInfoMap) {
DanglingDebugInfoVector &DDIV = DDIMI.second;
// If debug info is to be dropped, run it through final checks to see
// whether it can be salvaged.
for (auto &DDI : DDIV)
if (isMatchingDbgValue(DDI))
salvageUnresolvedDbgValue(DDI);
erase_if(DDIV, isMatchingDbgValue);
}
}
// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
// generate the debug data structures now that we've seen its definition.
void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
SDValue Val) {
auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
return;
DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
for (auto &DDI : DDIV) {
const DbgValueInst *DI = DDI.getDI();
assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
assert(DI && "Ill-formed DanglingDebugInfo");
DebugLoc dl = DDI.getdl();
unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
DILocalVariable *Variable = DI->getVariable();
DIExpression *Expr = DI->getExpression();
assert(Variable->isValidLocationForIntrinsic(dl) &&
"Expected inlined-at fields to agree");
SDDbgValue *SDV;
if (Val.getNode()) {
// FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
// FuncArgumentDbgValue (it would be hoisted to the function entry, and if
// we couldn't resolve it directly when examining the DbgValue intrinsic
// in the first place we should not be more successful here). Unless we
// have some test case that prove this to be correct we should avoid
// calling EmitFuncArgumentDbgValue here.
if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
<< DbgSDNodeOrder << "] for:\n " << *DI << "\n");
LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
// Increase the SDNodeOrder for the DbgValue here to make sure it is
// inserted after the definition of Val when emitting the instructions
// after ISel. An alternative could be to teach
// ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
<< "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
<< ValSDNodeOrder << "\n");
SDV = getDbgValue(Val, Variable, Expr, dl,
std::max(DbgSDNodeOrder, ValSDNodeOrder));
DAG.AddDbgValue(SDV, false);
} else
LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
<< "in EmitFuncArgumentDbgValue\n");
} else {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
auto SDV =
DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
DAG.AddDbgValue(SDV, false);
}
}
DDIV.clear();
}
void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
assert(!DDI.getDI()->hasArgList() &&
"Not implemented for variadic dbg_values");
Value *V = DDI.getDI()->getValue(0);
DILocalVariable *Var = DDI.getDI()->getVariable();
DIExpression *Expr = DDI.getDI()->getExpression();
DebugLoc DL = DDI.getdl();
DebugLoc InstDL = DDI.getDI()->getDebugLoc();
unsigned SDOrder = DDI.getSDNodeOrder();
// Currently we consider only dbg.value intrinsics -- we tell the salvager
// that DW_OP_stack_value is desired.
assert(isa<DbgValueInst>(DDI.getDI()));
bool StackValue = true;
// Can this Value can be encoded without any further work?
if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
return;
// Attempt to salvage back through as many instructions as possible. Bail if
// a non-instruction is seen, such as a constant expression or global
// variable. FIXME: Further work could recover those too.
while (isa<Instruction>(V)) {
Instruction &VAsInst = *cast<Instruction>(V);
// Temporary "0", awaiting real implementation.
DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0);
// If we cannot salvage any further, and haven't yet found a suitable debug
// expression, bail out.
if (!NewExpr)
break;
// New value and expr now represent this debuginfo.
V = VAsInst.getOperand(0);
Expr = NewExpr;
// Some kind of simplification occurred: check whether the operand of the
// salvaged debug expression can be encoded in this DAG.
if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
/*IsVariadic=*/false)) {
LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
<< DDI.getDI() << "\nBy stripping back to:\n " << V);
return;
}
}
// This was the final opportunity to salvage this debug information, and it
// couldn't be done. Place an undef DBG_VALUE at this location to terminate
// any earlier variable location.
auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
DAG.AddDbgValue(SDV, false);
LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
<< "\n");
LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
<< "\n");
}
bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
DILocalVariable *Var,
DIExpression *Expr, DebugLoc dl,
DebugLoc InstDL, unsigned Order,
bool IsVariadic) {
if (Values.empty())
return true;
SDDbgValue::LocOpVector LocationOps;
SDDbgValue::SDNodeVector Dependencies;
for (const Value *V : Values) {
// Constant value.
if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
isa<ConstantPointerNull>(V)) {
LocationOps.emplace_back(SDDbgOperand::fromConst(V));
continue;
}
// If the Value is a frame index, we can create a FrameIndex debug value
// without relying on the DAG at all.
if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
auto SI = FuncInfo.StaticAllocaMap.find(AI);
if (SI != FuncInfo.StaticAllocaMap.end()) {
LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
continue;
}
}
// Do not use getValue() in here; we don't want to generate code at
// this point if it hasn't been done yet.
SDValue N = NodeMap[V];
if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
N = UnusedArgNodeMap[V];
if (N.getNode()) {
// Only emit func arg dbg value for non-variadic dbg.values for now.
if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
return true;
Dependencies.push_back(N.getNode());
if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
// Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
// describe stack slot locations.
//
// Consider "int x = 0; int *px = &x;". There are two kinds of
// interesting debug values here after optimization:
//
// dbg.value(i32* %px, !"int *px", !DIExpression()), and
// dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
//
// Both describe the direct values of their associated variables.
LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
continue;
}
LocationOps.emplace_back(
SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
continue;
}
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
// Special rules apply for the first dbg.values of parameter variables in a
// function. Identify them by the fact they reference Argument Values, that
// they're parameters, and they are parameters of the current function. We
// need to let them dangle until they get an SDNode.
bool IsParamOfFunc =
isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
if (IsParamOfFunc)
return false;
// The value is not used in this block yet (or it would have an SDNode).
// We still want the value to appear for the user if possible -- if it has
// an associated VReg, we can refer to that instead.
auto VMI = FuncInfo.ValueMap.find(V);
if (VMI != FuncInfo.ValueMap.end()) {
unsigned Reg = VMI->second;
// If this is a PHI node, it may be split up into several MI PHI nodes
// (in FunctionLoweringInfo::set).
RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
V->getType(), None);
if (RFV.occupiesMultipleRegs()) {
// FIXME: We could potentially support variadic dbg_values here.
if (IsVariadic)
return false;
unsigned Offset = 0;
unsigned BitsToDescribe = 0;
if (auto VarSize = Var->getSizeInBits())
BitsToDescribe = *VarSize;
if (auto Fragment = Expr->getFragmentInfo())
BitsToDescribe = Fragment->SizeInBits;
for (auto RegAndSize : RFV.getRegsAndSizes()) {
// Bail out if all bits are described already.
if (Offset >= BitsToDescribe)
break;
// TODO: handle scalable vectors.
unsigned RegisterSize = RegAndSize.second;
unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
? BitsToDescribe - Offset
: RegisterSize;
auto FragmentExpr = DIExpression::createFragmentExpression(
Expr, Offset, FragmentSize);
if (!FragmentExpr)
continue;
SDDbgValue *SDV = DAG.getVRegDbgValue(
Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
DAG.AddDbgValue(SDV, false);
Offset += RegisterSize;
}
return true;
}
// We can use simple vreg locations for variadic dbg_values as well.
LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
continue;
}
// We failed to create a SDDbgOperand for V.
return false;
}
// We have created a SDDbgOperand for each Value in Values.
// Should use Order instead of SDNodeOrder?
assert(!LocationOps.empty());
SDDbgValue *SDV =
DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
/*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
DAG.AddDbgValue(SDV, /*isParameter=*/false);
return true;
}
void SelectionDAGBuilder::resolveOrClearDbgInfo() {
// Try to fixup any remaining dangling debug info -- and drop it if we can't.
for (auto &Pair : DanglingDebugInfoMap)
for (auto &DDI : Pair.second)
salvageUnresolvedDbgValue(DDI);
clearDanglingDebugInfo();
}
/// getCopyFromRegs - If there was virtual register allocated for the value V
/// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
SDValue Result;
if (It != FuncInfo.ValueMap.end()) {
Register InReg = It->second;
RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
DAG.getDataLayout(), InReg, Ty,
None); // This is not an ABI copy.
SDValue Chain = DAG.getEntryNode();
Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
V);
resolveDanglingDebugInfo(V, Result);
}
return Result;
}
/// getValue - Return an SDValue for the given Value.
SDValue SelectionDAGBuilder::getValue(const Value *V) {
// If we already have an SDValue for this value, use it. It's important
// to do this first, so that we don't create a CopyFromReg if we already
// have a regular SDValue.
SDValue &N = NodeMap[V];
if (N.getNode()) return N;
// If there's a virtual register allocated and initialized for this
// value, use it.
if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
return copyFromReg;
// Otherwise create a new SDValue and remember it.
SDValue Val = getValueImpl(V);
NodeMap[V] = Val;
resolveDanglingDebugInfo(V, Val);
return Val;
}
/// getNonRegisterValue - Return an SDValue for the given Value, but
/// don't look in FuncInfo.ValueMap for a virtual register.
SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
// If we already have an SDValue for this value, use it.
SDValue &N = NodeMap[V];
if (N.getNode()) {
if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
// Remove the debug location from the node as the node is about to be used
// in a location which may differ from the original debug location. This
// is relevant to Constant and ConstantFP nodes because they can appear
// as constant expressions inside PHI nodes.
N->setDebugLoc(DebugLoc());
}
return N;
}
// Otherwise create a new SDValue and remember it.
SDValue Val = getValueImpl(V);
NodeMap[V] = Val;
resolveDanglingDebugInfo(V, Val);
return Val;
}
/// getValueImpl - Helper function for getValue and getNonRegisterValue.
/// Create an SDValue for the given value.
SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (const Constant *C = dyn_cast<Constant>(V)) {
EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
return DAG.getConstant(*CI, getCurSDLoc(), VT);
if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
if (isa<ConstantPointerNull>(C)) {
unsigned AS = V->getType()->getPointerAddressSpace();
return DAG.getConstant(0, getCurSDLoc(),
TLI.getPointerTy(DAG.getDataLayout(), AS));
}
if (match(C, m_VScale(DAG.getDataLayout())))
return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
return DAG.getUNDEF(VT);
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
visit(CE->getOpcode(), *CE);
SDValue N1 = NodeMap[V];
assert(N1.getNode() && "visit didn't populate the NodeMap!");
return N1;
}
if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
SmallVector<SDValue, 4> Constants;
for (const Use &U : C->operands()) {
SDNode *Val = getValue(U).getNode();
// If the operand is an empty aggregate, there are no values.
if (!Val) continue;
// Add each leaf value from the operand to the Constants list
// to form a flattened list of all the values.
for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Constants.push_back(SDValue(Val, i));
}
return DAG.getMergeValues(Constants, getCurSDLoc());
}
if (const ConstantDataSequential *CDS =
dyn_cast<ConstantDataSequential>(C)) {
SmallVector<SDValue, 4> Ops;
for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
// Add each leaf value from the operand to the Constants list
// to form a flattened list of all the values.
for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Ops.push_back(SDValue(Val, i));
}
if (isa<ArrayType>(CDS->getType()))
return DAG.getMergeValues(Ops, getCurSDLoc());
return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
}
if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
"Unknown struct or array constant!");
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
unsigned NumElts = ValueVTs.size();
if (NumElts == 0)
return SDValue(); // empty struct
SmallVector<SDValue, 4> Constants(NumElts);
for (unsigned i = 0; i != NumElts; ++i) {
EVT EltVT = ValueVTs[i];
if (isa<UndefValue>(C))
Constants[i] = DAG.getUNDEF(EltVT);
else if (EltVT.isFloatingPoint())
Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
else
Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
}
return DAG.getMergeValues(Constants, getCurSDLoc());
}
if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
return DAG.getBlockAddress(BA, VT);
if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
return getValue(Equiv->getGlobalValue());
VectorType *VecTy = cast<VectorType>(V->getType());
// Now that we know the number and type of the elements, get that number of
// elements into the Ops array based on what kind of constant it is.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
SmallVector<SDValue, 16> Ops;
unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
for (unsigned i = 0; i != NumElements; ++i)
Ops.push_back(getValue(CV->getOperand(i)));
return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
} else if (isa<ConstantAggregateZero>(C)) {
EVT EltVT =
TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
SDValue Op;
if (EltVT.isFloatingPoint())
Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
else
Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
if (isa<ScalableVectorType>(VecTy))
return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
else {
SmallVector<SDValue, 16> Ops;
Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
}
}
llvm_unreachable("Unknown vector constant");
}
// If this is a static alloca, generate it as the frameindex instead of
// computation.
if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
DenseMap<const AllocaInst*, int>::iterator SI =
FuncInfo.StaticAllocaMap.find(AI);
if (SI != FuncInfo.StaticAllocaMap.end())
return DAG.getFrameIndex(SI->second,
TLI.getFrameIndexTy(DAG.getDataLayout()));
}
// If this is an instruction which fast-isel has deferred, select it now.
if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
Inst->getType(), None);
SDValue Chain = DAG.getEntryNode();
return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
}
if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
}
llvm_unreachable("Can't get register for value!");
}
void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
bool IsSEH = isAsynchronousEHPersonality(Pers);
MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
if (!IsSEH)
CatchPadMBB->setIsEHScopeEntry();
// In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
if (IsMSVCCXX || IsCoreCLR)
CatchPadMBB->setIsEHFuncletEntry();
}
void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
// Update machine-CFG edge.
MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
FuncInfo.MBB->addSuccessor(TargetMBB);
TargetMBB->setIsEHCatchretTarget(true);
DAG.getMachineFunction().setHasEHCatchret(true);
auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
bool IsSEH = isAsynchronousEHPersonality(Pers);
if (IsSEH) {
// If this is not a fall-through branch or optimizations are switched off,
// emit the branch.
if (TargetMBB != NextBlock(FuncInfo.MBB) ||
TM.getOptLevel() == CodeGenOpt::None)
DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
getControlRoot(), DAG.getBasicBlock(TargetMBB)));
return;
}
// Figure out the funclet membership for the catchret's successor.
// This will be used by the FuncletLayout pass to determine how to order the
// BB's.
// A 'catchret' returns to the outer scope's color.
Value *ParentPad = I.getCatchSwitchParentPad();
const BasicBlock *SuccessorColor;
if (isa<ConstantTokenNone>(ParentPad))
SuccessorColor = &FuncInfo.Fn->getEntryBlock();
else
SuccessorColor = cast<Instruction>(ParentPad)->getParent();
assert(SuccessorColor && "No parent funclet for catchret!");
MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
// Create the terminator node.
SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
getControlRoot(), DAG.getBasicBlock(TargetMBB),
DAG.getBasicBlock(SuccessorColorMBB));
DAG.setRoot(Ret);
}
void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
// Don't emit any special code for the cleanuppad instruction. It just marks
// the start of an EH scope/funclet.
FuncInfo.MBB->setIsEHScopeEntry();
auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
if (Pers != EHPersonality::Wasm_CXX) {
FuncInfo.MBB->setIsEHFuncletEntry();
FuncInfo.MBB->setIsCleanupFuncletEntry();
}
}
// In wasm EH, even though a catchpad may not catch an exception if a tag does
// not match, it is OK to add only the first unwind destination catchpad to the
// successors, because there will be at least one invoke instruction within the
// catch scope that points to the next unwind destination, if one exists, so
// CFGSort cannot mess up with BB sorting order.
// (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
// call within them, and catchpads only consisting of 'catch (...)' have a
// '__cxa_end_catch' call within them, both of which generate invokes in case
// the next unwind destination exists, i.e., the next unwind destination is not
// the caller.)
//
// Having at most one EH pad successor is also simpler and helps later
// transformations.
//
// For example,
// current:
// invoke void @foo to ... unwind label %catch.dispatch
// catch.dispatch:
// %0 = catchswitch within ... [label %catch.start] unwind label %next
// catch.start:
// ...
// ... in this BB or some other child BB dominated by this BB there will be an
// invoke that points to 'next' BB as an unwind destination
//
// next: ; We don't need to add this to 'current' BB's successor
// ...
static void findWasmUnwindDestinations(
FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
BranchProbability Prob,
SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
&UnwindDests) {
while (EHPadBB) {
const Instruction *Pad = EHPadBB->getFirstNonPHI();
if (isa<CleanupPadInst>(Pad)) {
// Stop on cleanup pads.
UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
UnwindDests.back().first->setIsEHScopeEntry();
break;
} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
// Add the catchpad handlers to the possible destinations. We don't
// continue to the unwind destination of the catchswitch for wasm.
for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
UnwindDests.back().first->setIsEHScopeEntry();
}
break;
} else {
continue;
}
}
}
/// When an invoke or a cleanupret unwinds to the next EH pad, there are
/// many places it could ultimately go. In the IR, we have a single unwind
/// destination, but in the machine CFG, we enumerate all the possible blocks.
/// This function skips over imaginary basic blocks that hold catchswitch
/// instructions, and finds all the "real" machine
/// basic block destinations. As those destinations may not be successors of
/// EHPadBB, here we also calculate the edge probability to those destinations.
/// The passed-in Prob is the edge probability to EHPadBB.
static void findUnwindDestinations(
FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
BranchProbability Prob,
SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
&UnwindDests) {
EHPersonality Personality =
classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
bool IsSEH = isAsynchronousEHPersonality(Personality);
if (IsWasmCXX) {
findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
assert(UnwindDests.size() <= 1 &&
"There should be at most one unwind destination for wasm");
return;
}
while (EHPadBB) {
const Instruction *Pad = EHPadBB->getFirstNonPHI();
BasicBlock *NewEHPadBB = nullptr;
if (isa<LandingPadInst>(Pad)) {
// Stop on landingpads. They are not funclets.
UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
break;
} else if (isa<CleanupPadInst>(Pad)) {
// Stop on cleanup pads. Cleanups are always funclet entries for all known
// personalities.
UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
UnwindDests.back().first->setIsEHScopeEntry();
UnwindDests.back().first->setIsEHFuncletEntry();
break;
} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
// Add the catchpad handlers to the possible destinations.
for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
// For MSVC++ and the CLR, catchblocks are funclets and need prologues.
if (IsMSVCCXX || IsCoreCLR)
UnwindDests.back().first->setIsEHFuncletEntry();
if (!IsSEH)
UnwindDests.back().first->setIsEHScopeEntry();
}
NewEHPadBB = CatchSwitch->getUnwindDest();
} else {
continue;
}
BranchProbabilityInfo *BPI = FuncInfo.BPI;
if (BPI && NewEHPadBB)
Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
EHPadBB = NewEHPadBB;
}
}
void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
// Update successor info.
SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
auto UnwindDest = I.getUnwindDest();
BranchProbabilityInfo *BPI = FuncInfo.BPI;
BranchProbability UnwindDestProb =
(BPI && UnwindDest)
? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
: BranchProbability::getZero();
findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
for (auto &UnwindDest : UnwindDests) {
UnwindDest.first->setIsEHPad();
addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
}
FuncInfo.MBB->normalizeSuccProbs();
// Create the terminator node.
SDValue Ret =
DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
DAG.setRoot(Ret);
}
void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
report_fatal_error("visitCatchSwitch not yet implemented!");
}
void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
auto &DL = DAG.getDataLayout();
SDValue Chain = getControlRoot();
SmallVector<ISD::OutputArg, 8> Outs;
SmallVector<SDValue, 8> OutVals;
// Calls to @llvm.experimental.deoptimize don't generate a return value, so
// lower
//
// %val = call <ty> @llvm.experimental.deoptimize()
// ret <ty> %val
//
// differently.
if (I.getParent()->getTerminatingDeoptimizeCall()) {
LowerDeoptimizingReturn();
return;
}
if (!FuncInfo.CanLowerReturn) {
unsigned DemoteReg = FuncInfo.DemoteRegister;
const Function *F = I.getParent()->getParent();
// Emit a store of the return value through the virtual register.
// Leave Outs empty so that LowerReturn won't try to load return
// registers the usual way.
SmallVector<EVT, 1> PtrValueVTs;
ComputeValueVTs(TLI, DL,
F->getReturnType()->getPointerTo(
DAG.getDataLayout().getAllocaAddrSpace()),
PtrValueVTs);
SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
DemoteReg, PtrValueVTs[0]);
SDValue RetOp = getValue(I.getOperand(0));
SmallVector<EVT, 4> ValueVTs, MemVTs;
SmallVector<uint64_t, 4> Offsets;
ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
&Offsets);
unsigned NumValues = ValueVTs.size();
SmallVector<SDValue, 4> Chains(NumValues);
Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
for (unsigned i = 0; i != NumValues; ++i) {
// An aggregate return value cannot wrap around the address space, so
// offsets to its parts don't wrap either.
SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
TypeSize::Fixed(Offsets[i]));
SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
if (MemVTs[i] != ValueVTs[i])
Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
Chains[i] = DAG.getStore(
Chain, getCurSDLoc(), Val,
// FIXME: better loc info would be nice.
Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
commonAlignment(BaseAlign, Offsets[i]));
}
Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
MVT::Other, Chains);
} else if (I.getNumOperands() != 0) {
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
unsigned NumValues = ValueVTs.size();
if (NumValues) {
SDValue RetOp = getValue(I.getOperand(0));
const Function *F = I.getParent()->getParent();
bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
I.getOperand(0)->getType(), F->getCallingConv(),
/*IsVarArg*/ false);
ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Attribute::SExt))
ExtendKind = ISD::SIGN_EXTEND;
else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
Attribute::ZExt))
ExtendKind = ISD::ZERO_EXTEND;
LLVMContext &Context = F->getContext();
bool RetInReg = F->getAttributes().hasAttribute(
AttributeList::ReturnIndex, Attribute::InReg);
for (unsigned j = 0; j != NumValues; ++j) {
EVT VT = ValueVTs[j];
if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
CallingConv::ID CC = F->getCallingConv();
unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
SmallVector<SDValue, 4> Parts(NumParts);
getCopyToParts(DAG, getCurSDLoc(),
SDValue(RetOp.getNode(), RetOp.getResNo() + j),
&Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
// 'inreg' on function refers to return value
ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
if (RetInReg)
Flags.setInReg();
if (I.getOperand(0)->getType()->isPointerTy()) {
Flags.setPointer();
Flags.setPointerAddrSpace(
cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
}
if (NeedsRegBlock) {
Flags.setInConsecutiveRegs();
if (j == NumValues - 1)
Flags.setInConsecutiveRegsLast();
}
// Propagate extension type if any
if (ExtendKind == ISD::SIGN_EXTEND)
Flags.setSExt();
else if (ExtendKind == ISD::ZERO_EXTEND)
Flags.setZExt();
for (unsigned i = 0; i < NumParts; ++i) {
Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
VT, /*isfixed=*/true, 0, 0));
OutVals.push_back(Parts[i]);
}
}
}
}
// Push in swifterror virtual register as the last element of Outs. This makes
// sure swifterror virtual register will be returned in the swifterror
// physical register.
const Function *F = I.getParent()->getParent();
if (TLI.supportSwiftError() &&
F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
assert(SwiftError.getFunctionArg() && "Need a swift error argument");
ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Flags.setSwiftError();
Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
EVT(TLI.getPointerTy(DL)) /*argvt*/,
true /*isfixed*/, 1 /*origidx*/,
0 /*partOffs*/));
// Create SDNode for the swifterror virtual register.
OutVals.push_back(
DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
&I, FuncInfo.MBB, SwiftError.getFunctionArg()),
EVT(TLI.getPointerTy(DL))));
}
bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
CallingConv::ID CallConv =
DAG.getMachineFunction().getFunction().getCallingConv();
Chain = DAG.getTargetLoweringInfo().LowerReturn(
Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
// Verify that the target's LowerReturn behaved as expected.
assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
"LowerReturn didn't return a valid chain!");
// Update the DAG with the new chain value resulting from return lowering.
DAG.setRoot(Chain);
}
/// CopyToExportRegsIfNeeded - If the given value has virtual registers
/// created for it, emit nodes to copy the value into the virtual
/// registers.
void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
// Skip empty types
if (V->getType()->isEmptyTy())
return;
DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
if (VMI != FuncInfo.ValueMap.end()) {
assert(!V->use_empty() && "Unused value assigned virtual registers!");
CopyValueToVirtualRegister(V, VMI->second);
}
}
/// ExportFromCurrentBlock - If this condition isn't known to be exported from
/// the current basic block, add it to ValueMap now so that we'll get a
/// CopyTo/FromReg.
void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
// No need to export constants.
if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
// Already exported?
if (FuncInfo.isExportedInst(V)) return;
unsigned Reg = FuncInfo.InitializeRegForValue(V);
CopyValueToVirtualRegister(V, Reg);
}
bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
const BasicBlock *FromBB) {
// The operands of the setcc have to be in this block. We don't know
// how to export them from some other block.
if (const Instruction *VI = dyn_cast<Instruction>(V)) {
// Can export from current BB.
if (VI->getParent() == FromBB)
return true;
// Is already exported, noop.
return FuncInfo.isExportedInst(V);
}
// If this is an argument, we can export it if the BB is the entry block or
// if it is already exported.
if (isa<Argument>(V)) {
if (FromBB == &FromBB->getParent()->getEntryBlock())
return true;
// Otherwise, can only export this if it is already exported.
return FuncInfo.isExportedInst(V);
}
// Otherwise, constants can always be exported.
return true;
}
/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
BranchProbability
SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
const MachineBasicBlock *Dst) const {
BranchProbabilityInfo *BPI = FuncInfo.BPI;
const BasicBlock *SrcBB = Src->getBasicBlock();
const BasicBlock *DstBB = Dst->getBasicBlock();
if (!BPI) {
// If BPI is not available, set the default probability as 1 / N, where N is
// the number of successors.
auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
return BranchProbability(1, SuccSize);
}
return BPI->getEdgeProbability(SrcBB, DstBB);
}
void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
MachineBasicBlock *Dst,
BranchProbability Prob) {
if (!FuncInfo.BPI)
Src->addSuccessorWithoutProb(Dst);
else {
if (Prob.isUnknown())
Prob = getEdgeProbability(Src, Dst);
Src->addSuccessor(Dst, Prob);
}
}
static bool InBlock(const Value *V, const BasicBlock *BB) {
if (const Instruction *I = dyn_cast<Instruction>(V))
return I->getParent() == BB;
return true;
}
/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
/// This function emits a branch and is used at the leaves of an OR or an
/// AND operator tree.
void
SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
MachineBasicBlock *CurBB,
MachineBasicBlock *SwitchBB,
BranchProbability TProb,
BranchProbability FProb,
bool InvertCond) {
const BasicBlock *BB = CurBB->getBasicBlock();
// If the leaf of the tree is a comparison, merge the condition into
// the caseblock.
if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
// The operands of the cmp have to be in this block. We don't know
// how to export them from some other block. If this is the first block
// of the sequence, no exporting is needed.
if (CurBB == SwitchBB ||
(isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
ISD::CondCode Condition;
if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
ICmpInst::Predicate Pred =
InvertCond ? IC->getInversePredicate() : IC->getPredicate();
Condition = getICmpCondCode(Pred);
} else {
const FCmpInst *FC = cast<FCmpInst>(Cond);
FCmpInst::Predicate Pred =
InvertCond ? FC->getInversePredicate() : FC->getPredicate();
Condition = getFCmpCondCode(Pred);
if (TM.Options.NoNaNsFPMath)
Condition = getFCmpCodeWithoutNaN(Condition);
}
CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
SL->SwitchCases.push_back(CB);
return;
}
}
// Create a CaseBlock record representing this branch.
ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
SL->SwitchCases.push_back(CB);
}
void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
MachineBasicBlock *TBB,
MachineBasicBlock *FBB,
MachineBasicBlock *CurBB,
MachineBasicBlock *SwitchBB,
Instruction::BinaryOps Opc,
BranchProbability TProb,
BranchProbability FProb,
bool InvertCond) {
// Skip over not part of the tree and remember to invert op and operands at
// next level.
Value *NotCond;
if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
InBlock(NotCond, CurBB->getBasicBlock())) {
FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
!InvertCond);
return;
}
const Instruction *BOp = dyn_cast<Instruction>(Cond);
const Value *BOpOp0, *BOpOp1;
// Compute the effective opcode for Cond, taking into account whether it needs
// to be inverted, e.g.
// and (not (or A, B)), C
// gets lowered as
// and (and (not A, not B), C)
Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
if (BOp) {
BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
? Instruction::And
: (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
? Instruction::Or
: (Instruction::BinaryOps)0);
if (InvertCond) {
if (BOpc == Instruction::And)
BOpc = Instruction::Or;
else if (BOpc == Instruction::Or)
BOpc = Instruction::And;
}
}
// If this node is not part of the or/and tree, emit it as a branch.
// Note that all nodes in the tree should have same opcode.
bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
!InBlock(BOpOp0, CurBB->getBasicBlock()) ||
!InBlock(BOpOp1, CurBB->getBasicBlock())) {
EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
TProb, FProb, InvertCond);
return;
}
// Create TmpBB after CurBB.
MachineFunction::iterator BBI(CurBB);
MachineFunction &MF = DAG.getMachineFunction();
MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
CurBB->getParent()->insert(++BBI, TmpBB);
if (Opc == Instruction::Or) {
// Codegen X | Y as:
// BB1:
// jmp_if_X TBB
// jmp TmpBB
// TmpBB:
// jmp_if_Y TBB
// jmp FBB
//
// We have flexibility in setting Prob for BB1 and Prob for TmpBB.
// The requirement is that
// TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
// = TrueProb for original BB.
// Assuming the original probabilities are A and B, one choice is to set
// BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
// A/(1+B) and 2B/(1+B). This choice assumes that
// TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
// Another choice is to assume TrueProb for BB1 equals to TrueProb for
// TmpBB, but the math is more complicated.
auto NewTrueProb = TProb / 2;
auto NewFalseProb = TProb / 2 + FProb;
// Emit the LHS condition.
FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
NewFalseProb, InvertCond);
// Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
// Emit the RHS condition into TmpBB.
FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
Probs[1], InvertCond);
} else {
assert(Opc == Instruction::And && "Unknown merge op!");
// Codegen X & Y as:
// BB1:
// jmp_if_X TmpBB
// jmp FBB
// TmpBB:
// jmp_if_Y TBB
// jmp FBB
//
// This requires creation of TmpBB after CurBB.
// We have flexibility in setting Prob for BB1 and Prob for TmpBB.
// The requirement is that
// FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
// = FalseProb for original BB.
// Assuming the original probabilities are A and B, one choice is to set
// BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
// 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
// TrueProb for BB1 * FalseProb for TmpBB.
auto NewTrueProb = TProb + FProb / 2;
auto NewFalseProb = FProb / 2;
// Emit the LHS condition.
FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
NewFalseProb, InvertCond);
// Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
// Emit the RHS condition into TmpBB.
FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
Probs[1], InvertCond);
}
}
/// If the set of cases should be emitted as a series of branches, return true.
/// If we should emit this as a bunch of and/or'd together conditions, return
/// false.
bool
SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
if (Cases.size() != 2) return true;
// If this is two comparisons of the same values or'd or and'd together, they
// will get folded into a single comparison, so don't emit two blocks.
if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
Cases[0].CmpRHS == Cases[1].CmpRHS) ||
(Cases[0].CmpRHS == Cases[1].CmpLHS &&
Cases[0].CmpLHS == Cases[1].CmpRHS)) {
return false;
}
// Handle: (X != null) | (Y != null) --> (X|Y) != 0
// Handle: (X == null) & (Y == null) --> (X|Y) == 0
if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
Cases[0].CC == Cases[1].CC &&
isa<Constant>(Cases[0].CmpRHS) &&
cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
return false;
if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
return false;
}
return true;
}
void SelectionDAGBuilder::visitBr(const BranchInst &I) {
MachineBasicBlock *BrMBB = FuncInfo.MBB;
// Update machine-CFG edges.
MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
if (I.isUnconditional()) {
// Update machine-CFG edges.
BrMBB->addSuccessor(Succ0MBB);
// If this is not a fall-through branch or optimizations are switched off,
// emit the branch.
if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
MVT::Other, getControlRoot(),
DAG.getBasicBlock(Succ0MBB)));
return;
}
// If this condition is one of the special cases we handle, do special stuff
// now.
const Value *CondVal = I.getCondition();
MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
// If this is a series of conditions that are or'd or and'd together, emit
// this as a sequence of branches instead of setcc's with and/or operations.
// As long as jumps are not expensive (exceptions for multi-use logic ops,
// unpredictable branches, and vector extracts because those jumps are likely
// expensive for any target), this should improve performance.
// For example, instead of something like:
// cmp A, B
// C = seteq
// cmp D, E
// F = setle
// or C, F
// jnz foo
// Emit:
// cmp A, B
// je foo
// cmp D, E
// jle foo
const Instruction *BOp = dyn_cast<Instruction>(CondVal);
if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
Value *Vec;
const Value *BOp0, *BOp1;
Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
Opcode = Instruction::And;
else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
Opcode = Instruction::Or;
if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
getEdgeProbability(BrMBB, Succ0MBB),
getEdgeProbability(BrMBB, Succ1MBB),
/*InvertCond=*/false);
// If the compares in later blocks need to use values not currently
// exported from this block, export them now. This block should always
// be the first entry.
assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
// Allow some cases to be rejected.
if (ShouldEmitAsBranches(SL->SwitchCases)) {
for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
}
// Emit the branch for this block.
visitSwitchCase(SL->SwitchCases[0], BrMBB);
SL->SwitchCases.erase(SL->SwitchCases.begin());
return;
}
// Okay, we decided not to do this, remove any inserted MBB's and clear
// SwitchCases.
for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
SL->SwitchCases.clear();
}
}
// Create a CaseBlock record representing this branch.
CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
// Use visitSwitchCase to actually insert the fast branch sequence for this
// cond branch.
visitSwitchCase(CB, BrMBB);
}
/// visitSwitchCase - Emits the necessary code to represent a single node in
/// the binary search tree resulting from lowering a switch instruction.
void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
MachineBasicBlock *SwitchBB) {
SDValue Cond;
SDValue CondLHS = getValue(CB.CmpLHS);
SDLoc dl = CB.DL;
if (CB.CC == ISD::SETTRUE) {
// Branch or fall through to TrueBB.
addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
SwitchBB->normalizeSuccProbs();
if (CB.TrueBB != NextBlock(SwitchBB)) {
DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
DAG.getBasicBlock(CB.TrueBB)));
}
return;
}
auto &TLI = DAG.getTargetLoweringInfo();
EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
// Build the setcc now.
if (!CB.CmpMHS) {
// Fold "(X == true)" to X and "(X == false)" to !X to
// handle common cases produced by branch lowering.
if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
CB.CC == ISD::SETEQ)
Cond = CondLHS;
else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
CB.CC == ISD::SETEQ) {
SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
} else {
SDValue CondRHS = getValue(CB.CmpRHS);
// If a pointer's DAG type is larger than its memory type then the DAG
// values are zero-extended. This breaks signed comparisons so truncate
// back to the underlying type before doing the compare.
if (CondLHS.getValueType() != MemVT) {
CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
}
Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
}
} else {
assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
SDValue CmpOp = getValue(CB.CmpMHS);
EVT VT = CmpOp.getValueType();
if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
ISD::SETLE);
} else {
SDValue SUB = DAG.getNode(ISD::SUB, dl,
VT, CmpOp, DAG.getConstant(Low, dl, VT));
Cond = DAG.getSetCC(dl, MVT::i1, SUB,
DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
}
}
// Update successor info
addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
// TrueBB and FalseBB are always different unless the incoming IR is
// degenerate. This only happens when running llc on weird IR.
if (CB.TrueBB != CB.FalseBB)
addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
SwitchBB->normalizeSuccProbs();
// If the lhs block is the next block, invert the condition so that we can
// fall through to the lhs instead of the rhs block.
if (CB.TrueBB == NextBlock(SwitchBB)) {
std::swap(CB.TrueBB, CB.FalseBB);
SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
}
SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
MVT::Other, getControlRoot(), Cond,
DAG.getBasicBlock(CB.TrueBB));
// Insert the false branch. Do this even if it's a fall through branch,
// this makes it easier to do DAG optimizations which require inverting
// the branch condition.
BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
DAG.getBasicBlock(CB.FalseBB));
DAG.setRoot(BrCond);
}
/// visitJumpTable - Emit JumpTable node in the current MBB
void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
// Emit the code for the jump table
assert(JT.Reg != -1U && "Should lower JT Header first!");
EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
JT.Reg, PTy);
SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
MVT::Other, Index.getValue(1),
Table, Index);
DAG.setRoot(BrJumpTable);
}
/// visitJumpTableHeader - This function emits necessary code to produce index
/// in the JumpTable from switch case.
void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
JumpTableHeader &JTH,
MachineBasicBlock *SwitchBB) {
SDLoc dl = getCurSDLoc();
// Subtract the lowest switch case value from the value being switched on.
SDValue SwitchOp = getValue(JTH.SValue);
EVT VT = SwitchOp.getValueType();
SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
DAG.getConstant(JTH.First, dl, VT));
// The SDNode we just created, which holds the value being switched on minus
// the smallest case value, needs to be copied to a virtual register so it
// can be used as an index into the jump table in a subsequent basic block.
// This value may be smaller or larger than the target's pointer type, and
// therefore require extension or truncating.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
unsigned JumpTableReg =
FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
JumpTableReg, SwitchOp);
JT.Reg = JumpTableReg;
if (!JTH.OmitRangeCheck) {
// Emit the range check for the jump table, and branch to the default block
// for the switch statement if the value being switched on exceeds the
// largest case in the switch.
SDValue CMP = DAG.getSetCC(
dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
Sub.getValueType()),
Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
MVT::Other, CopyTo, CMP,
DAG.getBasicBlock(JT.Default));
// Avoid emitting unnecessary branches to the next block.
if (JT.MBB != NextBlock(SwitchBB))
BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
DAG.getBasicBlock(JT.MBB));
DAG.setRoot(BrCond);
} else {
// Avoid emitting unnecessary branches to the next block.
if (JT.MBB != NextBlock(SwitchBB))
DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
DAG.getBasicBlock(JT.MBB)));
else
DAG.setRoot(CopyTo);
}
}
/// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
/// variable if there exists one.
static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
SDValue &Chain) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
MachineFunction &MF = DAG.getMachineFunction();
Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
MachineSDNode *Node =
DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
if (Global) {
MachinePointerInfo MPInfo(Global);
auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
MachineMemOperand::MODereferenceable;
MachineMemOperand *MemRef = MF.getMachineMemOperand(
MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
DAG.setNodeMemRefs(Node, {MemRef});
}
if (PtrTy != PtrMemTy)
return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
return SDValue(Node, 0);
}
/// Codegen a new tail for a stack protector check ParentMBB which has had its
/// tail spliced into a stack protector check success bb.
///
/// For a high level explanation of how this fits into the stack protector
/// generation see the comment on the declaration of class
/// StackProtectorDescriptor.
void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
MachineBasicBlock *ParentBB) {
// First create the loads to the guard/stack slot for the comparison.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
int FI = MFI.getStackProtectorIndex();
SDValue Guard;
SDLoc dl = getCurSDLoc();
SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
const Module &M = *ParentBB->getParent()->getFunction().getParent();
Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
// Generate code to load the content of the guard slot.
SDValue GuardVal = DAG.getLoad(
PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
MachineMemOperand::MOVolatile);
if (TLI.useStackGuardXorFP())
GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
// Retrieve guard check function, nullptr if instrumentation is inlined.
if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
// The target provides a guard check function to validate the guard value.
// Generate a call to that function with the content of the guard slot as
// argument.
FunctionType *FnTy = GuardCheckFn->getFunctionType();
assert(FnTy->getNumParams() == 1 && "Invalid function signature");
TargetLowering::ArgListTy Args;
TargetLowering::ArgListEntry Entry;
Entry.Node = GuardVal;
Entry.Ty = FnTy->getParamType(0);
if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
Entry.IsInReg = true;
Args.push_back(Entry);
TargetLowering::CallLoweringInfo CLI(DAG);
CLI.setDebugLoc(getCurSDLoc())
.setChain(DAG.getEntryNode())
.setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
getValue(GuardCheckFn), std::move(Args));
std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
DAG.setRoot(Result.second);
return;
}
// If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
// Otherwise, emit a volatile load to retrieve the stack guard value.
SDValue Chain = DAG.getEntryNode();
if (TLI.useLoadStackGuardNode()) {
Guard = getLoadStackGuard(DAG, dl, Chain);
} else {
const Value *IRGuard = TLI.getSDagStackGuard(M);
SDValue GuardPtr = getValue(IRGuard);
Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
MachinePointerInfo(IRGuard, 0), Align,
MachineMemOperand::MOVolatile);
}
// Perform the comparison via a getsetcc.
SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
*DAG.getContext(),
Guard.getValueType()),
Guard, GuardVal, ISD::SETNE);
// If the guard/stackslot do not equal, branch to failure MBB.
SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
MVT::Other, GuardVal.getOperand(0),
Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
// Otherwise branch to success MBB.
SDValue Br = DAG.getNode(ISD::BR, dl,
MVT::Other, BrCond,
DAG.getBasicBlock(SPD.getSuccessMBB()));
DAG.setRoot(Br);
}
/// Codegen the failure basic block for a stack protector check.
///
/// A failure stack protector machine basic block consists simply of a call to
/// __stack_chk_fail().
///
/// For a high level explanation of how this fits into the stack protector
/// generation see the comment on the declaration of class
/// StackProtectorDescriptor.
void
SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
TargetLowering::MakeLibCallOptions CallOptions;
CallOptions.setDiscardResult(true);
SDValue Chain =
TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
None, CallOptions, getCurSDLoc()).second;
// On PS4, the "return address" must still be within the calling function,
// even if it's at the very end, so emit an explicit TRAP here.
// Passing 'true' for doesNotReturn above won't generate the trap for us.
if (TM.getTargetTriple().isPS4CPU())
Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
// WebAssembly needs an unreachable instruction after a non-returning call,
// because the function return type can be different from __stack_chk_fail's
// return type (void).
if (TM.getTargetTriple().isWasm())
Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
DAG.setRoot(Chain);
}
/// visitBitTestHeader - This function emits necessary code to produce value
/// suitable for "bit tests"
void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
MachineBasicBlock *SwitchBB) {
SDLoc dl = getCurSDLoc();
// Subtract the minimum value.
SDValue SwitchOp = getValue(B.SValue);
EVT VT = SwitchOp.getValueType();
SDValue RangeSub =
DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
// Determine the type of the test operands.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
bool UsePtrType = false;
if (!TLI.isTypeLegal(VT)) {
UsePtrType = true;
} else {
for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
// Switch table case range are encoded into series of masks.
// Just use pointer type, it's guaranteed to fit.
UsePtrType = true;
break;
}
}
SDValue Sub = RangeSub;
if (UsePtrType) {
VT = TLI.getPointerTy(DAG.getDataLayout());
Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
}
B.RegVT = VT.getSimpleVT();
B.Reg = FuncInfo.CreateReg(B.RegVT);
SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
MachineBasicBlock* MBB = B.Cases[0].ThisBB;
if (!B.OmitRangeCheck)
addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
addSuccessorWithProb(SwitchBB, MBB, B.Prob);
SwitchBB->normalizeSuccProbs();
SDValue Root = CopyTo;
if (!B.OmitRangeCheck) {
// Conditional branch to the default block.
SDValue RangeCmp = DAG.getSetCC(dl,
TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
RangeSub.getValueType()),
RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
ISD::SETUGT);
Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
DAG.getBasicBlock(B.Default));
}
// Avoid emitting unnecessary branches to the next block.
if (MBB != NextBlock(SwitchBB))
Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
DAG.setRoot(Root);
}
/// visitBitTestCase - this function produces one "bit test"
void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
MachineBasicBlock* NextMBB,
BranchProbability BranchProbToNext,
unsigned Reg,
BitTestCase &B,
MachineBasicBlock *SwitchBB) {
SDLoc dl = getCurSDLoc();
MVT VT = BB.RegVT;
SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
SDValue Cmp;
unsigned PopCount = countPopulation(B.Mask);
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (PopCount == 1) {
// Testing for a single bit; just compare the shift count with what it
// would need to be to shift a 1 bit in that position.
Cmp = DAG.getSetCC(
dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
ISD::SETEQ);
} else if (PopCount == BB.Range) {
// There is only one zero bit in the range, test for it directly.
Cmp = DAG.getSetCC(
dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
ISD::SETNE);
} else {
// Make desired shift
SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
DAG.getConstant(1, dl, VT), ShiftOp);
// Emit bit tests and jumps
SDValue AndOp = DAG.getNode(ISD::AND, dl,
VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
Cmp = DAG.getSetCC(
dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
}
// The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
// The branch probability from SwitchBB to NextMBB is BranchProbToNext.
addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
// It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
// one as they are relative probabilities (and thus work more like weights),
// and hence we need to normalize them to let the sum of them become one.
SwitchBB->normalizeSuccProbs();
SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
MVT::Other, getControlRoot(),
Cmp, DAG.getBasicBlock(B.TargetBB));
// Avoid emitting unnecessary branches to the next block.
if (NextMBB != NextBlock(SwitchBB))
BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
DAG.getBasicBlock(NextMBB));
DAG.setRoot(BrAnd);
}
void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
// Retrieve successors. Look through artificial IR level blocks like
// catchswitch for successors.
MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
const BasicBlock *EHPadBB = I.getSuccessor(1);
// Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
// have to do anything here to lower funclet bundles.
assert(!I.hasOperandBundlesOtherThan(
{LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
LLVMContext::OB_cfguardtarget,
LLVMContext::OB_clang_arc_attachedcall}) &&
"Cannot lower invokes with arbitrary operand bundles yet!");
const Value *Callee(I.getCalledOperand());
const Function *Fn = dyn_cast<Function>(Callee);
if (isa<InlineAsm>(Callee))
visitInlineAsm(I);
else if (Fn && Fn->isIntrinsic()) {
switch (Fn->getIntrinsicID()) {
default:
llvm_unreachable("Cannot invoke this intrinsic");
case Intrinsic::donothing:
// Ignore invokes to @llvm.donothing: jump directly to the next BB.
break;
case Intrinsic::experimental_patchpoint_void:
case Intrinsic::experimental_patchpoint_i64:
visitPatchpoint(I, EHPadBB);
break;
case Intrinsic::experimental_gc_statepoint:
LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
break;
case Intrinsic::wasm_rethrow: {
// This is usually done in visitTargetIntrinsic, but this intrinsic is
// special because it can be invoked, so we manually lower it to a DAG
// node here.
SmallVector<SDValue, 8> Ops;
Ops.push_back(getRoot()); // inchain
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Ops.push_back(
DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
TLI.getPointerTy(DAG.getDataLayout())));
SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
break;
}
}
} else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
// Currently we do not lower any intrinsic calls with deopt operand bundles.
// Eventually we will support lowering the @llvm.experimental.deoptimize
// intrinsic, and right now there are no plans to support other intrinsics
// with deopt state.
LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
} else {
LowerCallTo(I, getValue(Callee), false, EHPadBB);
}
// If the value of the invoke is used outside of its defining block, make it
// available as a virtual register.
// We already took care of the exported value for the statepoint instruction
// during call to the LowerStatepoint.
if (!isa<GCStatepointInst>(I)) {
CopyToExportRegsIfNeeded(&I);
}
SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
BranchProbabilityInfo *BPI = FuncInfo.BPI;
BranchProbability EHPadBBProb =
BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
: BranchProbability::getZero();
findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
// Update successor info.
addSuccessorWithProb(InvokeMBB, Return);
for (auto &UnwindDest : UnwindDests) {
UnwindDest.first->setIsEHPad();
addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
}
InvokeMBB->normalizeSuccProbs();
// Drop into normal successor.
DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
DAG.getBasicBlock(Return)));
}
void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
// Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
// have to do anything here to lower funclet bundles.
assert(!I.hasOperandBundlesOtherThan(
{LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
"Cannot lower callbrs with arbitrary operand bundles yet!");
assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
visitInlineAsm(I);
CopyToExportRegsIfNeeded(&I);
// Retrieve successors.
MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
// Update successor info.
addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
Target->setIsInlineAsmBrIndirectTarget();
}
CallBrMBB->normalizeSuccProbs();
// Drop into default successor.
DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
MVT::Other, getControlRoot(),
DAG.getBasicBlock(Return)));
}
void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
}
void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
assert(FuncInfo.MBB->isEHPad() &&
"Call to landingpad not in landing pad!");
// If there aren't registers to copy the values into (e.g., during SjLj
// exceptions), then don't bother to create these DAG nodes.
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
return;
// If landingpad's return type is token type, we don't create DAG nodes
// for its exception pointer and selector value. The extraction of exception
// pointer or selector value from token type landingpads is not currently
// supported.
if (LP.getType()->isTokenTy())
return;
SmallVector<EVT, 2> ValueVTs;
SDLoc dl = getCurSDLoc();
ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
// Get the two live-in registers as SDValues. The physregs have already been
// copied into virtual registers.
SDValue Ops[2];
if (FuncInfo.ExceptionPointerVirtReg) {
Ops[0] = DAG.getZExtOrTrunc(
DAG.getCopyFromReg(DAG.getEntryNode(), dl,
FuncInfo.ExceptionPointerVirtReg,
TLI.getPointerTy(DAG.getDataLayout())),
dl, ValueVTs[0]);
} else {
Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
}
Ops[1] = DAG.getZExtOrTrunc(
DAG.getCopyFromReg(DAG.getEntryNode(), dl,
FuncInfo.ExceptionSelectorVirtReg,
TLI.getPointerTy(DAG.getDataLayout())),
dl, ValueVTs[1]);
// Merge into one.
SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
DAG.getVTList(ValueVTs), Ops);
setValue(&LP, Res);
}
void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
MachineBasicBlock *Last) {
// Update JTCases.
for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
if (SL->JTCases[i].first.HeaderBB == First)
SL->JTCases[i].first.HeaderBB = Last;
// Update BitTestCases.
for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
if (SL->BitTestCases[i].Parent == First)
SL->BitTestCases[i].Parent = Last;
}
void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
// Update machine-CFG edges with unique successors.
SmallSet<BasicBlock*, 32> Done;
for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
BasicBlock *BB = I.getSuccessor(i);
bool Inserted = Done.insert(BB).second;
if (!Inserted)
continue;
MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
addSuccessorWithProb(IndirectBrMBB, Succ);
}
IndirectBrMBB->normalizeSuccProbs();
DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
MVT::Other, getControlRoot(),
getValue(I.getAddress())));
}
void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
if (!DAG.getTarget().Options.TrapUnreachable)
return;
// We may be able to ignore unreachable behind a noreturn call.
if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
const BasicBlock &BB = *I.getParent();
if (&I != &BB.front()) {
BasicBlock::const_iterator PredI =
std::prev(BasicBlock::const_iterator(&I));
if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
if (Call->doesNotReturn())
return;
}
}
}
DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
}
void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
SDNodeFlags Flags;
SDValue Op = getValue(I.getOperand(0));
SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
Op, Flags);
setValue(&I, UnNodeValue);
}
void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
SDNodeFlags Flags;
if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
}
if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
Flags.setExact(ExactOp->isExact());
if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
Flags.copyFMF(*FPOp);
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
Op1, Op2, Flags);
setValue(&I, BinNodeValue);
}
void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
Op1.getValueType(), DAG.getDataLayout());
// Coerce the shift amount to the right type if we can.
if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
unsigned ShiftSize = ShiftTy.getSizeInBits();
unsigned Op2Size = Op2.getValueSizeInBits();
SDLoc DL = getCurSDLoc();
// If the operand is smaller than the shift count type, promote it.
if (ShiftSize > Op2Size)
Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
// If the operand is larger than the shift count type but the shift
// count type has enough bits to represent any shift value, truncate
// it now. This is a common case and it exposes the truncate to
// optimization early.
else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
// Otherwise we'll need to temporarily settle for some other convenient
// type. Type legalization will make adjustments once the shiftee is split.
else
Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
}
bool nuw = false;
bool nsw = false;
bool exact = false;
if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
if (const OverflowingBinaryOperator *OFBinOp =
dyn_cast<const OverflowingBinaryOperator>(&I)) {
nuw = OFBinOp->hasNoUnsignedWrap();
nsw = OFBinOp->hasNoSignedWrap();
}
if (const PossiblyExactOperator *ExactOp =
dyn_cast<const PossiblyExactOperator>(&I))
exact = ExactOp->isExact();
}
SDNodeFlags Flags;
Flags.setExact(exact);
Flags.setNoSignedWrap(nsw);
Flags.setNoUnsignedWrap(nuw);
SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
Flags);
setValue(&I, Res);
}
void SelectionDAGBuilder::visitSDiv(const User &I) {
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
SDNodeFlags Flags;
Flags.setExact(isa<PossiblyExactOperator>(&I) &&
cast<PossiblyExactOperator>(&I)->isExact());
setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
Op2, Flags));
}
void SelectionDAGBuilder::visitICmp(const User &I) {
ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
predicate = IC->getPredicate();
else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
predicate = ICmpInst::Predicate(IC->getPredicate());
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
ISD::CondCode Opcode = getICmpCondCode(predicate);
auto &TLI = DAG.getTargetLoweringInfo();
EVT MemVT =
TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
// If a pointer's DAG type is larger than its memory type then the DAG values
// are zero-extended. This breaks signed comparisons so truncate back to the
// underlying type before doing the compare.
if (Op1.getValueType() != MemVT) {
Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
}
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
}
void SelectionDAGBuilder::visitFCmp(const User &I) {
FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
predicate = FC->getPredicate();
else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
predicate = FCmpInst::Predicate(FC->getPredicate());
SDValue Op1 = getValue(I.getOperand(0));
SDValue Op2 = getValue(I.getOperand(1));
ISD::CondCode Condition = getFCmpCondCode(predicate);
auto *FPMO = cast<FPMathOperator>(&I);
if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
Condition = getFCmpCodeWithoutNaN(Condition);
SDNodeFlags Flags;
Flags.copyFMF(*FPMO);
SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
}
// Check if the condition of the select has one use or two users that are both
// selects with the same condition.
static bool hasOnlySelectUsers(const Value *Cond) {
return llvm::all_of(Cond->users(), [](const Value *V) {
return isa<SelectInst>(V);
});
}
void SelectionDAGBuilder::visitSelect(const User &I) {
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
ValueVTs);
unsigned NumValues = ValueVTs.size();
if (NumValues == 0) return;
SmallVector<SDValue, 4> Values(NumValues);
SDValue Cond = getValue(I.getOperand(0));
SDValue LHSVal = getValue(I.getOperand(1));
SDValue RHSVal = getValue(I.getOperand(2));
SmallVector<SDValue, 1> BaseOps(1, Cond);
ISD::NodeType OpCode =
Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
bool IsUnaryAbs = false;
bool Negate = false;
SDNodeFlags Flags;
if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
Flags.copyFMF(*FPOp);
// Min/max matching is only viable if all output VTs are the same.
if (is_splat(ValueVTs)) {
EVT VT = ValueVTs[0];
LLVMContext &Ctx = *DAG.getContext();
auto &TLI = DAG.getTargetLoweringInfo();
// We care about the legality of the operation after it has been type
// legalized.
while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
VT = TLI.getTypeToTransformTo(Ctx, VT);
// If the vselect is legal, assume we want to leave this as a vector setcc +
// vselect. Otherwise, if this is going to be scalarized, we want to see if
// min/max is legal on the scalar type.
bool UseScalarMinMax = VT.isVector() &&
!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
Value *LHS, *RHS;
auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
ISD::NodeType Opc = ISD::DELETED_NODE;
switch (SPR.Flavor) {
case SPF_UMAX: Opc = ISD::UMAX; break;
case SPF_UMIN: Opc = ISD::UMIN; break;
case SPF_SMAX: Opc = ISD::SMAX; break;
case SPF_SMIN: Opc = ISD::SMIN; break;
case SPF_FMINNUM:
switch (SPR.NaNBehavior) {
case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
case SPNB_RETURNS_ANY: {
if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
Opc = ISD::FMINNUM;
else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
Opc = ISD::FMINIMUM;
else if (UseScalarMinMax)
Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
ISD::FMINNUM : ISD::FMINIMUM;
break;
}
}
break;
case SPF_FMAXNUM:
switch (SPR.NaNBehavior) {
case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
case SPNB_RETURNS_ANY:
if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
Opc = ISD::FMAXNUM;
else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
Opc = ISD::FMAXIMUM;
else if (UseScalarMinMax)
Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
ISD::FMAXNUM : ISD::FMAXIMUM;
break;
}
break;
case SPF_NABS:
Negate = true;
LLVM_FALLTHROUGH;
case SPF_ABS:
IsUnaryAbs = true;
Opc = ISD::ABS;
break;
default: break;
}
if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
(TLI.isOperationLegalOrCustom(Opc, VT) ||
(UseScalarMinMax &&
TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
// If the underlying comparison instruction is used by any other
// instruction, the consumed instructions won't be destroyed, so it is
// not profitable to convert to a min/max.
hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
OpCode = Opc;
LHSVal = getValue(LHS);
RHSVal = getValue(RHS);
BaseOps.clear();
}
if (IsUnaryAbs) {
OpCode = Opc;
LHSVal = getValue(LHS);
BaseOps.clear();
}
}
if (IsUnaryAbs) {
for (unsigned i = 0; i != NumValues; ++i) {
SDLoc dl = getCurSDLoc();
EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
Values[i] =
DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
if (Negate)
Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
Values[i]);
}
} else {
for (unsigned i = 0; i != NumValues; ++i) {
SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
Values[i] = DAG.getNode(
OpCode, getCurSDLoc(),
LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
}
}
setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
DAG.getVTList(ValueVTs), Values));
}
void SelectionDAGBuilder::visitTrunc(const User &I) {
// TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitZExt(const User &I) {
// ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
// ZExt also can't be a cast to bool for same reason. So, nothing much to do
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitSExt(const User &I) {
// SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
// SExt also can't be a cast to bool for same reason. So, nothing much to do
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitFPTrunc(const User &I) {
// FPTrunc is never a no-op cast, no need to check
SDValue N = getValue(I.getOperand(0));
SDLoc dl = getCurSDLoc();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
DAG.getTargetConstant(
0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
}
void SelectionDAGBuilder::visitFPExt(const User &I) {
// FPExt is never a no-op cast, no need to check
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitFPToUI(const User &I) {
// FPToUI is never a no-op cast, no need to check
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitFPToSI(const User &I) {
// FPToSI is never a no-op cast, no need to check
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitUIToFP(const User &I) {
// UIToFP is never a no-op cast, no need to check
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitSIToFP(const User &I) {
// SIToFP is never a no-op cast, no need to check
SDValue N = getValue(I.getOperand(0));
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
}
void SelectionDAGBuilder::visitPtrToInt(const User &I) {
// What to do depends on the size of the integer and the size of the pointer.
// We can either truncate, zero extend, or no-op, accordingly.
SDValue N = getValue(I.getOperand(0));
auto &TLI = DAG.getTargetLoweringInfo();
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
EVT PtrMemVT =
TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
setValue(&I, N);
}
void SelectionDAGBuilder::visitIntToPtr(const User &I) {
// What to do depends on the size of the integer and the size of the pointer.
// We can either truncate, zero extend, or no-op, accordingly.
SDValue N = getValue(I.getOperand(0));
auto &TLI = DAG.getTargetLoweringInfo();
EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
setValue(&I, N);
}
void SelectionDAGBuilder::visitBitCast(const User &I) {
SDValue N = getValue(I.getOperand(0));
SDLoc dl = getCurSDLoc();
EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType());
// BitCast assures us that source and destination are the same size so this is
// either a BITCAST or a no-op.
if (DestVT != N.getValueType())
setValue(&I, DAG.getNode(ISD::BITCAST, dl,
DestVT, N)); // convert types.
// Check if the original LLVM IR Operand was a ConstantInt, because getValue()
// might fold any kind of constant expression to an integer constant and that
// is not what we are looking for. Only recognize a bitcast of a genuine
// constant integer as an opaque constant.
else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
/*isOpaque*/true));
else
setValue(&I, N); // noop cast.
}
void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const Value *SV = I.getOperand(0);
SDValue N = getValue(SV);
EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
unsigned SrcAS = SV->getType()->getPointerAddressSpace();
unsigned DestAS = I.getType()->getPointerAddressSpace();
if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
setValue(&I, N);
}
void SelectionDAGBuilder::visitInsertElement(const User &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SDValue InVec = getValue(I.getOperand(0));
SDValue InVal = getValue(I.getOperand(1));
SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
TLI.getVectorIdxTy(DAG.getDataLayout()));
setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
TLI.getValueType(DAG.getDataLayout(), I.getType()),
InVec, InVal, InIdx));
}
void SelectionDAGBuilder::visitExtractElement(const User &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SDValue InVec = getValue(I.getOperand(0));
SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
TLI.getVectorIdxTy(DAG.getDataLayout()));
setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
TLI.getValueType(DAG.getDataLayout(), I.getType()),
InVec, InIdx));
}
void SelectionDAGBuilder::visitShuffleVector(const User &I) {
SDValue Src1 = getValue(I.getOperand(0));
SDValue Src2 = getValue(I.getOperand(1));
ArrayRef<int> Mask;
if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
Mask = SVI->getShuffleMask();
else
Mask = cast<ConstantExpr>(I).getShuffleMask();
SDLoc DL = getCurSDLoc();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
EVT SrcVT = Src1.getValueType();
if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
VT.isScalableVector()) {
// Canonical splat form of first element of first input vector.
SDValue FirstElt =
DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
DAG.getVectorIdxConstant(0, DL));
setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
return;
}
// For now, we only handle splats for scalable vectors.
// The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
// for targets that support a SPLAT_VECTOR for non-scalable vector types.
assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
unsigned SrcNumElts = SrcVT.getVectorNumElements();
unsigned MaskNumElts = Mask.size();
if (SrcNumElts == MaskNumElts) {
setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
return;
}
// Normalize the shuffle vector since mask and vector length don't match.
if (SrcNumElts < MaskNumElts) {
// Mask is longer than the source vectors. We can use concatenate vector to
// make the mask and vectors lengths match.
if (MaskNumElts % SrcNumElts == 0) {
// Mask length is a multiple of the source vector length.
// Check if the shuffle is some kind of concatenation of the input
// vectors.
unsigned NumConcat = MaskNumElts / SrcNumElts;
bool IsConcat = true;
SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
for (unsigned i = 0; i != MaskNumElts; ++i) {
int Idx = Mask[i];
if (Idx < 0)
continue;
// Ensure the indices in each SrcVT sized piece are sequential and that
// the same source is used for the whole piece.
if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
(ConcatSrcs[i / SrcNumElts] >= 0 &&
ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
IsConcat = false;
break;
}
// Remember which source this index came from.
ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
}
// The shuffle is concatenating multiple vectors together. Just emit
// a CONCAT_VECTORS operation.
if (IsConcat) {
SmallVector<SDValue, 8> ConcatOps;
for (auto Src : ConcatSrcs) {
if (Src < 0)
ConcatOps.push_back(DAG.getUNDEF(SrcVT));
else if (Src == 0)
ConcatOps.push_back(Src1);
else
ConcatOps.push_back(Src2);
}
setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
return;
}
}
unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
PaddedMaskNumElts);
// Pad both vectors with undefs to make them the same length as the mask.
SDValue UndefVal = DAG.getUNDEF(SrcVT);
SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
MOps1[0] = Src1;
MOps2[0] = Src2;
Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
// Readjust mask for new input vector length.
SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
for (unsigned i = 0; i != MaskNumElts; ++i) {
int Idx = Mask[i];
if (Idx >= (int)SrcNumElts)
Idx -= SrcNumElts - PaddedMaskNumElts;
MappedOps[i] = Idx;
}
SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
// If the concatenated vector was padded, extract a subvector with the
// correct number of elements.
if (MaskNumElts != PaddedMaskNumElts)
Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
DAG.getVectorIdxConstant(0, DL));
setValue(&I, Result);
return;
}
if (SrcNumElts > MaskNumElts) {
// Analyze the access pattern of the vector to see if we can extract
// two subvectors and do the shuffle.
int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
bool CanExtract = true;
for (int Idx : Mask) {
unsigned Input = 0;
if (Idx < 0)
continue;
if (Idx >= (int)SrcNumElts) {
Input = 1;
Idx -= SrcNumElts;
}
// If all the indices come from the same MaskNumElts sized portion of
// the sources we can use extract. Also make sure the extract wouldn't
// extract past the end of the source.
int NewStartIdx = alignDown(Idx, MaskNumElts);
if (NewStartIdx + MaskNumElts > SrcNumElts ||
(StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
CanExtract = false;
// Make sure we always update StartIdx as we use it to track if all
// elements are undef.
StartIdx[Input] = NewStartIdx;
}
if (StartIdx[0] < 0 && StartIdx[1] < 0) {
setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
return;
}
if (CanExtract) {
// Extract appropriate subvector and generate a vector shuffle
for (unsigned Input = 0; Input < 2; ++Input) {
SDValue &Src = Input == 0 ? Src1 : Src2;
if (StartIdx[Input] < 0)
Src = DAG.getUNDEF(VT);
else {
Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
DAG.getVectorIdxConstant(StartIdx[Input], DL));
}
}
// Calculate new mask.
SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
for (int &Idx : MappedOps) {
if (Idx >= (int)SrcNumElts)
Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
else if (Idx >= 0)
Idx -= StartIdx[0];
}
setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
return;
}
}
// We can't use either concat vectors or extract subvectors so fall back to
// replacing the shuffle with extract and build vector.
// to insert and build vector.
EVT EltVT = VT.getVectorElementType();
SmallVector<SDValue,8> Ops;
for (int Idx : Mask) {
SDValue Res;
if (Idx < 0) {
Res = DAG.getUNDEF(EltVT);
} else {
SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
DAG.getVectorIdxConstant(Idx, DL));
}
Ops.push_back(Res);
}
setValue(&I, DAG.getBuildVector(VT, DL, Ops));
}
void SelectionDAGBuilder::visitInsertValue(const User &I) {
ArrayRef<unsigned> Indices;
if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
Indices = IV->getIndices();
else
Indices = cast<ConstantExpr>(&I)->getIndices();
const Value *Op0 = I.getOperand(0);
const Value *Op1 = I.getOperand(1);
Type *AggTy = I.getType();
Type *ValTy = Op1->getType();
bool IntoUndef = isa<UndefValue>(Op0);
bool FromUndef = isa<UndefValue>(Op1);
unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SmallVector<EVT, 4> AggValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
SmallVector<EVT, 4> ValValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
unsigned NumAggValues = AggValueVTs.size();
unsigned NumValValues = ValValueVTs.size();
SmallVector<SDValue, 4> Values(NumAggValues);
// Ignore an insertvalue that produces an empty object
if (!NumAggValues) {
setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
return;
}
SDValue Agg = getValue(Op0);
unsigned i = 0;
// Copy the beginning value(s) from the original aggregate.
for (; i != LinearIndex; ++i)
Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
SDValue(Agg.getNode(), Agg.getResNo() + i);
// Copy values from the inserted value(s).
if (NumValValues) {
SDValue Val = getValue(Op1);
for (; i != LinearIndex + NumValValues; ++i)
Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
}
// Copy remaining value(s) from the original aggregate.
for (; i != NumAggValues; ++i)
Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
SDValue(Agg.getNode(), Agg.getResNo() + i);
setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
DAG.getVTList(AggValueVTs), Values));
}
void SelectionDAGBuilder::visitExtractValue(const User &I) {
ArrayRef<unsigned> Indices;
if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
Indices = EV->getIndices();
else
Indices = cast<ConstantExpr>(&I)->getIndices();
const Value *Op0 = I.getOperand(0);
Type *AggTy = Op0->getType();
Type *ValTy = I.getType();
bool OutOfUndef = isa<UndefValue>(Op0);
unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SmallVector<EVT, 4> ValValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
unsigned NumValValues = ValValueVTs.size();
// Ignore a extractvalue that produces an empty object
if (!NumValValues) {
setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
return;
}
SmallVector<SDValue, 4> Values(NumValValues);
SDValue Agg = getValue(Op0);
// Copy out the selected value(s).
for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
Values[i - LinearIndex] =
OutOfUndef ?
DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
SDValue(Agg.getNode(), Agg.getResNo() + i);
setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
DAG.getVTList(ValValueVTs), Values));
}
void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Value *Op0 = I.getOperand(0);
// Note that the pointer operand may be a vector of pointers. Take the scalar
// element which holds a pointer.
unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
SDValue N = getValue(Op0);
SDLoc dl = getCurSDLoc();
auto &TLI = DAG.getTargetLoweringInfo();
// Normalize Vector GEP - all scalar operands should be converted to the
// splat vector.
bool IsVectorGEP = I.getType()->isVectorTy();
ElementCount VectorElementCount =
IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
: ElementCount::getFixed(0);
if (IsVectorGEP && !N.getValueType().isVector()) {
LLVMContext &Context = *DAG.getContext();
EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
if (VectorElementCount.isScalable())
N = DAG.getSplatVector(VT, dl, N);
else
N = DAG.getSplatBuildVector(VT, dl, N);
}
for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
GTI != E; ++GTI) {
const Value *Idx = GTI.getOperand();
if (StructType *StTy = GTI.getStructTypeOrNull()) {
unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
if (Field) {
// N = N + Offset
uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
// In an inbounds GEP with an offset that is nonnegative even when
// interpreted as signed, assume there is no unsigned overflow.
SDNodeFlags Flags;
if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
Flags.setNoUnsignedWrap(true);
N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
DAG.getConstant(Offset, dl, N.getValueType()), Flags);
}
} else {
// IdxSize is the width of the arithmetic according to IR semantics.
// In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
// (and fix up the result later).
unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
MVT IdxTy = MVT::getIntegerVT(IdxSize);
TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
// We intentionally mask away the high bits here; ElementSize may not
// fit in IdxTy.
APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
bool ElementScalable = ElementSize.isScalable();
// If this is a scalar constant or a splat vector of constants,
// handle it quickly.
const auto *C = dyn_cast<Constant>(Idx);
if (C && isa<VectorType>(C->getType()))
C = C->getSplatValue();
const auto *CI = dyn_cast_or_null<ConstantInt>(C);
if (CI && CI->isZero())
continue;
if (CI && !ElementScalable) {
APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
LLVMContext &Context = *DAG.getContext();
SDValue OffsVal;
if (IsVectorGEP)
OffsVal = DAG.getConstant(
Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
else
OffsVal = DAG.getConstant(Offs, dl, IdxTy);
// In an inbounds GEP with an offset that is nonnegative even when
// interpreted as signed, assume there is no unsigned overflow.
SDNodeFlags Flags;
if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
Flags.setNoUnsignedWrap(true);
OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
continue;
}
// N = N + Idx * ElementMul;
SDValue IdxN = getValue(Idx);
if (!IdxN.getValueType().isVector() && IsVectorGEP) {
EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
VectorElementCount);
if (VectorElementCount.isScalable())
IdxN = DAG.getSplatVector(VT, dl, IdxN);
else
IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
}
// If the index is smaller or larger than intptr_t, truncate or extend
// it.
IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
if (ElementScalable) {
EVT VScaleTy = N.getValueType().getScalarType();
SDValue VScale = DAG.getNode(
ISD::VSCALE, dl, VScaleTy,
DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
if (IsVectorGEP)
VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
} else {
// If this is a multiply by a power of two, turn it into a shl
// immediately. This is a very common case.
if (ElementMul != 1) {
if (ElementMul.isPowerOf2()) {
unsigned Amt = ElementMul.logBase2();
IdxN = DAG.getNode(ISD::SHL, dl,
N.getValueType(), IdxN,
DAG.getConstant(Amt, dl, IdxN.getValueType()));
} else {
SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
IdxN.getValueType());
IdxN = DAG.getNode(ISD::MUL, dl,
N.getValueType(), IdxN, Scale);
}
}
}
N = DAG.getNode(ISD::ADD, dl,
N.getValueType(), N, IdxN);
}
}
MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
if (IsVectorGEP) {
PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
}
if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
setValue(&I, N);
}
void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
// If this is a fixed sized alloca in the entry block of the function,
// allocate it statically on the stack.
if (FuncInfo.StaticAllocaMap.count(&I))
return; // getValue will auto-populate this.
SDLoc dl = getCurSDLoc();
Type *Ty = I.getAllocatedType();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
auto &DL = DAG.getDataLayout();
uint64_t TySize = DL.getTypeAllocSize(Ty);
MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
SDValue AllocSize = getValue(I.getArraySize());
EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
if (AllocSize.getValueType() != IntPtr)
AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
AllocSize,
DAG.getConstant(TySize, dl, IntPtr));
// Handle alignment. If the requested alignment is less than or equal to
// the stack alignment, ignore it. If the size is greater than or equal to
// the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
if (*Alignment <= StackAlign)
Alignment = None;
const uint64_t StackAlignMask = StackAlign.value() - 1U;
// Round the size of the allocation up to the stack alignment size
// by add SA-1 to the size. This doesn't overflow because we're computing
// an address inside an alloca.
SDNodeFlags Flags;
Flags.setNoUnsignedWrap(true);
AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
// Mask out the low bits for alignment purposes.
AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
DAG.getConstant(~StackAlignMask, dl, IntPtr));
SDValue Ops[] = {
getRoot(), AllocSize,
DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
setValue(&I, DSA);
DAG.setRoot(DSA.getValue(1));
assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
}
void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
if (I.isAtomic())
return visitAtomicLoad(I);
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const Value *SV = I.getOperand(0);
if (TLI.supportSwiftError()) {
// Swifterror values can come from either a function parameter with
// swifterror attribute or an alloca with swifterror attribute.
if (const Argument *Arg = dyn_cast<Argument>(SV)) {
if (Arg->hasSwiftErrorAttr())
return visitLoadFromSwiftError(I);
}
if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
if (Alloca->isSwiftError())
return visitLoadFromSwiftError(I);
}
}
SDValue Ptr = getValue(SV);
Type *Ty = I.getType();
Align Alignment = I.getAlign();
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
SmallVector<EVT, 4> ValueVTs, MemVTs;
SmallVector<uint64_t, 4> Offsets;
ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
unsigned NumValues = ValueVTs.size();
if (NumValues == 0)
return;
bool isVolatile = I.isVolatile();
SDValue Root;
bool ConstantMemory = false;
if (isVolatile)
// Serialize volatile loads with other side effects.
Root = getRoot();
else if (NumValues > MaxParallelChains)
Root = getMemoryRoot();
else if (AA &&
AA->pointsToConstantMemory(MemoryLocation(
SV,
LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
AAInfo))) {
// Do not serialize (non-volatile) loads of constant memory with anything.
Root = DAG.getEntryNode();
ConstantMemory = true;
} else {
// Do not serialize non-volatile loads against each other.
Root = DAG.getRoot();
}
SDLoc dl = getCurSDLoc();
if (isVolatile)
Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
// An aggregate load cannot wrap around the address space, so offsets to its
// parts don't wrap either.
SDNodeFlags Flags;
Flags.setNoUnsignedWrap(true);
SmallVector<SDValue, 4> Values(NumValues);
SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
EVT PtrVT = Ptr.getValueType();
MachineMemOperand::Flags MMOFlags
= TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
unsigned ChainI = 0;
for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
// Serializing loads here may result in excessive register pressure, and
// TokenFactor places arbitrary choke points on the scheduler. SD scheduling
// could recover a bit by hoisting nodes upward in the chain by recognizing
// they are side-effect free or do not alias. The optimizer should really
// avoid this case by converting large object/array copies to llvm.memcpy
// (MaxParallelChains should always remain as failsafe).
if (ChainI == MaxParallelChains) {
assert(PendingLoads.empty() && "PendingLoads must be serialized first");
SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
makeArrayRef(Chains.data(), ChainI));
Root = Chain;
ChainI = 0;
}
SDValue A = DAG.getNode(ISD::ADD, dl,
PtrVT, Ptr,
DAG.getConstant(Offsets[i], dl, PtrVT),
Flags);
SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
MachinePointerInfo(SV, Offsets[i]), Alignment,
MMOFlags, AAInfo, Ranges);
Chains[ChainI] = L.getValue(1);
if (MemVTs[i] != ValueVTs[i])
L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
Values[i] = L;
}
if (!ConstantMemory) {
SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
makeArrayRef(Chains.data(), ChainI));
if (isVolatile)
DAG.setRoot(Chain);
else
PendingLoads.push_back(Chain);
}
setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
DAG.getVTList(ValueVTs), Values));
}
void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
"call visitStoreToSwiftError when backend supports swifterror");
SmallVector<EVT, 4> ValueVTs;
SmallVector<uint64_t, 4> Offsets;
const Value *SrcV = I.getOperand(0);
ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
SrcV->getType(), ValueVTs, &Offsets);
assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
"expect a single EVT for swifterror");
SDValue Src = getValue(SrcV);
// Create a virtual register, then update the virtual register.
Register VReg =
SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
// Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
// Chain can be getRoot or getControlRoot.
SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
SDValue(Src.getNode(), Src.getResNo()));
DAG.setRoot(CopyNode);
}
void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
"call visitLoadFromSwiftError when backend supports swifterror");
assert(!I.isVolatile() &&
!I.hasMetadata(LLVMContext::MD_nontemporal) &&
!I.hasMetadata(LLVMContext::MD_invariant_load) &&
"Support volatile, non temporal, invariant for load_from_swift_error");
const Value *SV = I.getOperand(0);
Type *Ty = I.getType();
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
assert(
(!AA ||
!AA->pointsToConstantMemory(MemoryLocation(
SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
AAInfo))) &&
"load_from_swift_error should not be constant memory");
SmallVector<EVT, 4> ValueVTs;
SmallVector<uint64_t, 4> Offsets;
ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
ValueVTs, &Offsets);
assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
"expect a single EVT for swifterror");
// Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
SDValue L = DAG.getCopyFromReg(
getRoot(), getCurSDLoc(),
SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
setValue(&I, L);
}
void SelectionDAGBuilder::visitStore(const StoreInst &I) {
if (I.isAtomic())
return visitAtomicStore(I);
const Value *SrcV = I.getOperand(0);
const Value *PtrV = I.getOperand(1);
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (TLI.supportSwiftError()) {
// Swifterror values can come from either a function parameter with
// swifterror attribute or an alloca with swifterror attribute.
if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
if (Arg->hasSwiftErrorAttr())
return visitStoreToSwiftError(I);
}
if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
if (Alloca->isSwiftError())
return visitStoreToSwiftError(I);
}
}
SmallVector<EVT, 4> ValueVTs, MemVTs;
SmallVector<uint64_t, 4> Offsets;
ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
unsigned NumValues = ValueVTs.size();
if (NumValues == 0)
return;
// Get the lowered operands. Note that we do this after
// checking if NumResults is zero, because with zero results
// the operands won't have values in the map.
SDValue Src = getValue(SrcV);
SDValue Ptr = getValue(PtrV);
SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
SDLoc dl = getCurSDLoc();
Align Alignment = I.getAlign();
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
// An aggregate load cannot wrap around the address space, so offsets to its
// parts don't wrap either.
SDNodeFlags Flags;
Flags.setNoUnsignedWrap(true);
unsigned ChainI = 0;
for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
// See visitLoad comments.
if (ChainI == MaxParallelChains) {
SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
makeArrayRef(Chains.data(), ChainI));
Root = Chain;
ChainI = 0;
}
SDValue Add =
DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
if (MemVTs[i] != ValueVTs[i])
Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
SDValue St =
DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
Alignment, MMOFlags, AAInfo);
Chains[ChainI] = St;
}
SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
makeArrayRef(Chains.data(), ChainI));
DAG.setRoot(StoreNode);
}
void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
bool IsCompressing) {
SDLoc sdl = getCurSDLoc();
auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
MaybeAlign &Alignment) {
// llvm.masked.store.*(Src0, Ptr, alignment, Mask)
Src0 = I.getArgOperand(0);
Ptr = I.getArgOperand(1);
Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
Mask = I.getArgOperand(3);
};
auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
MaybeAlign &Alignment) {
// llvm.masked.compressstore.*(Src0, Ptr, Mask)
Src0 = I.getArgOperand(0);
Ptr = I.getArgOperand(1);
Mask = I.getArgOperand(2);
Alignment = None;
};
Value *PtrOperand, *MaskOperand, *Src0Operand;
MaybeAlign Alignment;
if (IsCompressing)
getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
else
getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
SDValue Ptr = getValue(PtrOperand);
SDValue Src0 = getValue(Src0Operand);
SDValue Mask = getValue(MaskOperand);
SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
EVT VT = Src0.getValueType();
if (!Alignment)
Alignment = DAG.getEVTAlign(VT);
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
// TODO: Make MachineMemOperands aware of scalable
// vectors.
VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
SDValue StoreNode =
DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
ISD::UNINDEXED, false /* Truncating */, IsCompressing);
DAG.setRoot(StoreNode);
setValue(&I, StoreNode);
}
// Get a uniform base for the Gather/Scatter intrinsic.
// The first argument of the Gather/Scatter intrinsic is a vector of pointers.
// We try to represent it as a base pointer + vector of indices.
// Usually, the vector of pointers comes from a 'getelementptr' instruction.
// The first operand of the GEP may be a single pointer or a vector of pointers
// Example:
// %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
// or
// %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
// %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
//
// When the first GEP operand is a single pointer - it is the uniform base we
// are looking for. If first operand of the GEP is a splat vector - we
// extract the splat value and use it as a uniform base.
// In all other cases the function returns 'false'.
static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
ISD::MemIndexType &IndexType, SDValue &Scale,
SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
SelectionDAG& DAG = SDB->DAG;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const DataLayout &DL = DAG.getDataLayout();
assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
// Handle splat constant pointer.
if (auto *C = dyn_cast<Constant>(Ptr)) {
C = C->getSplatValue();
if (!C)
return false;
Base = SDB->getValue(C);
unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
IndexType = ISD::SIGNED_SCALED;
Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
return true;
}
const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
if (!GEP || GEP->getParent() != CurBB)
return false;
if (GEP->getNumOperands() != 2)
return false;
const Value *BasePtr = GEP->getPointerOperand();
const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
// Make sure the base is scalar and the index is a vector.
if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
return false;
Base = SDB->getValue(BasePtr);
Index = SDB->getValue(IndexVal);
IndexType = ISD::SIGNED_SCALED;
Scale = DAG.getTargetConstant(
DL.getTypeAllocSize(GEP->getResultElementType()),
SDB->getCurSDLoc(), TLI.getPointerTy(DL));
return true;
}
void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
SDLoc sdl = getCurSDLoc();
// llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
const Value *Ptr = I.getArgOperand(1);
SDValue Src0 = getValue(I.getArgOperand(0));
SDValue Mask = getValue(I.getArgOperand(3));
EVT VT = Src0.getValueType();
Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
->getMaybeAlignValue()
.getValueOr(DAG.getEVTAlign(VT));
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
SDValue Base;
SDValue Index;
ISD::MemIndexType IndexType;
SDValue Scale;
bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
I.getParent());
unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
MachinePointerInfo(AS), MachineMemOperand::MOStore,
// TODO: Make MachineMemOperands aware of scalable
// vectors.
MemoryLocation::UnknownSize, Alignment, AAInfo);
if (!UniformBase) {
Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
Index = getValue(Ptr);
IndexType = ISD::SIGNED_UNSCALED;
Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
}
EVT IdxVT = Index.getValueType();
EVT EltTy = IdxVT.getVectorElementType();
if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
}
SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
Ops, MMO, IndexType, false);
DAG.setRoot(Scatter);
setValue(&I, Scatter);
}
void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
SDLoc sdl = getCurSDLoc();
auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
MaybeAlign &Alignment) {
// @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
Ptr = I.getArgOperand(0);
Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
Mask = I.getArgOperand(2);
Src0 = I.getArgOperand(3);
};
auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
MaybeAlign &Alignment) {
// @llvm.masked.expandload.*(Ptr, Mask, Src0)
Ptr = I.getArgOperand(0);
Alignment = None;
Mask = I.getArgOperand(1);
Src0 = I.getArgOperand(2);
};
Value *PtrOperand, *MaskOperand, *Src0Operand;
MaybeAlign Alignment;
if (IsExpanding)
getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
else
getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
SDValue Ptr = getValue(PtrOperand);
SDValue Src0 = getValue(Src0Operand);
SDValue Mask = getValue(MaskOperand);
SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
EVT VT = Src0.getValueType();
if (!Alignment)
Alignment = DAG.getEVTAlign(VT);
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
// Do not serialize masked loads of constant memory with anything.
MemoryLocation ML;
if (VT.isScalableVector())
ML = MemoryLocation::getAfter(PtrOperand);
else
ML = MemoryLocation(PtrOperand, LocationSize::precise(
DAG.getDataLayout().getTypeStoreSize(I.getType())),
AAInfo);
bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
// TODO: Make MachineMemOperands aware of scalable
// vectors.
VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
SDValue Load =
DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
if (AddToChain)
PendingLoads.push_back(Load.getValue(1));
setValue(&I, Load);
}
void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
SDLoc sdl = getCurSDLoc();
// @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
const Value *Ptr = I.getArgOperand(0);
SDValue Src0 = getValue(I.getArgOperand(3));
SDValue Mask = getValue(I.getArgOperand(2));
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
->getMaybeAlignValue()
.getValueOr(DAG.getEVTAlign(VT));
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
SDValue Root = DAG.getRoot();
SDValue Base;
SDValue Index;
ISD::MemIndexType IndexType;
SDValue Scale;
bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
I.getParent());
unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
MachinePointerInfo(AS), MachineMemOperand::MOLoad,
// TODO: Make MachineMemOperands aware of scalable
// vectors.
MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
if (!UniformBase) {
Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
Index = getValue(Ptr);
IndexType = ISD::SIGNED_UNSCALED;
Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
}
EVT IdxVT = Index.getValueType();
EVT EltTy = IdxVT.getVectorElementType();
if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
}
SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
Ops, MMO, IndexType, ISD::NON_EXTLOAD);
PendingLoads.push_back(Gather.getValue(1));
setValue(&I, Gather);
}
void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
SDLoc dl = getCurSDLoc();
AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
AtomicOrdering FailureOrdering = I.getFailureOrdering();
SyncScope::ID SSID = I.getSyncScopeID();
SDValue InChain = getRoot();
MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
MachineFunction &MF = DAG.getMachineFunction();
MachineMemOperand *MMO = MF.getMachineMemOperand(
MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
FailureOrdering);
SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
dl, MemVT, VTs, InChain,
getValue(I.getPointerOperand()),
getValue(I.getCompareOperand()),
getValue(I.getNewValOperand()), MMO);
SDValue OutChain = L.getValue(2);
setValue(&I, L);
DAG.setRoot(OutChain);
}
void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
SDLoc dl = getCurSDLoc();
ISD::NodeType NT;
switch (I.getOperation()) {
default: llvm_unreachable("Unknown atomicrmw operation");
case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
}
AtomicOrdering Ordering = I.getOrdering();
SyncScope::ID SSID = I.getSyncScopeID();
SDValue InChain = getRoot();
auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
MachineFunction &MF = DAG.getMachineFunction();
MachineMemOperand *MMO = MF.getMachineMemOperand(
MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
SDValue L =
DAG.getAtomic(NT, dl, MemVT, InChain,
getValue(I.getPointerOperand()), getValue(I.getValOperand()),
MMO);
SDValue OutChain = L.getValue(1);
setValue(&I, L);
DAG.setRoot(OutChain);
}
void SelectionDAGBuilder::visitFence(const FenceInst &I) {
SDLoc dl = getCurSDLoc();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SDValue Ops[3];
Ops[0] = getRoot();
Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
TLI.getFenceOperandTy(DAG.getDataLayout()));
Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
TLI.getFenceOperandTy(DAG.getDataLayout()));
DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
}
void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
SDLoc dl = getCurSDLoc();
AtomicOrdering Order = I.getOrdering();
SyncScope::ID SSID = I.getSyncScopeID();
SDValue InChain = getRoot();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
if (!TLI.supportsUnalignedAtomics() &&
I.getAlignment() < MemVT.getSizeInBits() / 8)
report_fatal_error("Cannot generate unaligned atomic load");
auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
SDValue Ptr = getValue(I.getPointerOperand());
if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
// TODO: Once this is better exercised by tests, it should be merged with
// the normal path for loads to prevent future divergence.
SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
if (MemVT != VT)
L = DAG.getPtrExtOrTrunc(L, dl, VT);
setValue(&I, L);
SDValue OutChain = L.getValue(1);
if (!I.isUnordered())
DAG.setRoot(OutChain);
else
PendingLoads.push_back(OutChain);
return;
}
SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
Ptr, MMO);
SDValue OutChain = L.getValue(1);
if (MemVT != VT)
L = DAG.getPtrExtOrTrunc(L, dl, VT);
setValue(&I, L);
DAG.setRoot(OutChain);
}
void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
SDLoc dl = getCurSDLoc();
AtomicOrdering Ordering = I.getOrdering();
SyncScope::ID SSID = I.getSyncScopeID();
SDValue InChain = getRoot();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT MemVT =
TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
if (I.getAlignment() < MemVT.getSizeInBits() / 8)
report_fatal_error("Cannot generate unaligned atomic store");
auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
MachineFunction &MF = DAG.getMachineFunction();
MachineMemOperand *MMO = MF.getMachineMemOperand(
MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
SDValue Val = getValue(I.getValueOperand());
if (Val.getValueType() != MemVT)
Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
SDValue Ptr = getValue(I.getPointerOperand());
if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
// TODO: Once this is better exercised by tests, it should be merged with
// the normal path for stores to prevent future divergence.
SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
DAG.setRoot(S);
return;
}
SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
Ptr, Val, MMO);
DAG.setRoot(OutChain);
}
/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
/// node.
void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
unsigned Intrinsic) {
// Ignore the callsite's attributes. A specific call site may be marked with
// readnone, but the lowering code will expect the chain based on the
// definition.
const Function *F = I.getCalledFunction();
bool HasChain = !F->doesNotAccessMemory();
bool OnlyLoad = HasChain && F->onlyReadsMemory();
// Build the operand list.
SmallVector<SDValue, 8> Ops;
if (HasChain) { // If this intrinsic has side-effects, chainify it.
if (OnlyLoad) {
// We don't need to serialize loads against other loads.
Ops.push_back(DAG.getRoot());
} else {
Ops.push_back(getRoot());
}
}
// Info is set by getTgtMemInstrinsic
TargetLowering::IntrinsicInfo Info;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
DAG.getMachineFunction(),
Intrinsic);
// Add the intrinsic ID as an integer operand if it's not a target intrinsic.
if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
Info.opc == ISD::INTRINSIC_W_CHAIN)
Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
TLI.getPointerTy(DAG.getDataLayout())));
// Add all operands of the call to the operand list.
for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
const Value *Arg = I.getArgOperand(i);
if (!I.paramHasAttr(i, Attribute::ImmArg)) {
Ops.push_back(getValue(Arg));
continue;
}
// Use TargetConstant instead of a regular constant for immarg.
EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
assert(CI->getBitWidth() <= 64 &&
"large intrinsic immediates not handled");
Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
} else {
Ops.push_back(
DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
}
}
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
if (HasChain)
ValueVTs.push_back(MVT::Other);
SDVTList VTs = DAG.getVTList(ValueVTs);
// Create the node.
SDValue Result;
if (IsTgtIntrinsic) {
// This is target intrinsic that touches memory
AAMDNodes AAInfo;
I.getAAMetadata(AAInfo);
Result =
DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
MachinePointerInfo(Info.ptrVal, Info.offset),
Info.align, Info.flags, Info.size, AAInfo);
} else if (!HasChain) {
Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
} else if (!I.getType()->isVoidTy()) {
Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
} else {
Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
}
if (HasChain) {
SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
if (OnlyLoad)
PendingLoads.push_back(Chain);
else
DAG.setRoot(Chain);
}
if (!I.getType()->isVoidTy()) {
if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
} else
Result = lowerRangeToAssertZExt(DAG, I, Result);
MaybeAlign Alignment = I.getRetAlign();
if (!Alignment)
Alignment = F->getAttributes().getRetAlignment();
// Insert `assertalign` node if there's an alignment.
if (InsertAssertAlign && Alignment) {
Result =
DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
}
setValue(&I, Result);
}
}
/// GetSignificand - Get the significand and build it into a floating-point
/// number with exponent of 1:
///
/// Op = (Op & 0x007fffff) | 0x3f800000;
///
/// where Op is the hexadecimal representation of floating point value.
static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
DAG.getConstant(0x007fffff, dl, MVT::i32));
SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
DAG.getConstant(0x3f800000, dl, MVT::i32));
return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
}
/// GetExponent - Get the exponent:
///
/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
///
/// where Op is the hexadecimal representation of floating point value.
static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
const TargetLowering &TLI, const SDLoc &dl) {
SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
DAG.getConstant(0x7f800000, dl, MVT::i32));
SDValue t1 = DAG.getNode(
ISD::SRL, dl, MVT::i32, t0,
DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
DAG.getConstant(127, dl, MVT::i32));
return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
}
/// getF32Constant - Get 32-bit floating point constant.
static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
const SDLoc &dl) {
return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
MVT::f32);
}
static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
SelectionDAG &DAG) {
// TODO: What fast-math-flags should be set on the floating-point nodes?
// IntegerPartOfX = ((int32_t)(t0);
SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
// FractionalPartOfX = t0 - (float)IntegerPartOfX;
SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
// IntegerPartOfX <<= 23;
IntegerPartOfX = DAG.getNode(
ISD::SHL, dl, MVT::i32, IntegerPartOfX,
DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
DAG.getDataLayout())));
SDValue TwoToFractionalPartOfX;
if (LimitFloatPrecision <= 6) {
// For floating-point precision of 6:
//
// TwoToFractionalPartOfX =
// 0.997535578f +
// (0.735607626f + 0.252464424f * x) * x;
//
// error 0.0144103317, which is 6 bits
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0x3e814304, dl));
SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3f3c50c8, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x3f7f5e7e, dl));
} else if (LimitFloatPrecision <= 12) {
// For floating-point precision of 12:
//
// TwoToFractionalPartOfX =
// 0.999892986f +
// (0.696457318f +
// (0.224338339f + 0.792043434e-1f * x) * x) * x;
//
// error 0.000107046256, which is 13 to 14 bits
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0x3da235e3, dl));
SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3e65b8f3, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x3f324b07, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
getF32Constant(DAG, 0x3f7ff8fd, dl));
} else { // LimitFloatPrecision <= 18
// For floating-point precision of 18:
//
// TwoToFractionalPartOfX =
// 0.999999982f +
// (0.693148872f +
// (0.240227044f +
// (0.554906021e-1f +
// (0.961591928e-2f +
// (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
// error 2.47208000*10^(-7), which is better than 18 bits
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0x3924b03e, dl));
SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3ab24b87, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x3c1d8c17, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
getF32Constant(DAG, 0x3d634a1d, dl));
SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
getF32Constant(DAG, 0x3e75fe14, dl));
SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
getF32Constant(DAG, 0x3f317234, dl));
SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
getF32Constant(DAG, 0x3f800000, dl));
}
// Add the exponent into the result in integer domain.
SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
}
/// expandExp - Lower an exp intrinsic. Handles the special sequences for
/// limited-precision mode.
static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
const TargetLowering &TLI, SDNodeFlags Flags) {
if (Op.getValueType() == MVT::f32 &&
LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
// Put the exponent in the right bit position for later addition to the
// final result:
//
// t0 = Op * log2(e)
// TODO: What fast-math-flags should be set here?
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
return getLimitedPrecisionExp2(t0, dl, DAG);
}
// No special expansion.
return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
}
/// expandLog - Lower a log intrinsic. Handles the special sequences for
/// limited-precision mode.
static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
const TargetLowering &TLI, SDNodeFlags Flags) {
// TODO: What fast-math-flags should be set on the floating-point nodes?
if (Op.getValueType() == MVT::f32 &&
LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
// Scale the exponent by log(2).
SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
SDValue LogOfExponent =
DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
// Get the significand and build it into a floating-point number with
// exponent of 1.
SDValue X = GetSignificand(DAG, Op1, dl);
SDValue LogOfMantissa;
if (LimitFloatPrecision <= 6) {
// For floating-point precision of 6:
//
// LogofMantissa =
// -1.1609546f +
// (1.4034025f - 0.23903021f * x) * x;
//
// error 0.0034276066, which is better than 8 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbe74c456, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3fb3a2b1, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3f949a29, dl));
} else if (LimitFloatPrecision <= 12) {
// For floating-point precision of 12:
//
// LogOfMantissa =
// -1.7417939f +
// (2.8212026f +
// (-1.4699568f +
// (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
//
// error 0.000061011436, which is 14 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbd67b6d6, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3ee4f4b8, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3fbc278b, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x40348e95, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
getF32Constant(DAG, 0x3fdef31a, dl));
} else { // LimitFloatPrecision <= 18
// For floating-point precision of 18:
//
// LogOfMantissa =
// -2.1072184f +
// (4.2372794f +
// (-3.7029485f +
// (2.2781945f +
// (-0.87823314f +
// (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
//
// error 0.0000023660568, which is better than 18 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbc91e5ac, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3e4350aa, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3f60d3e3, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x4011cdf0, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
getF32Constant(DAG, 0x406cfd1c, dl));
SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
getF32Constant(DAG, 0x408797cb, dl));
SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
getF32Constant(DAG, 0x4006dcab, dl));
}
return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
}
// No special expansion.
return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
}
/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
/// limited-precision mode.
static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
const TargetLowering &TLI, SDNodeFlags Flags) {
// TODO: What fast-math-flags should be set on the floating-point nodes?
if (Op.getValueType() == MVT::f32 &&
LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
// Get the exponent.
SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
// Get the significand and build it into a floating-point number with
// exponent of 1.
SDValue X = GetSignificand(DAG, Op1, dl);
// Different possible minimax approximations of significand in
// floating-point for various degrees of accuracy over [1,2].
SDValue Log2ofMantissa;
if (LimitFloatPrecision <= 6) {
// For floating-point precision of 6:
//
// Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
//
// error 0.0049451742, which is more than 7 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbeb08fe0, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x40019463, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3fd6633d, dl));
} else if (LimitFloatPrecision <= 12) {
// For floating-point precision of 12:
//
// Log2ofMantissa =
// -2.51285454f +
// (4.07009056f +
// (-2.12067489f +
// (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
//
// error 0.0000876136000, which is better than 13 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbda7262e, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3f25280b, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x4007b923, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x40823e2f, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
getF32Constant(DAG, 0x4020d29c, dl));
} else { // LimitFloatPrecision <= 18
// For floating-point precision of 18:
//
// Log2ofMantissa =
// -3.0400495f +
// (6.1129976f +
// (-5.3420409f +
// (3.2865683f +
// (-1.2669343f +
// (0.27515199f -
// 0.25691327e-1f * x) * x) * x) * x) * x) * x;
//
// error 0.0000018516, which is better than 18 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbcd2769e, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3e8ce0b9, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3fa22ae7, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
getF32Constant(DAG, 0x40525723, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
getF32Constant(DAG, 0x40aaf200, dl));
SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
getF32Constant(DAG, 0x40c39dad, dl));
SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
getF32Constant(DAG, 0x4042902c, dl));
}
return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
}
// No special expansion.
return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
}
/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
/// limited-precision mode.
static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
const TargetLowering &TLI, SDNodeFlags Flags) {
// TODO: What fast-math-flags should be set on the floating-point nodes?
if (Op.getValueType() == MVT::f32 &&
LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
// Scale the exponent by log10(2) [0.30102999f].
SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
getF32Constant(DAG, 0x3e9a209a, dl));
// Get the significand and build it into a floating-point number with
// exponent of 1.
SDValue X = GetSignificand(DAG, Op1, dl);
SDValue Log10ofMantissa;
if (LimitFloatPrecision <= 6) {
// For floating-point precision of 6:
//
// Log10ofMantissa =
// -0.50419619f +
// (0.60948995f - 0.10380950f * x) * x;
//
// error 0.0014886165, which is 6 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0xbdd49a13, dl));
SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3f1c0789, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3f011300, dl));
} else if (LimitFloatPrecision <= 12) {
// For floating-point precision of 12:
//
// Log10ofMantissa =
// -0.64831180f +
// (0.91751397f +
// (-0.31664806f + 0.47637168e-1f * x) * x) * x;
//
// error 0.00019228036, which is better than 12 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0x3d431f31, dl));
SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3ea21fb2, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3f6ae232, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
getF32Constant(DAG, 0x3f25f7c3, dl));
} else { // LimitFloatPrecision <= 18
// For floating-point precision of 18:
//
// Log10ofMantissa =
// -0.84299375f +
// (1.5327582f +
// (-1.0688956f +
// (0.49102474f +
// (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
//
// error 0.0000037995730, which is better than 18 bits
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
getF32Constant(DAG, 0x3c5d51ce, dl));
SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
getF32Constant(DAG, 0x3e00685a, dl));
SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
getF32Constant(DAG, 0x3efb6798, dl));
SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
getF32Constant(DAG, 0x3f88d192, dl));
SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
getF32Constant(DAG, 0x3fc4316c, dl));
SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
getF32Constant(DAG, 0x3f57ce70, dl));
}
return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
}
// No special expansion.
return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
}
/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
/// limited-precision mode.
static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
const TargetLowering &TLI, SDNodeFlags Flags) {
if (Op.getValueType() == MVT::f32 &&
LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
return getLimitedPrecisionExp2(Op, dl, DAG);
// No special expansion.
return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
}
/// visitPow - Lower a pow intrinsic. Handles the special sequences for
/// limited-precision mode with x == 10.0f.
static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
SelectionDAG &DAG, const TargetLowering &TLI,
SDNodeFlags Flags) {
bool IsExp10 = false;
if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
APFloat Ten(10.0f);
IsExp10 = LHSC->isExactlyValue(Ten);
}
}
// TODO: What fast-math-flags should be set on the FMUL node?
if (IsExp10) {
// Put the exponent in the right bit position for later addition to the
// final result:
//
// #define LOG2OF10 3.3219281f
// t0 = Op * LOG2OF10;
SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
getF32Constant(DAG, 0x40549a78, dl));
return getLimitedPrecisionExp2(t0, dl, DAG);
}
// No special expansion.
return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
}
/// ExpandPowI - Expand a llvm.powi intrinsic.
static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
SelectionDAG &DAG) {
// If RHS is a constant, we can expand this out to a multiplication tree,
// otherwise we end up lowering to a call to __powidf2 (for example). When
// optimizing for size, we only want to do this if the expansion would produce
// a small number of multiplies, otherwise we do the full expansion.
if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
// Get the exponent as a positive value.
unsigned Val = RHSC->getSExtValue();
if ((int)Val < 0) Val = -Val;
// powi(x, 0) -> 1.0
if (Val == 0)
return DAG.getConstantFP(1.0, DL, LHS.getValueType());
bool OptForSize = DAG.shouldOptForSize();
if (!OptForSize ||
// If optimizing for size, don't insert too many multiplies.
// This inserts up to 5 multiplies.
countPopulation(Val) + Log2_32(Val) < 7) {
// We use the simple binary decomposition method to generate the multiply
// sequence. There are more optimal ways to do this (for example,
// powi(x,15) generates one more multiply than it should), but this has
// the benefit of being both really simple and much better than a libcall.
SDValue Res; // Logically starts equal to 1.0
SDValue CurSquare = LHS;
// TODO: Intrinsics should have fast-math-flags that propagate to these
// nodes.
while (Val) {
if (Val & 1) {
if (Res.getNode())
Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
else
Res = CurSquare; // 1.0*CurSquare.
}
CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
CurSquare, CurSquare);
Val >>= 1;
}
// If the original was negative, invert the result, producing 1/(x*x*x).
if (RHSC->getSExtValue() < 0)
Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
return Res;
}
}
// Otherwise, expand to a libcall.
return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
}
static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
SDValue LHS, SDValue RHS, SDValue Scale,
SelectionDAG &DAG, const TargetLowering &TLI) {
EVT VT = LHS.getValueType();
bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
LLVMContext &Ctx = *DAG.getContext();
// If the type is legal but the operation isn't, this node might survive all
// the way to operation legalization. If we end up there and we do not have
// the ability to widen the type (if VT*2 is not legal), we cannot expand the
// node.
// Coax the legalizer into expanding the node during type legalization instead
// by bumping the size by one bit. This will force it to Promote, enabling the
// early expansion and avoiding the need to expand later.
// We don't have to do this if Scale is 0; that can always be expanded, unless
// it's a saturating signed operation. Those can experience true integer
// division overflow, a case which we must avoid.
// FIXME: We wouldn't have to do this (or any of the early
// expansion/promotion) if it was possible to expand a libcall of an
// illegal type during operation legalization. But it's not, so things
// get a bit hacky.
unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
if ((ScaleInt > 0 || (Saturating && Signed)) &&
(TLI.isTypeLegal(VT) ||
(VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
Opcode, VT, ScaleInt);
if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
EVT PromVT;
if (VT.isScalarInteger())
PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
else if (VT.isVector()) {
PromVT = VT.getVectorElementType();
PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
} else
llvm_unreachable("Wrong VT for DIVFIX?");
if (Signed) {
LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
} else {
LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
}
EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
// For saturating operations, we need to shift up the LHS to get the
// proper saturation width, and then shift down again afterwards.
if (Saturating)
LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
DAG.getConstant(1, DL, ShiftTy));
SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
if (Saturating)
Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
DAG.getConstant(1, DL, ShiftTy));
return DAG.getZExtOrTrunc(Res, DL, VT);
}
}
return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
}
// getUnderlyingArgRegs - Find underlying registers used for a truncated,
// bitcasted, or split argument. Returns a list of <Register, size in bits>
static void
getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
const SDValue &N) {
switch (N.getOpcode()) {
case ISD::CopyFromReg: {
SDValue Op = N.getOperand(1);
Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
Op.getValueType().getSizeInBits());
return;
}
case ISD::BITCAST:
case ISD::AssertZext:
case ISD::AssertSext:
case ISD::TRUNCATE:
getUnderlyingArgRegs(Regs, N.getOperand(0));
return;
case ISD::BUILD_PAIR:
case ISD::BUILD_VECTOR:
case ISD::CONCAT_VECTORS:
for (SDValue Op : N->op_values())
getUnderlyingArgRegs(Regs, Op);
return;
default:
return;
}
}
/// If the DbgValueInst is a dbg_value of a function argument, create the
/// corresponding DBG_VALUE machine instruction for it now. At the end of
/// instruction selection, they will be inserted to the entry BB.
/// We don't currently support this for variadic dbg_values, as they shouldn't
/// appear for function arguments or in the prologue.
bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
const Value *V, DILocalVariable *Variable, DIExpression *Expr,
DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
const Argument *Arg = dyn_cast<Argument>(V);
if (!Arg)
return false;
if (!IsDbgDeclare) {
// ArgDbgValues are hoisted to the beginning of the entry block. So we
// should only emit as ArgDbgValue if the dbg.value intrinsic is found in
// the entry block.
bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
if (!IsInEntryBlock)
return false;
// ArgDbgValues are hoisted to the beginning of the entry block. So we
// should only emit as ArgDbgValue if the dbg.value intrinsic describes a
// variable that also is a param.
//
// Although, if we are at the top of the entry block already, we can still
// emit using ArgDbgValue. This might catch some situations when the
// dbg.value refers to an argument that isn't used in the entry block, so
// any CopyToReg node would be optimized out and the only way to express
// this DBG_VALUE is by using the physical reg (or FI) as done in this
// method. ArgDbgValues are hoisted to the beginning of the entry block. So
// we should only emit as ArgDbgValue if the Variable is an argument to the
// current function, and the dbg.value intrinsic is found in the entry
// block.
bool VariableIsFunctionInputArg = Variable->isParameter() &&
!DL->getInlinedAt();
bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
if (!IsInPrologue && !VariableIsFunctionInputArg)
return false;
// Here we assume that a function argument on IR level only can be used to
// describe one input parameter on source level. If we for example have
// source code like this
//
// struct A { long x, y; };
// void foo(struct A a, long b) {
// ...
// b = a.x;
// ...
// }
//
// and IR like this
//
// define void @foo(i32 %a1, i32 %a2, i32 %b) {
// entry:
// call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
// call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
// call void @llvm.dbg.value(metadata i32 %b, "b",
// ...
// call void @llvm.dbg.value(metadata i32 %a1, "b"
// ...
//
// then the last dbg.value is describing a parameter "b" using a value that
// is an argument. But since we already has used %a1 to describe a parameter
// we should not handle that last dbg.value here (that would result in an
// incorrect hoisting of the DBG_VALUE to the function entry).
// Notice that we allow one dbg.value per IR level argument, to accommodate
// for the situation with fragments above.
if (VariableIsFunctionInputArg) {
unsigned ArgNo = Arg->getArgNo();
if (ArgNo >= FuncInfo.DescribedArgs.size())
FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
return false;
FuncInfo.DescribedArgs.set(ArgNo);
}
}
MachineFunction &MF = DAG.getMachineFunction();
const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
bool IsIndirect = false;
Optional<MachineOperand> Op;
// Some arguments' frame index is recorded during argument lowering.
int FI = FuncInfo.getArgumentFrameIndex(Arg);
if (FI != std::numeric_limits<int>::max())
Op = MachineOperand::CreateFI(FI);
SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
if (!Op && N.getNode()) {
getUnderlyingArgRegs(ArgRegsAndSizes, N);
Register Reg;
if (ArgRegsAndSizes.size() == 1)
Reg = ArgRegsAndSizes.front().first;
if (Reg && Reg.isVirtual()) {
MachineRegisterInfo &RegInfo = MF.getRegInfo();
Register PR = RegInfo.getLiveInPhysReg(Reg);
if (PR)
Reg = PR;
}
if (Reg) {
Op = MachineOperand::CreateReg(Reg, false);
IsIndirect = IsDbgDeclare;
}
}
if (!Op && N.getNode()) {
// Check if frame index is available.
SDValue LCandidate = peekThroughBitcasts(N);
if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
if (FrameIndexSDNode *FINode =
dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
Op = MachineOperand::CreateFI(FINode->getIndex());
}
if (!Op) {
// Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
SplitRegs) {
unsigned Offset = 0;
for (auto RegAndSize : SplitRegs) {
// If the expression is already a fragment, the current register
// offset+size might extend beyond the fragment. In this case, only
// the register bits that are inside the fragment are relevant.
int RegFragmentSizeInBits = RegAndSize.second;
if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
// The register is entirely outside the expression fragment,
// so is irrelevant for debug info.
if (Offset >= ExprFragmentSizeInBits)
break;
// The register is partially outside the expression fragment, only
// the low bits within the fragment are relevant for debug info.
if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
}
}
auto FragmentExpr = DIExpression::createFragmentExpression(
Expr, Offset, RegFragmentSizeInBits);
Offset += RegAndSize.second;
// If a valid fragment expression cannot be created, the variable's
// correct value cannot be determined and so it is set as Undef.
if (!FragmentExpr) {
SDDbgValue *SDV = DAG.getConstantDbgValue(
Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
DAG.AddDbgValue(SDV, false);
continue;
}
assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
FuncInfo.ArgDbgValues.push_back(
BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
RegAndSize.first, Variable, *FragmentExpr));
}
};
// Check if ValueMap has reg number.
DenseMap<const Value *, Register>::const_iterator
VMI = FuncInfo.ValueMap.find(V);
if (VMI != FuncInfo.ValueMap.end()) {
const auto &TLI = DAG.getTargetLoweringInfo();
RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
V->getType(), None);
if (RFV.occupiesMultipleRegs()) {
splitMultiRegDbgValue(RFV.getRegsAndSizes());
return true;
}
Op = MachineOperand::CreateReg(VMI->second, false);
IsIndirect = IsDbgDeclare;
} else if (ArgRegsAndSizes.size() > 1) {
// This was split due to the calling convention, and no virtual register
// mapping exists for the value.
splitMultiRegDbgValue(ArgRegsAndSizes);
return true;
}
}
if (!Op)
return false;
assert(Variable->isValidLocationForIntrinsic(DL) &&
"Expected inlined-at fields to agree");
IsIndirect = (Op->isReg()) ? IsIndirect : true;
FuncInfo.ArgDbgValues.push_back(
BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
*Op, Variable, Expr));
return true;
}
/// Return the appropriate SDDbgValue based on N.
SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
DILocalVariable *Variable,
DIExpression *Expr,
const DebugLoc &dl,
unsigned DbgSDNodeOrder) {
if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
// Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
// stack slot locations.
//
// Consider "int x = 0; int *px = &x;". There are two kinds of interesting
// debug values here after optimization:
//
// dbg.value(i32* %px, !"int *px", !DIExpression()), and
// dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
//
// Both describe the direct values of their associated variables.
return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
/*IsIndirect*/ false, dl, DbgSDNodeOrder);
}
return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
/*IsIndirect*/ false, dl, DbgSDNodeOrder);
}
static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
switch (Intrinsic) {
case Intrinsic::smul_fix:
return ISD::SMULFIX;
case Intrinsic::umul_fix:
return ISD::UMULFIX;
case Intrinsic::smul_fix_sat:
return ISD::SMULFIXSAT;
case Intrinsic::umul_fix_sat:
return ISD::UMULFIXSAT;
case Intrinsic::sdiv_fix:
return ISD::SDIVFIX;
case Intrinsic::udiv_fix:
return ISD::UDIVFIX;
case Intrinsic::sdiv_fix_sat:
return ISD::SDIVFIXSAT;
case Intrinsic::udiv_fix_sat:
return ISD::UDIVFIXSAT;
default:
llvm_unreachable("Unhandled fixed point intrinsic");
}
}
void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
const char *FunctionName) {
assert(FunctionName && "FunctionName must not be nullptr");
SDValue Callee = DAG.getExternalSymbol(
FunctionName,
DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
LowerCallTo(I, Callee, I.isTailCall());
}
/// Given a @llvm.call.preallocated.setup, return the corresponding
/// preallocated call.
static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
assert(cast<CallBase>(PreallocatedSetup)
->getCalledFunction()
->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
"expected call_preallocated_setup Value");
for (auto *U : PreallocatedSetup->users()) {
auto *UseCall = cast<CallBase>(U);
const Function *Fn = UseCall->getCalledFunction();
if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
return UseCall;
}
}
llvm_unreachable("expected corresponding call to preallocated setup/arg");
}
/// Lower the call to the specified intrinsic function.
void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
unsigned Intrinsic) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SDLoc sdl = getCurSDLoc();
DebugLoc dl = getCurDebugLoc();
SDValue Res;
SDNodeFlags Flags;
if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
Flags.copyFMF(*FPOp);
switch (Intrinsic) {
default:
// By default, turn this into a target intrinsic node.
visitTargetIntrinsic(I, Intrinsic);
return;
case Intrinsic::vscale: {
match(&I, m_VScale(DAG.getDataLayout()));
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
setValue(&I,
DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
return;
}
case Intrinsic::vastart: visitVAStart(I); return;
case Intrinsic::vaend: visitVAEnd(I); return;
case Intrinsic::vacopy: visitVACopy(I); return;
case Intrinsic::returnaddress:
setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
TLI.getPointerTy(DAG.getDataLayout()),
getValue(I.getArgOperand(0))));
return;
case Intrinsic::addressofreturnaddress:
setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
TLI.getPointerTy(DAG.getDataLayout())));
return;
case Intrinsic::sponentry:
setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
TLI.getFrameIndexTy(DAG.getDataLayout())));
return;
case Intrinsic::frameaddress:
setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
TLI.getFrameIndexTy(DAG.getDataLayout()),
getValue(I.getArgOperand(0))));
return;
case Intrinsic::read_volatile_register:
case Intrinsic::read_register: {
Value *Reg = I.getArgOperand(0);
SDValue Chain = getRoot();
SDValue RegName =
DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
Res = DAG.getNode(ISD::READ_REGISTER, sdl,
DAG.getVTList(VT, MVT::Other), Chain, RegName);
setValue(&I, Res);
DAG.setRoot(Res.getValue(1));
return;
}
case Intrinsic::write_register: {
Value *Reg = I.getArgOperand(0);
Value *RegValue = I.getArgOperand(1);
SDValue Chain = getRoot();
SDValue RegName =
DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
RegName, getValue(RegValue)));
return;
}
case Intrinsic::memcpy: {
const auto &MCI = cast<MemCpyInst>(I);
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
SDValue Op3 = getValue(I.getArgOperand(2));
// @llvm.memcpy defines 0 and 1 to both mean no alignment.
Align DstAlign = MCI.getDestAlign().valueOrOne();
Align SrcAlign = MCI.getSourceAlign().valueOrOne();
Align Alignment = commonAlignment(DstAlign, SrcAlign);
bool isVol = MCI.isVolatile();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
// FIXME: Support passing different dest/src alignments to the memcpy DAG
// node.
SDValue Root = isVol ? getRoot() : getMemoryRoot();
SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
/* AlwaysInline */ false, isTC,
MachinePointerInfo(I.getArgOperand(0)),
MachinePointerInfo(I.getArgOperand(1)));
updateDAGForMaybeTailCall(MC);
return;
}
case Intrinsic::memcpy_inline: {
const auto &MCI = cast<MemCpyInlineInst>(I);
SDValue Dst = getValue(I.getArgOperand(0));
SDValue Src = getValue(I.getArgOperand(1));
SDValue Size = getValue(I.getArgOperand(2));
assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
// @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
Align DstAlign = MCI.getDestAlign().valueOrOne();
Align SrcAlign = MCI.getSourceAlign().valueOrOne();
Align Alignment = commonAlignment(DstAlign, SrcAlign);
bool isVol = MCI.isVolatile();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
// FIXME: Support passing different dest/src alignments to the memcpy DAG
// node.
SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
/* AlwaysInline */ true, isTC,
MachinePointerInfo(I.getArgOperand(0)),
MachinePointerInfo(I.getArgOperand(1)));
updateDAGForMaybeTailCall(MC);
return;
}
case Intrinsic::memset: {
const auto &MSI = cast<MemSetInst>(I);
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
SDValue Op3 = getValue(I.getArgOperand(2));
// @llvm.memset defines 0 and 1 to both mean no alignment.
Align Alignment = MSI.getDestAlign().valueOrOne();
bool isVol = MSI.isVolatile();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
SDValue Root = isVol ? getRoot() : getMemoryRoot();
SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
MachinePointerInfo(I.getArgOperand(0)));
updateDAGForMaybeTailCall(MS);
return;
}
case Intrinsic::memmove: {
const auto &MMI = cast<MemMoveInst>(I);
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
SDValue Op3 = getValue(I.getArgOperand(2));
// @llvm.memmove defines 0 and 1 to both mean no alignment.
Align DstAlign = MMI.getDestAlign().valueOrOne();
Align SrcAlign = MMI.getSourceAlign().valueOrOne();
Align Alignment = commonAlignment(DstAlign, SrcAlign);
bool isVol = MMI.isVolatile();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
// FIXME: Support passing different dest/src alignments to the memmove DAG
// node.
SDValue Root = isVol ? getRoot() : getMemoryRoot();
SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
isTC, MachinePointerInfo(I.getArgOperand(0)),
MachinePointerInfo(I.getArgOperand(1)));
updateDAGForMaybeTailCall(MM);
return;
}
case Intrinsic::memcpy_element_unordered_atomic: {
const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
SDValue Dst = getValue(MI.getRawDest());
SDValue Src = getValue(MI.getRawSource());
SDValue Length = getValue(MI.getLength());
unsigned DstAlign = MI.getDestAlignment();
unsigned SrcAlign = MI.getSourceAlignment();
Type *LengthTy = MI.getLength()->getType();
unsigned ElemSz = MI.getElementSizeInBytes();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
SrcAlign, Length, LengthTy, ElemSz, isTC,
MachinePointerInfo(MI.getRawDest()),
MachinePointerInfo(MI.getRawSource()));
updateDAGForMaybeTailCall(MC);
return;
}
case Intrinsic::memmove_element_unordered_atomic: {
auto &MI = cast<AtomicMemMoveInst>(I);
SDValue Dst = getValue(MI.getRawDest());
SDValue Src = getValue(MI.getRawSource());
SDValue Length = getValue(MI.getLength());
unsigned DstAlign = MI.getDestAlignment();
unsigned SrcAlign = MI.getSourceAlignment();
Type *LengthTy = MI.getLength()->getType();
unsigned ElemSz = MI.getElementSizeInBytes();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
SrcAlign, Length, LengthTy, ElemSz, isTC,
MachinePointerInfo(MI.getRawDest()),
MachinePointerInfo(MI.getRawSource()));
updateDAGForMaybeTailCall(MC);
return;
}
case Intrinsic::memset_element_unordered_atomic: {
auto &MI = cast<AtomicMemSetInst>(I);
SDValue Dst = getValue(MI.getRawDest());
SDValue Val = getValue(MI.getValue());
SDValue Length = getValue(MI.getLength());
unsigned DstAlign = MI.getDestAlignment();
Type *LengthTy = MI.getLength()->getType();
unsigned ElemSz = MI.getElementSizeInBytes();
bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
LengthTy, ElemSz, isTC,
MachinePointerInfo(MI.getRawDest()));
updateDAGForMaybeTailCall(MC);
return;
}
case Intrinsic::call_preallocated_setup: {
const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
getRoot(), SrcValue);
setValue(&I, Res);
DAG.setRoot(Res);
return;
}
case Intrinsic::call_preallocated_arg: {
const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
SDValue Ops[3];
Ops[0] = getRoot();
Ops[1] = SrcValue;
Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
MVT::i32); // arg index
SDValue Res = DAG.getNode(
ISD::PREALLOCATED_ARG, sdl,
DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
setValue(&I, Res);
DAG.setRoot(Res.getValue(1));
return;
}
case Intrinsic::dbg_addr:
case Intrinsic::dbg_declare: {
// Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
// they are non-variadic.
const auto &DI = cast<DbgVariableIntrinsic>(I);
assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
DILocalVariable *Variable = DI.getVariable();
DIExpression *Expression = DI.getExpression();
dropDanglingDebugInfo(Variable, Expression);
assert(Variable && "Missing variable");
LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
<< "\n");
// Check if address has undef value.
const Value *Address = DI.getVariableLocationOp(0);
if (!Address || isa<UndefValue>(Address) ||
(Address->use_empty() && !isa<Argument>(Address))) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
<< " (bad/undef/unused-arg address)\n");
return;
}
bool isParameter = Variable->isParameter() || isa<Argument>(Address);
// Check if this variable can be described by a frame index, typically
// either as a static alloca or a byval parameter.
int FI = std::numeric_limits<int>::max();
if (const auto *AI =
dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
if (AI->isStaticAlloca()) {
auto I = FuncInfo.StaticAllocaMap.find(AI);
if (I != FuncInfo.StaticAllocaMap.end())
FI = I->second;
}
} else if (const auto *Arg = dyn_cast<Argument>(
Address->stripInBoundsConstantOffsets())) {
FI = FuncInfo.getArgumentFrameIndex(Arg);
}
// llvm.dbg.addr is control dependent and always generates indirect
// DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
// the MachineFunction variable table.
if (FI != std::numeric_limits<int>::max()) {
if (Intrinsic == Intrinsic::dbg_addr) {
SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
dl, SDNodeOrder);
DAG.AddDbgValue(SDV, isParameter);
} else {
LLVM_DEBUG(dbgs() << "Skipping " << DI
<< " (variable info stashed in MF side table)\n");
}
return;
}
SDValue &N = NodeMap[Address];
if (!N.getNode() && isa<Argument>(Address))
// Check unused arguments map.
N = UnusedArgNodeMap[Address];
SDDbgValue *SDV;
if (N.getNode()) {
if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
Address = BCI->getOperand(0);
// Parameters are handled specially.
auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
if (isParameter && FINode) {
// Byval parameter. We have a frame index at this point.
SDV =
DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
/*IsIndirect*/ true, dl, SDNodeOrder);
} else if (isa<Argument>(Address)) {
// Address is an argument, so try to emit its dbg value using
// virtual register info from the FuncInfo.ValueMap.
EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
return;
} else {
SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
true, dl, SDNodeOrder);
}
DAG.AddDbgValue(SDV, isParameter);
} else {
// If Address is an argument then try to emit its dbg value using
// virtual register info from the FuncInfo.ValueMap.
if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
N)) {
LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
<< " (could not emit func-arg dbg_value)\n");
}
}
return;
}
case Intrinsic::dbg_label: {
const DbgLabelInst &DI = cast<DbgLabelInst>(I);
DILabel *Label = DI.getLabel();
assert(Label && "Missing label");
SDDbgLabel *SDV;
SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
DAG.AddDbgLabel(SDV);
return;
}
case Intrinsic::dbg_value: {
const DbgValueInst &DI = cast<DbgValueInst>(I);
assert(DI.getVariable() && "Missing variable");
DILocalVariable *Variable = DI.getVariable();
DIExpression *Expression = DI.getExpression();
dropDanglingDebugInfo(Variable, Expression);
SmallVector<Value *, 4> Values(DI.getValues());
if (Values.empty())
return;
if (std::count(Values.begin(), Values.end(), nullptr))
return;
bool IsVariadic = DI.hasArgList();
if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
SDNodeOrder, IsVariadic))
addDanglingDebugInfo(&DI, dl, SDNodeOrder);
return;
}
case Intrinsic::eh_typeid_for: {
// Find the type id for the given typeinfo.
GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
Res = DAG.getConstant(TypeID, sdl, MVT::i32);
setValue(&I, Res);
return;
}
case Intrinsic::eh_return_i32:
case Intrinsic::eh_return_i64:
DAG.getMachineFunction().setCallsEHReturn(true);
DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
MVT::Other,
getControlRoot(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1))));
return;
case Intrinsic::eh_unwind_init:
DAG.getMachineFunction().setCallsUnwindInit(true);
return;
case Intrinsic::eh_dwarf_cfa:
setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
TLI.getPointerTy(DAG.getDataLayout()),
getValue(I.getArgOperand(0))));
return;
case Intrinsic::eh_sjlj_callsite: {
MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
MMI.setCurrentCallSite(CI->getZExtValue());
return;
}
case Intrinsic::eh_sjlj_functioncontext: {
// Get and store the index of the function context.
MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
AllocaInst *FnCtx =
cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
int FI = FuncInfo.StaticAllocaMap[FnCtx];
MFI.setFunctionContextIndex(FI);
return;
}
case Intrinsic::eh_sjlj_setjmp: {
SDValue Ops[2];
Ops[0] = getRoot();
Ops[1] = getValue(I.getArgOperand(0));
SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
DAG.getVTList(MVT::i32, MVT::Other), Ops);
setValue(&I, Op.getValue(0));
DAG.setRoot(Op.getValue(1));
return;
}
case Intrinsic::eh_sjlj_longjmp:
DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
getRoot(), getValue(I.getArgOperand(0))));
return;
case Intrinsic::eh_sjlj_setup_dispatch:
DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
getRoot()));
return;
case Intrinsic::masked_gather:
visitMaskedGather(I);
return;
case Intrinsic::masked_load:
visitMaskedLoad(I);
return;
case Intrinsic::masked_scatter:
visitMaskedScatter(I);
return;
case Intrinsic::masked_store:
visitMaskedStore(I);
return;
case Intrinsic::masked_expandload:
visitMaskedLoad(I, true /* IsExpanding */);
return;
case Intrinsic::masked_compressstore:
visitMaskedStore(I, true /* IsCompressing */);
return;
case Intrinsic::powi:
setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), DAG));
return;
case Intrinsic::log:
setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
return;
case Intrinsic::log2:
setValue(&I,
expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
return;
case Intrinsic::log10:
setValue(&I,
expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
return;
case Intrinsic::exp:
setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
return;
case Intrinsic::exp2:
setValue(&I,
expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
return;
case Intrinsic::pow:
setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), DAG, TLI, Flags));
return;
case Intrinsic::sqrt:
case Intrinsic::fabs:
case Intrinsic::sin:
case Intrinsic::cos:
case Intrinsic::floor:
case Intrinsic::ceil:
case Intrinsic::trunc:
case Intrinsic::rint:
case Intrinsic::nearbyint:
case Intrinsic::round:
case Intrinsic::roundeven:
case Intrinsic::canonicalize: {
unsigned Opcode;
switch (Intrinsic) {
default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
case Intrinsic::fabs: Opcode = ISD::FABS; break;
case Intrinsic::sin: Opcode = ISD::FSIN; break;
case Intrinsic::cos: Opcode = ISD::FCOS; break;
case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
case Intrinsic::rint: Opcode = ISD::FRINT; break;
case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
case Intrinsic::round: Opcode = ISD::FROUND; break;
case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
}
setValue(&I, DAG.getNode(Opcode, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)), Flags));
return;
}
case Intrinsic::lround:
case Intrinsic::llround:
case Intrinsic::lrint:
case Intrinsic::llrint: {
unsigned Opcode;
switch (Intrinsic) {
default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
case Intrinsic::lround: Opcode = ISD::LROUND; break;
case Intrinsic::llround: Opcode = ISD::LLROUND; break;
case Intrinsic::lrint: Opcode = ISD::LRINT; break;
case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
}
EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
getValue(I.getArgOperand(0))));
return;
}
case Intrinsic::minnum:
setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), Flags));
return;
case Intrinsic::maxnum:
setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), Flags));
return;
case Intrinsic::minimum:
setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), Flags));
return;
case Intrinsic::maximum:
setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), Flags));
return;
case Intrinsic::copysign:
setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), Flags));
return;
case Intrinsic::fma:
setValue(&I, DAG.getNode(
ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
getValue(I.getArgOperand(2)), Flags));
return;
#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
case Intrinsic::INTRINSIC:
#include "llvm/IR/ConstrainedOps.def"
visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
return;
#define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
#include "llvm/IR/VPIntrinsics.def"
visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
return;
case Intrinsic::fmuladd: {
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
setValue(&I, DAG.getNode(ISD::FMA, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)),
getValue(I.getArgOperand(2)), Flags));
} else {
// TODO: Intrinsic calls should have fast-math-flags.
SDValue Mul = DAG.getNode(
ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
SDValue Add = DAG.getNode(ISD::FADD, sdl,
getValue(I.getArgOperand(0)).getValueType(),
Mul, getValue(I.getArgOperand(2)), Flags);
setValue(&I, Add);
}
return;
}
case Intrinsic::convert_to_fp16:
setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
getValue(I.getArgOperand(0)),
DAG.getTargetConstant(0, sdl,
MVT::i32))));
return;
case Intrinsic::convert_from_fp16:
setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
TLI.getValueType(DAG.getDataLayout(), I.getType()),
DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
getValue(I.getArgOperand(0)))));
return;
case Intrinsic::fptosi_sat: {
EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type,
getValue(I.getArgOperand(0)), SatW));
return;
}
case Intrinsic::fptoui_sat: {
EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type,
getValue(I.getArgOperand(0)), SatW));
return;
}
case Intrinsic::set_rounding:
Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
{getRoot(), getValue(I.getArgOperand(0))});
setValue(&I, Res);
DAG.setRoot(Res.getValue(0));
return;
case Intrinsic::pcmarker: {
SDValue Tmp = getValue(I.getArgOperand(0));
DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
return;
}
case Intrinsic::readcyclecounter: {
SDValue Op = getRoot();
Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
DAG.getVTList(MVT::i64, MVT::Other), Op);
setValue(&I, Res);
DAG.setRoot(Res.getValue(1));
return;
}
case Intrinsic::bitreverse:
setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0))));
return;
case Intrinsic::bswap:
setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
getValue(I.getArgOperand(0)).getValueType(),
getValue(I.getArgOperand(0))));
return;
case Intrinsic::cttz: {
SDValue Arg = getValue(I.getArgOperand(0));
ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
EVT Ty = Arg.getValueType();
setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
sdl, Ty, Arg));
return;
}
case Intrinsic::ctlz: {
SDValue Arg = getValue(I.getArgOperand(0));
ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
EVT Ty = Arg.getValueType();
setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
sdl, Ty, Arg));
return;
}
case Intrinsic::ctpop: {
SDValue Arg = getValue(I.getArgOperand(0));
EVT Ty = Arg.getValueType();
setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
return;
}
case Intrinsic::fshl:
case Intrinsic::fshr: {
bool IsFSHL = Intrinsic == Intrinsic::fshl;
SDValue X = getValue(I.getArgOperand(0));
SDValue Y = getValue(I.getArgOperand(1));
SDValue Z = getValue(I.getArgOperand(2));
EVT VT = X.getValueType();
if (X == Y) {
auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
} else {
auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
}
return;
}
case Intrinsic::sadd_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::uadd_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::ssub_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::usub_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::sshl_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::ushl_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::smul_fix:
case Intrinsic::umul_fix:
case Intrinsic::smul_fix_sat:
case Intrinsic::umul_fix_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
SDValue Op3 = getValue(I.getArgOperand(2));
setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
Op1.getValueType(), Op1, Op2, Op3));
return;
}
case Intrinsic::sdiv_fix:
case Intrinsic::udiv_fix:
case Intrinsic::sdiv_fix_sat:
case Intrinsic::udiv_fix_sat: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
SDValue Op3 = getValue(I.getArgOperand(2));
setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
Op1, Op2, Op3, DAG, TLI));
return;
}
case Intrinsic::smax: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::smin: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::umax: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::umin: {
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
return;
}
case Intrinsic::abs: {
// TODO: Preserve "int min is poison" arg in SDAG?
SDValue Op1 = getValue(I.getArgOperand(0));
setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
return;
}
case Intrinsic::stacksave: {
SDValue Op = getRoot();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
setValue(&I, Res);
DAG.setRoot(Res.getValue(1));
return;
}
case Intrinsic::stackrestore:
Res = getValue(I.getArgOperand(0));
DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
return;
case Intrinsic::get_dynamic_area_offset: {
SDValue Op = getRoot();
EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
// Result type for @llvm.get.dynamic.area.offset should match PtrTy for
// target.
if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
" intrinsic!");
Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
Op);
DAG.setRoot(Op);
setValue(&I, Res);
return;
}
case Intrinsic::stackguard: {
MachineFunction &MF = DAG.getMachineFunction();
const Module &M = *MF.getFunction().getParent();
SDValue Chain = getRoot();
if (TLI.useLoadStackGuardNode()) {
Res = getLoadStackGuard(DAG, sdl, Chain);
} else {
EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
const Value *Global = TLI.getSDagStackGuard(M);
Align Align = DL->getPrefTypeAlign(Global->getType());
Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
MachinePointerInfo(Global, 0), Align,
MachineMemOperand::MOVolatile);
}
if (TLI.useStackGuardXorFP())
Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
DAG.setRoot(Chain);
setValue(&I, Res);
return;
}
case Intrinsic::stackprotector: {
// Emit code into the DAG to store the stack guard onto the stack.
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo &MFI = MF.getFrameInfo();
SDValue Src, Chain = getRoot();
if (TLI.useLoadStackGuardNode())
Src = getLoadStackGuard(DAG, sdl, Chain);
else
Src = getValue(I.getArgOperand(0)); // The guard's value.
AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
int FI = FuncInfo.StaticAllocaMap[Slot];
MFI.setStackProtectorIndex(FI);
EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
// Store the stack protector onto the stack.
Res = DAG.getStore(
Chain, sdl, Src, FIN,
MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
MaybeAlign(), MachineMemOperand::MOVolatile);
setValue(&I, Res);
DAG.setRoot(Res);
return;
}
case Intrinsic::objectsize:
llvm_unreachable("llvm.objectsize.* should have been lowered already");
case Intrinsic::is_constant:
llvm_unreachable("llvm.is.constant.* should have been lowered already");
case Intrinsic::annotation:
case Intrinsic::ptr_annotation:
case Intrinsic::launder_invariant_group:
case Intrinsic::strip_invariant_group:
// Drop the intrinsic, but forward the value
setValue(&I, getValue(I.getOperand(0)));
return;
case Intrinsic::assume:
case Intrinsic::experimental_noalias_scope_decl:
case Intrinsic::var_annotation:
case Intrinsic::sideeffect:
// Discard annotate attributes, noalias scope declarations, assumptions, and
// artificial side-effects.
return;
case Intrinsic::codeview_annotation: {
// Emit a label associated with this metadata.
MachineFunction &MF = DAG.getMachineFunction();
MCSymbol *Label =
MF.getMMI().getContext().createTempSymbol("annotation", true);
Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
DAG.setRoot(Res);
return;
}
case Intrinsic::init_trampoline: {
const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
SDValue Ops[6];
Ops[0] = getRoot();
Ops[1] = getValue(I.getArgOperand(0));
Ops[2] = getValue(I.getArgOperand(1));
Ops[3] = getValue(I.getArgOperand(2));
Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Ops[5] = DAG.getSrcValue(F);
Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
DAG.setRoot(Res);
return;
}
case Intrinsic::adjust_trampoline:
setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
TLI.getPointerTy(DAG.getDataLayout()),
getValue(I.getArgOperand(0))));
return;
case Intrinsic::gcroot: {
assert(DAG.getMachineFunction().getFunction().hasGC() &&
"only valid in functions with gc specified, enforced by Verifier");
assert(GFI && "implied by previous");
const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
GFI->addStackRoot(FI->getIndex(), TypeMap);
return;
}
case Intrinsic::gcread:
case Intrinsic::gcwrite:
llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
case Intrinsic::flt_rounds:
Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
setValue(&I, Res);
DAG.setRoot(Res.getValue(1));
return;
case Intrinsic::expect:
// Just replace __builtin_expect(exp, c) with EXP.
setValue(&I, getValue(I.getArgOperand(0)));
return;
case Intrinsic::ubsantrap:
case Intrinsic::debugtrap:
case Intrinsic::trap: {
StringRef TrapFuncName =
I.getAttributes()
.getAttribute(AttributeList::FunctionIndex, "trap-func-name")
.getValueAsString();
if (TrapFuncName.empty()) {
switch (Intrinsic) {
case Intrinsic::trap:
DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
break;
case Intrinsic::debugtrap:
DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
break;
case Intrinsic::ubsantrap:
DAG.setRoot(DAG.getNode(
ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
DAG.getTargetConstant(
cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
MVT::i32)));
break;
default: llvm_unreachable("unknown trap intrinsic");
}
return;
}
TargetLowering::ArgListTy Args;
if (Intrinsic == Intrinsic::ubsantrap) {
Args.push_back(TargetLoweringBase::ArgListEntry());
Args[0].Val = I.getArgOperand(0);
Args[0].Node = getValue(Args[0].Val);
Args[0].Ty = Args[0].Val->getType();
}
TargetLowering::CallLoweringInfo CLI(DAG);
CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
CallingConv::C, I.getType(),
DAG.getExternalSymbol(TrapFuncName.data(),
TLI.getPointerTy(DAG.getDataLayout())),
std::move(Args));
std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
DAG.setRoot(Result.second);
return;
}
case Intrinsic::uadd_with_overflow:
case Intrinsic::sadd_with_overflow:
case Intrinsic::usub_with_overflow:
case Intrinsic::ssub_with_overflow:
case Intrinsic::umul_with_overflow:
case Intrinsic::smul_with_overflow: {
ISD::NodeType Op;
switch (Intrinsic) {
default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
}
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2 = getValue(I.getArgOperand(1));
EVT ResultVT = Op1.getValueType();
EVT OverflowVT = MVT::i1;
if (ResultVT.isVector())
OverflowVT = EVT::getVectorVT(
*Context, OverflowVT, ResultVT.getVectorElementCount());
SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
return;
}
case Intrinsic::prefetch: {
SDValue Ops[5];
unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
Ops[0] = DAG.getRoot();
Ops[1] = getValue(I.getArgOperand(0));
Ops[2] = getValue(I.getArgOperand(1));
Ops[3] = getValue(I.getArgOperand(2));
Ops[4] = getValue(I.getArgOperand(3));
SDValue Result = DAG.getMemIntrinsicNode(
ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
/* align */ None, Flags);
// Chain the prefetch in parallell with any pending loads, to stay out of
// the way of later optimizations.
PendingLoads.push_back(Result);
Result = getRoot();
DAG.setRoot(Result);
return;
}
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end: {
bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
// Stack coloring is not enabled in O0, discard region information.
if (TM.getOptLevel() == CodeGenOpt::None)
return;
const int64_t ObjectSize =
cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
Value *const ObjectPtr = I.getArgOperand(1);
SmallVector<const Value *, 4> Allocas;
getUnderlyingObjects(ObjectPtr, Allocas);
for (const Value *Alloca : Allocas) {
const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
// Could not find an Alloca.
if (!LifetimeObject)
continue;
// First check that the Alloca is static, otherwise it won't have a
// valid frame index.
auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
if (SI == FuncInfo.StaticAllocaMap.end())
return;
const int FrameIndex = SI->second;
int64_t Offset;
if (GetPointerBaseWithConstantOffset(
ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
Offset = -1; // Cannot determine offset from alloca to lifetime object.
Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
Offset);
DAG.setRoot(Res);
}
return;
}
case Intrinsic::pseudoprobe: {
auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
DAG.setRoot(Res);
return;
}
case Intrinsic::invariant_start:
// Discard region information.
setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
return;
case Intrinsic::invariant_end:
// Discard region information.
return;
case Intrinsic::clear_cache:
/// FunctionName may be null.
if (const char *FunctionName = TLI.getClearCacheBuiltinName())
lowerCallToExternalSymbol(I, FunctionName);
return;
case Intrinsic::donothing:
// ignore
return;
case Intrinsic::experimental_stackmap:
visitStackmap(I);
return;
case Intrinsic::experimental_patchpoint_void:
case Intrinsic::experimental_patchpoint_i64:
visitPatchpoint(I);
return;
case Intrinsic::experimental_gc_statepoint:
LowerStatepoint(cast<GCStatepointInst>(I));
return;
case Intrinsic::experimental_gc_result:
visitGCResult(cast<GCResultInst>(I));
return;
case Intrinsic::experimental_gc_relocate:
visitGCRelocate(cast<GCRelocateInst>(I));
return;
case Intrinsic::instrprof_increment:
llvm_unreachable("instrprof failed to lower an increment");
case Intrinsic::instrprof_value_profile:
llvm_unreachable("instrprof failed to lower a value profiling call");
case Intrinsic::localescape: {
MachineFunction &MF = DAG.getMachineFunction();
const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
// Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
// is the same on all targets.
for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
if (isa<ConstantPointerNull>(Arg))
continue; // Skip null pointers. They represent a hole in index space.
AllocaInst *Slot = cast<AllocaInst>(Arg);
assert(FuncInfo.StaticAllocaMap.count(Slot) &&
"can only escape static allocas");
int FI = FuncInfo.StaticAllocaMap[Slot];
MCSymbol *FrameAllocSym =
MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
TII->get(TargetOpcode::LOCAL_ESCAPE))
.addSym(FrameAllocSym)
.addFrameIndex(FI);
}
return;
}
case Intrinsic::localrecover: {
// i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
MachineFunction &MF = DAG.getMachineFunction();
// Get the symbol that defines the frame offset.
auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
unsigned IdxVal =
unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
MCSymbol *FrameAllocSym =
MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
Value *FP = I.getArgOperand(1);
SDValue FPVal = getValue(FP);
EVT PtrVT = FPVal.getValueType();
// Create a MCSymbol for the label to avoid any target lowering
// that would make this PC relative.
SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
SDValue OffsetVal =
DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
// Add the offset to the FP.
SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
setValue(&I, Add);
return;
}
case Intrinsic::eh_exceptionpointer:
case Intrinsic::eh_exceptioncode: {
// Get the exception pointer vreg, copy from it, and resize it to fit.
const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
SDValue N =
DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
if (Intrinsic == Intrinsic::eh_exceptioncode)
N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
setValue(&I, N);
return;
}
case Intrinsic::xray_customevent: {
// Here we want to make sure that the intrinsic behaves as if it has a
// specific calling convention, and only for x86_64.
// FIXME: Support other platforms later.
const auto &Triple = DAG.getTarget().getTargetTriple();
if (Triple.getArch() != Triple::x86_64)
return;
SDLoc DL = getCurSDLoc();
SmallVector<SDValue, 8> Ops;
// We want to say that we always want the arguments in registers.
SDValue LogEntryVal = getValue(I.getArgOperand(0));
SDValue StrSizeVal = getValue(I.getArgOperand(1));
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue Chain = getRoot();
Ops.push_back(LogEntryVal);
Ops.push_back(StrSizeVal);
Ops.push_back(Chain);
// We need to enforce the calling convention for the callsite, so that
// argument ordering is enforced correctly, and that register allocation can
// see that some registers may be assumed clobbered and have to preserve
// them across calls to the intrinsic.
MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
DL, NodeTys, Ops);
SDValue patchableNode = SDValue(MN, 0);
DAG.setRoot(patchableNode);
setValue(&I, patchableNode);
return;
}
case Intrinsic::xray_typedevent: {
// Here we want to make sure that the intrinsic behaves as if it has a
// specific calling convention, and only for x86_64.
// FIXME: Support other platforms later.
const auto &Triple = DAG.getTarget().getTargetTriple();
if (Triple.getArch() != Triple::x86_64)
return;
SDLoc DL = getCurSDLoc();
SmallVector<SDValue, 8> Ops;
// We want to say that we always want the arguments in registers.
// It's unclear to me how manipulating the selection DAG here forces callers
// to provide arguments in registers instead of on the stack.
SDValue LogTypeId = getValue(I.getArgOperand(0));
SDValue LogEntryVal = getValue(I.getArgOperand(1));
SDValue StrSizeVal = getValue(I.getArgOperand(2));
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue Chain = getRoot();
Ops.push_back(LogTypeId);
Ops.push_back(LogEntryVal);
Ops.push_back(StrSizeVal);
Ops.push_back(Chain);
// We need to enforce the calling convention for the callsite, so that
// argument ordering is enforced correctly, and that register allocation can
// see that some registers may be assumed clobbered and have to preserve
// them across calls to the intrinsic.
MachineSDNode *MN = DAG.getMachineNode(
TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
SDValue patchableNode = SDValue(MN, 0);
DAG.setRoot(patchableNode);
setValue(&I, patchableNode);
return;
}
case Intrinsic::experimental_deoptimize:
LowerDeoptimizeCall(&I);
return;
case Intrinsic::vector_reduce_fadd:
case Intrinsic::vector_reduce_fmul:
case Intrinsic::vector_reduce_add:
case Intrinsic::vector_reduce_mul:
case Intrinsic::vector_reduce_and:
case Intrinsic::vector_reduce_or:
case Intrinsic::vector_reduce_xor:
case Intrinsic::vector_reduce_smax:
case Intrinsic::vector_reduce_smin:
case Intrinsic::vector_reduce_umax:
case Intrinsic::vector_reduce_umin:
case Intrinsic::vector_reduce_fmax:
case Intrinsic::vector_reduce_fmin:
visitVectorReduce(I, Intrinsic);
return;
case Intrinsic::icall_branch_funnel: {
SmallVector<SDValue, 16> Ops;
Ops.push_back(getValue(I.getArgOperand(0)));
int64_t Offset;
auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
I.getArgOperand(1), Offset, DAG.getDataLayout()));
if (!Base)
report_fatal_error(
"llvm.icall.branch.funnel operand must be a GlobalValue");
Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
struct BranchFunnelTarget {
int64_t Offset;
SDValue Target;
};
SmallVector<BranchFunnelTarget, 8> Targets;
for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
I.getArgOperand(Op), Offset, DAG.getDataLayout()));
if (ElemBase != Base)
report_fatal_error("all llvm.icall.branch.funnel operands must refer "
"to the same GlobalValue");
SDValue Val = getValue(I.getArgOperand(Op + 1));
auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
if (!GA)
report_fatal_error(
"llvm.icall.branch.funnel operand must be a GlobalValue");
Targets.push_back({Offset, DAG.getTargetGlobalAddress(
GA->getGlobal(), getCurSDLoc(),
Val.getValueType(), GA->getOffset())});
}
llvm::sort(Targets,
[](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
return T1.Offset < T2.Offset;
});
for (auto &T : Targets) {
Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
Ops.push_back(T.Target);
}
Ops.push_back(DAG.getRoot()); // Chain
SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
getCurSDLoc(), MVT::Other, Ops),
0);
DAG.setRoot(N);
setValue(&I, N);
HasTailCall = true;
return;
}
case Intrinsic::wasm_landingpad_index:
// Information this intrinsic contained has been transferred to
// MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
// delete it now.
return;
case Intrinsic::aarch64_settag:
case Intrinsic::aarch64_settag_zero: {
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
SDValue Val = TSI.EmitTargetCodeForSetTag(
DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
ZeroMemory);
DAG.setRoot(Val);
setValue(&I, Val);
return;
}
case Intrinsic::ptrmask: {
SDValue Ptr = getValue(I.getOperand(0));
SDValue Const = getValue(I.getOperand(1));
EVT PtrVT = Ptr.getValueType();
setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
return;
}
case Intrinsic::get_active_lane_mask: {
auto DL = getCurSDLoc();
SDValue Index = getValue(I.getOperand(0));
SDValue TripCount = getValue(I.getOperand(1));
Type *ElementTy = I.getOperand(0)->getType();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
unsigned VecWidth = VT.getVectorNumElements();
SmallVector<SDValue, 16> OpsTripCount;
SmallVector<SDValue, 16> OpsIndex;
SmallVector<SDValue, 16> OpsStepConstants;
for (unsigned i = 0; i < VecWidth; i++) {
OpsTripCount.push_back(TripCount);
OpsIndex.push_back(Index);
OpsStepConstants.push_back(
DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
}
EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
SDValue VectorInduction = DAG.getNode(
ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
VectorTripCount, ISD::CondCode::SETULT);
setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
SetCC));
return;
}
case Intrinsic::experimental_vector_insert: {
auto DL = getCurSDLoc();
SDValue Vec = getValue(I.getOperand(0));
SDValue SubVec = getValue(I.getOperand(1));
SDValue Index = getValue(I.getOperand(2));
// The intrinsic's index type is i64, but the SDNode requires an index type
// suitable for the target. Convert the index as required.
MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
if (Index.getValueType() != VectorIdxTy)
Index = DAG.getVectorIdxConstant(
cast<ConstantSDNode>(Index)->getZExtValue(), DL);
EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
Index));
return;
}
case Intrinsic::experimental_vector_extract: {
auto DL = getCurSDLoc();
SDValue Vec = getValue(I.getOperand(0));
SDValue Index = getValue(I.getOperand(1));
EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
// The intrinsic's index type is i64, but the SDNode requires an index type
// suitable for the target. Convert the index as required.
MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
if (Index.getValueType() != VectorIdxTy)
Index = DAG.getVectorIdxConstant(
cast<ConstantSDNode>(Index)->getZExtValue(), DL);
setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
return;
}
case Intrinsic::experimental_vector_reverse:
visitVectorReverse(I);
return;
case Intrinsic::experimental_vector_splice:
visitVectorSplice(I);
return;
}
}
void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
const ConstrainedFPIntrinsic &FPI) {
SDLoc sdl = getCurSDLoc();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
ValueVTs.push_back(MVT::Other); // Out chain
// We do not need to serialize constrained FP intrinsics against
// each other or against (nonvolatile) loads, so they can be
// chained like loads.
SDValue Chain = DAG.getRoot();
SmallVector<SDValue, 4> Opers;
Opers.push_back(Chain);
if (FPI.isUnaryOp()) {
Opers.push_back(getValue(FPI.getArgOperand(0)));
} else if (FPI.isTernaryOp()) {
Opers.push_back(getValue(FPI.getArgOperand(0)));
Opers.push_back(getValue(FPI.getArgOperand(1)));
Opers.push_back(getValue(FPI.getArgOperand(2)));
} else {
Opers.push_back(getValue(FPI.getArgOperand(0)));
Opers.push_back(getValue(FPI.getArgOperand(1)));
}
auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
assert(Result.getNode()->getNumValues() == 2);
// Push node to the appropriate list so that future instructions can be
// chained up correctly.
SDValue OutChain = Result.getValue(1);
switch (EB) {
case fp::ExceptionBehavior::ebIgnore:
// The only reason why ebIgnore nodes still need to be chained is that
// they might depend on the current rounding mode, and therefore must
// not be moved across instruction that may change that mode.
LLVM_FALLTHROUGH;
case fp::ExceptionBehavior::ebMayTrap:
// These must not be moved across calls or instructions that may change
// floating-point exception masks.
PendingConstrainedFP.push_back(OutChain);
break;
case fp::ExceptionBehavior::ebStrict:
// These must not be moved across calls or instructions that may change
// floating-point exception masks or read floating-point exception flags.
// In addition, they cannot be optimized out even if unused.
PendingConstrainedFPStrict.push_back(OutChain);
break;
}
};
SDVTList VTs = DAG.getVTList(ValueVTs);
fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
SDNodeFlags Flags;
if (EB == fp::ExceptionBehavior::ebIgnore)
Flags.setNoFPExcept(true);
if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
Flags.copyFMF(*FPOp);
unsigned Opcode;
switch (FPI.getIntrinsicID()) {
default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
case Intrinsic::INTRINSIC: \
Opcode = ISD::STRICT_##DAGN; \
break;
#include "llvm/IR/ConstrainedOps.def"
case Intrinsic::experimental_constrained_fmuladd: {
Opcode = ISD::STRICT_FMA;
// Break fmuladd into fmul and fadd.
if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
!TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
ValueVTs[0])) {
Opers.pop_back();
SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
pushOutChain(Mul, EB);
Opcode = ISD::STRICT_FADD;
Opers.clear();
Opers.push_back(Mul.getValue(1));
Opers.push_back(Mul.getValue(0));
Opers.push_back(getValue(FPI.getArgOperand(2)));
}
break;
}
}
// A few strict DAG nodes carry additional operands that are not
// set up by the default code above.
switch (Opcode) {
default: break;
case ISD::STRICT_FP_ROUND:
Opers.push_back(
DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
break;
case ISD::STRICT_FSETCC:
case ISD::STRICT_FSETCCS: {
auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
if (TM.Options.NoNaNsFPMath)
Condition = getFCmpCodeWithoutNaN(Condition);
Opers.push_back(DAG.getCondCode(Condition));
break;
}
}
SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
pushOutChain(Result, EB);
SDValue FPResult = Result.getValue(0);
setValue(&FPI, FPResult);
}
static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
Optional<unsigned> ResOPC;
switch (VPIntrin.getIntrinsicID()) {
#define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
#define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
#define END_REGISTER_VP_INTRINSIC(...) break;
#include "llvm/IR/VPIntrinsics.def"
}
if (!ResOPC.hasValue())
llvm_unreachable(
"Inconsistency: no SDNode available for this VPIntrinsic!");
return ResOPC.getValue();
}
void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
const VPIntrinsic &VPIntrin) {
unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
SmallVector<EVT, 4> ValueVTs;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
SDVTList VTs = DAG.getVTList(ValueVTs);
// Request operands.
SmallVector<SDValue, 7> OpValues;
for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
SDLoc DL = getCurSDLoc();
SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
setValue(&VPIntrin, Result);
}
std::pair<SDValue, SDValue>
SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
const BasicBlock *EHPadBB) {
MachineFunction &MF = DAG.getMachineFunction();
MachineModuleInfo &MMI = MF.getMMI();
MCSymbol *BeginLabel = nullptr;
if (EHPadBB) {
// Insert a label before the invoke call to mark the try range. This can be
// used to detect deletion of the invoke via the MachineModuleInfo.
BeginLabel = MMI.getContext().createTempSymbol();
// For SjLj, keep track of which landing pads go with which invokes
// so as to maintain the ordering of pads in the LSDA.
unsigned CallSiteIndex = MMI.getCurrentCallSite();
if (CallSiteIndex) {
MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
// Now that the call site is handled, stop tracking it.
MMI.setCurrentCallSite(0);
}
// Both PendingLoads and PendingExports must be flushed here;
// this call might not return.
(void)getRoot();
DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
CLI.setChain(getRoot());
}
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
assert((CLI.IsTailCall || Result.second.getNode()) &&
"Non-null chain expected with non-tail call!");
assert((Result.second.getNode() || !Result.first.getNode()) &&
"Null value expected with tail call!");
if (!Result.second.getNode()) {
// As a special case, a null chain means that a tail call has been emitted
// and the DAG root is already updated.
HasTailCall = true;
// Since there's no actual continuation from this block, nothing can be
// relying on us setting vregs for them.
PendingExports.clear();
} else {
DAG.setRoot(Result.second);
}
if (EHPadBB) {
// Insert a label at the end of the invoke call to mark the try range. This
// can be used to detect deletion of the invoke via the MachineModuleInfo.
MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
// Inform MachineModuleInfo of range.
auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
// There is a platform (e.g. wasm) that uses funclet style IR but does not
// actually use outlined funclets and their LSDA info style.
if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
assert(CLI.CB);
WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
} else if (!isScopedEHPersonality(Pers)) {
MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
}
}
return Result;
}
void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
bool isTailCall,
const BasicBlock *EHPadBB) {
auto &DL = DAG.getDataLayout();
FunctionType *FTy = CB.getFunctionType();
Type *RetTy = CB.getType();
TargetLowering::ArgListTy Args;
Args.reserve(CB.arg_size());
const Value *SwiftErrorVal = nullptr;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (isTailCall) {
// Avoid emitting tail calls in functions with the disable-tail-calls
// attribute.
auto *Caller = CB.getParent()->getParent();
if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
"true")
isTailCall = false;
// We can't tail call inside a function with a swifterror argument. Lowering
// does not support this yet. It would have to move into the swifterror
// register before the call.
if (TLI.supportSwiftError() &&
Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
isTailCall = false;
}
for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
TargetLowering::ArgListEntry Entry;
const Value *V = *I;
// Skip empty types
if (V->getType()->isEmptyTy())
continue;
SDValue ArgNode = getValue(V);
Entry.Node = ArgNode; Entry.Ty = V->getType();
Entry.setAttributes(&CB, I - CB.arg_begin());
// Use swifterror virtual register as input to the call.
if (Entry.IsSwiftError && TLI.supportSwiftError()) {
SwiftErrorVal = V;
// We find the virtual register for the actual swifterror argument.
// Instead of using the Value, we use the virtual register instead.
Entry.Node =
DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
EVT(TLI.getPointerTy(DL)));
}
Args.push_back(Entry);
// If we have an explicit sret argument that is an Instruction, (i.e., it
// might point to function-local memory), we can't meaningfully tail-call.
if (Entry.IsSRet && isa<Instruction>(V))
isTailCall = false;
}
// If call site has a cfguardtarget operand bundle, create and add an
// additional ArgListEntry.
if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
TargetLowering::ArgListEntry Entry;
Value *V = Bundle->Inputs[0];
SDValue ArgNode = getValue(V);
Entry.Node = ArgNode;
Entry.Ty = V->getType();
Entry.IsCFGuardTarget = true;
Args.push_back(Entry);
}
// Check if target-independent constraints permit a tail call here.
// Target-dependent constraints are checked within TLI->LowerCallTo.
if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
isTailCall = false;
// Disable tail calls if there is an swifterror argument. Targets have not
// been updated to support tail calls.
if (TLI.supportSwiftError() && SwiftErrorVal)
isTailCall = false;
TargetLowering::CallLoweringInfo CLI(DAG);
CLI.setDebugLoc(getCurSDLoc())
.setChain(getRoot())
.setCallee(RetTy, FTy, Callee, std::move(Args), CB)
.setTailCall(isTailCall)
.setConvergent(CB.isConvergent())
.setIsPreallocated(
CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
if (Result.first.getNode()) {
Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
setValue(&CB, Result.first);
}
// The last element of CLI.InVals has the SDValue for swifterror return.
// Here we copy it to a virtual register and update SwiftErrorMap for
// book-keeping.
if (SwiftErrorVal && TLI.supportSwiftError()) {
// Get the last element of InVals.
SDValue Src = CLI.InVals.back();
Register VReg =
SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
DAG.setRoot(CopyNode);
}
}
static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
SelectionDAGBuilder &Builder) {
// Check to see if this load can be trivially constant folded, e.g. if the
// input is from a string literal.
if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
// Cast pointer to the type we really want to load.
Type *LoadTy =
Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
if (LoadVT.isVector())
LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
PointerType::getUnqual(LoadTy));
if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
return Builder.getValue(LoadCst);
}
// Otherwise, we have to emit the load. If the pointer is to unfoldable but
// still constant memory, the input chain can be the entry node.
SDValue Root;
bool ConstantMemory = false;
// Do not serialize (non-volatile) loads of constant memory with anything.
if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
Root = Builder.DAG.getEntryNode();
ConstantMemory = true;
} else {
// Do not serialize non-volatile loads against each other.
Root = Builder.DAG.getRoot();
}
SDValue Ptr = Builder.getValue(PtrVal);
SDValue LoadVal =
Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
MachinePointerInfo(PtrVal), Align(1));
if (!ConstantMemory)
Builder.PendingLoads.push_back(LoadVal.getValue(1));
return LoadVal;
}
/// Record the value for an instruction that produces an integer result,
/// converting the type where necessary.
void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
SDValue Value,
bool IsSigned) {
EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType(), true);
if (IsSigned)
Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
else
Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
setValue(&I, Value);
}
/// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
/// true and lower it. Otherwise return false, and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
const Value *Size = I.getArgOperand(2);
const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
if (CSize && CSize->getZExtValue() == 0) {
EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
I.getType(), true);
setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
return true;
}
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
if (Res.first.getNode()) {
processIntegerCallValue(I, Res.first, true);
PendingLoads.push_back(Res.second);
return true;
}
// memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
// memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
return false;
// If the target has a fast compare for the given size, it will return a
// preferred load type for that size. Require that the load VT is legal and
// that the target supports unaligned loads of that type. Otherwise, return
// INVALID.
auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
MVT LVT = TLI.hasFastEqualityCompare(NumBits);
if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
// TODO: Handle 5 byte compare as 4-byte + 1 byte.
// TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
// TODO: Check alignment of src and dest ptrs.
unsigned DstAS = LHS->getType()->getPointerAddressSpace();
unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
if (!TLI.isTypeLegal(LVT) ||
!TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
!TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
}
return LVT;
};
// This turns into unaligned loads. We only do this if the target natively
// supports the MVT we'll be loading or if it is small enough (<= 4) that
// we'll only produce a small number of byte loads.
MVT LoadVT;
unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
switch (NumBitsToCompare) {
default:
return false;
case 16:
LoadVT = MVT::i16;
break;
case 32:
LoadVT = MVT::i32;
break;
case 64:
case 128:
case 256:
LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
break;
}
if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
return false;
SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
// Bitcast to a wide integer type if the loads are vectors.
if (LoadVT.isVector()) {
EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
LoadL = DAG.getBitcast(CmpVT, LoadL);
LoadR = DAG.getBitcast(CmpVT, LoadR);
}
SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
processIntegerCallValue(I, Cmp, false);
return true;
}
/// See if we can lower a memchr call into an optimized form. If so, return
/// true and lower it. Otherwise return false, and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
const Value *Src = I.getArgOperand(0);
const Value *Char = I.getArgOperand(1);
const Value *Length = I.getArgOperand(2);
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
std::pair<SDValue, SDValue> Res =
TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
getValue(Src), getValue(Char), getValue(Length),
MachinePointerInfo(Src));
if (Res.first.getNode()) {
setValue(&I, Res.first);
PendingLoads.push_back(Res.second);
return true;
}
return false;
}
/// See if we can lower a mempcpy call into an optimized form. If so, return
/// true and lower it. Otherwise return false, and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
SDValue Dst = getValue(I.getArgOperand(0));
SDValue Src = getValue(I.getArgOperand(1));
SDValue Size = getValue(I.getArgOperand(2));
Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
// DAG::getMemcpy needs Alignment to be defined.
Align Alignment = std::min(DstAlign, SrcAlign);
bool isVol = false;
SDLoc sdl = getCurSDLoc();
// In the mempcpy context we need to pass in a false value for isTailCall
// because the return pointer needs to be adjusted by the size of
// the copied memory.
SDValue Root = isVol ? getRoot() : getMemoryRoot();
SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
/*isTailCall=*/false,
MachinePointerInfo(I.getArgOperand(0)),
MachinePointerInfo(I.getArgOperand(1)));
assert(MC.getNode() != nullptr &&
"** memcpy should not be lowered as TailCall in mempcpy context **");
DAG.setRoot(MC);
// Check if Size needs to be truncated or extended.
Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
// Adjust return pointer to point just past the last dst byte.
SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
Dst, Size);
setValue(&I, DstPlusSize);
return true;
}
/// See if we can lower a strcpy call into an optimized form. If so, return
/// true and lower it, otherwise return false and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
std::pair<SDValue, SDValue> Res =
TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
getValue(Arg0), getValue(Arg1),
MachinePointerInfo(Arg0),
MachinePointerInfo(Arg1), isStpcpy);
if (Res.first.getNode()) {
setValue(&I, Res.first);
DAG.setRoot(Res.second);
return true;
}
return false;
}
/// See if we can lower a strcmp call into an optimized form. If so, return
/// true and lower it, otherwise return false and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
std::pair<SDValue, SDValue> Res =
TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
getValue(Arg0), getValue(Arg1),
MachinePointerInfo(Arg0),
MachinePointerInfo(Arg1));
if (Res.first.getNode()) {
processIntegerCallValue(I, Res.first, true);
PendingLoads.push_back(Res.second);
return true;
}
return false;
}
/// See if we can lower a strlen call into an optimized form. If so, return
/// true and lower it, otherwise return false and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
const Value *Arg0 = I.getArgOperand(0);
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
std::pair<SDValue, SDValue> Res =
TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
getValue(Arg0), MachinePointerInfo(Arg0));
if (Res.first.getNode()) {
processIntegerCallValue(I, Res.first, false);
PendingLoads.push_back(Res.second);
return true;
}
return false;
}
/// See if we can lower a strnlen call into an optimized form. If so, return
/// true and lower it, otherwise return false and it will be lowered like a
/// normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
std::pair<SDValue, SDValue> Res =
TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
getValue(Arg0), getValue(Arg1),
MachinePointerInfo(Arg0));
if (Res.first.getNode()) {
processIntegerCallValue(I, Res.first, false);
PendingLoads.push_back(Res.second);
return true;
}
return false;
}
/// See if we can lower a unary floating-point operation into an SDNode with
/// the specified Opcode. If so, return true and lower it, otherwise return
/// false and it will be lowered like a normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
unsigned Opcode) {
// We already checked this call's prototype; verify it doesn't modify errno.
if (!I.onlyReadsMemory())
return false;
SDNodeFlags Flags;
Flags.copyFMF(cast<FPMathOperator>(I));
SDValue Tmp = getValue(I.getArgOperand(0));
setValue(&I,
DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
return true;
}
/// See if we can lower a binary floating-point operation into an SDNode with
/// the specified Opcode. If so, return true and lower it. Otherwise return
/// false, and it will be lowered like a normal call.
/// The caller already checked that \p I calls the appropriate LibFunc with a
/// correct prototype.
bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
unsigned Opcode) {
// We already checked this call's prototype; verify it doesn't modify errno.
if (!I.onlyReadsMemory())
return false;
SDNodeFlags Flags;
Flags.copyFMF(cast<FPMathOperator>(I));
SDValue Tmp0 = getValue(I.getArgOperand(0));
SDValue Tmp1 = getValue(I.getArgOperand(1));
EVT VT = Tmp0.getValueType();
setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
return true;
}
void SelectionDAGBuilder::visitCall(const CallInst &I) {
// Handle inline assembly differently.
if (I.isInlineAsm()) {
visitInlineAsm(I);
return;
}
if (Function *F = I.getCalledFunction()) {
if (F->isDeclaration()) {
// Is this an LLVM intrinsic or a target-specific intrinsic?
unsigned IID = F->getIntrinsicID();
if (!IID)
if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
IID = II->getIntrinsicID(F);
if (IID) {
visitIntrinsicCall(I, IID);
return;
}
}
// Check for well-known libc/libm calls. If the function is internal, it
// can't be a library call. Don't do the check if marked as nobuiltin for
// some reason or the call site requires strict floating point semantics.
LibFunc Func;
if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
F->hasName() && LibInfo->getLibFunc(*F, Func) &&
LibInfo->hasOptimizedCodeGen(Func)) {
switch (Func) {
default: break;
case LibFunc_bcmp:
if (visitMemCmpBCmpCall(I))
return;
break;
case LibFunc_copysign:
case LibFunc_copysignf:
case LibFunc_copysignl:
// We already checked this call's prototype; verify it doesn't modify
// errno.
if (I.onlyReadsMemory()) {
SDValue LHS = getValue(I.getArgOperand(0));
SDValue RHS = getValue(I.getArgOperand(1));
setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
LHS.getValueType(), LHS, RHS));
return;
}
break;
case LibFunc_fabs:
case LibFunc_fabsf:
case LibFunc_fabsl:
if (visitUnaryFloatCall(I, ISD::FABS))
return;
break;
case LibFunc_fmin:
case LibFunc_fminf:
case LibFunc_fminl:
if (visitBinaryFloatCall(I, ISD::FMINNUM))
return;
break;
case LibFunc_fmax:
case LibFunc_fmaxf:
case LibFunc_fmaxl:
if (visitBinaryFloatCall(I, ISD::FMAXNUM))
return;
break;
case LibFunc_sin:
case LibFunc_sinf:
case LibFunc_sinl:
if (visitUnaryFloatCall(I, ISD::FSIN))
return;
break;
case LibFunc_cos:
case LibFunc_cosf:
case LibFunc_cosl:
if (visitUnaryFloatCall(I, ISD::FCOS))
return;
break;
case LibFunc_sqrt:
case LibFunc_sqrtf:
case LibFunc_sqrtl:
case LibFunc_sqrt_finite:
case LibFunc_sqrtf_finite:
case LibFunc_sqrtl_finite:
if (visitUnaryFloatCall(I, ISD::FSQRT))
return;
break;
case LibFunc_floor:
case LibFunc_floorf:
case LibFunc_floorl:
if (visitUnaryFloatCall(I, ISD::FFLOOR))
return;
break;
case LibFunc_nearbyint:
case LibFunc_nearbyintf:
case LibFunc_nearbyintl:
if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
return;
break;
case LibFunc_ceil:
case LibFunc_ceilf:
case LibFunc_ceill:
if (visitUnaryFloatCall(I, ISD::FCEIL))
return;
break;
case LibFunc_rint:
case LibFunc_rintf:
case LibFunc_rintl:
if (visitUnaryFloatCall(I, ISD::FRINT))
return;
break;
case LibFunc_round:
case LibFunc_roundf:
case LibFunc_roundl:
if (visitUnaryFloatCall(I, ISD::FROUND))
return;
break;
case LibFunc_trunc:
case LibFunc_truncf:
case LibFunc_truncl:
if (visitUnaryFloatCall(I, ISD::FTRUNC))
return;
break;
case LibFunc_log2:
case LibFunc_log2f:
case LibFunc_log2l:
if (visitUnaryFloatCall(I, ISD::FLOG2))
return;
break;
case LibFunc_exp2:
case LibFunc_exp2f:
case LibFunc_exp2l:
if (visitUnaryFloatCall(I, ISD::FEXP2))
return;
break;
case LibFunc_memcmp:
if (visitMemCmpBCmpCall(I))
return;
break;
case LibFunc_mempcpy:
if (visitMemPCpyCall(I))
return;
break;
case LibFunc_memchr:
if (visitMemChrCall(I))
return;
break;
case LibFunc_strcpy:
if (visitStrCpyCall(I, false))
return;
break;
case LibFunc_stpcpy:
if (visitStrCpyCall(I, true))
return;
break;
case LibFunc_strcmp:
if (visitStrCmpCall(I))
return;
break;
case LibFunc_strlen:
if (visitStrLenCall(I))
return;
break;
case LibFunc_strnlen:
if (visitStrNLenCall(I))
return;
break;
}
}
}
// Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
// have to do anything here to lower funclet bundles.
// CFGuardTarget bundles are lowered in LowerCallTo.
assert(!I.hasOperandBundlesOtherThan(
{LLVMContext::OB_deopt, LLVMContext::OB_funclet,
LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
LLVMContext::OB_clang_arc_attachedcall}) &&
"Cannot lower calls with arbitrary operand bundles!");
SDValue Callee = getValue(I.getCalledOperand());
if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
else
// Check if we can potentially perform a tail call. More detailed checking
// is be done within LowerCallTo, after more information about the call is
// known.
LowerCallTo(I, Callee, I.isTailCall());
}
namespace {
/// AsmOperandInfo - This contains information for each constraint that we are
/// lowering.
class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
public:
/// CallOperand - If this is the result output operand or a clobber
/// this is null, otherwise it is the incoming operand to the CallInst.
/// This gets modified as the asm is processed.
SDValue CallOperand;
/// AssignedRegs - If this is a register or register class operand, this
/// contains the set of register corresponding to the operand.
RegsForValue AssignedRegs;
explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
: TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
}
/// Whether or not this operand accesses memory
bool hasMemory(const TargetLowering &TLI) const {
// Indirect operand accesses access memory.
if (isIndirect)
return true;
for (const auto &Code : Codes)
if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
return true;
return false;
}
/// getCallOperandValEVT - Return the EVT of the Value* that this operand
/// corresponds to. If there is no Value* for this operand, it returns
/// MVT::Other.
EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
const DataLayout &DL) const {
if (!CallOperandVal) return MVT::Other;
if (isa<BasicBlock>(CallOperandVal))
return TLI.getProgramPointerTy(DL);
llvm::Type *OpTy = CallOperandVal->getType();
// FIXME: code duplicated from TargetLowering::ParseConstraints().
// If this is an indirect operand, the operand is a pointer to the
// accessed type.
if (isIndirect) {
PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
if (!PtrTy)
report_fatal_error("Indirect operand for inline asm not a pointer!");
OpTy = PtrTy->getElementType();
}
// Look for vector wrapped in a struct. e.g. { <16 x i8> }.
if (StructType *STy = dyn_cast<StructType>(OpTy))
if (STy->getNumElements() == 1)
OpTy = STy->getElementType(0);
// If OpTy is not a single value, it may be a struct/union that we
// can tile with integers.
if (!OpTy->isSingleValueType() && OpTy->isSized()) {
unsigned BitSize = DL.getTypeSizeInBits(OpTy);
switch (BitSize) {
default: break;
case 1:
case 8:
case 16:
case 32:
case 64:
case 128:
OpTy = IntegerType::get(Context, BitSize);
break;
}
}
return TLI.getValueType(DL, OpTy, true);
}
};
} // end anonymous namespace
/// Make sure that the output operand \p OpInfo and its corresponding input
/// operand \p MatchingOpInfo have compatible constraint types (otherwise error
/// out).
static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
SDISelAsmOperandInfo &MatchingOpInfo,
SelectionDAG &DAG) {
if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
return;
const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
const auto &TLI = DAG.getTargetLoweringInfo();
std::pair<unsigned, const TargetRegisterClass *> MatchRC =
TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
OpInfo.ConstraintVT);
std::pair<unsigned, const TargetRegisterClass *> InputRC =
TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
MatchingOpInfo.ConstraintVT);
if ((OpInfo.ConstraintVT.isInteger() !=
MatchingOpInfo.ConstraintVT.isInteger()) ||
(MatchRC.second != InputRC.second)) {
// FIXME: error out in a more elegant fashion
report_fatal_error("Unsupported asm: input constraint"
" with a matching output constraint of"
" incompatible type!");
}
MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
}
/// Get a direct memory input to behave well as an indirect operand.
/// This may introduce stores, hence the need for a \p Chain.
/// \return The (possibly updated) chain.
static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
SDISelAsmOperandInfo &OpInfo,
SelectionDAG &DAG) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
// If we don't have an indirect input, put it in the constpool if we can,
// otherwise spill it to a stack slot.
// TODO: This isn't quite right. We need to handle these according to
// the addressing mode that the constraint wants. Also, this may take
// an additional register for the computation and we don't want that
// either.
// If the operand is a float, integer, or vector constant, spill to a
// constant pool entry to get its address.
const Value *OpVal = OpInfo.CallOperandVal;
if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
OpInfo.CallOperand = DAG.getConstantPool(
cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
return Chain;
}
// Otherwise, create a stack slot and emit a store to it before the asm.
Type *Ty = OpVal->getType();
auto &DL = DAG.getDataLayout();
uint64_t TySize = DL.getTypeAllocSize(Ty);
MachineFunction &MF = DAG.getMachineFunction();
int SSFI = MF.getFrameInfo().CreateStackObject(
TySize, DL.getPrefTypeAlign(Ty), false);
SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
MachinePointerInfo::getFixedStack(MF, SSFI),
TLI.getMemValueType(DL, Ty));
OpInfo.CallOperand = StackSlot;
return Chain;
}
/// GetRegistersForValue - Assign registers (virtual or physical) for the
/// specified operand. We prefer to assign virtual registers, to allow the
/// register allocator to handle the assignment process. However, if the asm
/// uses features that we can't model on machineinstrs, we have SDISel do the
/// allocation. This produces generally horrible, but correct, code.
///
/// OpInfo describes the operand
/// RefOpInfo describes the matching operand if any, the operand otherwise
static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
SDISelAsmOperandInfo &OpInfo,
SDISelAsmOperandInfo &RefOpInfo) {
LLVMContext &Context = *DAG.getContext();
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
MachineFunction &MF = DAG.getMachineFunction();
SmallVector<unsigned, 4> Regs;
const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
// No work to do for memory operations.
if (OpInfo.ConstraintType == TargetLowering::C_Memory)
return;
// If this is a constraint for a single physreg, or a constraint for a
// register class, find it.
unsigned AssignedReg;
const TargetRegisterClass *RC;
std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
&TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
// RC is unset only on failure. Return immediately.
if (!RC)
return;
// Get the actual register value type. This is important, because the user
// may have asked for (e.g.) the AX register in i32 type. We need to
// remember that AX is actually i16 to get the right extension.
const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
if (OpInfo.ConstraintVT != MVT::Other) {
// If this is an FP operand in an integer register (or visa versa), or more
// generally if the operand value disagrees with the register class we plan
// to stick it in, fix the operand type.
//
// If this is an input value, the bitcast to the new type is done now.
// Bitcast for output value is done at the end of visitInlineAsm().
if ((OpInfo.Type == InlineAsm::isOutput ||
OpInfo.Type == InlineAsm::isInput) &&
!TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
// Try to convert to the first EVT that the reg class contains. If the
// types are identical size, use a bitcast to convert (e.g. two differing
// vector types). Note: output bitcast is done at the end of
// visitInlineAsm().
if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
// Exclude indirect inputs while they are unsupported because the code
// to perform the load is missing and thus OpInfo.CallOperand still
// refers to the input address rather than the pointed-to value.
if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
OpInfo.CallOperand =
DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
OpInfo.ConstraintVT = RegVT;
// If the operand is an FP value and we want it in integer registers,
// use the corresponding integer type. This turns an f64 value into
// i64, which can be passed with two i32 values on a 32-bit machine.
} else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
if (OpInfo.Type == InlineAsm::isInput)
OpInfo.CallOperand =
DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
OpInfo.ConstraintVT = VT;
}
}
}
// No need to allocate a matching input constraint since the constraint it's
// matching to has already been allocated.
if (OpInfo.isMatchingInputConstraint())
return;
EVT ValueVT = OpInfo.ConstraintVT;
if (OpInfo.ConstraintVT == MVT::Other)
ValueVT = RegVT;
// Initialize NumRegs.
unsigned NumRegs = 1;
if (OpInfo.ConstraintVT != MVT::Other)
NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
// If this is a constraint for a specific physical register, like {r17},
// assign it now.
// If this associated to a specific register, initialize iterator to correct
// place. If virtual, make sure we have enough registers
// Initialize iterator if necessary
TargetRegisterClass::iterator I = RC->begin();
MachineRegisterInfo &RegInfo = MF.getRegInfo();
// Do not check for single registers.
if (AssignedReg) {
for (; *I != AssignedReg; ++I)
assert(I != RC->end() && "AssignedReg should be member of RC");
}
for (; NumRegs; --NumRegs, ++I) {
assert(I != RC->end() && "Ran out of registers to allocate!");
Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
Regs.push_back(R);
}
OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
}
static unsigned
findMatchingInlineAsmOperand(unsigned OperandNo,
const std::vector<SDValue> &AsmNodeOperands) {
// Scan until we find the definition we already emitted of this operand.
unsigned CurOp = InlineAsm::Op_FirstOperand;
for (; OperandNo; --OperandNo) {
// Advance to the next operand.
unsigned OpFlag =
cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
assert((InlineAsm::isRegDefKind(OpFlag) ||
InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
InlineAsm::isMemKind(OpFlag)) &&
"Skipped past definitions?");
CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
}
return CurOp;
}
namespace {
class ExtraFlags {
unsigned Flags = 0;
public:
explicit ExtraFlags(const CallBase &Call) {
const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
if (IA->hasSideEffects())
Flags |= InlineAsm::Extra_HasSideEffects;
if (IA->isAlignStack())
Flags |= InlineAsm::Extra_IsAlignStack;
if (Call.isConvergent())
Flags |= InlineAsm::Extra_IsConvergent;
Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
}
void update(const TargetLowering::AsmOperandInfo &OpInfo) {
// Ideally, we would only check against memory constraints. However, the
// meaning of an Other constraint can be target-specific and we can't easily
// reason about it. Therefore, be conservative and set MayLoad/MayStore
// for Other constraints as well.
if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
OpInfo.ConstraintType == TargetLowering::C_Other) {
if (OpInfo.Type == InlineAsm::isInput)
Flags |= InlineAsm::Extra_MayLoad;
else if (OpInfo.Type == InlineAsm::isOutput)
Flags |= InlineAsm::Extra_MayStore;
else if (OpInfo.Type == InlineAsm::isClobber)
Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
}
}
unsigned get() const { return Flags; }
};
} // end anonymous namespace
/// visitInlineAsm - Handle a call to an InlineAsm object.
void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
/// ConstraintOperands - Information about all of the constraints.
SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
// First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
// AsmDialect, MayLoad, MayStore).
bool HasSideEffect = IA->hasSideEffects();
ExtraFlags ExtraInfo(Call);
unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
unsigned ResNo = 0; // ResNo - The result number of the next output.
unsigned NumMatchingOps = 0;
for (auto &T : TargetConstraints) {
ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
// Compute the value type for each operand.
if (OpInfo.Type == InlineAsm::isInput ||
(OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
// Process the call argument. BasicBlocks are labels, currently appearing
// only in asm's.
if (isa<CallBrInst>(Call) &&
ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
cast<CallBrInst>(&Call)->getNumIndirectDests() -
NumMatchingOps) &&
(NumMatchingOps == 0 ||
ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
NumMatchingOps))) {
const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
} else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
} else {
OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
}
EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
DAG.getDataLayout());
OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
} else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
// The return value of the call is this value. As such, there is no
// corresponding argument.
assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
OpInfo.ConstraintVT = TLI.getSimpleValueType(
DAG.getDataLayout(), STy->getElementType(ResNo));
} else {
assert(ResNo == 0 && "Asm only has one result!");
OpInfo.ConstraintVT =
TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
}
++ResNo;
} else {
OpInfo.ConstraintVT = MVT::Other;
}
if (OpInfo.hasMatchingInput())
++NumMatchingOps;
if (!HasSideEffect)
HasSideEffect = OpInfo.hasMemory(TLI);
// Determine if this InlineAsm MayLoad or MayStore based on the constraints.
// FIXME: Could we compute this on OpInfo rather than T?
// Compute the constraint code and ConstraintType to use.
TLI.ComputeConstraintToUse(T, SDValue());
if (T.ConstraintType == TargetLowering::C_Immediate &&
OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
// We've delayed emitting a diagnostic like the "n" constraint because
// inlining could cause an integer showing up.
return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
"' expects an integer constant "
"expression");
ExtraInfo.update(T);
}
// We won't need to flush pending loads if this asm doesn't touch
// memory and is nonvolatile.
SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
bool IsCallBr = isa<CallBrInst>(Call);
if (IsCallBr) {
// If this is a callbr we need to flush pending exports since inlineasm_br
// is a terminator. We need to do this before nodes are glued to
// the inlineasm_br node.
Chain = getControlRoot();
}
// Second pass over the constraints: compute which constraint option to use.
for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
// If this is an output operand with a matching input operand, look up the
// matching input. If their types mismatch, e.g. one is an integer, the
// other is floating point, or their sizes are different, flag it as an
// error.
if (OpInfo.hasMatchingInput()) {
SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
patchMatchingInput(OpInfo, Input, DAG);
}
// Compute the constraint code and ConstraintType to use.
TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
OpInfo.Type == InlineAsm::isClobber)
continue;
// If this is a memory input, and if the operand is not indirect, do what we
// need to provide an address for the memory input.
if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
!OpInfo.isIndirect) {
assert((OpInfo.isMultipleAlternative ||
(OpInfo.Type == InlineAsm::isInput)) &&
"Can only indirectify direct input operands!");
// Memory operands really want the address of the value.
Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
// There is no longer a Value* corresponding to this operand.
OpInfo.CallOperandVal = nullptr;
// It is now an indirect operand.
OpInfo.isIndirect = true;
}
}
// AsmNodeOperands - The operands for the ISD::INLINEASM node.
std::vector<SDValue> AsmNodeOperands;
AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
// If we have a !srcloc metadata node associated with it, we want to attach
// this to the ultimately generated inline asm machineinstr. To do this, we
// pass in the third operand as this (potentially null) inline asm MDNode.
const MDNode *SrcLoc = Call.getMetadata("srcloc");
AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
// Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
// bits as operand 3.
AsmNodeOperands.push_back(DAG.getTargetConstant(
ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
// Third pass: Loop over operands to prepare DAG-level operands.. As part of
// this, assign virtual and physical registers for inputs and otput.
for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
// Assign Registers.
SDISelAsmOperandInfo &RefOpInfo =
OpInfo.isMatchingInputConstraint()
? ConstraintOperands[OpInfo.getMatchedOperand()]
: OpInfo;
GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
auto DetectWriteToReservedRegister = [&]() {
const MachineFunction &MF = DAG.getMachineFunction();
const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
if (Register::isPhysicalRegister(Reg) &&
TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
const char *RegName = TRI.getName(Reg);
emitInlineAsmError(Call, "write to reserved register '" +
Twine(RegName) + "'");
return true;
}
}
return false;
};
switch (OpInfo.Type) {
case InlineAsm::isOutput:
if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
unsigned ConstraintID =
TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
assert(ConstraintID != InlineAsm::Constraint_Unknown &&
"Failed to convert memory constraint code to constraint id.");
// Add information to the INLINEASM node to know about this output.
unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
MVT::i32));
AsmNodeOperands.push_back(OpInfo.CallOperand);
} else {
// Otherwise, this outputs to a register (directly for C_Register /
// C_RegisterClass, and a target-defined fashion for
// C_Immediate/C_Other). Find a register that we can use.
if (OpInfo.AssignedRegs.Regs.empty()) {
emitInlineAsmError(
Call, "couldn't allocate output register for constraint '" +
Twine(OpInfo.ConstraintCode) + "'");
return;
}
if (DetectWriteToReservedRegister())
return;
// Add information to the INLINEASM node to know that this register is
// set.
OpInfo.AssignedRegs.AddInlineAsmOperands(
OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
: InlineAsm::Kind_RegDef,
false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
}
break;
case InlineAsm::isInput: {
SDValue InOperandVal = OpInfo.CallOperand;
if (OpInfo.isMatchingInputConstraint()) {
// If this is required to match an output register we have already set,
// just use its register.
auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
AsmNodeOperands);
unsigned OpFlag =
cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
if (InlineAsm::isRegDefKind(OpFlag) ||
InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
// Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
if (OpInfo.isIndirect) {
// This happens on gcc/testsuite/gcc.dg/pr8788-1.c
emitInlineAsmError(Call, "inline asm not supported yet: "
"don't know how to handle tied "
"indirect register inputs");
return;
}
MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
SmallVector<unsigned, 4> Regs;
if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
MachineRegisterInfo &RegInfo =
DAG.getMachineFunction().getRegInfo();
for (unsigned i = 0; i != NumRegs; ++i)
Regs.push_back(RegInfo.createVirtualRegister(RC));
} else {
emitInlineAsmError(Call,
"inline asm error: This value type register "
"class is not natively supported!");
return;
}
RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
SDLoc dl = getCurSDLoc();
// Use the produced MatchedRegs object to
MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
true, OpInfo.getMatchedOperand(), dl,
DAG, AsmNodeOperands);
break;
}
assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
"Unexpected number of operands");
// Add information to the INLINEASM node to know about this input.
// See InlineAsm.h isUseOperandTiedToDef.
OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
OpInfo.getMatchedOperand());
AsmNodeOperands.push_back(DAG.getTargetConstant(
OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
break;
}
// Treat indirect 'X' constraint as memory.
if (OpInfo.ConstraintType == TargetLowering::C_Other &&
OpInfo.isIndirect)
OpInfo.ConstraintType = TargetLowering::C_Memory;
if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
OpInfo.ConstraintType == TargetLowering::C_Other) {
std::vector<SDValue> Ops;
TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
Ops, DAG);
if (Ops.empty()) {
if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
if (isa<ConstantSDNode>(InOperandVal)) {
emitInlineAsmError(Call, "value out of range for constraint '" +
Twine(OpInfo.ConstraintCode) + "'");
return;
}
emitInlineAsmError(Call,
"invalid operand for inline asm constraint '" +
Twine(OpInfo.ConstraintCode) + "'");
return;
}
// Add information to the INLINEASM node to know about this input.
unsigned ResOpType =
InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
AsmNodeOperands.push_back(DAG.getTargetConstant(
ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
llvm::append_range(AsmNodeOperands, Ops);
break;
}
if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
assert(InOperandVal.getValueType() ==
TLI.getPointerTy(DAG.getDataLayout()) &&
"Memory operands expect pointer values");
unsigned ConstraintID =
TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
assert(ConstraintID != InlineAsm::Constraint_Unknown &&
"Failed to convert memory constraint code to constraint id.");
// Add information to the INLINEASM node to know about this input.
unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
getCurSDLoc(),
MVT::i32));
AsmNodeOperands.push_back(InOperandVal);
break;
}
assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
OpInfo.ConstraintType == TargetLowering::C_Register) &&
"Unknown constraint type!");
// TODO: Support this.
if (OpInfo.isIndirect) {
emitInlineAsmError(
Call, "Don't know how to handle indirect register inputs yet "
"for constraint '" +
Twine(OpInfo.ConstraintCode) + "'");
return;
}
// Copy the input into the appropriate registers.
if (OpInfo.AssignedRegs.Regs.empty()) {
emitInlineAsmError(Call,
"couldn't allocate input reg for constraint '" +
Twine(OpInfo.ConstraintCode) + "'");
return;
}
if (DetectWriteToReservedRegister())
return;
SDLoc dl = getCurSDLoc();
OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
&Call);
OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
dl, DAG, AsmNodeOperands);
break;
}
case InlineAsm::isClobber:
// Add the clobbered value to the operand list, so that the register
// allocator is aware that the physreg got clobbered.
if (!OpInfo.AssignedRegs.Regs.empty())
OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
false, 0, getCurSDLoc(), DAG,
AsmNodeOperands);
break;
}
}
// Finish up input operands. Set the input chain and add the flag last.
AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
Flag = Chain.getValue(1);
// Do additional work to generate outputs.
SmallVector<EVT, 1> ResultVTs;
SmallVector<SDValue, 1> ResultValues;
SmallVector<SDValue, 8> OutChains;
llvm::Type *CallResultType = Call.getType();
ArrayRef<Type *> ResultTypes;
if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
ResultTypes = StructResult->elements();
else if (!CallResultType->isVoidTy())
ResultTypes = makeArrayRef(CallResultType);
auto CurResultType = ResultTypes.begin();
auto handleRegAssign = [&](SDValue V) {
assert(CurResultType != ResultTypes.end() && "Unexpected value");
assert((*CurResultType)->isSized() && "Unexpected unsized type");
EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
++CurResultType;
// If the type of the inline asm call site return value is different but has
// same size as the type of the asm output bitcast it. One example of this
// is for vectors with different width / number of elements. This can
// happen for register classes that can contain multiple different value
// types. The preg or vreg allocated may not have the same VT as was
// expected.
//
// This can also happen for a return value that disagrees with the register
// class it is put in, eg. a double in a general-purpose register on a
// 32-bit machine.
if (ResultVT != V.getValueType() &&
ResultVT.getSizeInBits() == V.getValueSizeInBits())
V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
V.getValueType().isInteger()) {
// If a result value was tied to an input value, the computed result
// may have a wider width than the expected result. Extract the
// relevant portion.
V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
}
assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
ResultVTs.push_back(ResultVT);
ResultValues.push_back(V);
};
// Deal with output operands.
for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
if (OpInfo.Type == InlineAsm::isOutput) {
SDValue Val;
// Skip trivial output operands.
if (OpInfo.AssignedRegs.Regs.empty())
continue;
switch (OpInfo.ConstraintType) {
case TargetLowering::C_Register:
case TargetLowering::C_RegisterClass:
Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
Chain, &Flag, &Call);
break;
case TargetLowering::C_Immediate:
case TargetLowering::C_Other:
Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
OpInfo, DAG);
break;
case TargetLowering::C_Memory:
break; // Already handled.
case TargetLowering::C_Unknown:
assert(false && "Unexpected unknown constraint");
}
// Indirect output manifest as stores. Record output chains.
if (OpInfo.isIndirect) {
const Value *Ptr = OpInfo.CallOperandVal;
assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
MachinePointerInfo(Ptr));
OutChains.push_back(Store);
} else {
// generate CopyFromRegs to associated registers.
assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
if (Val.getOpcode() == ISD::MERGE_VALUES) {
for (const SDValue &V : Val->op_values())
handleRegAssign(V);
} else
handleRegAssign(Val);
}
}
}
// Set results.
if (!ResultValues.empty()) {
assert(CurResultType == ResultTypes.end() &&
"Mismatch in number of ResultTypes");
assert(ResultValues.size() == ResultTypes.size() &&
"Mismatch in number of output operands in asm result");
SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
DAG.getVTList(ResultVTs), ResultValues);
setValue(&Call, V);
}
// Collect store chains.
if (!OutChains.empty())
Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
// Only Update Root if inline assembly has a memory effect.
if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
DAG.setRoot(Chain);
}
void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
const Twine &Message) {
LLVMContext &Ctx = *DAG.getContext();
Ctx.emitError(&Call, Message);
// Make sure we leave the DAG in a valid state
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SmallVector<EVT, 1> ValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
if (ValueVTs.empty())
return;
SmallVector<SDValue, 1> Ops;
for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
}
void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
MVT::Other, getRoot(),
getValue(I.getArgOperand(0)),
DAG.getSrcValue(I.getArgOperand(0))));
}
void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
const DataLayout &DL = DAG.getDataLayout();
SDValue V = DAG.getVAArg(
TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
DL.getABITypeAlign(I.getType()).value());
DAG.setRoot(V.getValue(1));
if (I.getType()->isPointerTy())
V = DAG.getPtrExtOrTrunc(
V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
setValue(&I, V);
}
void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
MVT::Other, getRoot(),
getValue(I.getArgOperand(0)),
DAG.getSrcValue(I.getArgOperand(0))));
}
void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
MVT::Other, getRoot(),
getValue(I.getArgOperand(0)),
getValue(I.getArgOperand(1)),
DAG.getSrcValue(I.getArgOperand(0)),
DAG.getSrcValue(I.getArgOperand(1))));
}
SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
const Instruction &I,
SDValue Op) {
const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
if (!Range)
return Op;
ConstantRange CR = getConstantRangeFromMetadata(*Range);
if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
return Op;
APInt Lo = CR.getUnsignedMin();
if (!Lo.isMinValue())
return Op;
APInt Hi = CR.getUnsignedMax();
unsigned Bits = std::max(Hi.getActiveBits(),
static_cast<unsigned>(IntegerType::MIN_INT_BITS));
EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
SDLoc SL = getCurSDLoc();
SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
DAG.getValueType(SmallVT));
unsigned NumVals = Op.getNode()->getNumValues();
if (NumVals == 1)
return ZExt;
SmallVector<SDValue, 4> Ops;
Ops.push_back(ZExt);
for (unsigned I = 1; I != NumVals; ++I)
Ops.push_back(Op.getValue(I));
return DAG.getMergeValues(Ops, SL);
}
/// Populate a CallLowerinInfo (into \p CLI) based on the properties of
/// the call being lowered.
///
/// This is a helper for lowering intrinsics that follow a target calling
/// convention or require stack pointer adjustment. Only a subset of the
/// intrinsic's operands need to participate in the calling convention.
void SelectionDAGBuilder::populateCallLoweringInfo(
TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
bool IsPatchPoint) {
TargetLowering::ArgListTy Args;
Args.reserve(NumArgs);
// Populate the argument list.
// Attributes for args start at offset 1, after the return attribute.
for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
ArgI != ArgE; ++ArgI) {
const Value *V = Call->getOperand(ArgI);
assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
TargetLowering::ArgListEntry Entry;
Entry.Node = getValue(V);
Entry.Ty = V->getType();
Entry.setAttributes(Call, ArgI);
Args.push_back(Entry);
}
CLI.setDebugLoc(getCurSDLoc())
.setChain(getRoot())
.setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
.setDiscardResult(Call->use_empty())
.setIsPatchPoint(IsPatchPoint)
.setIsPreallocated(
Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
}
/// Add a stack map intrinsic call's live variable operands to a stackmap
/// or patchpoint target node's operand list.
///
/// Constants are converted to TargetConstants purely as an optimization to
/// avoid constant materialization and register allocation.
///
/// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
/// generate addess computation nodes, and so FinalizeISel can convert the
/// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
/// address materialization and register allocation, but may also be required
/// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
/// alloca in the entry block, then the runtime may assume that the alloca's
/// StackMap location can be read immediately after compilation and that the
/// location is valid at any point during execution (this is similar to the
/// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
/// only available in a register, then the runtime would need to trap when
/// execution reaches the StackMap in order to read the alloca's location.
static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
SelectionDAGBuilder &Builder) {
for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
Ops.push_back(
Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
Ops.push_back(
Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
} else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
Ops.push_back(Builder.DAG.getTargetFrameIndex(
FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
} else
Ops.push_back(OpVal);
}
}
/// Lower llvm.experimental.stackmap directly to its target opcode.
void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
// void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
// [live variables...])
assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
SDValue Chain, InFlag, Callee, NullPtr;
SmallVector<SDValue, 32> Ops;
SDLoc DL = getCurSDLoc();
Callee = getValue(CI.getCalledOperand());
NullPtr = DAG.getIntPtrConstant(0, DL, true);
// The stackmap intrinsic only records the live variables (the arguments
// passed to it) and emits NOPS (if requested). Unlike the patchpoint
// intrinsic, this won't be lowered to a function call. This means we don't
// have to worry about calling conventions and target specific lowering code.
// Instead we perform the call lowering right here.
//
// chain, flag = CALLSEQ_START(chain, 0, 0)
// chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
// chain, flag = CALLSEQ_END(chain, 0, 0, flag)
//
Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
InFlag = Chain.getValue(1);
// Add the <id> and <numBytes> constants.
SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
Ops.push_back(DAG.getTargetConstant(
cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
Ops.push_back(DAG.getTargetConstant(
cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
MVT::i32));
// Push live variables for the stack map.
addStackMapLiveVars(CI, 2, DL, Ops, *this);
// We are not pushing any register mask info here on the operands list,
// because the stackmap doesn't clobber anything.
// Push the chain and the glue flag.
Ops.push_back(Chain);
Ops.push_back(InFlag);
// Create the STACKMAP node.
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
Chain = SDValue(SM, 0);
InFlag = Chain.getValue(1);
Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
// Stackmaps don't generate values, so nothing goes into the NodeMap.
// Set the root to the target-lowered call chain.
DAG.setRoot(Chain);
// Inform the Frame Information that we have a stackmap in this function.
FuncInfo.MF->getFrameInfo().setHasStackMap();
}
/// Lower llvm.experimental.patchpoint directly to its target opcode.
void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
const BasicBlock *EHPadBB) {
// void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
// i32 <numBytes>,
// i8* <target>,
// i32 <numArgs>,
// [Args...],
// [live variables...])
CallingConv::ID CC = CB.getCallingConv();
bool IsAnyRegCC = CC == CallingConv::AnyReg;
bool HasDef = !CB.getType()->isVoidTy();
SDLoc dl = getCurSDLoc();
SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
// Handle immediate and symbolic callees.
if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
/*isTarget=*/true);
else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
SDLoc(SymbolicCallee),
SymbolicCallee->getValueType(0));
// Get the real number of arguments participating in the call <numArgs>
SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
// Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
// Intrinsics include all meta-operands up to but not including CC.
unsigned NumMetaOpers = PatchPointOpers::CCPos;
assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
"Not enough arguments provided to the patchpoint intrinsic");
// For AnyRegCC the arguments are lowered later on manually.
unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
Type *ReturnTy =
IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
TargetLowering::CallLoweringInfo CLI(DAG);
populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
ReturnTy, true);
std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
SDNode *CallEnd = Result.second.getNode();
if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
CallEnd = CallEnd->getOperand(0).getNode();
/// Get a call instruction from the call sequence chain.
/// Tail calls are not allowed.
assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
"Expected a callseq node.");
SDNode *Call = CallEnd->getOperand(0).getNode();
bool HasGlue = Call->getGluedNode();
// Replace the target specific call node with the patchable intrinsic.
SmallVector<SDValue, 8> Ops;
// Add the <id> and <numBytes> constants.
SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
Ops.push_back(DAG.getTargetConstant(
cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
Ops.push_back(DAG.getTargetConstant(
cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
MVT::i32));
// Add the callee.
Ops.push_back(Callee);
// Adjust <numArgs> to account for any arguments that have been passed on the
// stack instead.
// Call Node: Chain, Target, {Args}, RegMask, [Glue]
unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
// Add the calling convention
Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
// Add the arguments we omitted previously. The register allocator should
// place these in any free register.
if (IsAnyRegCC)
for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
Ops.push_back(getValue(CB.getArgOperand(i)));
// Push the arguments from the call instruction up to the register mask.
SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
Ops.append(Call->op_begin() + 2, e);
// Push live variables for the stack map.
addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
// Push the register mask info.
if (HasGlue)
Ops.push_back(*(Call->op_end()-2));
else
Ops.push_back(*(Call->op_end()-1));
// Push the chain (this is originally the first operand of the call, but
// becomes now the last or second to last operand).
Ops.push_back(*(Call->op_begin()));
// Push the glue flag (last operand).
if (HasGlue)
Ops.push_back(*(Call->op_end()-1));
SDVTList NodeTys;
if (IsAnyRegCC && HasDef) {
// Create the return types based on the intrinsic definition
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SmallVector<EVT, 3> ValueVTs;
ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
assert(ValueVTs.size() == 1 && "Expected only one return value type.");
// There is always a chain and a glue type at the end
ValueVTs.push_back(MVT::Other);
ValueVTs.push_back(MVT::Glue);
NodeTys = DAG.getVTList(ValueVTs);
} else
NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
// Replace the target specific call node with a PATCHPOINT node.
MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
dl, NodeTys, Ops);
// Update the NodeMap.
if (HasDef) {
if (IsAnyRegCC)
setValue(&CB, SDValue(MN, 0));
else
setValue(&CB, Result.first);
}
// Fixup the consumers of the intrinsic. The chain and glue may be used in the
// call sequence. Furthermore the location of the chain and glue can change
// when the AnyReg calling convention is used and the intrinsic returns a
// value.
if (IsAnyRegCC && HasDef) {
SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
} else
DAG.ReplaceAllUsesWith(Call, MN);
DAG.DeleteNode(Call);
// Inform the Frame Information that we have a patchpoint in this function.
FuncInfo.MF->getFrameInfo().setHasPatchPoint();
}
void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
unsigned Intrinsic) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
SDValue Op1 = getValue(I.getArgOperand(0));
SDValue Op2;
if (I.getNumArgOperands() > 1)
Op2 = getValue(I.getArgOperand(1));
SDLoc dl = getCurSDLoc();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
SDValue Res;
SDNodeFlags SDFlags;
if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
SDFlags.copyFMF(*FPMO);
switch (Intrinsic) {
case Intrinsic::vector_reduce_fadd:
if (SDFlags.hasAllowReassociation())
Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
SDFlags);
else
Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
break;
case Intrinsic::vector_reduce_fmul:
if (SDFlags.hasAllowReassociation())
Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
SDFlags);
else
Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
break;
case Intrinsic::vector_reduce_add:
Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_mul:
Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_and:
Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_or:
Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_xor:
Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_smax:
Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_smin:
Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_umax:
Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_umin:
Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
break;
case Intrinsic::vector_reduce_fmax:
Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
break;
case Intrinsic::vector_reduce_fmin:
Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
break;
default:
llvm_unreachable("Unhandled vector reduce intrinsic");
}
setValue(&I, Res);
}
/// Returns an AttributeList representing the attributes applied to the return
/// value of the given call.
static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
SmallVector<Attribute::AttrKind, 2> Attrs;
if (CLI.RetSExt)
Attrs.push_back(Attribute::SExt);
if (CLI.RetZExt)
Attrs.push_back(Attribute::ZExt);
if (CLI.IsInReg)
Attrs.push_back(Attribute::InReg);
return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
Attrs);
}
/// TargetLowering::LowerCallTo - This is the default LowerCallTo
/// implementation, which just calls LowerCall.
/// FIXME: When all targets are
/// migrated to using LowerCall, this hook should be integrated into SDISel.
std::pair<SDValue, SDValue>
TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
// Handle the incoming return values from the call.
CLI.Ins.clear();
Type *OrigRetTy = CLI.RetTy;
SmallVector<EVT, 4> RetTys;
SmallVector<uint64_t, 4> Offsets;
auto &DL = CLI.DAG.getDataLayout();
ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
if (CLI.IsPostTypeLegalization) {
// If we are lowering a libcall after legalization, split the return type.
SmallVector<EVT, 4> OldRetTys;
SmallVector<uint64_t, 4> OldOffsets;
RetTys.swap(OldRetTys);
Offsets.swap(OldOffsets);
for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
EVT RetVT = OldRetTys[i];
uint64_t Offset = OldOffsets[i];
MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
RetTys.append(NumRegs, RegisterVT);
for (unsigned j = 0; j != NumRegs; ++j)
Offsets.push_back(Offset + j * RegisterVTByteSZ);
}
}
SmallVector<ISD::OutputArg, 4> Outs;
GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
bool CanLowerReturn =
this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
CLI.IsVarArg, Outs, CLI.RetTy->getContext());
SDValue DemoteStackSlot;
int DemoteStackIdx = -100;
if (!CanLowerReturn) {
// FIXME: equivalent assert?
// assert(!CS.hasInAllocaArgument() &&
// "sret demotion is incompatible with inalloca");
uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
MachineFunction &MF = CLI.DAG.getMachineFunction();
DemoteStackIdx =
MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
DL.getAllocaAddrSpace());
DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
ArgListEntry Entry;
Entry.Node = DemoteStackSlot;
Entry.Ty = StackSlotPtrType;
Entry.IsSExt = false;
Entry.IsZExt = false;
Entry.IsInReg = false;
Entry.IsSRet = true;
Entry.IsNest = false;
Entry.IsByVal = false;
Entry.IsByRef = false;
Entry.IsReturned = false;
Entry.IsSwiftSelf = false;
Entry.IsSwiftError = false;
Entry.IsCFGuardTarget = false;
Entry.Alignment = Alignment;
CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
CLI.NumFixedArgs += 1;
CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
// sret demotion isn't compatible with tail-calls, since the sret argument
// points into the callers stack frame.
CLI.IsTailCall = false;
} else {
bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
ISD::ArgFlagsTy Flags;
if (NeedsRegBlock) {
Flags.setInConsecutiveRegs();
if (I == RetTys.size() - 1)
Flags.setInConsecutiveRegsLast();
}
EVT VT = RetTys[I];
MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
CLI.CallConv, VT);
unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
CLI.CallConv, VT);
for (unsigned i = 0; i != NumRegs; ++i) {
ISD::InputArg MyFlags;
MyFlags.Flags = Flags;
MyFlags.VT = RegisterVT;
MyFlags.ArgVT = VT;
MyFlags.Used = CLI.IsReturnValueUsed;
if (CLI.RetTy->isPointerTy()) {
MyFlags.Flags.setPointer();
MyFlags.Flags.setPointerAddrSpace(
cast<PointerType>(CLI.RetTy)->getAddressSpace());
}
if (CLI.RetSExt)
MyFlags.Flags.setSExt();
if (CLI.RetZExt)
MyFlags.Flags.setZExt();
if (CLI.IsInReg)
MyFlags.Flags.setInReg();
CLI.Ins.push_back(MyFlags);
}
}
}
// We push in swifterror return as the last element of CLI.Ins.
ArgListTy &Args = CLI.getArgs();
if (supportSwiftError()) {
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
if (Args[i].IsSwiftError) {
ISD::InputArg MyFlags;
MyFlags.VT = getPointerTy(DL);
MyFlags.ArgVT = EVT(getPointerTy(DL));
MyFlags.Flags.setSwiftError();
CLI.Ins.push_back(MyFlags);
}
}
}
// Handle all of the outgoing arguments.
CLI.Outs.clear();
CLI.OutVals.clear();
for (unsigned i = 0, e = Args.size(); i != e; ++i) {
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
// FIXME: Split arguments if CLI.IsPostTypeLegalization
Type *FinalType = Args[i].Ty;
if (Args[i].IsByVal)
FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
FinalType, CLI.CallConv, CLI.IsVarArg);
for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
++Value) {
EVT VT = ValueVTs[Value];
Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
SDValue Op = SDValue(Args[i].Node.getNode(),
Args[i].Node.getResNo() + Value);
ISD::ArgFlagsTy Flags;
// Certain targets (such as MIPS), may have a different ABI alignment
// for a type depending on the context. Give the target a chance to
// specify the alignment it wants.
const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
if (Args[i].Ty->isPointerTy()) {
Flags.setPointer();
Flags.setPointerAddrSpace(
cast<PointerType>(Args[i].Ty)->getAddressSpace());
}
if (Args[i].IsZExt)
Flags.setZExt();
if (Args[i].IsSExt)
Flags.setSExt();
if (Args[i].IsInReg) {
// If we are using vectorcall calling convention, a structure that is
// passed InReg - is surely an HVA
if (CLI.CallConv == CallingConv::X86_VectorCall &&
isa<StructType>(FinalType)) {
// The first value of a structure is marked
if (0 == Value)
Flags.setHvaStart();
Flags.setHva();
}
// Set InReg Flag
Flags.setInReg();
}
if (Args[i].IsSRet)
Flags.setSRet();
if (Args[i].IsSwiftSelf)
Flags.setSwiftSelf();
if (Args[i].IsSwiftError)
Flags.setSwiftError();
if (Args[i].IsCFGuardTarget)
Flags.setCFGuardTarget();
if (Args[i].IsByVal)
Flags.setByVal();
if (Args[i].IsByRef)
Flags.setByRef();
if (Args[i].IsPreallocated) {
Flags.setPreallocated();
// Set the byval flag for CCAssignFn callbacks that don't know about
// preallocated. This way we can know how many bytes we should've
// allocated and how many bytes a callee cleanup function will pop. If
// we port preallocated to more targets, we'll have to add custom
// preallocated handling in the various CC lowering callbacks.
Flags.setByVal();
}
if (Args[i].IsInAlloca) {
Flags.setInAlloca();
// Set the byval flag for CCAssignFn callbacks that don't know about
// inalloca. This way we can know how many bytes we should've allocated
// and how many bytes a callee cleanup function will pop. If we port
// inalloca to more targets, we'll have to add custom inalloca handling
// in the various CC lowering callbacks.
Flags.setByVal();
}
if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
PointerType *Ty = cast<PointerType>(Args[i].Ty);
Type *ElementTy = Ty->getElementType();
unsigned FrameSize = DL.getTypeAllocSize(
Args[i].ByValType ? Args[i].ByValType : ElementTy);
Flags.setByValSize(FrameSize);
// info is not there but there are cases it cannot get right.
Align FrameAlign;
if (auto MA = Args[i].Alignment)
FrameAlign = *MA;
else
FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
Flags.setByValAlign(FrameAlign);
}
if (Args[i].IsNest)
Flags.setNest();
if (NeedsRegBlock)
Flags.setInConsecutiveRegs();
Flags.setOrigAlign(OriginalAlignment);
MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
CLI.CallConv, VT);
unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
CLI.CallConv, VT);
SmallVector<SDValue, 4> Parts(NumParts);
ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
if (Args[i].IsSExt)
ExtendKind = ISD::SIGN_EXTEND;
else if (Args[i].IsZExt)
ExtendKind = ISD::ZERO_EXTEND;
// Conservatively only handle 'returned' on non-vectors that can be lowered,
// for now.
if (Args[i].IsReturned && !Op.getValueType().isVector() &&
CanLowerReturn) {
assert((CLI.RetTy == Args[i].Ty ||
(CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
CLI.RetTy->getPointerAddressSpace() ==
Args[i].Ty->getPointerAddressSpace())) &&
RetTys.size() == NumValues && "unexpected use of 'returned'");
// Before passing 'returned' to the target lowering code, ensure that
// either the register MVT and the actual EVT are the same size or that
// the return value and argument are extended in the same way; in these
// cases it's safe to pass the argument register value unchanged as the
// return register value (although it's at the target's option whether
// to do so)
// TODO: allow code generation to take advantage of partially preserved
// registers rather than clobbering the entire register when the
// parameter extension method is not compatible with the return
// extension method
if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
(ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
CLI.RetZExt == Args[i].IsZExt))
Flags.setReturned();
}
getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
CLI.CallConv, ExtendKind);
for (unsigned j = 0; j != NumParts; ++j) {
// if it isn't first piece, alignment must be 1
// For scalable vectors the scalable part is currently handled
// by individual targets, so we just use the known minimum size here.
ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
i < CLI.NumFixedArgs, i,
j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
if (NumParts > 1 && j == 0)
MyFlags.Flags.setSplit();
else if (j != 0) {
MyFlags.Flags.setOrigAlign(Align(1));
if (j == NumParts - 1)
MyFlags.Flags.setSplitEnd();
}
CLI.Outs.push_back(MyFlags);
CLI.OutVals.push_back(Parts[j]);
}
if (NeedsRegBlock && Value == NumValues - 1)
CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
}
}
SmallVector<SDValue, 4> InVals;
CLI.Chain = LowerCall(CLI, InVals);
// Update CLI.InVals to use outside of this function.
CLI.InVals = InVals;
// Verify that the target's LowerCall behaved as expected.
assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
"LowerCall didn't return a valid chain!");
assert((!CLI.IsTailCall || InVals.empty()) &&
"LowerCall emitted a return value for a tail call!");
assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
"LowerCall didn't emit the correct number of values!");
// For a tail call, the return value is merely live-out and there aren't
// any nodes in the DAG representing it. Return a special value to
// indicate that a tail call has been emitted and no more Instructions
// should be processed in the current block.
if (CLI.IsTailCall) {
CLI.DAG.setRoot(CLI.Chain);
return std::make_pair(SDValue(), SDValue());
}
#ifndef NDEBUG
for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
assert(InVals[i].getNode() && "LowerCall emitted a null value!");
assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
"LowerCall emitted a value with the wrong type!");
}
#endif
SmallVector<SDValue, 4> ReturnValues;
if (!CanLowerReturn) {
// The instruction result is the result of loading from the
// hidden sret parameter.
SmallVector<EVT, 1> PVTs;
Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
assert(PVTs.size() == 1 && "Pointers should fit in one register");
EVT PtrVT = PVTs[0];
unsigned NumValues = RetTys.size();
ReturnValues.resize(NumValues);
SmallVector<SDValue, 4> Chains(NumValues);
// An aggregate return value cannot wrap around the address space, so
// offsets to its parts don't wrap either.
SDNodeFlags Flags;
Flags.setNoUnsignedWrap(true);
MachineFunction &MF = CLI.DAG.getMachineFunction();
Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
for (unsigned i = 0; i < NumValues; ++i) {
SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
CLI.DAG.getConstant(Offsets[i], CLI.DL,
PtrVT), Flags);
SDValue L = CLI.DAG.getLoad(
RetTys[i], CLI.DL, CLI.Chain, Add,
MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
DemoteStackIdx, Offsets[i]),
HiddenSRetAlign);
ReturnValues[i] = L;
Chains[i] = L.getValue(1);
}
CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
} else {
// Collect the legal value parts into potentially illegal values
// that correspond to the original function's return values.
Optional<ISD::NodeType> AssertOp;
if (CLI.RetSExt)
AssertOp = ISD::AssertSext;
else if (CLI.RetZExt)
AssertOp = ISD::AssertZext;
unsigned CurReg = 0;
for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
EVT VT = RetTys[I];
MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
CLI.CallConv, VT);
unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
CLI.CallConv, VT);
ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
NumRegs, RegisterVT, VT, nullptr,
CLI.CallConv, AssertOp));
CurReg += NumRegs;
}
// For a function returning void, there is no return value. We can't create
// such a node, so we just return a null return value in that case. In
// that case, nothing will actually look at the value.
if (ReturnValues.empty())
return std::make_pair(SDValue(), CLI.Chain);
}
SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
CLI.DAG.getVTList(RetTys), ReturnValues);
return std::make_pair(Res, CLI.Chain);
}
/// Places new result values for the node in Results (their number
/// and types must exactly match those of the original return values of
/// the node), or leaves Results empty, which indicates that the node is not
/// to be custom lowered after all.
void TargetLowering::LowerOperationWrapper(SDNode *N,
SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG) const {
SDValue Res = LowerOperation(SDValue(N, 0), DAG);
if (!Res.getNode())
return;
// If the original node has one result, take the return value from
// LowerOperation as is. It might not be result number 0.
if (N->getNumValues() == 1) {
Results.push_back(Res);
return;
}
// If the original node has multiple results, then the return node should
// have the same number of results.
assert((N->getNumValues() == Res->getNumValues()) &&
"Lowering returned the wrong number of results!");
// Places new result values base on N result number.
for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
Results.push_back(Res.getValue(I));
}
SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
llvm_unreachable("LowerOperation not implemented for this target!");
}
void
SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
SDValue Op = getNonRegisterValue(V);
assert((Op.getOpcode() != ISD::CopyFromReg ||
cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
"Copy from a reg to the same reg!");
assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
// If this is an InlineAsm we have to match the registers required, not the
// notional registers required by the type.
RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
None); // This is not an ABI copy.
SDValue Chain = DAG.getEntryNode();
ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
FuncInfo.PreferredExtendType.end())
? ISD::ANY_EXTEND
: FuncInfo.PreferredExtendType[V];
RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
PendingExports.push_back(Chain);
}
#include "llvm/CodeGen/SelectionDAGISel.h"
/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
/// entry block, return true. This includes arguments used by switches, since
/// the switch may expand into multiple basic blocks.
static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
// With FastISel active, we may be splitting blocks, so force creation
// of virtual registers for all non-dead arguments.
if (FastISel)
return A->use_empty();
const BasicBlock &Entry = A->getParent()->front();
for (const User *U : A->users())
if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
return false; // Use not in entry block.
return true;
}
using ArgCopyElisionMapTy =
DenseMap<const Argument *,
std::pair<const AllocaInst *, const StoreInst *>>;
/// Scan the entry block of the function in FuncInfo for arguments that look
/// like copies into a local alloca. Record any copied arguments in
/// ArgCopyElisionCandidates.
static void
findArgumentCopyElisionCandidates(const DataLayout &DL,
FunctionLoweringInfo *FuncInfo,
ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
// Record the state of every static alloca used in the entry block. Argument
// allocas are all used in the entry block, so we need approximately as many
// entries as we have arguments.
enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
unsigned NumArgs = FuncInfo->Fn->arg_size();
StaticAllocas.reserve(NumArgs * 2);
auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
if (!V)
return nullptr;
V = V->stripPointerCasts();
const auto *AI = dyn_cast<AllocaInst>(V);
if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
return nullptr;
auto Iter = StaticAllocas.insert({AI, Unknown});
return &Iter.first->second;
};
// Look for stores of arguments to static allocas. Look through bitcasts and
// GEPs to handle type coercions, as long as the alloca is fully initialized
// by the store. Any non-store use of an alloca escapes it and any subsequent
// unanalyzed store might write it.
// FIXME: Handle structs initialized with multiple stores.
for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
// Look for stores, and handle non-store uses conservatively.
const auto *SI = dyn_cast<StoreInst>(&I);
if (!SI) {
// We will look through cast uses, so ignore them completely.
if (I.isCast())
continue;
// Ignore debug info and pseudo op intrinsics, they don't escape or store
// to allocas.
if (I.isDebugOrPseudoInst())
continue;
// This is an unknown instruction. Assume it escapes or writes to all
// static alloca operands.
for (const Use &U : I.operands()) {
if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
*Info = StaticAllocaInfo::Clobbered;
}
continue;
}
// If the stored value is a static alloca, mark it as escaped.
if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
*Info = StaticAllocaInfo::Clobbered;
// Check if the destination is a static alloca.
const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
if (!Info)
continue;
const AllocaInst *AI = cast<AllocaInst>(Dst);
// Skip allocas that have been initialized or clobbered.
if (*Info != StaticAllocaInfo::Unknown)
continue;
// Check if the stored value is an argument, and that this store fully
// initializes the alloca. Don't elide copies from the same argument twice.
const Value *Val = SI->getValueOperand()->stripPointerCasts();
const auto *Arg = dyn_cast<Argument>(Val);
if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
Arg->getType()->isEmptyTy() ||
DL.getTypeStoreSize(Arg->getType()) !=
DL.getTypeAllocSize(AI->getAllocatedType()) ||
ArgCopyElisionCandidates.count(Arg)) {
*Info = StaticAllocaInfo::Clobbered;
continue;
}
LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
<< '\n');
// Mark this alloca and store for argument copy elision.
*Info = StaticAllocaInfo::Elidable;
ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
// Stop scanning if we've seen all arguments. This will happen early in -O0
// builds, which is useful, because -O0 builds have large entry blocks and
// many allocas.
if (ArgCopyElisionCandidates.size() == NumArgs)
break;
}
}
/// Try to elide argument copies from memory into a local alloca. Succeeds if
/// ArgVal is a load from a suitable fixed stack object.
static void tryToElideArgumentCopy(
FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
SDValue ArgVal, bool &ArgHasUses) {
// Check if this is a load from a fixed stack object.
auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
if (!LNode)
return;
auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
if (!FINode)
return;
// Check that the fixed stack object is the right size and alignment.
// Look at the alignment that the user wrote on the alloca instead of looking
// at the stack object.
auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
assert(ArgCopyIter != ArgCopyElisionCandidates.end());
const AllocaInst *AI = ArgCopyIter->second.first;
int FixedIndex = FINode->getIndex();
int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
int OldIndex = AllocaIndex;
MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
LLVM_DEBUG(
dbgs() << " argument copy elision failed due to bad fixed stack "
"object size\n");
return;
}
Align RequiredAlignment = AI->getAlign();
if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
"greater than stack argument alignment ("
<< DebugStr(RequiredAlignment) << " vs "
<< DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
return;
}
// Perform the elision. Delete the old stack object and replace its only use
// in the variable info map. Mark the stack object as mutable.
LLVM_DEBUG({
dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
<< " Replacing frame index " << OldIndex << " with " << FixedIndex
<< '\n';
});
MFI.RemoveStackObject(OldIndex);
MFI.setIsImmutableObjectIndex(FixedIndex, false);
AllocaIndex = FixedIndex;
ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
Chains.push_back(ArgVal.getValue(1));
// Avoid emitting code for the store implementing the copy.
const StoreInst *SI = ArgCopyIter->second.second;
ElidedArgCopyInstrs.insert(SI);
// Check for uses of the argument again so that we can avoid exporting ArgVal
// if it is't used by anything other than the store.
for (const Value *U : Arg.users()) {
if (U != SI) {
ArgHasUses = true;
break;
}
}
}
void SelectionDAGISel::LowerArguments(const Function &F) {
SelectionDAG &DAG = SDB->DAG;
SDLoc dl = SDB->getCurSDLoc();
const DataLayout &DL = DAG.getDataLayout();
SmallVector<ISD::InputArg, 16> Ins;
// In Naked functions we aren't going to save any registers.
if (F.hasFnAttribute(Attribute::Naked))
return;
if (!FuncInfo->CanLowerReturn) {
// Put in an sret pointer parameter before all the other parameters.
SmallVector<EVT, 1> ValueVTs;
ComputeValueVTs(*TLI, DAG.getDataLayout(),
F.getReturnType()->getPointerTo(
DAG.getDataLayout().getAllocaAddrSpace()),
ValueVTs);
// NOTE: Assuming that a pointer will never break down to more than one VT
// or one register.
ISD::ArgFlagsTy Flags;
Flags.setSRet();
MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
ISD::InputArg::NoArgIndex, 0);
Ins.push_back(RetArg);
}
// Look for stores of arguments to static allocas. Mark such arguments with a
// flag to ask the target to give us the memory location of that argument if
// available.
ArgCopyElisionMapTy ArgCopyElisionCandidates;
findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
ArgCopyElisionCandidates);
// Set up the incoming argument description vector.
for (const Argument &Arg : F.args()) {
unsigned ArgNo = Arg.getArgNo();
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
bool isArgValueUsed = !Arg.use_empty();
unsigned PartBase = 0;
Type *FinalType = Arg.getType();
if (Arg.hasAttribute(Attribute::ByVal))
FinalType = Arg.getParamByValType();
bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
FinalType, F.getCallingConv(), F.isVarArg());
for (unsigned Value = 0, NumValues = ValueVTs.size();
Value != NumValues; ++Value) {
EVT VT = ValueVTs[Value];
Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
ISD::ArgFlagsTy Flags;
// Certain targets (such as MIPS), may have a different ABI alignment
// for a type depending on the context. Give the target a chance to
// specify the alignment it wants.
const Align OriginalAlignment(
TLI->getABIAlignmentForCallingConv(ArgTy, DL));
if (Arg.getType()->isPointerTy()) {
Flags.setPointer();
Flags.setPointerAddrSpace(
cast<PointerType>(Arg.getType())->getAddressSpace());
}
if (Arg.hasAttribute(Attribute::ZExt))
Flags.setZExt();
if (Arg.hasAttribute(Attribute::SExt))
Flags.setSExt();
if (Arg.hasAttribute(Attribute::InReg)) {
// If we are using vectorcall calling convention, a structure that is
// passed InReg - is surely an HVA
if (F.getCallingConv() == CallingConv::X86_VectorCall &&
isa<StructType>(Arg.getType())) {
// The first value of a structure is marked
if (0 == Value)
Flags.setHvaStart();
Flags.setHva();
}
// Set InReg Flag
Flags.setInReg();
}
if (Arg.hasAttribute(Attribute::StructRet))
Flags.setSRet();
if (Arg.hasAttribute(Attribute::SwiftSelf))
Flags.setSwiftSelf();
if (Arg.hasAttribute(Attribute::SwiftError))
Flags.setSwiftError();
if (Arg.hasAttribute(Attribute::ByVal))
Flags.setByVal();
if (Arg.hasAttribute(Attribute::ByRef))
Flags.setByRef();
if (Arg.hasAttribute(Attribute::InAlloca)) {
Flags.setInAlloca();
// Set the byval flag for CCAssignFn callbacks that don't know about
// inalloca. This way we can know how many bytes we should've allocated
// and how many bytes a callee cleanup function will pop. If we port
// inalloca to more targets, we'll have to add custom inalloca handling
// in the various CC lowering callbacks.
Flags.setByVal();
}
if (Arg.hasAttribute(Attribute::Preallocated)) {
Flags.setPreallocated();
// Set the byval flag for CCAssignFn callbacks that don't know about
// preallocated. This way we can know how many bytes we should've
// allocated and how many bytes a callee cleanup function will pop. If
// we port preallocated to more targets, we'll have to add custom
// preallocated handling in the various CC lowering callbacks.
Flags.setByVal();
}
Type *ArgMemTy = nullptr;
if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
Flags.isByRef()) {
if (!ArgMemTy)
ArgMemTy = Arg.getPointeeInMemoryValueType();
uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
// For in-memory arguments, size and alignment should be passed from FE.
// BE will guess if this info is not there but there are cases it cannot
// get right.
MaybeAlign MemAlign = Arg.getParamAlign();
if (!MemAlign)
MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
if (Flags.isByRef()) {
Flags.setByRefSize(MemSize);
Flags.setByRefAlign(*MemAlign);
} else {
Flags.setByValSize(MemSize);
Flags.setByValAlign(*MemAlign);
}
}
if (Arg.hasAttribute(Attribute::Nest))
Flags.setNest();
if (NeedsRegBlock)
Flags.setInConsecutiveRegs();
Flags.setOrigAlign(OriginalAlignment);
if (ArgCopyElisionCandidates.count(&Arg))
Flags.setCopyElisionCandidate();
if (Arg.hasAttribute(Attribute::Returned))
Flags.setReturned();
MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
*CurDAG->getContext(), F.getCallingConv(), VT);
unsigned NumRegs = TLI->getNumRegistersForCallingConv(
*CurDAG->getContext(), F.getCallingConv(), VT);
for (unsigned i = 0; i != NumRegs; ++i) {
// For scalable vectors, use the minimum size; individual targets
// are responsible for handling scalable vector arguments and
// return values.
ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
if (NumRegs > 1 && i == 0)
MyFlags.Flags.setSplit();
// if it isn't first piece, alignment must be 1
else if (i > 0) {
MyFlags.Flags.setOrigAlign(Align(1));
if (i == NumRegs - 1)
MyFlags.Flags.setSplitEnd();
}
Ins.push_back(MyFlags);
}
if (NeedsRegBlock && Value == NumValues - 1)
Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
PartBase += VT.getStoreSize().getKnownMinSize();
}
}
// Call the target to set up the argument values.
SmallVector<SDValue, 8> InVals;
SDValue NewRoot = TLI->LowerFormalArguments(
DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
// Verify that the target's LowerFormalArguments behaved as expected.
assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
"LowerFormalArguments didn't return a valid chain!");
assert(InVals.size() == Ins.size() &&
"LowerFormalArguments didn't emit the correct number of values!");
LLVM_DEBUG({
for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
assert(InVals[i].getNode() &&
"LowerFormalArguments emitted a null value!");
assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
"LowerFormalArguments emitted a value with the wrong type!");
}
});
// Update the DAG with the new chain value resulting from argument lowering.
DAG.setRoot(NewRoot);
// Set up the argument values.
unsigned i = 0;
if (!FuncInfo->CanLowerReturn) {
// Create a virtual register for the sret pointer, and put in a copy
// from the sret argument into it.
SmallVector<EVT, 1> ValueVTs;
ComputeValueVTs(*TLI, DAG.getDataLayout(),
F.getReturnType()->getPointerTo(
DAG.getDataLayout().getAllocaAddrSpace()),
ValueVTs);
MVT VT = ValueVTs[0].getSimpleVT();
MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
Optional<ISD::NodeType> AssertOp = None;
SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
nullptr, F.getCallingConv(), AssertOp);
MachineFunction& MF = SDB->DAG.getMachineFunction();
MachineRegisterInfo& RegInfo = MF.getRegInfo();
Register SRetReg =
RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
FuncInfo->DemoteRegister = SRetReg;
NewRoot =
SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
DAG.setRoot(NewRoot);
// i indexes lowered arguments. Bump it past the hidden sret argument.
++i;
}
SmallVector<SDValue, 4> Chains;
DenseMap<int, int> ArgCopyElisionFrameIndexMap;
for (const Argument &Arg : F.args()) {
SmallVector<SDValue, 4> ArgValues;
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
unsigned NumValues = ValueVTs.size();
if (NumValues == 0)
continue;
bool ArgHasUses = !Arg.use_empty();
// Elide the copying store if the target loaded this argument from a
// suitable fixed stack object.
if (Ins[i].Flags.isCopyElisionCandidate()) {
tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
InVals[i], ArgHasUses);
}
// If this argument is unused then remember its value. It is used to generate
// debugging information.
bool isSwiftErrorArg =
TLI->supportSwiftError() &&
Arg.hasAttribute(Attribute::SwiftError);
if (!ArgHasUses && !isSwiftErrorArg) {
SDB->setUnusedArgValue(&Arg, InVals[i]);
// Also remember any frame index for use in FastISel.
if (FrameIndexSDNode *FI =
dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
}
for (unsigned Val = 0; Val != NumValues; ++Val) {
EVT VT = ValueVTs[Val];
MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
F.getCallingConv(), VT);
unsigned NumParts = TLI->getNumRegistersForCallingConv(
*CurDAG->getContext(), F.getCallingConv(), VT);
// Even an apparent 'unused' swifterror argument needs to be returned. So
// we do generate a copy for it that can be used on return from the
// function.
if (ArgHasUses || isSwiftErrorArg) {
Optional<ISD::NodeType> AssertOp;
if (Arg.hasAttribute(Attribute::SExt))
AssertOp = ISD::AssertSext;
else if (Arg.hasAttribute(Attribute::ZExt))
AssertOp = ISD::AssertZext;
ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
PartVT, VT, nullptr,
F.getCallingConv(), AssertOp));
}
i += NumParts;
}
// We don't need to do anything else for unused arguments.
if (ArgValues.empty())
continue;
// Note down frame index.
if (FrameIndexSDNode *FI =
dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
SDB->getCurSDLoc());
SDB->setValue(&Arg, Res);
if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
// We want to associate the argument with the frame index, among
// involved operands, that correspond to the lowest address. The
// getCopyFromParts function, called earlier, is swapping the order of
// the operands to BUILD_PAIR depending on endianness. The result of
// that swapping is that the least significant bits of the argument will
// be in the first operand of the BUILD_PAIR node, and the most
// significant bits will be in the second operand.
unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
if (LoadSDNode *LNode =
dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
if (FrameIndexSDNode *FI =
dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
}
// Analyses past this point are naive and don't expect an assertion.
if (Res.getOpcode() == ISD::AssertZext)
Res = Res.getOperand(0);
// Update the SwiftErrorVRegDefMap.
if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
if (Register::isVirtualRegister(Reg))
SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
Reg);
}
// If this argument is live outside of the entry block, insert a copy from
// wherever we got it to the vreg that other BB's will reference it as.
if (Res.getOpcode() == ISD::CopyFromReg) {
// If we can, though, try to skip creating an unnecessary vreg.
// FIXME: This isn't very clean... it would be nice to make this more
// general.
unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
if (Register::isVirtualRegister(Reg)) {
FuncInfo->ValueMap[&Arg] = Reg;
continue;
}
}
if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
FuncInfo->InitializeRegForValue(&Arg);
SDB->CopyToExportRegsIfNeeded(&Arg);
}
}
if (!Chains.empty()) {
Chains.push_back(NewRoot);
NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
}
DAG.setRoot(NewRoot);
assert(i == InVals.size() && "Argument register count mismatch!");
// If any argument copy elisions occurred and we have debug info, update the
// stale frame indices used in the dbg.declare variable info table.
MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
if (I != ArgCopyElisionFrameIndexMap.end())
VI.Slot = I->second;
}
}
// Finally, if the target has anything special to do, allow it to do so.
emitFunctionEntryCode();
}
/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
/// ensure constants are generated when needed. Remember the virtual registers
/// that need to be added to the Machine PHI nodes as input. We cannot just
/// directly add them, because expansion might result in multiple MBB's for one
/// BB. As such, the start of the BB might correspond to a different MBB than
/// the end.
void
SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
const Instruction *TI = LLVMBB->getTerminator();
SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
// Check PHI nodes in successors that expect a value to be available from this
// block.
for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
const BasicBlock *SuccBB = TI->getSuccessor(succ);
if (!isa<PHINode>(SuccBB->begin())) continue;
MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
// If this terminator has multiple identical successors (common for
// switches), only handle each succ once.
if (!SuccsHandled.insert(SuccMBB).second)
continue;
MachineBasicBlock::iterator MBBI = SuccMBB->begin();
// At this point we know that there is a 1-1 correspondence between LLVM PHI
// nodes and Machine PHI nodes, but the incoming operands have not been
// emitted yet.
for (const PHINode &PN : SuccBB->phis()) {
// Ignore dead phi's.
if (PN.use_empty())
continue;
// Skip empty types
if (PN.getType()->isEmptyTy())
continue;
unsigned Reg;
const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
unsigned &RegOut = ConstantsOut[C];
if (RegOut == 0) {
RegOut = FuncInfo.CreateRegs(C);
CopyValueToVirtualRegister(C, RegOut);
}
Reg = RegOut;
} else {
DenseMap<const Value *, Register>::iterator I =
FuncInfo.ValueMap.find(PHIOp);
if (I != FuncInfo.ValueMap.end())
Reg = I->second;
else {
assert(isa<AllocaInst>(PHIOp) &&
FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
"Didn't codegen value into a register!??");
Reg = FuncInfo.CreateRegs(PHIOp);
CopyValueToVirtualRegister(PHIOp, Reg);
}
}
// Remember that this register needs to added to the machine PHI node as
// the input for this MBB.
SmallVector<EVT, 4> ValueVTs;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
EVT VT = ValueVTs[vti];
unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
for (unsigned i = 0, e = NumRegisters; i != e; ++i)
FuncInfo.PHINodesToUpdate.push_back(
std::make_pair(&*MBBI++, Reg + i));
Reg += NumRegisters;
}
}
}
ConstantsOut.clear();
}
/// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
/// is 0.
MachineBasicBlock *
SelectionDAGBuilder::StackProtectorDescriptor::
AddSuccessorMBB(const BasicBlock *BB,
MachineBasicBlock *ParentMBB,
bool IsLikely,
MachineBasicBlock *SuccMBB) {
// If SuccBB has not been created yet, create it.
if (!SuccMBB) {
MachineFunction *MF = ParentMBB->getParent();
MachineFunction::iterator BBI(ParentMBB);
SuccMBB = MF->CreateMachineBasicBlock(BB);
MF->insert(++BBI, SuccMBB);
}
// Add it as a successor of ParentMBB.
ParentMBB->addSuccessor(
SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
return SuccMBB;
}
MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
MachineFunction::iterator I(MBB);
if (++I == FuncInfo.MF->end())
return nullptr;
return &*I;
}
/// During lowering new call nodes can be created (such as memset, etc.).
/// Those will become new roots of the current DAG, but complications arise
/// when they are tail calls. In such cases, the call lowering will update
/// the root, but the builder still needs to know that a tail call has been
/// lowered in order to avoid generating an additional return.
void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
// If the node is null, we do have a tail call.
if (MaybeTC.getNode() != nullptr)
DAG.setRoot(MaybeTC);
else
HasTailCall = true;
}
void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
MachineBasicBlock *SwitchMBB,
MachineBasicBlock *DefaultMBB) {
MachineFunction *CurMF = FuncInfo.MF;
MachineBasicBlock *NextMBB = nullptr;
MachineFunction::iterator BBI(W.MBB);
if (++BBI != FuncInfo.MF->end())
NextMBB = &*BBI;
unsigned Size = W.LastCluster - W.FirstCluster + 1;
BranchProbabilityInfo *BPI = FuncInfo.BPI;
if (Size == 2 && W.MBB == SwitchMBB) {
// If any two of the cases has the same destination, and if one value
// is the same as the other, but has one bit unset that the other has set,
// use bit manipulation to do two compares at once. For example:
// "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
// TODO: This could be extended to merge any 2 cases in switches with 3
// cases.
// TODO: Handle cases where W.CaseBB != SwitchBB.
CaseCluster &Small = *W.FirstCluster;
CaseCluster &Big = *W.LastCluster;
if (Small.Low == Small.High && Big.Low == Big.High &&
Small.MBB == Big.MBB) {
const APInt &SmallValue = Small.Low->getValue();
const APInt &BigValue = Big.Low->getValue();
// Check that there is only one bit different.
APInt CommonBit = BigValue ^ SmallValue;
if (CommonBit.isPowerOf2()) {
SDValue CondLHS = getValue(Cond);
EVT VT = CondLHS.getValueType();
SDLoc DL = getCurSDLoc();
SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
DAG.getConstant(CommonBit, DL, VT));
SDValue Cond = DAG.getSetCC(
DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
ISD::SETEQ);
// Update successor info.
// Both Small and Big will jump to Small.BB, so we sum up the
// probabilities.
addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
if (BPI)
addSuccessorWithProb(
SwitchMBB, DefaultMBB,
// The default destination is the first successor in IR.
BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
else
addSuccessorWithProb(SwitchMBB, DefaultMBB);
// Insert the true branch.
SDValue BrCond =
DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
DAG.getBasicBlock(Small.MBB));
// Insert the false branch.
BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
DAG.getBasicBlock(DefaultMBB));
DAG.setRoot(BrCond);
return;
}
}
}
if (TM.getOptLevel() != CodeGenOpt::None) {
// Here, we order cases by probability so the most likely case will be
// checked first. However, two clusters can have the same probability in
// which case their relative ordering is non-deterministic. So we use Low
// as a tie-breaker as clusters are guaranteed to never overlap.
llvm::sort(W.FirstCluster, W.LastCluster + 1,
[](const CaseCluster &a, const CaseCluster &b) {
return a.Prob != b.Prob ?
a.Prob > b.Prob :
a.Low->getValue().slt(b.Low->getValue());
});
// Rearrange the case blocks so that the last one falls through if possible
// without changing the order of probabilities.
for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
--I;
if (I->Prob > W.LastCluster->Prob)
break;
if (I->Kind == CC_Range && I->MBB == NextMBB) {
std::swap(*I, *W.LastCluster);
break;
}
}
}
// Compute total probability.
BranchProbability DefaultProb = W.DefaultProb;
BranchProbability UnhandledProbs = DefaultProb;
for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
UnhandledProbs += I->Prob;
MachineBasicBlock *CurMBB = W.MBB;
for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
bool FallthroughUnreachable = false;
MachineBasicBlock *Fallthrough;
if (I == W.LastCluster) {
// For the last cluster, fall through to the default destination.
Fallthrough = DefaultMBB;
FallthroughUnreachable = isa<UnreachableInst>(
DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
} else {
Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
CurMF->insert(BBI, Fallthrough);
// Put Cond in a virtual register to make it available from the new blocks.
ExportFromCurrentBlock(Cond);
}
UnhandledProbs -= I->Prob;
switch (I->Kind) {
case CC_JumpTable: {
// FIXME: Optimize away range check based on pivot comparisons.
JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
// The jump block hasn't been inserted yet; insert it here.
MachineBasicBlock *JumpMBB = JT->MBB;
CurMF->insert(BBI, JumpMBB);
auto JumpProb = I->Prob;
auto FallthroughProb = UnhandledProbs;
// If the default statement is a target of the jump table, we evenly
// distribute the default probability to successors of CurMBB. Also
// update the probability on the edge from JumpMBB to Fallthrough.
for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
SE = JumpMBB->succ_end();
SI != SE; ++SI) {
if (*SI == DefaultMBB) {
JumpProb += DefaultProb / 2;
FallthroughProb -= DefaultProb / 2;
JumpMBB->setSuccProbability(SI, DefaultProb / 2);
JumpMBB->normalizeSuccProbs();
break;
}
}
if (FallthroughUnreachable) {
// Skip the range check if the fallthrough block is unreachable.
JTH->OmitRangeCheck = true;
}
if (!JTH->OmitRangeCheck)
addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
CurMBB->normalizeSuccProbs();
// The jump table header will be inserted in our current block, do the
// range check, and fall through to our fallthrough block.
JTH->HeaderBB = CurMBB;
JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
// If we're in the right place, emit the jump table header right now.
if (CurMBB == SwitchMBB) {
visitJumpTableHeader(*JT, *JTH, SwitchMBB);
JTH->Emitted = true;
}
break;
}
case CC_BitTests: {
// FIXME: Optimize away range check based on pivot comparisons.
BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
// The bit test blocks haven't been inserted yet; insert them here.
for (BitTestCase &BTC : BTB->Cases)
CurMF->insert(BBI, BTC.ThisBB);
// Fill in fields of the BitTestBlock.
BTB->Parent = CurMBB;
BTB->Default = Fallthrough;
BTB->DefaultProb = UnhandledProbs;
// If the cases in bit test don't form a contiguous range, we evenly
// distribute the probability on the edge to Fallthrough to two
// successors of CurMBB.
if (!BTB->ContiguousRange) {
BTB->Prob += DefaultProb / 2;
BTB->DefaultProb -= DefaultProb / 2;
}
if (FallthroughUnreachable) {
// Skip the range check if the fallthrough block is unreachable.
BTB->OmitRangeCheck = true;
}
// If we're in the right place, emit the bit test header right now.
if (CurMBB == SwitchMBB) {
visitBitTestHeader(*BTB, SwitchMBB);
BTB->Emitted = true;
}
break;
}
case CC_Range: {
const Value *RHS, *LHS, *MHS;
ISD::CondCode CC;
if (I->Low == I->High) {
// Check Cond == I->Low.
CC = ISD::SETEQ;
LHS = Cond;
RHS=I->Low;
MHS = nullptr;
} else {
// Check I->Low <= Cond <= I->High.
CC = ISD::SETLE;
LHS = I->Low;
MHS = Cond;
RHS = I->High;
}
// If Fallthrough is unreachable, fold away the comparison.
if (FallthroughUnreachable)
CC = ISD::SETTRUE;
// The false probability is the sum of all unhandled cases.
CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
getCurSDLoc(), I->Prob, UnhandledProbs);
if (CurMBB == SwitchMBB)
visitSwitchCase(CB, SwitchMBB);
else
SL->SwitchCases.push_back(CB);
break;
}
}
CurMBB = Fallthrough;
}
}
unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
CaseClusterIt First,
CaseClusterIt Last) {
return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
if (X.Prob != CC.Prob)
return X.Prob > CC.Prob;
// Ties are broken by comparing the case value.
return X.Low->getValue().slt(CC.Low->getValue());
});
}
void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
const SwitchWorkListItem &W,
Value *Cond,
MachineBasicBlock *SwitchMBB) {
assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
"Clusters not sorted?");
assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
// Balance the tree based on branch probabilities to create a near-optimal (in
// terms of search time given key frequency) binary search tree. See e.g. Kurt
// Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
CaseClusterIt LastLeft = W.FirstCluster;
CaseClusterIt FirstRight = W.LastCluster;
auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
// Move LastLeft and FirstRight towards each other from opposite directions to
// find a partitioning of the clusters which balances the probability on both
// sides. If LeftProb and RightProb are equal, alternate which side is
// taken to ensure 0-probability nodes are distributed evenly.
unsigned I = 0;
while (LastLeft + 1 < FirstRight) {
if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
LeftProb += (++LastLeft)->Prob;
else
RightProb += (--FirstRight)->Prob;
I++;
}
while (true) {
// Our binary search tree differs from a typical BST in that ours can have up
// to three values in each leaf. The pivot selection above doesn't take that
// into account, which means the tree might require more nodes and be less
// efficient. We compensate for this here.
unsigned NumLeft = LastLeft - W.FirstCluster + 1;
unsigned NumRight = W.LastCluster - FirstRight + 1;
if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
// If one side has less than 3 clusters, and the other has more than 3,
// consider taking a cluster from the other side.
if (NumLeft < NumRight) {
// Consider moving the first cluster on the right to the left side.
CaseCluster &CC = *FirstRight;
unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
if (LeftSideRank <= RightSideRank) {
// Moving the cluster to the left does not demote it.
++LastLeft;
++FirstRight;
continue;
}
} else {
assert(NumRight < NumLeft);
// Consider moving the last element on the left to the right side.
CaseCluster &CC = *LastLeft;
unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
if (RightSideRank <= LeftSideRank) {
// Moving the cluster to the right does not demot it.
--LastLeft;
--FirstRight;
continue;
}
}
}
break;
}
assert(LastLeft + 1 == FirstRight);
assert(LastLeft >= W.FirstCluster);
assert(FirstRight <= W.LastCluster);
// Use the first element on the right as pivot since we will make less-than
// comparisons against it.
CaseClusterIt PivotCluster = FirstRight;
assert(PivotCluster > W.FirstCluster);
assert(PivotCluster <= W.LastCluster);
CaseClusterIt FirstLeft = W.FirstCluster;
CaseClusterIt LastRight = W.LastCluster;
const ConstantInt *Pivot = PivotCluster->Low;
// New blocks will be inserted immediately after the current one.
MachineFunction::iterator BBI(W.MBB);
++BBI;
// We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
// we can branch to its destination directly if it's squeezed exactly in
// between the known lower bound and Pivot - 1.
MachineBasicBlock *LeftMBB;
if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
FirstLeft->Low == W.GE &&
(FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
LeftMBB = FirstLeft->MBB;
} else {
LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
FuncInfo.MF->insert(BBI, LeftMBB);
WorkList.push_back(
{LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
// Put Cond in a virtual register to make it available from the new blocks.
ExportFromCurrentBlock(Cond);
}
// Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
// single cluster, RHS.Low == Pivot, and we can branch to its destination
// directly if RHS.High equals the current upper bound.
MachineBasicBlock *RightMBB;
if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
RightMBB = FirstRight->MBB;
} else {
RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
FuncInfo.MF->insert(BBI, RightMBB);
WorkList.push_back(
{RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
// Put Cond in a virtual register to make it available from the new blocks.
ExportFromCurrentBlock(Cond);
}
// Create the CaseBlock record that will be used to lower the branch.
CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
getCurSDLoc(), LeftProb, RightProb);
if (W.MBB == SwitchMBB)
visitSwitchCase(CB, SwitchMBB);
else
SL->SwitchCases.push_back(CB);
}
// Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
// from the swith statement.
static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
BranchProbability PeeledCaseProb) {
if (PeeledCaseProb == BranchProbability::getOne())
return BranchProbability::getZero();
BranchProbability SwitchProb = PeeledCaseProb.getCompl();
uint32_t Numerator = CaseProb.getNumerator();
uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
return BranchProbability(Numerator, std::max(Numerator, Denominator));
}
// Try to peel the top probability case if it exceeds the threshold.
// Return current MachineBasicBlock for the switch statement if the peeling
// does not occur.
// If the peeling is performed, return the newly created MachineBasicBlock
// for the peeled switch statement. Also update Clusters to remove the peeled
// case. PeeledCaseProb is the BranchProbability for the peeled case.
MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
const SwitchInst &SI, CaseClusterVector &Clusters,
BranchProbability &PeeledCaseProb) {
MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
// Don't perform if there is only one cluster or optimizing for size.
if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
TM.getOptLevel() == CodeGenOpt::None ||
SwitchMBB->getParent()->getFunction().hasMinSize())
return SwitchMBB;
BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
unsigned PeeledCaseIndex = 0;
bool SwitchPeeled = false;
for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
CaseCluster &CC = Clusters[Index];
if (CC.Prob < TopCaseProb)
continue;
TopCaseProb = CC.Prob;
PeeledCaseIndex = Index;
SwitchPeeled = true;
}
if (!SwitchPeeled)
return SwitchMBB;
LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
<< TopCaseProb << "\n");
// Record the MBB for the peeled switch statement.
MachineFunction::iterator BBI(SwitchMBB);
++BBI;
MachineBasicBlock *PeeledSwitchMBB =
FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
ExportFromCurrentBlock(SI.getCondition());
auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
nullptr, nullptr, TopCaseProb.getCompl()};
lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
Clusters.erase(PeeledCaseIt);
for (CaseCluster &CC : Clusters) {
LLVM_DEBUG(
dbgs() << "Scale the probablity for one cluster, before scaling: "
<< CC.Prob << "\n");
CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
}
PeeledCaseProb = TopCaseProb;
return PeeledSwitchMBB;
}
void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
// Extract cases from the switch.
BranchProbabilityInfo *BPI = FuncInfo.BPI;
CaseClusterVector Clusters;
Clusters.reserve(SI.getNumCases());
for (auto I : SI.cases()) {
MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
const ConstantInt *CaseVal = I.getCaseValue();
BranchProbability Prob =
BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
: BranchProbability(1, SI.getNumCases() + 1);
Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
}
MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
// Cluster adjacent cases with the same destination. We do this at all
// optimization levels because it's cheap to do and will make codegen faster
// if there are many clusters.
sortAndRangeify(Clusters);
// The branch probablity of the peeled case.
BranchProbability PeeledCaseProb = BranchProbability::getZero();
MachineBasicBlock *PeeledSwitchMBB =
peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
// If there is only the default destination, jump there directly.
MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
if (Clusters.empty()) {
assert(PeeledSwitchMBB == SwitchMBB);
SwitchMBB->addSuccessor(DefaultMBB);
if (DefaultMBB != NextBlock(SwitchMBB)) {
DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
}
return;
}
SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
SL->findBitTestClusters(Clusters, &SI);
LLVM_DEBUG({
dbgs() << "Case clusters: ";
for (const CaseCluster &C : Clusters) {
if (C.Kind == CC_JumpTable)
dbgs() << "JT:";
if (C.Kind == CC_BitTests)
dbgs() << "BT:";
C.Low->getValue().print(dbgs(), true);
if (C.Low != C.High) {
dbgs() << '-';
C.High->getValue().print(dbgs(), true);
}
dbgs() << ' ';
}
dbgs() << '\n';
});
assert(!Clusters.empty());
SwitchWorkList WorkList;
CaseClusterIt First = Clusters.begin();
CaseClusterIt Last = Clusters.end() - 1;
auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
// Scale the branchprobability for DefaultMBB if the peel occurs and
// DefaultMBB is not replaced.
if (PeeledCaseProb != BranchProbability::getZero() &&
DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
WorkList.push_back(
{PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
while (!WorkList.empty()) {
SwitchWorkListItem W = WorkList.pop_back_val();
unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
!DefaultMBB->getParent()->getFunction().hasMinSize()) {
// For optimized builds, lower large range as a balanced binary tree.
splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
continue;
}
lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
}
}
void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
SDLoc DL = getCurSDLoc();
SDValue V = getValue(I.getOperand(0));
assert(VT == V.getValueType() && "Malformed vector.reverse!");
if (VT.isScalableVector()) {
setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
return;
}
// Use VECTOR_SHUFFLE for the fixed-length vector
// to maintain existing behavior.
SmallVector<int, 8> Mask;
unsigned NumElts = VT.getVectorMinNumElements();
for (unsigned i = 0; i != NumElts; ++i)
Mask.push_back(NumElts - 1 - i);
setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
}
void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
SmallVector<EVT, 4> ValueVTs;
ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
ValueVTs);
unsigned NumValues = ValueVTs.size();
if (NumValues == 0) return;
SmallVector<SDValue, 4> Values(NumValues);
SDValue Op = getValue(I.getOperand(0));
for (unsigned i = 0; i != NumValues; ++i)
Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
SDValue(Op.getNode(), Op.getResNo() + i));
setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
DAG.getVTList(ValueVTs), Values));
}
void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
SDLoc DL = getCurSDLoc();
SDValue V1 = getValue(I.getOperand(0));
SDValue V2 = getValue(I.getOperand(1));
int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
// VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
if (VT.isScalableVector()) {
MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
DAG.getConstant(Imm, DL, IdxVT)));
return;
}
unsigned NumElts = VT.getVectorNumElements();
if ((-Imm > NumElts) || (Imm >= NumElts)) {
// Result is undefined if immediate is out-of-bounds.
setValue(&I, DAG.getUNDEF(VT));
return;
}
uint64_t Idx = (NumElts + Imm) % NumElts;
// Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
SmallVector<int, 8> Mask;
for (unsigned i = 0; i < NumElts; ++i)
Mask.push_back(Idx + i);
setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
}
|
; You may customize this and other start-up templates;
; The location of this template is c:\emu8086\inc\0_com_template.txt
org 100h
MOV DX,0
MOV AH,1
INT 21H
WHILE_:
CMP AL,0DH
JE END_WHILE_
INC DX
INT 21H
JMP WHILE_
END_WHILE_:
MOV AH,4CH
INT 21H
ret
|
;*****************************************************************************
;* const-a.asm: x86 global constants
;*****************************************************************************
;* Copyright (C) 2010-2021 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Fiona Glaser <fiona@x264.com>
;*
;* This program is free software; you can redistribute it and/or modify
;* it under the terms of the GNU General Public License as published by
;* the Free Software Foundation; either version 2 of the License, or
;* (at your option) any later version.
;*
;* This program is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;* GNU General Public License for more details.
;*
;* You should have received a copy of the GNU General Public License
;* along with this program; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
;*
;* This program is also available under a commercial proprietary license.
;* For more information, contact us at licensing@x264.com.
;*****************************************************************************
%include "x86inc.asm"
SECTION_RODATA 32
const pb_1, times 32 db 1
const hsub_mul, times 16 db 1, -1
const pw_1, times 16 dw 1
const pw_16, times 16 dw 16
const pw_32, times 16 dw 32
const pw_512, times 16 dw 512
const pw_00ff, times 16 dw 0x00ff
const pw_pixel_max,times 16 dw ((1 << BIT_DEPTH)-1)
const pw_0to15, dw 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
const pd_1, times 8 dd 1
const pd_0123, dd 0,1,2,3
const pd_4567, dd 4,5,6,7
const deinterleave_shufd, dd 0,4,1,5,2,6,3,7
const pb_unpackbd1, times 2 db 0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3
const pb_unpackbd2, times 2 db 4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7
const pb_01, times 8 db 0,1
const pb_0, times 16 db 0
const pb_a1, times 16 db 0xa1
const pb_3, times 16 db 3
const pb_shuf8x8c, db 0,0,0,0,2,2,2,2,4,4,4,4,6,6,6,6
const pw_2, times 8 dw 2
const pw_m2, times 8 dw -2
const pw_4, times 8 dw 4
const pw_8, times 8 dw 8
const pw_64, times 8 dw 64
const pw_256, times 8 dw 256
const pw_32_0, times 4 dw 32
times 4 dw 0
const pw_8000, times 8 dw 0x8000
const pw_3fff, times 8 dw 0x3fff
const pw_ppppmmmm, dw 1,1,1,1,-1,-1,-1,-1
const pw_ppmmppmm, dw 1,1,-1,-1,1,1,-1,-1
const pw_pmpmpmpm, dw 1,-1,1,-1,1,-1,1,-1
const pw_pmmpzzzz, dw 1,-1,-1,1,0,0,0,0
const pd_8, times 4 dd 8
const pd_32, times 4 dd 32
const pd_1024, times 4 dd 1024
const pd_ffff, times 4 dd 0xffff
const pw_ff00, times 8 dw 0xff00
const popcnt_table
%assign x 0
%rep 256
; population count
db ((x>>0)&1)+((x>>1)&1)+((x>>2)&1)+((x>>3)&1)+((x>>4)&1)+((x>>5)&1)+((x>>6)&1)+((x>>7)&1)
%assign x x+1
%endrep
const sw_64, dd 64
|
// Copyright (c) 2011-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 <util/system.h>
#include <clientversion.h>
#include <hash.h> // For Hash()
#include <key.h> // For CKey
#include <optional.h>
#include <sync.h>
#include <test/util/setup_common.h>
#include <test/util/str.h>
#include <uint256.h>
#include <util/message.h> // For MessageSign(), MessageVerify(), MESSAGE_MAGIC
#include <util/moneystr.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/time.h>
#include <util/spanparsing.h>
#include <util/vector.h>
#include <array>
#include <stdint.h>
#include <thread>
#include <univalue.h>
#include <utility>
#include <vector>
#ifndef WIN32
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#endif
#include <boost/test/unit_test.hpp>
/* defined in logging.cpp */
namespace BCLog {
std::string LogEscapeMessage(const std::string& str);
}
BOOST_FIXTURE_TEST_SUITE(util_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(util_criticalsection)
{
RecursiveMutex cs;
do {
LOCK(cs);
break;
BOOST_ERROR("break was swallowed!");
} while(0);
do {
TRY_LOCK(cs, lockTest);
if (lockTest) {
BOOST_CHECK(true); // Needed to suppress "Test case [...] did not check any assertions"
break;
}
BOOST_ERROR("break was swallowed!");
} while(0);
}
static const unsigned char ParseHex_expected[65] = {
0x04, 0x67, 0x8a, 0xfd, 0xb0, 0xfe, 0x55, 0x48, 0x27, 0x19, 0x67, 0xf1, 0xa6, 0x71, 0x30, 0xb7,
0x10, 0x5c, 0xd6, 0xa8, 0x28, 0xe0, 0x39, 0x09, 0xa6, 0x79, 0x62, 0xe0, 0xea, 0x1f, 0x61, 0xde,
0xb6, 0x49, 0xf6, 0xbc, 0x3f, 0x4c, 0xef, 0x38, 0xc4, 0xf3, 0x55, 0x04, 0xe5, 0x1e, 0xc1, 0x12,
0xde, 0x5c, 0x38, 0x4d, 0xf7, 0xba, 0x0b, 0x8d, 0x57, 0x8a, 0x4c, 0x70, 0x2b, 0x6b, 0xf1, 0x1d,
0x5f
};
BOOST_AUTO_TEST_CASE(util_ParseHex)
{
std::vector<unsigned char> result;
std::vector<unsigned char> expected(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected));
// Basic test vector
result = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
BOOST_CHECK_EQUAL_COLLECTIONS(result.begin(), result.end(), expected.begin(), expected.end());
// Spaces between bytes must be supported
result = ParseHex("12 34 56 78");
BOOST_CHECK(result.size() == 4 && result[0] == 0x12 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
// Leading space must be supported (used in BerkeleyEnvironment::Salvage)
result = ParseHex(" 89 34 56 78");
BOOST_CHECK(result.size() == 4 && result[0] == 0x89 && result[1] == 0x34 && result[2] == 0x56 && result[3] == 0x78);
// Stop parsing at invalid value
result = ParseHex("1234 invalid 1234");
BOOST_CHECK(result.size() == 2 && result[0] == 0x12 && result[1] == 0x34);
}
BOOST_AUTO_TEST_CASE(util_HexStr)
{
BOOST_CHECK_EQUAL(
HexStr(ParseHex_expected, ParseHex_expected + sizeof(ParseHex_expected)),
"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
BOOST_CHECK_EQUAL(
HexStr(ParseHex_expected + sizeof(ParseHex_expected),
ParseHex_expected + sizeof(ParseHex_expected)),
"");
BOOST_CHECK_EQUAL(
HexStr(ParseHex_expected, ParseHex_expected),
"");
std::vector<unsigned char> ParseHex_vec(ParseHex_expected, ParseHex_expected + 5);
BOOST_CHECK_EQUAL(
HexStr(ParseHex_vec.rbegin(), ParseHex_vec.rend()),
"b0fd8a6704"
);
BOOST_CHECK_EQUAL(
HexStr(std::reverse_iterator<const uint8_t *>(ParseHex_expected),
std::reverse_iterator<const uint8_t *>(ParseHex_expected)),
""
);
BOOST_CHECK_EQUAL(
HexStr(std::reverse_iterator<const uint8_t *>(ParseHex_expected + 1),
std::reverse_iterator<const uint8_t *>(ParseHex_expected)),
"04"
);
BOOST_CHECK_EQUAL(
HexStr(std::reverse_iterator<const uint8_t *>(ParseHex_expected + 5),
std::reverse_iterator<const uint8_t *>(ParseHex_expected)),
"b0fd8a6704"
);
BOOST_CHECK_EQUAL(
HexStr(std::reverse_iterator<const uint8_t *>(ParseHex_expected + 65),
std::reverse_iterator<const uint8_t *>(ParseHex_expected)),
"5f1df16b2b704c8a578d0bbaf74d385cde12c11ee50455f3c438ef4c3fbcf649b6de611feae06279a60939e028a8d65c10b73071a6f16719274855feb0fd8a6704"
);
}
BOOST_AUTO_TEST_CASE(util_Join)
{
// Normal version
BOOST_CHECK_EQUAL(Join({}, ", "), "");
BOOST_CHECK_EQUAL(Join({"foo"}, ", "), "foo");
BOOST_CHECK_EQUAL(Join({"foo", "bar"}, ", "), "foo, bar");
// Version with unary operator
const auto op_upper = [](const std::string& s) { return ToUpper(s); };
BOOST_CHECK_EQUAL(Join<std::string>({}, ", ", op_upper), "");
BOOST_CHECK_EQUAL(Join<std::string>({"foo"}, ", ", op_upper), "FOO");
BOOST_CHECK_EQUAL(Join<std::string>({"foo", "bar"}, ", ", op_upper), "FOO, BAR");
}
BOOST_AUTO_TEST_CASE(util_FormatParseISO8601DateTime)
{
BOOST_CHECK_EQUAL(FormatISO8601DateTime(1317425777), "2011-09-30T23:36:17Z");
BOOST_CHECK_EQUAL(FormatISO8601DateTime(0), "1970-01-01T00:00:00Z");
BOOST_CHECK_EQUAL(ParseISO8601DateTime("1970-01-01T00:00:00Z"), 0);
BOOST_CHECK_EQUAL(ParseISO8601DateTime("1960-01-01T00:00:00Z"), 0);
BOOST_CHECK_EQUAL(ParseISO8601DateTime("2011-09-30T23:36:17Z"), 1317425777);
auto time = GetSystemTimeInSeconds();
BOOST_CHECK_EQUAL(ParseISO8601DateTime(FormatISO8601DateTime(time)), time);
}
BOOST_AUTO_TEST_CASE(util_FormatISO8601Date)
{
BOOST_CHECK_EQUAL(FormatISO8601Date(1317425777), "2011-09-30");
}
struct TestArgsManager : public ArgsManager
{
TestArgsManager() { m_network_only_args.clear(); }
void ReadConfigString(const std::string str_config)
{
std::istringstream streamConfig(str_config);
{
LOCK(cs_args);
m_settings.ro_config.clear();
m_config_sections.clear();
}
std::string error;
BOOST_REQUIRE(ReadConfigStream(streamConfig, "", error));
}
void SetNetworkOnlyArg(const std::string arg)
{
LOCK(cs_args);
m_network_only_args.insert(arg);
}
void SetupArgs(const std::vector<std::pair<std::string, unsigned int>>& args)
{
for (const auto& arg : args) {
AddArg(arg.first, "", arg.second, OptionsCategory::OPTIONS);
}
}
using ArgsManager::GetSetting;
using ArgsManager::GetSettingsList;
using ArgsManager::ReadConfigStream;
using ArgsManager::cs_args;
using ArgsManager::m_network;
using ArgsManager::m_settings;
};
//! Test GetSetting and GetArg type coercion, negation, and default value handling.
class CheckValueTest : public TestChain100Setup
{
public:
struct Expect {
util::SettingsValue setting;
bool default_string = false;
bool default_int = false;
bool default_bool = false;
const char* string_value = nullptr;
Optional<int64_t> int_value;
Optional<bool> bool_value;
Optional<std::vector<std::string>> list_value;
const char* error = nullptr;
Expect(util::SettingsValue s) : setting(std::move(s)) {}
Expect& DefaultString() { default_string = true; return *this; }
Expect& DefaultInt() { default_int = true; return *this; }
Expect& DefaultBool() { default_bool = true; return *this; }
Expect& String(const char* s) { string_value = s; return *this; }
Expect& Int(int64_t i) { int_value = i; return *this; }
Expect& Bool(bool b) { bool_value = b; return *this; }
Expect& List(std::vector<std::string> m) { list_value = std::move(m); return *this; }
Expect& Error(const char* e) { error = e; return *this; }
};
void CheckValue(unsigned int flags, const char* arg, const Expect& expect)
{
TestArgsManager test;
test.SetupArgs({{"-value", flags}});
const char* argv[] = {"ignored", arg};
std::string error;
bool success = test.ParseParameters(arg ? 2 : 1, (char**)argv, error);
BOOST_CHECK_EQUAL(test.GetSetting("-value").write(), expect.setting.write());
auto settings_list = test.GetSettingsList("-value");
if (expect.setting.isNull() || expect.setting.isFalse()) {
BOOST_CHECK_EQUAL(settings_list.size(), 0);
} else {
BOOST_CHECK_EQUAL(settings_list.size(), 1);
BOOST_CHECK_EQUAL(settings_list[0].write(), expect.setting.write());
}
if (expect.error) {
BOOST_CHECK(!success);
BOOST_CHECK_NE(error.find(expect.error), std::string::npos);
} else {
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(error, "");
}
if (expect.default_string) {
BOOST_CHECK_EQUAL(test.GetArg("-value", "zzzzz"), "zzzzz");
} else if (expect.string_value) {
BOOST_CHECK_EQUAL(test.GetArg("-value", "zzzzz"), expect.string_value);
} else {
BOOST_CHECK(!success);
}
if (expect.default_int) {
BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), 99999);
} else if (expect.int_value) {
BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), *expect.int_value);
} else {
BOOST_CHECK(!success);
}
if (expect.default_bool) {
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), false);
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), true);
} else if (expect.bool_value) {
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), *expect.bool_value);
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), *expect.bool_value);
} else {
BOOST_CHECK(!success);
}
if (expect.list_value) {
auto l = test.GetArgs("-value");
BOOST_CHECK_EQUAL_COLLECTIONS(l.begin(), l.end(), expect.list_value->begin(), expect.list_value->end());
} else {
BOOST_CHECK(!success);
}
}
};
BOOST_FIXTURE_TEST_CASE(util_CheckValue, CheckValueTest)
{
using M = ArgsManager;
CheckValue(M::ALLOW_ANY, nullptr, Expect{{}}.DefaultString().DefaultInt().DefaultBool().List({}));
CheckValue(M::ALLOW_ANY, "-novalue", Expect{false}.String("0").Int(0).Bool(false).List({}));
CheckValue(M::ALLOW_ANY, "-novalue=", Expect{false}.String("0").Int(0).Bool(false).List({}));
CheckValue(M::ALLOW_ANY, "-novalue=0", Expect{true}.String("1").Int(1).Bool(true).List({"1"}));
CheckValue(M::ALLOW_ANY, "-novalue=1", Expect{false}.String("0").Int(0).Bool(false).List({}));
CheckValue(M::ALLOW_ANY, "-novalue=2", Expect{false}.String("0").Int(0).Bool(false).List({}));
CheckValue(M::ALLOW_ANY, "-novalue=abc", Expect{true}.String("1").Int(1).Bool(true).List({"1"}));
CheckValue(M::ALLOW_ANY, "-value", Expect{""}.String("").Int(0).Bool(true).List({""}));
CheckValue(M::ALLOW_ANY, "-value=", Expect{""}.String("").Int(0).Bool(true).List({""}));
CheckValue(M::ALLOW_ANY, "-value=0", Expect{"0"}.String("0").Int(0).Bool(false).List({"0"}));
CheckValue(M::ALLOW_ANY, "-value=1", Expect{"1"}.String("1").Int(1).Bool(true).List({"1"}));
CheckValue(M::ALLOW_ANY, "-value=2", Expect{"2"}.String("2").Int(2).Bool(true).List({"2"}));
CheckValue(M::ALLOW_ANY, "-value=abc", Expect{"abc"}.String("abc").Int(0).Bool(false).List({"abc"}));
}
BOOST_AUTO_TEST_CASE(util_ParseParameters)
{
TestArgsManager testArgs;
const auto a = std::make_pair("-a", ArgsManager::ALLOW_ANY);
const auto b = std::make_pair("-b", ArgsManager::ALLOW_ANY);
const auto ccc = std::make_pair("-ccc", ArgsManager::ALLOW_ANY);
const auto d = std::make_pair("-d", ArgsManager::ALLOW_ANY);
const char *argv_test[] = {"-ignored", "-a", "-b", "-ccc=argument", "-ccc=multiple", "f", "-d=e"};
std::string error;
LOCK(testArgs.cs_args);
testArgs.SetupArgs({a, b, ccc, d});
BOOST_CHECK(testArgs.ParseParameters(0, (char**)argv_test, error));
BOOST_CHECK(testArgs.m_settings.command_line_options.empty() && testArgs.m_settings.ro_config.empty());
BOOST_CHECK(testArgs.ParseParameters(1, (char**)argv_test, error));
BOOST_CHECK(testArgs.m_settings.command_line_options.empty() && testArgs.m_settings.ro_config.empty());
BOOST_CHECK(testArgs.ParseParameters(7, (char**)argv_test, error));
// expectation: -ignored is ignored (program name argument),
// -a, -b and -ccc end up in map, -d ignored because it is after
// a non-option argument (non-GNU option parsing)
BOOST_CHECK(testArgs.m_settings.command_line_options.size() == 3 && testArgs.m_settings.ro_config.empty());
BOOST_CHECK(testArgs.IsArgSet("-a") && testArgs.IsArgSet("-b") && testArgs.IsArgSet("-ccc")
&& !testArgs.IsArgSet("f") && !testArgs.IsArgSet("-d"));
BOOST_CHECK(testArgs.m_settings.command_line_options.count("a") && testArgs.m_settings.command_line_options.count("b") && testArgs.m_settings.command_line_options.count("ccc")
&& !testArgs.m_settings.command_line_options.count("f") && !testArgs.m_settings.command_line_options.count("d"));
BOOST_CHECK(testArgs.m_settings.command_line_options["a"].size() == 1);
BOOST_CHECK(testArgs.m_settings.command_line_options["a"].front().get_str() == "");
BOOST_CHECK(testArgs.m_settings.command_line_options["ccc"].size() == 2);
BOOST_CHECK(testArgs.m_settings.command_line_options["ccc"].front().get_str() == "argument");
BOOST_CHECK(testArgs.m_settings.command_line_options["ccc"].back().get_str() == "multiple");
BOOST_CHECK(testArgs.GetArgs("-ccc").size() == 2);
}
BOOST_AUTO_TEST_CASE(util_ParseInvalidParameters)
{
TestArgsManager test;
test.SetupArgs({{"-registered", ArgsManager::ALLOW_ANY}});
const char* argv[] = {"ignored", "-registered"};
std::string error;
BOOST_CHECK(test.ParseParameters(2, (char**)argv, error));
BOOST_CHECK_EQUAL(error, "");
argv[1] = "-unregistered";
BOOST_CHECK(!test.ParseParameters(2, (char**)argv, error));
BOOST_CHECK_EQUAL(error, "Invalid parameter -unregistered");
// Make sure registered parameters prefixed with a chain name trigger errors.
// (Previously, they were accepted and ignored.)
argv[1] = "-test.registered";
BOOST_CHECK(!test.ParseParameters(2, (char**)argv, error));
BOOST_CHECK_EQUAL(error, "Invalid parameter -test.registered");
}
static void TestParse(const std::string& str, bool expected_bool, int64_t expected_int)
{
TestArgsManager test;
test.SetupArgs({{"-value", ArgsManager::ALLOW_ANY}});
std::string arg = "-value=" + str;
const char* argv[] = {"ignored", arg.c_str()};
std::string error;
BOOST_CHECK(test.ParseParameters(2, (char**)argv, error));
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", false), expected_bool);
BOOST_CHECK_EQUAL(test.GetBoolArg("-value", true), expected_bool);
BOOST_CHECK_EQUAL(test.GetArg("-value", 99998), expected_int);
BOOST_CHECK_EQUAL(test.GetArg("-value", 99999), expected_int);
}
// Test bool and int parsing.
BOOST_AUTO_TEST_CASE(util_ArgParsing)
{
// Some of these cases could be ambiguous or surprising to users, and might
// be worth triggering errors or warnings in the future. But for now basic
// test coverage is useful to avoid breaking backwards compatibility
// unintentionally.
TestParse("", true, 0);
TestParse(" ", false, 0);
TestParse("0", false, 0);
TestParse("0 ", false, 0);
TestParse(" 0", false, 0);
TestParse("+0", false, 0);
TestParse("-0", false, 0);
TestParse("5", true, 5);
TestParse("5 ", true, 5);
TestParse(" 5", true, 5);
TestParse("+5", true, 5);
TestParse("-5", true, -5);
TestParse("0 5", false, 0);
TestParse("5 0", true, 5);
TestParse("050", true, 50);
TestParse("0.", false, 0);
TestParse("5.", true, 5);
TestParse("0.0", false, 0);
TestParse("0.5", false, 0);
TestParse("5.0", true, 5);
TestParse("5.5", true, 5);
TestParse("x", false, 0);
TestParse("x0", false, 0);
TestParse("x5", false, 0);
TestParse("0x", false, 0);
TestParse("5x", true, 5);
TestParse("0x5", false, 0);
TestParse("false", false, 0);
TestParse("true", false, 0);
TestParse("yes", false, 0);
TestParse("no", false, 0);
}
BOOST_AUTO_TEST_CASE(util_GetBoolArg)
{
TestArgsManager testArgs;
const auto a = std::make_pair("-a", ArgsManager::ALLOW_ANY);
const auto b = std::make_pair("-b", ArgsManager::ALLOW_ANY);
const auto c = std::make_pair("-c", ArgsManager::ALLOW_ANY);
const auto d = std::make_pair("-d", ArgsManager::ALLOW_ANY);
const auto e = std::make_pair("-e", ArgsManager::ALLOW_ANY);
const auto f = std::make_pair("-f", ArgsManager::ALLOW_ANY);
const char *argv_test[] = {
"ignored", "-a", "-nob", "-c=0", "-d=1", "-e=false", "-f=true"};
std::string error;
LOCK(testArgs.cs_args);
testArgs.SetupArgs({a, b, c, d, e, f});
BOOST_CHECK(testArgs.ParseParameters(7, (char**)argv_test, error));
// Each letter should be set.
for (const char opt : "abcdef")
BOOST_CHECK(testArgs.IsArgSet({'-', opt}) || !opt);
// Nothing else should be in the map
BOOST_CHECK(testArgs.m_settings.command_line_options.size() == 6 &&
testArgs.m_settings.ro_config.empty());
// The -no prefix should get stripped on the way in.
BOOST_CHECK(!testArgs.IsArgSet("-nob"));
// The -b option is flagged as negated, and nothing else is
BOOST_CHECK(testArgs.IsArgNegated("-b"));
BOOST_CHECK(!testArgs.IsArgNegated("-a"));
// Check expected values.
BOOST_CHECK(testArgs.GetBoolArg("-a", false) == true);
BOOST_CHECK(testArgs.GetBoolArg("-b", true) == false);
BOOST_CHECK(testArgs.GetBoolArg("-c", true) == false);
BOOST_CHECK(testArgs.GetBoolArg("-d", false) == true);
BOOST_CHECK(testArgs.GetBoolArg("-e", true) == false);
BOOST_CHECK(testArgs.GetBoolArg("-f", true) == false);
}
BOOST_AUTO_TEST_CASE(util_GetBoolArgEdgeCases)
{
// Test some awful edge cases that hopefully no user will ever exercise.
TestArgsManager testArgs;
// Params test
const auto foo = std::make_pair("-foo", ArgsManager::ALLOW_ANY);
const auto bar = std::make_pair("-bar", ArgsManager::ALLOW_ANY);
const char *argv_test[] = {"ignored", "-nofoo", "-foo", "-nobar=0"};
testArgs.SetupArgs({foo, bar});
std::string error;
BOOST_CHECK(testArgs.ParseParameters(4, (char**)argv_test, error));
// This was passed twice, second one overrides the negative setting.
BOOST_CHECK(!testArgs.IsArgNegated("-foo"));
BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "");
// A double negative is a positive, and not marked as negated.
BOOST_CHECK(!testArgs.IsArgNegated("-bar"));
BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1");
// Config test
const char *conf_test = "nofoo=1\nfoo=1\nnobar=0\n";
BOOST_CHECK(testArgs.ParseParameters(1, (char**)argv_test, error));
testArgs.ReadConfigString(conf_test);
// This was passed twice, second one overrides the negative setting,
// and the value.
BOOST_CHECK(!testArgs.IsArgNegated("-foo"));
BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "1");
// A double negative is a positive, and does not count as negated.
BOOST_CHECK(!testArgs.IsArgNegated("-bar"));
BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "1");
// Combined test
const char *combo_test_args[] = {"ignored", "-nofoo", "-bar"};
const char *combo_test_conf = "foo=1\nnobar=1\n";
BOOST_CHECK(testArgs.ParseParameters(3, (char**)combo_test_args, error));
testArgs.ReadConfigString(combo_test_conf);
// Command line overrides, but doesn't erase old setting
BOOST_CHECK(testArgs.IsArgNegated("-foo"));
BOOST_CHECK(testArgs.GetArg("-foo", "xxx") == "0");
BOOST_CHECK(testArgs.GetArgs("-foo").size() == 0);
// Command line overrides, but doesn't erase old setting
BOOST_CHECK(!testArgs.IsArgNegated("-bar"));
BOOST_CHECK(testArgs.GetArg("-bar", "xxx") == "");
BOOST_CHECK(testArgs.GetArgs("-bar").size() == 1
&& testArgs.GetArgs("-bar").front() == "");
}
BOOST_AUTO_TEST_CASE(util_ReadConfigStream)
{
const char *str_config =
"a=\n"
"b=1\n"
"ccc=argument\n"
"ccc=multiple\n"
"d=e\n"
"nofff=1\n"
"noggg=0\n"
"h=1\n"
"noh=1\n"
"noi=1\n"
"i=1\n"
"sec1.ccc=extend1\n"
"\n"
"[sec1]\n"
"ccc=extend2\n"
"d=eee\n"
"h=1\n"
"[sec2]\n"
"ccc=extend3\n"
"iii=2\n";
TestArgsManager test_args;
LOCK(test_args.cs_args);
const auto a = std::make_pair("-a", ArgsManager::ALLOW_ANY);
const auto b = std::make_pair("-b", ArgsManager::ALLOW_ANY);
const auto ccc = std::make_pair("-ccc", ArgsManager::ALLOW_ANY);
const auto d = std::make_pair("-d", ArgsManager::ALLOW_ANY);
const auto e = std::make_pair("-e", ArgsManager::ALLOW_ANY);
const auto fff = std::make_pair("-fff", ArgsManager::ALLOW_ANY);
const auto ggg = std::make_pair("-ggg", ArgsManager::ALLOW_ANY);
const auto h = std::make_pair("-h", ArgsManager::ALLOW_ANY);
const auto i = std::make_pair("-i", ArgsManager::ALLOW_ANY);
const auto iii = std::make_pair("-iii", ArgsManager::ALLOW_ANY);
test_args.SetupArgs({a, b, ccc, d, e, fff, ggg, h, i, iii});
test_args.ReadConfigString(str_config);
// expectation: a, b, ccc, d, fff, ggg, h, i end up in map
// so do sec1.ccc, sec1.d, sec1.h, sec2.ccc, sec2.iii
BOOST_CHECK(test_args.m_settings.command_line_options.empty());
BOOST_CHECK(test_args.m_settings.ro_config.size() == 3);
BOOST_CHECK(test_args.m_settings.ro_config[""].size() == 8);
BOOST_CHECK(test_args.m_settings.ro_config["sec1"].size() == 3);
BOOST_CHECK(test_args.m_settings.ro_config["sec2"].size() == 2);
BOOST_CHECK(test_args.m_settings.ro_config[""].count("a")
&& test_args.m_settings.ro_config[""].count("b")
&& test_args.m_settings.ro_config[""].count("ccc")
&& test_args.m_settings.ro_config[""].count("d")
&& test_args.m_settings.ro_config[""].count("fff")
&& test_args.m_settings.ro_config[""].count("ggg")
&& test_args.m_settings.ro_config[""].count("h")
&& test_args.m_settings.ro_config[""].count("i")
);
BOOST_CHECK(test_args.m_settings.ro_config["sec1"].count("ccc")
&& test_args.m_settings.ro_config["sec1"].count("h")
&& test_args.m_settings.ro_config["sec2"].count("ccc")
&& test_args.m_settings.ro_config["sec2"].count("iii")
);
BOOST_CHECK(test_args.IsArgSet("-a")
&& test_args.IsArgSet("-b")
&& test_args.IsArgSet("-ccc")
&& test_args.IsArgSet("-d")
&& test_args.IsArgSet("-fff")
&& test_args.IsArgSet("-ggg")
&& test_args.IsArgSet("-h")
&& test_args.IsArgSet("-i")
&& !test_args.IsArgSet("-zzz")
&& !test_args.IsArgSet("-iii")
);
BOOST_CHECK(test_args.GetArg("-a", "xxx") == ""
&& test_args.GetArg("-b", "xxx") == "1"
&& test_args.GetArg("-ccc", "xxx") == "argument"
&& test_args.GetArg("-d", "xxx") == "e"
&& test_args.GetArg("-fff", "xxx") == "0"
&& test_args.GetArg("-ggg", "xxx") == "1"
&& test_args.GetArg("-h", "xxx") == "0"
&& test_args.GetArg("-i", "xxx") == "1"
&& test_args.GetArg("-zzz", "xxx") == "xxx"
&& test_args.GetArg("-iii", "xxx") == "xxx"
);
for (const bool def : {false, true}) {
BOOST_CHECK(test_args.GetBoolArg("-a", def)
&& test_args.GetBoolArg("-b", def)
&& !test_args.GetBoolArg("-ccc", def)
&& !test_args.GetBoolArg("-d", def)
&& !test_args.GetBoolArg("-fff", def)
&& test_args.GetBoolArg("-ggg", def)
&& !test_args.GetBoolArg("-h", def)
&& test_args.GetBoolArg("-i", def)
&& test_args.GetBoolArg("-zzz", def) == def
&& test_args.GetBoolArg("-iii", def) == def
);
}
BOOST_CHECK(test_args.GetArgs("-a").size() == 1
&& test_args.GetArgs("-a").front() == "");
BOOST_CHECK(test_args.GetArgs("-b").size() == 1
&& test_args.GetArgs("-b").front() == "1");
BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2
&& test_args.GetArgs("-ccc").front() == "argument"
&& test_args.GetArgs("-ccc").back() == "multiple");
BOOST_CHECK(test_args.GetArgs("-fff").size() == 0);
BOOST_CHECK(test_args.GetArgs("-nofff").size() == 0);
BOOST_CHECK(test_args.GetArgs("-ggg").size() == 1
&& test_args.GetArgs("-ggg").front() == "1");
BOOST_CHECK(test_args.GetArgs("-noggg").size() == 0);
BOOST_CHECK(test_args.GetArgs("-h").size() == 0);
BOOST_CHECK(test_args.GetArgs("-noh").size() == 0);
BOOST_CHECK(test_args.GetArgs("-i").size() == 1
&& test_args.GetArgs("-i").front() == "1");
BOOST_CHECK(test_args.GetArgs("-noi").size() == 0);
BOOST_CHECK(test_args.GetArgs("-zzz").size() == 0);
BOOST_CHECK(!test_args.IsArgNegated("-a"));
BOOST_CHECK(!test_args.IsArgNegated("-b"));
BOOST_CHECK(!test_args.IsArgNegated("-ccc"));
BOOST_CHECK(!test_args.IsArgNegated("-d"));
BOOST_CHECK(test_args.IsArgNegated("-fff"));
BOOST_CHECK(!test_args.IsArgNegated("-ggg"));
BOOST_CHECK(test_args.IsArgNegated("-h")); // last setting takes precedence
BOOST_CHECK(!test_args.IsArgNegated("-i")); // last setting takes precedence
BOOST_CHECK(!test_args.IsArgNegated("-zzz"));
// Test sections work
test_args.SelectConfigNetwork("sec1");
// same as original
BOOST_CHECK(test_args.GetArg("-a", "xxx") == ""
&& test_args.GetArg("-b", "xxx") == "1"
&& test_args.GetArg("-fff", "xxx") == "0"
&& test_args.GetArg("-ggg", "xxx") == "1"
&& test_args.GetArg("-zzz", "xxx") == "xxx"
&& test_args.GetArg("-iii", "xxx") == "xxx"
);
// d is overridden
BOOST_CHECK(test_args.GetArg("-d", "xxx") == "eee");
// section-specific setting
BOOST_CHECK(test_args.GetArg("-h", "xxx") == "1");
// section takes priority for multiple values
BOOST_CHECK(test_args.GetArg("-ccc", "xxx") == "extend1");
// check multiple values works
const std::vector<std::string> sec1_ccc_expected = {"extend1","extend2","argument","multiple"};
const auto& sec1_ccc_res = test_args.GetArgs("-ccc");
BOOST_CHECK_EQUAL_COLLECTIONS(sec1_ccc_res.begin(), sec1_ccc_res.end(), sec1_ccc_expected.begin(), sec1_ccc_expected.end());
test_args.SelectConfigNetwork("sec2");
// same as original
BOOST_CHECK(test_args.GetArg("-a", "xxx") == ""
&& test_args.GetArg("-b", "xxx") == "1"
&& test_args.GetArg("-d", "xxx") == "e"
&& test_args.GetArg("-fff", "xxx") == "0"
&& test_args.GetArg("-ggg", "xxx") == "1"
&& test_args.GetArg("-zzz", "xxx") == "xxx"
&& test_args.GetArg("-h", "xxx") == "0"
);
// section-specific setting
BOOST_CHECK(test_args.GetArg("-iii", "xxx") == "2");
// section takes priority for multiple values
BOOST_CHECK(test_args.GetArg("-ccc", "xxx") == "extend3");
// check multiple values works
const std::vector<std::string> sec2_ccc_expected = {"extend3","argument","multiple"};
const auto& sec2_ccc_res = test_args.GetArgs("-ccc");
BOOST_CHECK_EQUAL_COLLECTIONS(sec2_ccc_res.begin(), sec2_ccc_res.end(), sec2_ccc_expected.begin(), sec2_ccc_expected.end());
// Test section only options
test_args.SetNetworkOnlyArg("-d");
test_args.SetNetworkOnlyArg("-ccc");
test_args.SetNetworkOnlyArg("-h");
test_args.SelectConfigNetwork(CBaseChainParams::MAIN);
BOOST_CHECK(test_args.GetArg("-d", "xxx") == "e");
BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2);
BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0");
test_args.SelectConfigNetwork("sec1");
BOOST_CHECK(test_args.GetArg("-d", "xxx") == "eee");
BOOST_CHECK(test_args.GetArgs("-d").size() == 1);
BOOST_CHECK(test_args.GetArgs("-ccc").size() == 2);
BOOST_CHECK(test_args.GetArg("-h", "xxx") == "1");
test_args.SelectConfigNetwork("sec2");
BOOST_CHECK(test_args.GetArg("-d", "xxx") == "xxx");
BOOST_CHECK(test_args.GetArgs("-d").size() == 0);
BOOST_CHECK(test_args.GetArgs("-ccc").size() == 1);
BOOST_CHECK(test_args.GetArg("-h", "xxx") == "0");
}
BOOST_AUTO_TEST_CASE(util_GetArg)
{
TestArgsManager testArgs;
LOCK(testArgs.cs_args);
testArgs.m_settings.command_line_options.clear();
testArgs.m_settings.command_line_options["strtest1"] = {"string..."};
// strtest2 undefined on purpose
testArgs.m_settings.command_line_options["inttest1"] = {"12345"};
testArgs.m_settings.command_line_options["inttest2"] = {"81985529216486895"};
// inttest3 undefined on purpose
testArgs.m_settings.command_line_options["booltest1"] = {""};
// booltest2 undefined on purpose
testArgs.m_settings.command_line_options["booltest3"] = {"0"};
testArgs.m_settings.command_line_options["booltest4"] = {"1"};
// priorities
testArgs.m_settings.command_line_options["pritest1"] = {"a", "b"};
testArgs.m_settings.ro_config[""]["pritest2"] = {"a", "b"};
testArgs.m_settings.command_line_options["pritest3"] = {"a"};
testArgs.m_settings.ro_config[""]["pritest3"] = {"b"};
testArgs.m_settings.command_line_options["pritest4"] = {"a","b"};
testArgs.m_settings.ro_config[""]["pritest4"] = {"c","d"};
BOOST_CHECK_EQUAL(testArgs.GetArg("strtest1", "default"), "string...");
BOOST_CHECK_EQUAL(testArgs.GetArg("strtest2", "default"), "default");
BOOST_CHECK_EQUAL(testArgs.GetArg("inttest1", -1), 12345);
BOOST_CHECK_EQUAL(testArgs.GetArg("inttest2", -1), 81985529216486895LL);
BOOST_CHECK_EQUAL(testArgs.GetArg("inttest3", -1), -1);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest1", false), true);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest2", false), false);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest3", false), false);
BOOST_CHECK_EQUAL(testArgs.GetBoolArg("booltest4", false), true);
BOOST_CHECK_EQUAL(testArgs.GetArg("pritest1", "default"), "b");
BOOST_CHECK_EQUAL(testArgs.GetArg("pritest2", "default"), "a");
BOOST_CHECK_EQUAL(testArgs.GetArg("pritest3", "default"), "a");
BOOST_CHECK_EQUAL(testArgs.GetArg("pritest4", "default"), "b");
}
BOOST_AUTO_TEST_CASE(util_GetChainName)
{
TestArgsManager test_args;
const auto testnet = std::make_pair("-testnet", ArgsManager::ALLOW_ANY);
const auto regtest = std::make_pair("-regtest", ArgsManager::ALLOW_ANY);
test_args.SetupArgs({testnet, regtest});
const char* argv_testnet[] = {"cmd", "-testnet"};
const char* argv_regtest[] = {"cmd", "-regtest"};
const char* argv_test_no_reg[] = {"cmd", "-testnet", "-noregtest"};
const char* argv_both[] = {"cmd", "-testnet", "-regtest"};
// equivalent to "-testnet"
// regtest in testnet section is ignored
const char* testnetconf = "testnet=1\nregtest=0\n[test]\nregtest=1";
std::string error;
BOOST_CHECK(test_args.ParseParameters(0, (char**)argv_testnet, error));
BOOST_CHECK_EQUAL(test_args.GetChainName(), "main");
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_testnet, error));
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_regtest, error));
BOOST_CHECK_EQUAL(test_args.GetChainName(), "regtest");
BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_test_no_reg, error));
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_both, error));
BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
BOOST_CHECK(test_args.ParseParameters(0, (char**)argv_testnet, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_testnet, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_regtest, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_test_no_reg, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_both, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
// check setting the network to test (and thus making
// [test] regtest=1 potentially relevant) doesn't break things
test_args.SelectConfigNetwork("test");
BOOST_CHECK(test_args.ParseParameters(0, (char**)argv_testnet, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_testnet, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_regtest, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
BOOST_CHECK(test_args.ParseParameters(2, (char**)argv_test_no_reg, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_EQUAL(test_args.GetChainName(), "test");
BOOST_CHECK(test_args.ParseParameters(3, (char**)argv_both, error));
test_args.ReadConfigString(testnetconf);
BOOST_CHECK_THROW(test_args.GetChainName(), std::runtime_error);
}
// Test different ways settings can be merged, and verify results. This test can
// be used to confirm that updates to settings code don't change behavior
// unintentionally.
//
// The test covers:
//
// - Combining different setting actions. Possible actions are: configuring a
// setting, negating a setting (adding "-no" prefix), and configuring/negating
// settings in a network section (adding "main." or "test." prefixes).
//
// - Combining settings from command line arguments and a config file.
//
// - Combining SoftSet and ForceSet calls.
//
// - Testing "main" and "test" network values to make sure settings from network
// sections are applied and to check for mainnet-specific behaviors like
// inheriting settings from the default section.
//
// - Testing network-specific settings like "-wallet", that may be ignored
// outside a network section, and non-network specific settings like "-server"
// that aren't sensitive to the network.
//
struct ArgsMergeTestingSetup : public BasicTestingSetup {
//! Max number of actions to sequence together. Can decrease this when
//! debugging to make test results easier to understand.
static constexpr int MAX_ACTIONS = 3;
enum Action { NONE, SET, NEGATE, SECTION_SET, SECTION_NEGATE };
using ActionList = Action[MAX_ACTIONS];
//! Enumerate all possible test configurations.
template <typename Fn>
void ForEachMergeSetup(Fn&& fn)
{
ActionList arg_actions = {};
// command_line_options do not have sections. Only iterate over SET and NEGATE
ForEachNoDup(arg_actions, SET, NEGATE, [&] {
ActionList conf_actions = {};
ForEachNoDup(conf_actions, SET, SECTION_NEGATE, [&] {
for (bool soft_set : {false, true}) {
for (bool force_set : {false, true}) {
for (const std::string& section : {CBaseChainParams::MAIN, CBaseChainParams::TESTNET}) {
for (const std::string& network : {CBaseChainParams::MAIN, CBaseChainParams::TESTNET}) {
for (bool net_specific : {false, true}) {
fn(arg_actions, conf_actions, soft_set, force_set, section, network, net_specific);
}
}
}
}
}
});
});
}
//! Translate actions into a list of <key>=<value> setting strings.
std::vector<std::string> GetValues(const ActionList& actions,
const std::string& section,
const std::string& name,
const std::string& value_prefix)
{
std::vector<std::string> values;
int suffix = 0;
for (Action action : actions) {
if (action == NONE) break;
std::string prefix;
if (action == SECTION_SET || action == SECTION_NEGATE) prefix = section + ".";
if (action == SET || action == SECTION_SET) {
for (int i = 0; i < 2; ++i) {
values.push_back(prefix + name + "=" + value_prefix + std::to_string(++suffix));
}
}
if (action == NEGATE || action == SECTION_NEGATE) {
values.push_back(prefix + "no" + name + "=1");
}
}
return values;
}
};
// Regression test covering different ways config settings can be merged. The
// test parses and merges settings, representing the results as strings that get
// compared against an expected hash. To debug, the result strings can be dumped
// to a file (see comments below).
BOOST_FIXTURE_TEST_CASE(util_ArgsMerge, ArgsMergeTestingSetup)
{
CHash256 out_sha;
FILE* out_file = nullptr;
if (const char* out_path = getenv("ARGS_MERGE_TEST_OUT")) {
out_file = fsbridge::fopen(out_path, "w");
if (!out_file) throw std::system_error(errno, std::generic_category(), "fopen failed");
}
ForEachMergeSetup([&](const ActionList& arg_actions, const ActionList& conf_actions, bool soft_set, bool force_set,
const std::string& section, const std::string& network, bool net_specific) {
TestArgsManager parser;
LOCK(parser.cs_args);
std::string desc = "net=";
desc += network;
parser.m_network = network;
const std::string& name = net_specific ? "wallet" : "server";
const std::string key = "-" + name;
parser.AddArg(key, name, ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
if (net_specific) parser.SetNetworkOnlyArg(key);
auto args = GetValues(arg_actions, section, name, "a");
std::vector<const char*> argv = {"ignored"};
for (auto& arg : args) {
arg.insert(0, "-");
desc += " ";
desc += arg;
argv.push_back(arg.c_str());
}
std::string error;
BOOST_CHECK(parser.ParseParameters(argv.size(), argv.data(), error));
BOOST_CHECK_EQUAL(error, "");
std::string conf;
for (auto& conf_val : GetValues(conf_actions, section, name, "c")) {
desc += " ";
desc += conf_val;
conf += conf_val;
conf += "\n";
}
std::istringstream conf_stream(conf);
BOOST_CHECK(parser.ReadConfigStream(conf_stream, "filepath", error));
BOOST_CHECK_EQUAL(error, "");
if (soft_set) {
desc += " soft";
parser.SoftSetArg(key, "soft1");
parser.SoftSetArg(key, "soft2");
}
if (force_set) {
desc += " force";
parser.ForceSetArg(key, "force1");
parser.ForceSetArg(key, "force2");
}
desc += " || ";
if (!parser.IsArgSet(key)) {
desc += "unset";
BOOST_CHECK(!parser.IsArgNegated(key));
BOOST_CHECK_EQUAL(parser.GetArg(key, "default"), "default");
BOOST_CHECK(parser.GetArgs(key).empty());
} else if (parser.IsArgNegated(key)) {
desc += "negated";
BOOST_CHECK_EQUAL(parser.GetArg(key, "default"), "0");
BOOST_CHECK(parser.GetArgs(key).empty());
} else {
desc += parser.GetArg(key, "default");
desc += " |";
for (const auto& arg : parser.GetArgs(key)) {
desc += " ";
desc += arg;
}
}
std::set<std::string> ignored = parser.GetUnsuitableSectionOnlyArgs();
if (!ignored.empty()) {
desc += " | ignored";
for (const auto& arg : ignored) {
desc += " ";
desc += arg;
}
}
desc += "\n";
out_sha.Write((const unsigned char*)desc.data(), desc.size());
if (out_file) {
BOOST_REQUIRE(fwrite(desc.data(), 1, desc.size(), out_file) == desc.size());
}
});
if (out_file) {
if (fclose(out_file)) throw std::system_error(errno, std::generic_category(), "fclose failed");
out_file = nullptr;
}
unsigned char out_sha_bytes[CSHA256::OUTPUT_SIZE];
out_sha.Finalize(out_sha_bytes);
std::string out_sha_hex = HexStr(std::begin(out_sha_bytes), std::end(out_sha_bytes));
// If check below fails, should manually dump the results with:
//
// ARGS_MERGE_TEST_OUT=results.txt ./test_bitcoin --run_test=util_tests/util_ArgsMerge
//
// And verify diff against previous results to make sure the changes are expected.
//
// Results file is formatted like:
//
// <input> || <IsArgSet/IsArgNegated/GetArg output> | <GetArgs output> | <GetUnsuitable output>
BOOST_CHECK_EQUAL(out_sha_hex, "8fd4877bb8bf337badca950ede6c917441901962f160e52514e06a60dea46cde");
}
// Similar test as above, but for ArgsManager::GetChainName function.
struct ChainMergeTestingSetup : public BasicTestingSetup {
static constexpr int MAX_ACTIONS = 2;
enum Action { NONE, ENABLE_TEST, DISABLE_TEST, NEGATE_TEST, ENABLE_REG, DISABLE_REG, NEGATE_REG };
using ActionList = Action[MAX_ACTIONS];
//! Enumerate all possible test configurations.
template <typename Fn>
void ForEachMergeSetup(Fn&& fn)
{
ActionList arg_actions = {};
ForEachNoDup(arg_actions, ENABLE_TEST, NEGATE_REG, [&] {
ActionList conf_actions = {};
ForEachNoDup(conf_actions, ENABLE_TEST, NEGATE_REG, [&] { fn(arg_actions, conf_actions); });
});
}
};
BOOST_FIXTURE_TEST_CASE(util_ChainMerge, ChainMergeTestingSetup)
{
CHash256 out_sha;
FILE* out_file = nullptr;
if (const char* out_path = getenv("CHAIN_MERGE_TEST_OUT")) {
out_file = fsbridge::fopen(out_path, "w");
if (!out_file) throw std::system_error(errno, std::generic_category(), "fopen failed");
}
ForEachMergeSetup([&](const ActionList& arg_actions, const ActionList& conf_actions) {
TestArgsManager parser;
LOCK(parser.cs_args);
parser.AddArg("-regtest", "regtest", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
parser.AddArg("-testnet", "testnet", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
auto arg = [](Action action) { return action == ENABLE_TEST ? "-testnet=1" :
action == DISABLE_TEST ? "-testnet=0" :
action == NEGATE_TEST ? "-notestnet=1" :
action == ENABLE_REG ? "-regtest=1" :
action == DISABLE_REG ? "-regtest=0" :
action == NEGATE_REG ? "-noregtest=1" : nullptr; };
std::string desc;
std::vector<const char*> argv = {"ignored"};
for (Action action : arg_actions) {
const char* argstr = arg(action);
if (!argstr) break;
argv.push_back(argstr);
desc += " ";
desc += argv.back();
}
std::string error;
BOOST_CHECK(parser.ParseParameters(argv.size(), argv.data(), error));
BOOST_CHECK_EQUAL(error, "");
std::string conf;
for (Action action : conf_actions) {
const char* argstr = arg(action);
if (!argstr) break;
desc += " ";
desc += argstr + 1;
conf += argstr + 1;
conf += "\n";
}
std::istringstream conf_stream(conf);
BOOST_CHECK(parser.ReadConfigStream(conf_stream, "filepath", error));
BOOST_CHECK_EQUAL(error, "");
desc += " || ";
try {
desc += parser.GetChainName();
} catch (const std::runtime_error& e) {
desc += "error: ";
desc += e.what();
}
desc += "\n";
out_sha.Write((const unsigned char*)desc.data(), desc.size());
if (out_file) {
BOOST_REQUIRE(fwrite(desc.data(), 1, desc.size(), out_file) == desc.size());
}
});
if (out_file) {
if (fclose(out_file)) throw std::system_error(errno, std::generic_category(), "fclose failed");
out_file = nullptr;
}
unsigned char out_sha_bytes[CSHA256::OUTPUT_SIZE];
out_sha.Finalize(out_sha_bytes);
std::string out_sha_hex = HexStr(std::begin(out_sha_bytes), std::end(out_sha_bytes));
// If check below fails, should manually dump the results with:
//
// CHAIN_MERGE_TEST_OUT=results.txt ./test_bitcoin --run_test=util_tests/util_ChainMerge
//
// And verify diff against previous results to make sure the changes are expected.
//
// Results file is formatted like:
//
// <input> || <output>
BOOST_CHECK_EQUAL(out_sha_hex, "f0b3a3c29869edc765d579c928f7f1690a71fbb673b49ccf39cbc4de18156a0d");
}
BOOST_AUTO_TEST_CASE(util_FormatMoney)
{
BOOST_CHECK_EQUAL(FormatMoney(0), "0.00");
BOOST_CHECK_EQUAL(FormatMoney((COIN/10000)*123456789), "12345.6789");
BOOST_CHECK_EQUAL(FormatMoney(-COIN), "-1.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*100000000), "100000000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*10000000), "10000000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*1000000), "1000000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*100000), "100000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*10000), "10000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*1000), "1000.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*100), "100.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN*10), "10.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN), "1.00");
BOOST_CHECK_EQUAL(FormatMoney(COIN/10), "0.10");
BOOST_CHECK_EQUAL(FormatMoney(COIN/100), "0.01");
BOOST_CHECK_EQUAL(FormatMoney(COIN/1000), "0.001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/10000), "0.0001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/100000), "0.00001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/1000000), "0.000001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/10000000), "0.0000001");
BOOST_CHECK_EQUAL(FormatMoney(COIN/100000000), "0.00000001");
}
BOOST_AUTO_TEST_CASE(util_ParseMoney)
{
CAmount ret = 0;
BOOST_CHECK(ParseMoney("0.0", ret));
BOOST_CHECK_EQUAL(ret, 0);
BOOST_CHECK(ParseMoney("12345.6789", ret));
BOOST_CHECK_EQUAL(ret, (COIN/10000)*123456789);
BOOST_CHECK(ParseMoney("100000000.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*100000000);
BOOST_CHECK(ParseMoney("10000000.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*10000000);
BOOST_CHECK(ParseMoney("1000000.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*1000000);
BOOST_CHECK(ParseMoney("100000.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*100000);
BOOST_CHECK(ParseMoney("10000.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*10000);
BOOST_CHECK(ParseMoney("1000.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*1000);
BOOST_CHECK(ParseMoney("100.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*100);
BOOST_CHECK(ParseMoney("10.00", ret));
BOOST_CHECK_EQUAL(ret, COIN*10);
BOOST_CHECK(ParseMoney("1.00", ret));
BOOST_CHECK_EQUAL(ret, COIN);
BOOST_CHECK(ParseMoney("1", ret));
BOOST_CHECK_EQUAL(ret, COIN);
BOOST_CHECK(ParseMoney("0.1", ret));
BOOST_CHECK_EQUAL(ret, COIN/10);
BOOST_CHECK(ParseMoney("0.01", ret));
BOOST_CHECK_EQUAL(ret, COIN/100);
BOOST_CHECK(ParseMoney("0.001", ret));
BOOST_CHECK_EQUAL(ret, COIN/1000);
BOOST_CHECK(ParseMoney("0.0001", ret));
BOOST_CHECK_EQUAL(ret, COIN/10000);
BOOST_CHECK(ParseMoney("0.00001", ret));
BOOST_CHECK_EQUAL(ret, COIN/100000);
BOOST_CHECK(ParseMoney("0.000001", ret));
BOOST_CHECK_EQUAL(ret, COIN/1000000);
BOOST_CHECK(ParseMoney("0.0000001", ret));
BOOST_CHECK_EQUAL(ret, COIN/10000000);
BOOST_CHECK(ParseMoney("0.00000001", ret));
BOOST_CHECK_EQUAL(ret, COIN/100000000);
// Parsing amount that can not be represented in ret should fail
BOOST_CHECK(!ParseMoney("0.000000001", ret));
// Parsing empty string should fail
BOOST_CHECK(!ParseMoney("", ret));
// Attempted 63 bit overflow should fail
BOOST_CHECK(!ParseMoney("92233720368.54775808", ret));
// Parsing negative amounts must fail
BOOST_CHECK(!ParseMoney("-1", ret));
// Parsing strings with embedded NUL characters should fail
BOOST_CHECK(!ParseMoney(std::string("\0-1", 3), ret));
BOOST_CHECK(!ParseMoney(std::string("\01", 2), ret));
BOOST_CHECK(!ParseMoney(std::string("1\0", 2), ret));
}
BOOST_AUTO_TEST_CASE(util_IsHex)
{
BOOST_CHECK(IsHex("00"));
BOOST_CHECK(IsHex("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
BOOST_CHECK(IsHex("ff"));
BOOST_CHECK(IsHex("FF"));
BOOST_CHECK(!IsHex(""));
BOOST_CHECK(!IsHex("0"));
BOOST_CHECK(!IsHex("a"));
BOOST_CHECK(!IsHex("eleven"));
BOOST_CHECK(!IsHex("00xx00"));
BOOST_CHECK(!IsHex("0x0000"));
}
BOOST_AUTO_TEST_CASE(util_IsHexNumber)
{
BOOST_CHECK(IsHexNumber("0x0"));
BOOST_CHECK(IsHexNumber("0"));
BOOST_CHECK(IsHexNumber("0x10"));
BOOST_CHECK(IsHexNumber("10"));
BOOST_CHECK(IsHexNumber("0xff"));
BOOST_CHECK(IsHexNumber("ff"));
BOOST_CHECK(IsHexNumber("0xFfa"));
BOOST_CHECK(IsHexNumber("Ffa"));
BOOST_CHECK(IsHexNumber("0x00112233445566778899aabbccddeeffAABBCCDDEEFF"));
BOOST_CHECK(IsHexNumber("00112233445566778899aabbccddeeffAABBCCDDEEFF"));
BOOST_CHECK(!IsHexNumber("")); // empty string not allowed
BOOST_CHECK(!IsHexNumber("0x")); // empty string after prefix not allowed
BOOST_CHECK(!IsHexNumber("0x0 ")); // no spaces at end,
BOOST_CHECK(!IsHexNumber(" 0x0")); // or beginning,
BOOST_CHECK(!IsHexNumber("0x 0")); // or middle,
BOOST_CHECK(!IsHexNumber(" ")); // etc.
BOOST_CHECK(!IsHexNumber("0x0ga")); // invalid character
BOOST_CHECK(!IsHexNumber("x0")); // broken prefix
BOOST_CHECK(!IsHexNumber("0x0x00")); // two prefixes not allowed
}
BOOST_AUTO_TEST_CASE(util_seed_insecure_rand)
{
SeedInsecureRand(SeedRand::ZEROS);
for (int mod=2;mod<11;mod++)
{
int mask = 1;
// Really rough binomial confidence approximation.
int err = 30*10000./mod*sqrt((1./mod*(1-1./mod))/10000.);
//mask is 2^ceil(log2(mod))-1
while(mask<mod-1)mask=(mask<<1)+1;
int count = 0;
//How often does it get a zero from the uniform range [0,mod)?
for (int i = 0; i < 10000; i++) {
uint32_t rval;
do{
rval=InsecureRand32()&mask;
}while(rval>=(uint32_t)mod);
count += rval==0;
}
BOOST_CHECK(count<=10000/mod+err);
BOOST_CHECK(count>=10000/mod-err);
}
}
BOOST_AUTO_TEST_CASE(util_TimingResistantEqual)
{
BOOST_CHECK(TimingResistantEqual(std::string(""), std::string("")));
BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("")));
BOOST_CHECK(!TimingResistantEqual(std::string(""), std::string("abc")));
BOOST_CHECK(!TimingResistantEqual(std::string("a"), std::string("aa")));
BOOST_CHECK(!TimingResistantEqual(std::string("aa"), std::string("a")));
BOOST_CHECK(TimingResistantEqual(std::string("abc"), std::string("abc")));
BOOST_CHECK(!TimingResistantEqual(std::string("abc"), std::string("aba")));
}
/* Test strprintf formatting directives.
* Put a string before and after to ensure sanity of element sizes on stack. */
#define B "check_prefix"
#define E "check_postfix"
BOOST_AUTO_TEST_CASE(strprintf_numbers)
{
int64_t s64t = -9223372036854775807LL; /* signed 64 bit test value */
uint64_t u64t = 18446744073709551615ULL; /* unsigned 64 bit test value */
BOOST_CHECK(strprintf("%s %d %s", B, s64t, E) == B" -9223372036854775807 " E);
BOOST_CHECK(strprintf("%s %u %s", B, u64t, E) == B" 18446744073709551615 " E);
BOOST_CHECK(strprintf("%s %x %s", B, u64t, E) == B" ffffffffffffffff " E);
size_t st = 12345678; /* unsigned size_t test value */
ssize_t sst = -12345678; /* signed size_t test value */
BOOST_CHECK(strprintf("%s %d %s", B, sst, E) == B" -12345678 " E);
BOOST_CHECK(strprintf("%s %u %s", B, st, E) == B" 12345678 " E);
BOOST_CHECK(strprintf("%s %x %s", B, st, E) == B" bc614e " E);
ptrdiff_t pt = 87654321; /* positive ptrdiff_t test value */
ptrdiff_t spt = -87654321; /* negative ptrdiff_t test value */
BOOST_CHECK(strprintf("%s %d %s", B, spt, E) == B" -87654321 " E);
BOOST_CHECK(strprintf("%s %u %s", B, pt, E) == B" 87654321 " E);
BOOST_CHECK(strprintf("%s %x %s", B, pt, E) == B" 5397fb1 " E);
}
#undef B
#undef E
/* Check for mingw/wine issue #3494
* Remove this test before time.ctime(0xffffffff) == 'Sun Feb 7 07:28:15 2106'
*/
BOOST_AUTO_TEST_CASE(gettime)
{
BOOST_CHECK((GetTime() & ~0xFFFFFFFFLL) == 0);
}
BOOST_AUTO_TEST_CASE(util_time_GetTime)
{
SetMockTime(111);
// Check that mock time does not change after a sleep
for (const auto& num_sleep : {0, 1}) {
UninterruptibleSleep(std::chrono::milliseconds{num_sleep});
BOOST_CHECK_EQUAL(111, GetTime()); // Deprecated time getter
BOOST_CHECK_EQUAL(111, GetTime<std::chrono::seconds>().count());
BOOST_CHECK_EQUAL(111000, GetTime<std::chrono::milliseconds>().count());
BOOST_CHECK_EQUAL(111000000, GetTime<std::chrono::microseconds>().count());
}
SetMockTime(0);
// Check that system time changes after a sleep
const auto ms_0 = GetTime<std::chrono::milliseconds>();
const auto us_0 = GetTime<std::chrono::microseconds>();
UninterruptibleSleep(std::chrono::milliseconds{1});
BOOST_CHECK(ms_0 < GetTime<std::chrono::milliseconds>());
BOOST_CHECK(us_0 < GetTime<std::chrono::microseconds>());
}
BOOST_AUTO_TEST_CASE(test_IsDigit)
{
BOOST_CHECK_EQUAL(IsDigit('0'), true);
BOOST_CHECK_EQUAL(IsDigit('1'), true);
BOOST_CHECK_EQUAL(IsDigit('8'), true);
BOOST_CHECK_EQUAL(IsDigit('9'), true);
BOOST_CHECK_EQUAL(IsDigit('0' - 1), false);
BOOST_CHECK_EQUAL(IsDigit('9' + 1), false);
BOOST_CHECK_EQUAL(IsDigit(0), false);
BOOST_CHECK_EQUAL(IsDigit(1), false);
BOOST_CHECK_EQUAL(IsDigit(8), false);
BOOST_CHECK_EQUAL(IsDigit(9), false);
}
BOOST_AUTO_TEST_CASE(test_ParseInt32)
{
int32_t n;
// Valid values
BOOST_CHECK(ParseInt32("1234", nullptr));
BOOST_CHECK(ParseInt32("0", &n) && n == 0);
BOOST_CHECK(ParseInt32("1234", &n) && n == 1234);
BOOST_CHECK(ParseInt32("01234", &n) && n == 1234); // no octal
BOOST_CHECK(ParseInt32("2147483647", &n) && n == 2147483647);
BOOST_CHECK(ParseInt32("-2147483648", &n) && n == (-2147483647 - 1)); // (-2147483647 - 1) equals INT_MIN
BOOST_CHECK(ParseInt32("-1234", &n) && n == -1234);
// Invalid values
BOOST_CHECK(!ParseInt32("", &n));
BOOST_CHECK(!ParseInt32(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseInt32("1 ", &n));
BOOST_CHECK(!ParseInt32("1a", &n));
BOOST_CHECK(!ParseInt32("aap", &n));
BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex
BOOST_CHECK(!ParseInt32("0x1", &n)); // no hex
const char test_bytes[] = {'1', 0, '1'};
std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseInt32(teststr, &n)); // no embedded NULs
// Overflow and underflow
BOOST_CHECK(!ParseInt32("-2147483649", nullptr));
BOOST_CHECK(!ParseInt32("2147483648", nullptr));
BOOST_CHECK(!ParseInt32("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseInt32("32482348723847471234", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseInt64)
{
int64_t n;
// Valid values
BOOST_CHECK(ParseInt64("1234", nullptr));
BOOST_CHECK(ParseInt64("0", &n) && n == 0LL);
BOOST_CHECK(ParseInt64("1234", &n) && n == 1234LL);
BOOST_CHECK(ParseInt64("01234", &n) && n == 1234LL); // no octal
BOOST_CHECK(ParseInt64("2147483647", &n) && n == 2147483647LL);
BOOST_CHECK(ParseInt64("-2147483648", &n) && n == -2147483648LL);
BOOST_CHECK(ParseInt64("9223372036854775807", &n) && n == (int64_t)9223372036854775807);
BOOST_CHECK(ParseInt64("-9223372036854775808", &n) && n == (int64_t)-9223372036854775807-1);
BOOST_CHECK(ParseInt64("-1234", &n) && n == -1234LL);
// Invalid values
BOOST_CHECK(!ParseInt64("", &n));
BOOST_CHECK(!ParseInt64(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseInt64("1 ", &n));
BOOST_CHECK(!ParseInt64("1a", &n));
BOOST_CHECK(!ParseInt64("aap", &n));
BOOST_CHECK(!ParseInt64("0x1", &n)); // no hex
const char test_bytes[] = {'1', 0, '1'};
std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseInt64(teststr, &n)); // no embedded NULs
// Overflow and underflow
BOOST_CHECK(!ParseInt64("-9223372036854775809", nullptr));
BOOST_CHECK(!ParseInt64("9223372036854775808", nullptr));
BOOST_CHECK(!ParseInt64("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseInt64("32482348723847471234", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseUInt32)
{
uint32_t n;
// Valid values
BOOST_CHECK(ParseUInt32("1234", nullptr));
BOOST_CHECK(ParseUInt32("0", &n) && n == 0);
BOOST_CHECK(ParseUInt32("1234", &n) && n == 1234);
BOOST_CHECK(ParseUInt32("01234", &n) && n == 1234); // no octal
BOOST_CHECK(ParseUInt32("2147483647", &n) && n == 2147483647);
BOOST_CHECK(ParseUInt32("2147483648", &n) && n == (uint32_t)2147483648);
BOOST_CHECK(ParseUInt32("4294967295", &n) && n == (uint32_t)4294967295);
// Invalid values
BOOST_CHECK(!ParseUInt32("", &n));
BOOST_CHECK(!ParseUInt32(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseUInt32(" -1", &n));
BOOST_CHECK(!ParseUInt32("1 ", &n));
BOOST_CHECK(!ParseUInt32("1a", &n));
BOOST_CHECK(!ParseUInt32("aap", &n));
BOOST_CHECK(!ParseUInt32("0x1", &n)); // no hex
BOOST_CHECK(!ParseUInt32("0x1", &n)); // no hex
const char test_bytes[] = {'1', 0, '1'};
std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseUInt32(teststr, &n)); // no embedded NULs
// Overflow and underflow
BOOST_CHECK(!ParseUInt32("-2147483648", &n));
BOOST_CHECK(!ParseUInt32("4294967296", &n));
BOOST_CHECK(!ParseUInt32("-1234", &n));
BOOST_CHECK(!ParseUInt32("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseUInt32("32482348723847471234", nullptr));
}
BOOST_AUTO_TEST_CASE(test_ParseUInt64)
{
uint64_t n;
// Valid values
BOOST_CHECK(ParseUInt64("1234", nullptr));
BOOST_CHECK(ParseUInt64("0", &n) && n == 0LL);
BOOST_CHECK(ParseUInt64("1234", &n) && n == 1234LL);
BOOST_CHECK(ParseUInt64("01234", &n) && n == 1234LL); // no octal
BOOST_CHECK(ParseUInt64("2147483647", &n) && n == 2147483647LL);
BOOST_CHECK(ParseUInt64("9223372036854775807", &n) && n == 9223372036854775807ULL);
BOOST_CHECK(ParseUInt64("9223372036854775808", &n) && n == 9223372036854775808ULL);
BOOST_CHECK(ParseUInt64("18446744073709551615", &n) && n == 18446744073709551615ULL);
// Invalid values
BOOST_CHECK(!ParseUInt64("", &n));
BOOST_CHECK(!ParseUInt64(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseUInt64(" -1", &n));
BOOST_CHECK(!ParseUInt64("1 ", &n));
BOOST_CHECK(!ParseUInt64("1a", &n));
BOOST_CHECK(!ParseUInt64("aap", &n));
BOOST_CHECK(!ParseUInt64("0x1", &n)); // no hex
const char test_bytes[] = {'1', 0, '1'};
std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseUInt64(teststr, &n)); // no embedded NULs
// Overflow and underflow
BOOST_CHECK(!ParseUInt64("-9223372036854775809", nullptr));
BOOST_CHECK(!ParseUInt64("18446744073709551616", nullptr));
BOOST_CHECK(!ParseUInt64("-32482348723847471234", nullptr));
BOOST_CHECK(!ParseUInt64("-2147483648", &n));
BOOST_CHECK(!ParseUInt64("-9223372036854775808", &n));
BOOST_CHECK(!ParseUInt64("-1234", &n));
}
BOOST_AUTO_TEST_CASE(test_ParseDouble)
{
double n;
// Valid values
BOOST_CHECK(ParseDouble("1234", nullptr));
BOOST_CHECK(ParseDouble("0", &n) && n == 0.0);
BOOST_CHECK(ParseDouble("1234", &n) && n == 1234.0);
BOOST_CHECK(ParseDouble("01234", &n) && n == 1234.0); // no octal
BOOST_CHECK(ParseDouble("2147483647", &n) && n == 2147483647.0);
BOOST_CHECK(ParseDouble("-2147483648", &n) && n == -2147483648.0);
BOOST_CHECK(ParseDouble("-1234", &n) && n == -1234.0);
BOOST_CHECK(ParseDouble("1e6", &n) && n == 1e6);
BOOST_CHECK(ParseDouble("-1e6", &n) && n == -1e6);
// Invalid values
BOOST_CHECK(!ParseDouble("", &n));
BOOST_CHECK(!ParseDouble(" 1", &n)); // no padding inside
BOOST_CHECK(!ParseDouble("1 ", &n));
BOOST_CHECK(!ParseDouble("1a", &n));
BOOST_CHECK(!ParseDouble("aap", &n));
BOOST_CHECK(!ParseDouble("0x1", &n)); // no hex
const char test_bytes[] = {'1', 0, '1'};
std::string teststr(test_bytes, sizeof(test_bytes));
BOOST_CHECK(!ParseDouble(teststr, &n)); // no embedded NULs
// Overflow and underflow
BOOST_CHECK(!ParseDouble("-1e10000", nullptr));
BOOST_CHECK(!ParseDouble("1e10000", nullptr));
}
BOOST_AUTO_TEST_CASE(test_FormatParagraph)
{
BOOST_CHECK_EQUAL(FormatParagraph("", 79, 0), "");
BOOST_CHECK_EQUAL(FormatParagraph("test", 79, 0), "test");
BOOST_CHECK_EQUAL(FormatParagraph(" test", 79, 0), " test");
BOOST_CHECK_EQUAL(FormatParagraph("test test", 79, 0), "test test");
BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 0), "test\ntest");
BOOST_CHECK_EQUAL(FormatParagraph("testerde test", 4, 0), "testerde\ntest");
BOOST_CHECK_EQUAL(FormatParagraph("test test", 4, 4), "test\n test");
// Make sure we don't indent a fully-new line following a too-long line ending
BOOST_CHECK_EQUAL(FormatParagraph("test test\nabc", 4, 4), "test\n test\nabc");
BOOST_CHECK_EQUAL(FormatParagraph("This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length until it gets here", 79), "This_is_a_very_long_test_string_without_any_spaces_so_it_should_just_get_returned_as_is_despite_the_length\nuntil it gets here");
// Test wrap length is exact
BOOST_CHECK_EQUAL(FormatParagraph("a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p");
BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p", 79), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\nf g h i j k l m n o p");
// Indent should be included in length of lines
BOOST_CHECK_EQUAL(FormatParagraph("x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg h i j k", 79, 4), "x\na b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 a b c de\n f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e fg\n h i j k");
BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string. This is a second sentence in the very long test string.", 79), "This is a very long test string. This is a second sentence in the very long\ntest string.");
BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string.");
BOOST_CHECK_EQUAL(FormatParagraph("This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third sentence in the very long test string.", 79), "This is a very long test string.\n\nThis is a second sentence in the very long test string. This is a third\nsentence in the very long test string.");
BOOST_CHECK_EQUAL(FormatParagraph("Testing that normal newlines do not get indented.\nLike here.", 79), "Testing that normal newlines do not get indented.\nLike here.");
}
BOOST_AUTO_TEST_CASE(test_FormatSubVersion)
{
std::vector<std::string> comments;
comments.push_back(std::string("comment1"));
std::vector<std::string> comments2;
comments2.push_back(std::string("comment1"));
comments2.push_back(SanitizeString(std::string("Comment2; .,_?@-; !\"#$%&'()*+/<=>[]\\^`{|}~"), SAFE_CHARS_UA_COMMENT)); // Semicolon is discouraged but not forbidden by BIP-0014
BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, std::vector<std::string>()),std::string("/Test:0.9.99/"));
BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments),std::string("/Test:0.9.99(comment1)/"));
BOOST_CHECK_EQUAL(FormatSubVersion("Test", 99900, comments2),std::string("/Test:0.9.99(comment1; Comment2; .,_?@-; )/"));
}
BOOST_AUTO_TEST_CASE(test_ParseFixedPoint)
{
int64_t amount = 0;
BOOST_CHECK(ParseFixedPoint("0", 8, &amount));
BOOST_CHECK_EQUAL(amount, 0LL);
BOOST_CHECK(ParseFixedPoint("1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 100000000LL);
BOOST_CHECK(ParseFixedPoint("0.0", 8, &amount));
BOOST_CHECK_EQUAL(amount, 0LL);
BOOST_CHECK(ParseFixedPoint("-0.1", 8, &amount));
BOOST_CHECK_EQUAL(amount, -10000000LL);
BOOST_CHECK(ParseFixedPoint("1.1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 110000000LL);
BOOST_CHECK(ParseFixedPoint("1.10000000000000000", 8, &amount));
BOOST_CHECK_EQUAL(amount, 110000000LL);
BOOST_CHECK(ParseFixedPoint("1.1e1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 1100000000LL);
BOOST_CHECK(ParseFixedPoint("1.1e-1", 8, &amount));
BOOST_CHECK_EQUAL(amount, 11000000LL);
BOOST_CHECK(ParseFixedPoint("1000", 8, &amount));
BOOST_CHECK_EQUAL(amount, 100000000000LL);
BOOST_CHECK(ParseFixedPoint("-1000", 8, &amount));
BOOST_CHECK_EQUAL(amount, -100000000000LL);
BOOST_CHECK(ParseFixedPoint("0.00000001", 8, &amount));
BOOST_CHECK_EQUAL(amount, 1LL);
BOOST_CHECK(ParseFixedPoint("0.0000000100000000", 8, &amount));
BOOST_CHECK_EQUAL(amount, 1LL);
BOOST_CHECK(ParseFixedPoint("-0.00000001", 8, &amount));
BOOST_CHECK_EQUAL(amount, -1LL);
BOOST_CHECK(ParseFixedPoint("1000000000.00000001", 8, &amount));
BOOST_CHECK_EQUAL(amount, 100000000000000001LL);
BOOST_CHECK(ParseFixedPoint("9999999999.99999999", 8, &amount));
BOOST_CHECK_EQUAL(amount, 999999999999999999LL);
BOOST_CHECK(ParseFixedPoint("-9999999999.99999999", 8, &amount));
BOOST_CHECK_EQUAL(amount, -999999999999999999LL);
BOOST_CHECK(!ParseFixedPoint("", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("a-1000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-a1000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-1000a", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-01000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("00.1", 8, &amount));
BOOST_CHECK(!ParseFixedPoint(".1", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("--0.1", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("0.000000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-0.000000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("0.00000001000000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-10000000000.00000000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("10000000000.00000000", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-10000000000.00000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("10000000000.00000001", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-10000000000.00000009", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("10000000000.00000009", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-99999999999.99999999", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("99999909999.09999999", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("92233720368.54775807", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("92233720368.54775808", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-92233720368.54775808", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("-92233720368.54775809", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("1.1e", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("1.1e-", 8, &amount));
BOOST_CHECK(!ParseFixedPoint("1.", 8, &amount));
}
static void TestOtherThread(fs::path dirname, std::string lockname, bool *result)
{
*result = LockDirectory(dirname, lockname);
}
#ifndef WIN32 // Cannot do this test on WIN32 due to lack of fork()
static constexpr char LockCommand = 'L';
static constexpr char UnlockCommand = 'U';
static constexpr char ExitCommand = 'X';
static void TestOtherProcess(fs::path dirname, std::string lockname, int fd)
{
char ch;
while (true) {
int rv = read(fd, &ch, 1); // Wait for command
assert(rv == 1);
switch(ch) {
case LockCommand:
ch = LockDirectory(dirname, lockname);
rv = write(fd, &ch, 1);
assert(rv == 1);
break;
case UnlockCommand:
ReleaseDirectoryLocks();
ch = true; // Always succeeds
rv = write(fd, &ch, 1);
assert(rv == 1);
break;
case ExitCommand:
close(fd);
exit(0);
default:
assert(0);
}
}
}
#endif
BOOST_AUTO_TEST_CASE(test_LockDirectory)
{
fs::path dirname = GetDataDir() / "lock_dir";
const std::string lockname = ".lock";
#ifndef WIN32
// Revert SIGCHLD to default, otherwise boost.test will catch and fail on
// it: there is BOOST_TEST_IGNORE_SIGCHLD but that only works when defined
// at build-time of the boost library
void (*old_handler)(int) = signal(SIGCHLD, SIG_DFL);
// Fork another process for testing before creating the lock, so that we
// won't fork while holding the lock (which might be undefined, and is not
// relevant as test case as that is avoided with -daemonize).
int fd[2];
BOOST_CHECK_EQUAL(socketpair(AF_UNIX, SOCK_STREAM, 0, fd), 0);
pid_t pid = fork();
if (!pid) {
BOOST_CHECK_EQUAL(close(fd[1]), 0); // Child: close parent end
TestOtherProcess(dirname, lockname, fd[0]);
}
BOOST_CHECK_EQUAL(close(fd[0]), 0); // Parent: close child end
#endif
// Lock on non-existent directory should fail
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), false);
fs::create_directories(dirname);
// Probing lock on new directory should succeed
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Persistent lock on new directory should succeed
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), true);
// Another lock on the directory from the same thread should succeed
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname), true);
// Another lock on the directory from a different thread within the same process should succeed
bool threadresult;
std::thread thr(TestOtherThread, dirname, lockname, &threadresult);
thr.join();
BOOST_CHECK_EQUAL(threadresult, true);
#ifndef WIN32
// Try to acquire lock in child process while we're holding it, this should fail.
char ch;
BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
BOOST_CHECK_EQUAL((bool)ch, false);
// Give up our lock
ReleaseDirectoryLocks();
// Probing lock from our side now should succeed, but not hold on to the lock.
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Try to acquire the lock in the child process, this should be successful.
BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
BOOST_CHECK_EQUAL((bool)ch, true);
// When we try to probe the lock now, it should fail.
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), false);
// Unlock the lock in the child process
BOOST_CHECK_EQUAL(write(fd[1], &UnlockCommand, 1), 1);
BOOST_CHECK_EQUAL(read(fd[1], &ch, 1), 1);
BOOST_CHECK_EQUAL((bool)ch, true);
// When we try to probe the lock now, it should succeed.
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Re-lock the lock in the child process, then wait for it to exit, check
// successful return. After that, we check that exiting the process
// has released the lock as we would expect by probing it.
int processstatus;
BOOST_CHECK_EQUAL(write(fd[1], &LockCommand, 1), 1);
BOOST_CHECK_EQUAL(write(fd[1], &ExitCommand, 1), 1);
BOOST_CHECK_EQUAL(waitpid(pid, &processstatus, 0), pid);
BOOST_CHECK_EQUAL(processstatus, 0);
BOOST_CHECK_EQUAL(LockDirectory(dirname, lockname, true), true);
// Restore SIGCHLD
signal(SIGCHLD, old_handler);
BOOST_CHECK_EQUAL(close(fd[1]), 0); // Close our side of the socketpair
#endif
// Clean up
ReleaseDirectoryLocks();
fs::remove_all(dirname);
}
BOOST_AUTO_TEST_CASE(test_DirIsWritable)
{
// Should be able to write to the data dir.
fs::path tmpdirname = GetDataDir();
BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true);
// Should not be able to write to a non-existent dir.
tmpdirname = tmpdirname / fs::unique_path();
BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), false);
fs::create_directory(tmpdirname);
// Should be able to write to it now.
BOOST_CHECK_EQUAL(DirIsWritable(tmpdirname), true);
fs::remove(tmpdirname);
}
BOOST_AUTO_TEST_CASE(test_ToLower)
{
BOOST_CHECK_EQUAL(ToLower('@'), '@');
BOOST_CHECK_EQUAL(ToLower('A'), 'a');
BOOST_CHECK_EQUAL(ToLower('Z'), 'z');
BOOST_CHECK_EQUAL(ToLower('['), '[');
BOOST_CHECK_EQUAL(ToLower(0), 0);
BOOST_CHECK_EQUAL(ToLower('\xff'), '\xff');
BOOST_CHECK_EQUAL(ToLower(""), "");
BOOST_CHECK_EQUAL(ToLower("#HODL"), "#hodl");
BOOST_CHECK_EQUAL(ToLower("\x00\xfe\xff"), "\x00\xfe\xff");
}
BOOST_AUTO_TEST_CASE(test_ToUpper)
{
BOOST_CHECK_EQUAL(ToUpper('`'), '`');
BOOST_CHECK_EQUAL(ToUpper('a'), 'A');
BOOST_CHECK_EQUAL(ToUpper('z'), 'Z');
BOOST_CHECK_EQUAL(ToUpper('{'), '{');
BOOST_CHECK_EQUAL(ToUpper(0), 0);
BOOST_CHECK_EQUAL(ToUpper('\xff'), '\xff');
BOOST_CHECK_EQUAL(ToUpper(""), "");
BOOST_CHECK_EQUAL(ToUpper("#hodl"), "#HODL");
BOOST_CHECK_EQUAL(ToUpper("\x00\xfe\xff"), "\x00\xfe\xff");
}
BOOST_AUTO_TEST_CASE(test_Capitalize)
{
BOOST_CHECK_EQUAL(Capitalize(""), "");
BOOST_CHECK_EQUAL(Capitalize("bitcoin"), "Bitcoin");
BOOST_CHECK_EQUAL(Capitalize("\x00\xfe\xff"), "\x00\xfe\xff");
}
static std::string SpanToStr(Span<const char>& span)
{
return std::string(span.begin(), span.end());
}
BOOST_AUTO_TEST_CASE(test_spanparsing)
{
using namespace spanparsing;
std::string input;
Span<const char> sp;
bool success;
// Const(...): parse a constant, update span to skip it if successful
input = "MilkToastHoney";
sp = MakeSpan(input);
success = Const("", sp); // empty
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
success = Const("Milk", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
success = Const("Bread", sp);
BOOST_CHECK(!success);
success = Const("Toast", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
success = Const("Honeybadger", sp);
BOOST_CHECK(!success);
success = Const("Honey", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "");
// Func(...): parse a function call, update span to argument if successful
input = "Foo(Bar(xy,z()))";
sp = MakeSpan(input);
success = Func("FooBar", sp);
BOOST_CHECK(!success);
success = Func("Foo(", sp);
BOOST_CHECK(!success);
success = Func("Foo", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "Bar(xy,z())");
success = Func("Bar", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "xy,z()");
success = Func("xy", sp);
BOOST_CHECK(!success);
// Expr(...): return expression that span begins with, update span to skip it
Span<const char> result;
input = "(n*(n-1))/2";
sp = MakeSpan(input);
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "(n*(n-1))/2");
BOOST_CHECK_EQUAL(SpanToStr(sp), "");
input = "foo,bar";
sp = MakeSpan(input);
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "foo");
BOOST_CHECK_EQUAL(SpanToStr(sp), ",bar");
input = "(aaaaa,bbbbb()),c";
sp = MakeSpan(input);
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "(aaaaa,bbbbb())");
BOOST_CHECK_EQUAL(SpanToStr(sp), ",c");
input = "xyz)foo";
sp = MakeSpan(input);
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "xyz");
BOOST_CHECK_EQUAL(SpanToStr(sp), ")foo");
input = "((a),(b),(c)),xxx";
sp = MakeSpan(input);
result = Expr(sp);
BOOST_CHECK_EQUAL(SpanToStr(result), "((a),(b),(c))");
BOOST_CHECK_EQUAL(SpanToStr(sp), ",xxx");
// Split(...): split a string on every instance of sep, return vector
std::vector<Span<const char>> results;
input = "xxx";
results = Split(MakeSpan(input), 'x');
BOOST_CHECK_EQUAL(results.size(), 4);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[1]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[2]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[3]), "");
input = "one#two#three";
results = Split(MakeSpan(input), '-');
BOOST_CHECK_EQUAL(results.size(), 1);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one#two#three");
input = "one#two#three";
results = Split(MakeSpan(input), '#');
BOOST_CHECK_EQUAL(results.size(), 3);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "one");
BOOST_CHECK_EQUAL(SpanToStr(results[1]), "two");
BOOST_CHECK_EQUAL(SpanToStr(results[2]), "three");
input = "*foo*bar*";
results = Split(MakeSpan(input), '*');
BOOST_CHECK_EQUAL(results.size(), 4);
BOOST_CHECK_EQUAL(SpanToStr(results[0]), "");
BOOST_CHECK_EQUAL(SpanToStr(results[1]), "foo");
BOOST_CHECK_EQUAL(SpanToStr(results[2]), "bar");
BOOST_CHECK_EQUAL(SpanToStr(results[3]), "");
}
BOOST_AUTO_TEST_CASE(test_LogEscapeMessage)
{
// ASCII and UTF-8 must pass through unaltered.
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Valid log message貓"), "Valid log message貓");
// Newlines must pass through unaltered.
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("Message\n with newlines\n"), "Message\n with newlines\n");
// Other control characters are escaped in C syntax.
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage("\x01\x7f Corrupted log message\x0d"), R"(\x01\x7f Corrupted log message\x0d)");
// Embedded NULL characters are escaped too.
const std::string NUL("O\x00O", 3);
BOOST_CHECK_EQUAL(BCLog::LogEscapeMessage(NUL), R"(O\x00O)");
}
namespace {
struct Tracker
{
//! Points to the original object (possibly itself) we moved/copied from
const Tracker* origin;
//! How many copies where involved between the original object and this one (moves are not counted)
int copies;
Tracker() noexcept : origin(this), copies(0) {}
Tracker(const Tracker& t) noexcept : origin(t.origin), copies(t.copies + 1) {}
Tracker(Tracker&& t) noexcept : origin(t.origin), copies(t.copies) {}
Tracker& operator=(const Tracker& t) noexcept
{
origin = t.origin;
copies = t.copies + 1;
return *this;
}
Tracker& operator=(Tracker&& t) noexcept
{
origin = t.origin;
copies = t.copies;
return *this;
}
};
}
BOOST_AUTO_TEST_CASE(test_tracked_vector)
{
Tracker t1;
Tracker t2;
Tracker t3;
BOOST_CHECK(t1.origin == &t1);
BOOST_CHECK(t2.origin == &t2);
BOOST_CHECK(t3.origin == &t3);
auto v1 = Vector(t1);
BOOST_CHECK_EQUAL(v1.size(), 1);
BOOST_CHECK(v1[0].origin == &t1);
BOOST_CHECK_EQUAL(v1[0].copies, 1);
auto v2 = Vector(std::move(t2));
BOOST_CHECK_EQUAL(v2.size(), 1);
BOOST_CHECK(v2[0].origin == &t2);
BOOST_CHECK_EQUAL(v2[0].copies, 0);
auto v3 = Vector(t1, std::move(t2));
BOOST_CHECK_EQUAL(v3.size(), 2);
BOOST_CHECK(v3[0].origin == &t1);
BOOST_CHECK(v3[1].origin == &t2);
BOOST_CHECK_EQUAL(v3[0].copies, 1);
BOOST_CHECK_EQUAL(v3[1].copies, 0);
auto v4 = Vector(std::move(v3[0]), v3[1], std::move(t3));
BOOST_CHECK_EQUAL(v4.size(), 3);
BOOST_CHECK(v4[0].origin == &t1);
BOOST_CHECK(v4[1].origin == &t2);
BOOST_CHECK(v4[2].origin == &t3);
BOOST_CHECK_EQUAL(v4[0].copies, 1);
BOOST_CHECK_EQUAL(v4[1].copies, 1);
BOOST_CHECK_EQUAL(v4[2].copies, 0);
auto v5 = Cat(v1, v4);
BOOST_CHECK_EQUAL(v5.size(), 4);
BOOST_CHECK(v5[0].origin == &t1);
BOOST_CHECK(v5[1].origin == &t1);
BOOST_CHECK(v5[2].origin == &t2);
BOOST_CHECK(v5[3].origin == &t3);
BOOST_CHECK_EQUAL(v5[0].copies, 2);
BOOST_CHECK_EQUAL(v5[1].copies, 2);
BOOST_CHECK_EQUAL(v5[2].copies, 2);
BOOST_CHECK_EQUAL(v5[3].copies, 1);
auto v6 = Cat(std::move(v1), v3);
BOOST_CHECK_EQUAL(v6.size(), 3);
BOOST_CHECK(v6[0].origin == &t1);
BOOST_CHECK(v6[1].origin == &t1);
BOOST_CHECK(v6[2].origin == &t2);
BOOST_CHECK_EQUAL(v6[0].copies, 1);
BOOST_CHECK_EQUAL(v6[1].copies, 2);
BOOST_CHECK_EQUAL(v6[2].copies, 1);
auto v7 = Cat(v2, std::move(v4));
BOOST_CHECK_EQUAL(v7.size(), 4);
BOOST_CHECK(v7[0].origin == &t2);
BOOST_CHECK(v7[1].origin == &t1);
BOOST_CHECK(v7[2].origin == &t2);
BOOST_CHECK(v7[3].origin == &t3);
BOOST_CHECK_EQUAL(v7[0].copies, 1);
BOOST_CHECK_EQUAL(v7[1].copies, 1);
BOOST_CHECK_EQUAL(v7[2].copies, 1);
BOOST_CHECK_EQUAL(v7[3].copies, 0);
auto v8 = Cat(std::move(v2), std::move(v3));
BOOST_CHECK_EQUAL(v8.size(), 3);
BOOST_CHECK(v8[0].origin == &t2);
BOOST_CHECK(v8[1].origin == &t1);
BOOST_CHECK(v8[2].origin == &t2);
BOOST_CHECK_EQUAL(v8[0].copies, 0);
BOOST_CHECK_EQUAL(v8[1].copies, 1);
BOOST_CHECK_EQUAL(v8[2].copies, 0);
}
BOOST_AUTO_TEST_CASE(message_sign)
{
const std::array<unsigned char, 32> privkey_bytes = {
// just some random data
// derived address from this private key: Mzmo9u8xMCN7s3QSQ76s91npTE2P1CAQdw
0xD9, 0x7F, 0x51, 0x08, 0xF1, 0x1C, 0xDA, 0x6E,
0xEE, 0xBA, 0xAA, 0x42, 0x0F, 0xEF, 0x07, 0x26,
0xB1, 0xF8, 0x98, 0x06, 0x0B, 0x98, 0x48, 0x9F,
0xA3, 0x09, 0x84, 0x63, 0xC0, 0x03, 0x28, 0x66
};
const std::string message = "Trust no one";
const std::string expected_signature =
"H1aQ7WWEyMxq/wPB4yiCcw5pqmYnH+SXcp+tKse9AlLqGaH4JEj4gesdKW7JHFZfQCt+GIITL0mVJqXXNwOQwLo=";
CKey privkey;
std::string generated_signature;
BOOST_REQUIRE_MESSAGE(!privkey.IsValid(),
"Confirm the private key is invalid");
BOOST_CHECK_MESSAGE(!MessageSign(privkey, message, generated_signature),
"Sign with an invalid private key");
privkey.Set(privkey_bytes.begin(), privkey_bytes.end(), true);
BOOST_REQUIRE_MESSAGE(privkey.IsValid(),
"Confirm the private key is valid");
BOOST_CHECK_MESSAGE(MessageSign(privkey, message, generated_signature),
"Sign with a valid private key");
BOOST_CHECK_EQUAL(expected_signature, generated_signature);
}
BOOST_AUTO_TEST_CASE(message_verify)
{
BOOST_CHECK_EQUAL(
MessageVerify(
"invalid address",
"signature should be irrelevant",
"message too"),
MessageVerificationResult::ERR_INVALID_ADDRESS);
BOOST_CHECK_EQUAL(
MessageVerify(
"6PnVHjcpv2C9TZajr6DA1XkcZCpXBCNDub",
"signature should be irrelevant",
"message too"),
MessageVerificationResult::ERR_ADDRESS_NO_KEY);
BOOST_CHECK_EQUAL(
MessageVerify(
"NFQxPTqwzdFzHzdiLJtMRjyTTysyjBG6zV",
"invalid signature, not in base64 encoding",
"message should be irrelevant"),
MessageVerificationResult::ERR_MALFORMED_SIGNATURE);
BOOST_CHECK_EQUAL(
MessageVerify(
"NFQxPTqwzdFzHzdiLJtMRjyTTysyjBG6zV",
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
"message should be irrelevant"),
MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED);
/* For the signatures, we use N4sm2FCx896aRjtzpex7rrFbRFpnrcvGYr as the
signing address. The corresponding private key is
TdaRhYXbedL5g81EJA7bLMgfQDUwdfvi9qxcN4BMsZRPi6uAc7kb. */
BOOST_CHECK_EQUAL(
MessageVerify(
"Mzmo9u8xMCN7s3QSQ76s91npTE2P1CAQdw",
"IB45dwTxClrM2DFEW4eW5lpe9HJA7gZqbwHyCvMdNGaML6qgjyfpdA4Vou6eIBO0DzIrEq8ztBnW8ytfRU7yWjA=",
"I never signed this"),
MessageVerificationResult::ERR_NOT_SIGNED);
BOOST_CHECK_EQUAL(
MessageVerify(
"N4sm2FCx896aRjtzpex7rrFbRFpnrcvGYr",
"H+k6FIN5AhSoslH1O2aS9GerYLMzmPDh5lLHLGg5wVMiSRuHNFkVtcQAUx8kYEjjHTpeBruiA+DY/TZ0PAl2kq8=",
"Trust no one"),
MessageVerificationResult::OK);
BOOST_CHECK_EQUAL(
MessageVerify(
"N4sm2FCx896aRjtzpex7rrFbRFpnrcvGYr",
"Hwf2fTyHTrOJjzahwJHCPBXAhgu80WRPmSt0SAsUVXHkW4p1fYx6w2wTn3Kq4tFdnqeUnzUTZA+502ANeTbSvO0=",
"Trust me"),
MessageVerificationResult::OK);
}
BOOST_AUTO_TEST_CASE(message_hash)
{
const std::string unsigned_tx = "...";
const std::string prefixed_message =
std::string(1, (char)MESSAGE_MAGIC.length()) +
MESSAGE_MAGIC +
std::string(1, (char)unsigned_tx.length()) +
unsigned_tx;
const uint256 signature_hash = Hash(unsigned_tx.begin(), unsigned_tx.end());
const uint256 message_hash1 = Hash(prefixed_message.begin(), prefixed_message.end());
const uint256 message_hash2 = MessageHash(unsigned_tx);
BOOST_CHECK_EQUAL(message_hash1, message_hash2);
BOOST_CHECK_NE(message_hash1, signature_hash);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "ObParameter.h"
namespace OB{
Parameter::Parameter(Object* parent):Object(parent){
};
Parameter::~Parameter(){
};
Parameter::Parameter(const Parameter& other):Object(other){
m_type = other.m_type;
m_name = other.m_name;
};
Parameter& Parameter::operator= (const Parameter& other){
if(this != &other){
Object::operator=(other);
m_type = other.m_type;
m_name = other.m_name;
}
return *this;
};
/// initialize by reading an TiXmlElement
/// params:
/// - element: the TiXMLElement
/// - error: the error information, when return false
/// Return:
/// - bool: readObXML successful or not
bool Parameter::readObXML(TiXmlElement* element, std::string& error)
{
string id;
if(!getStringAttribute(element, "ID", id, error)){
error += "Fail to find ID attribute for Parameter element.\n";
return false;
}
if(!getStringAttribute(element, "Name", m_name, error, true)){
error += "Fail to find Name attribute for Parameter element.\n";
return false;
}
/// Set the ID
if(!setID(id, error)){
error += "Fail to set ID for Parameter.\n";
return false;
}
bool hasType = false;
bool hasUnit = false;
for(const TiXmlNode* child = element->FirstChild(); child; child=child->NextSibling())
{
if(child->Type() != TiXmlNode::ELEMENT) continue;
TiXmlElement *childElement = (TiXmlElement*)child;
if(!strcmp(child->Value(),"Description")){
setDescription(childElement->GetText());
}else if(!strcmp(child->Value(),"Unit")){
m_unit = atoi(childElement->GetText());
}else if(!strcmp(child->Value(),"Type")){
hasType = true;
string type = childElement->GetText();
if(type == "RoomAirTemperature")
m_type = Parameter_RoomTemperature;
else if(type == "RoomCO2Concentration")
m_type = Parameter_RoomCO2Concentration;
else if(type == "RoomWorkPlaneDaylightIlluminance")
m_type = Parameter_RoomWorkPlaneDaylightIlluminance;
else if(type == "RoomLightsPowerDensity")
m_type = Parameter_RoomLightsPowerDensity;
else if(type == "OutdoorDryBulbTemperature")
m_type = Parameter_OutdoorDryBulbTemperature;
else if(type == "OutdoorRainIndicator")
m_type = Parameter_OutdoorRainIndicator;
else{
error+= "Find unexpected parameter type: (";
error += type;
error += ") in Space element.\n";
return false;
}
}else{
error+= "Found unexpected child element: (";
error += child->Value();
error += ") in Parameter element.\n";
return false;
}
}
return true;
};
Parameter::ParameterType Parameter::getParameterType(){
return m_type;
};
}; |
; void __CALLEE__ l_qsort_callee(void *base, unsigned int size, void *cmp)
; 01.2007 aralbrec
XLIB l_qsort_callee
XDEF ASMDISP_L_QSORT_CALLEE
LIB Lqsort, l_jpiy
.l_qsort_callee
pop de
pop iy
pop hl
pop bc
push de
.centry
ld ix,compare
jp Lqsort
.compare
push hl
push de
push bc
call l_jpiy
ld a,l
pop bc
pop de
pop hl
ret
DEFC ASMDISP_L_QSORT_CALLEE = centry - l_qsort_callee
|
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace std;
class vecto{
private:
int n;//kich thuoc vecto
int *a;
public:
void nhap ();
void xuat();
int tich(vecto v2);
float chieudai();
};
void vecto::nhap(){
cout<<"Nhap kich thuoc vecto:";
cin>>n;
a= new int [n];
for ( int i=0; i<n;++i){
cout<<"a["<<i<<"]";
cin>>a[i];
}
}
void vecto::xuat(){
cout<<endl;
for ( int i=0;i<n;++i)
cout<<a[i]<<" ";
}
int vecto::tich(vecto v2){//tich vo huong 2 vecto
int s=0;
if (n!=v2.n){
cout<<"Hai vecto khong cung kich thuoc";
return -1;}
else
for ( int i=0;i<n;++i)
s=s+a[i]*v2.a[i];
return s;
}
float vecto::chieudai()//modun vecto
{
float d=0.0;
for( int i=0;i<n;i++)
d=d+a[i]*a[i];
return sqrt (d);
}
int main(){
vecto v1, v2;
v1.nhap();
v2.nhap();
v1.xuat();
v2.xuat();
float k=v1.tich(v2);
if ( k==-1)
cout<<endl<<"Khong tinh duoc tich cua 2 vecto khong cung kich thuoc";
else
cout<<endl<<"Tich vo huong cua 2 vecto la :"<<v1.tich(v2)<<endl;
cout<<"Mo dun cua 2 vecto la :"<<v1.chieudai();
return 0;
}
|
; A006481: Euler characteristics of polytopes.
; 1,2,3,4,5,11,21,36,57,127,253,463,793,1717,3433,6436,11441,24311,48621,92379,167961,352717,705433,1352079,2496145,5200301,10400601,20058301,37442161,77558761,155117521,300540196,565722721,1166803111,2333606221,4537567651,8597496601,17672631901,35345263801,68923264411,131282408401,269128937221,538257874441,1052049481861,2012616400081,4116715363801,8233430727601,16123801841551,30957699535777,63205303218877,126410606437753,247959266474053,477551179875953,973469712824057,1946939425648113,3824345300380221,7384942649010081
mov $5,$0
add $5,1
mov $7,$0
lpb $5,1
mov $0,$7
sub $5,1
sub $0,$5
mov $2,$0
sub $0,1
mov $3,$0
div $0,4
mul $0,2
lpb $2,1
sub $2,1
mov $4,$0
mov $6,$3
lpe
bin $6,$4
add $1,$6
lpe
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/ink/BaseShapeWidget.hpp>
namespace RED4ext
{
namespace ink {
struct RectangleWidget : ink::BaseShapeWidget
{
static constexpr const char* NAME = "inkRectangleWidget";
static constexpr const char* ALIAS = NAME;
uint8_t unk220[0x230 - 0x220]; // 220
};
RED4EXT_ASSERT_SIZE(RectangleWidget, 0x230);
} // namespace ink
} // namespace RED4ext
|
; A336751: Smallest side of integer-sided triangles whose sides a < b < c are in arithmetic progression.
; 2,3,3,4,4,5,4,5,6,5,6,7,5,6,7,8,6,7,8,9,6,7,8,9,10,7,8,9,10,11,7,8,9,10,11,12,8,9,10,11,12,13,8,9,10,11,12,13,14,9,10,11,12,13,14,15,9,10,11,12,13,14,15,16,10,11,12,13,14,15,16,17,10,11,12,13,14
lpb $0
add $1,$2
cmp $1,$2
add $2,$1
sub $0,$2
lpe
add $0,$2
add $0,2
|
; A221461: Number of 0..6 arrays of length n with each element unequal to at least one neighbor, starting with 0
; 0,6,36,252,1728,11880,81648,561168,3856896,26508384,182191680,1252200384,8606352384,59151316608,406546013952,2794183983360,19204379983872,131991383803392,907174582723584,6234995799161856,42853022291312640,294528108542846976,2024286785004957696,13912889361286828032,95623056877750714368,657215677434225254400,4517032405871855812608,31045488499836486402048,213375125434250053287936,1466523683604519238139904,10079392854232615748567040,69275499227022809920241664,476129352487532554012852224,3272429110287332183598563328,22491350776649188425668493312,154582679321619123655602339840,1062444180589609872487624998912,7302161159467373976859364032512,50187632040341903096081934188544,344938759198855662437647789326336,2370758347435185393202378341089280,16294182639804246333840156782493696,111989645923436590362255210741497856,769702971379445020176572205143949312
mov $1,1
lpb $0
sub $0,1
mov $2,$3
add $3,$1
mov $1,$2
mul $3,6
lpe
mov $0,-6
mov $4,$3
add $4,7
add $0,$4
sub $0,1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Geoworks 1994 -- All Rights Reserved
PROJECT: Condo viewer
MODULE: main - view and text
FILE: mainManager.asm
AUTHOR: Jonathan Magasin, May 6, 1994
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
JM 5/ 6/94 Initial revision
DESCRIPTION:
$Id: mainManager.asm,v 1.1 97/04/04 17:49:24 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
include contentGeode.def ; Common include stuff.
include Internal/heapInt.def ; need ThreadPrivateData definition
include Internal/interrup.def ; for Sys{Enter,Exit}Critical
include mainConstant.def ; extra class definitions
;------------------------------------------------------------------------------
; Classes
;------------------------------------------------------------------------------
ConviewClassStructures segment resource
ContentGenViewClass
ContentDocClass
ContentTextClass
ConviewClassStructures ends
;------------------------------------------------------------------------------
; Resource definitions
;------------------------------------------------------------------------------
;------------------------------------------------------------------------------
; Resources
;------------------------------------------------------------------------------
include mainManager.rdef
;------------------------------------------------------------------------------
; Code
;------------------------------------------------------------------------------
include mainStartEnd.asm
include mainLink.asm
include mainSpecialLink.asm
include mainText.asm
include mainName.asm
include mainUtils.asm
include mainBook.asm
include mainFile.asm
include mainContentPointer.asm
include mainNotify.asm
include mainCopy.asm
include mainSearch.asm
include mainHotspot.asm
|
; A153010: Indices of A153007 where the entry equals zero.
; 0,1,2,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215,33554431,67108863,134217727,268435455,536870911,1073741823,2147483647,4294967295
mov $1,$0
sub $1,1
mov $2,2
pow $2,$1
bin $0,$2
add $0,$2
sub $0,1
|
EXTERN VDP_STATUS
tms9118_interrupt:
push af
push hl
ld a, +(VDP_STATUS / 256)
and a
jr z,read_port
ld a,(VDP_STATUS)
jr done_read
read_port:
in a,(VDP_STATUS % 256)
done_read:
or a
jp p,int_not_VBL
jp int_VBL
int_not_VBL:
pop hl
pop af
ei
reti
|
;------------------------------------------------------------------------------ ;
; Copyright (c) 2016 - 2018, 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:
;
; SmiEntry.nasm
;
; Abstract:
;
; Code template of the SMI handler for a particular processor
;
;-------------------------------------------------------------------------------
%include "StuffRsb.inc"
;
; Variables referrenced by C code
;
%define MSR_IA32_MISC_ENABLE 0x1A0
%define MSR_EFER 0xc0000080
%define MSR_EFER_XD 0x800
;
; Constants relating to TXT_PROCESSOR_SMM_DESCRIPTOR
;
%define DSC_OFFSET 0xfb00
%define DSC_GDTPTR 0x48
%define DSC_GDTSIZ 0x50
%define DSC_CS 0x14
%define DSC_DS 0x16
%define DSC_SS 0x18
%define DSC_OTHERSEG 0x1a
;
; Constants relating to CPU State Save Area
;
%define SSM_DR6 0xffd0
%define SSM_DR7 0xffc8
%define PROTECT_MODE_CS 0x8
%define PROTECT_MODE_DS 0x20
%define LONG_MODE_CS 0x38
%define TSS_SEGMENT 0x40
%define GDT_SIZE 0x50
extern ASM_PFX(SmiRendezvous)
extern ASM_PFX(gStmSmiHandlerIdtr)
extern ASM_PFX(CpuSmmDebugEntry)
extern ASM_PFX(CpuSmmDebugExit)
global ASM_PFX(gStmSmbase)
global ASM_PFX(gStmXdSupported)
global ASM_PFX(gStmSmiStack)
global ASM_PFX(gStmSmiCr3)
global ASM_PFX(gcStmSmiHandlerTemplate)
global ASM_PFX(gcStmSmiHandlerSize)
global ASM_PFX(gcStmSmiHandlerOffset)
ASM_PFX(gStmSmbase) EQU StmSmbasePatch - 4
ASM_PFX(gStmSmiStack) EQU StmSmiStackPatch - 4
ASM_PFX(gStmSmiCr3) EQU StmSmiCr3Patch - 4
ASM_PFX(gStmXdSupported) EQU StmXdSupportedPatch - 1
DEFAULT REL
SECTION .text
BITS 16
ASM_PFX(gcStmSmiHandlerTemplate):
_StmSmiEntryPoint:
mov bx, _StmGdtDesc - _StmSmiEntryPoint + 0x8000
mov ax,[cs:DSC_OFFSET + DSC_GDTSIZ]
dec ax
mov [cs:bx], ax
mov eax, [cs:DSC_OFFSET + DSC_GDTPTR]
mov [cs:bx + 2], eax
o32 lgdt [cs:bx] ; lgdt fword ptr cs:[bx]
mov ax, PROTECT_MODE_CS
mov [cs:bx-0x2],ax
o32 mov edi, strict dword 0
StmSmbasePatch:
lea eax, [edi + (@ProtectedMode - _StmSmiEntryPoint) + 0x8000]
mov [cs:bx-0x6],eax
mov ebx, cr0
and ebx, 0x9ffafff3
or ebx, 0x23
mov cr0, ebx
jmp dword 0x0:0x0
_StmGdtDesc:
DW 0
DD 0
BITS 32
@ProtectedMode:
mov ax, PROTECT_MODE_DS
o16 mov ds, ax
o16 mov es, ax
o16 mov fs, ax
o16 mov gs, ax
o16 mov ss, ax
mov esp, strict dword 0
StmSmiStackPatch:
jmp ProtFlatMode
BITS 64
ProtFlatMode:
mov eax, strict dword 0
StmSmiCr3Patch:
mov cr3, rax
mov eax, 0x668 ; as cr4.PGE is not set here, refresh cr3
mov cr4, rax ; in PreModifyMtrrs() to flush TLB.
; Load TSS
sub esp, 8 ; reserve room in stack
sgdt [rsp]
mov eax, [rsp + 2] ; eax = GDT base
add esp, 8
mov dl, 0x89
mov [rax + TSS_SEGMENT + 5], dl ; clear busy flag
mov eax, TSS_SEGMENT
ltr ax
; enable NXE if supported
mov al, strict byte 1
StmXdSupportedPatch:
cmp al, 0
jz @SkipXd
;
; Check XD disable bit
;
mov ecx, MSR_IA32_MISC_ENABLE
rdmsr
sub esp, 4
push rdx ; save MSR_IA32_MISC_ENABLE[63-32]
test edx, BIT2 ; MSR_IA32_MISC_ENABLE[34]
jz .0
and dx, 0xFFFB ; clear XD Disable bit if it is set
wrmsr
.0:
mov ecx, MSR_EFER
rdmsr
or ax, MSR_EFER_XD ; enable NXE
wrmsr
jmp @XdDone
@SkipXd:
sub esp, 8
@XdDone:
; Switch into @LongMode
push LONG_MODE_CS ; push cs hardcore here
call Base ; push return address for retf later
Base:
add dword [rsp], @LongMode - Base; offset for far retf, seg is the 1st arg
mov ecx, MSR_EFER
rdmsr
or ah, 1 ; enable LME
wrmsr
mov rbx, cr0
or ebx, 0x80010023 ; enable paging + WP + NE + MP + PE
mov cr0, rbx
retf
@LongMode: ; long mode (64-bit code) starts here
mov rax, strict qword 0 ; mov rax, ASM_PFX(gStmSmiHandlerIdtr)
StmSmiEntrySmiHandlerIdtrAbsAddr:
lidt [rax]
lea ebx, [rdi + DSC_OFFSET]
mov ax, [rbx + DSC_DS]
mov ds, eax
mov ax, [rbx + DSC_OTHERSEG]
mov es, eax
mov fs, eax
mov gs, eax
mov ax, [rbx + DSC_SS]
mov ss, eax
mov rax, strict qword 0 ; mov rax, CommonHandler
StmSmiEntryCommonHandlerAbsAddr:
jmp rax
CommonHandler:
mov rbx, [rsp + 0x08] ; rbx <- CpuIndex
;
; Save FP registers
;
sub rsp, 0x200
fxsave64 [rsp]
add rsp, -0x20
mov rcx, rbx
call ASM_PFX(CpuSmmDebugEntry)
mov rcx, rbx
call ASM_PFX(SmiRendezvous)
mov rcx, rbx
call ASM_PFX(CpuSmmDebugExit)
add rsp, 0x20
;
; Restore FP registers
;
fxrstor64 [rsp]
add rsp, 0x200
lea rax, [ASM_PFX(gStmXdSupported)]
mov al, [rax]
cmp al, 0
jz .1
pop rdx ; get saved MSR_IA32_MISC_ENABLE[63-32]
test edx, BIT2
jz .1
mov ecx, MSR_IA32_MISC_ENABLE
rdmsr
or dx, BIT2 ; set XD Disable bit if it was set before entering into SMM
wrmsr
.1:
StuffRsb64
rsm
_StmSmiHandler:
;
; Check XD disable bit
;
xor r8, r8
lea rax, [ASM_PFX(gStmXdSupported)]
mov al, [rax]
cmp al, 0
jz @StmXdDone
mov ecx, MSR_IA32_MISC_ENABLE
rdmsr
mov r8, rdx ; save MSR_IA32_MISC_ENABLE[63-32]
test edx, BIT2 ; MSR_IA32_MISC_ENABLE[34]
jz .0
and dx, 0xFFFB ; clear XD Disable bit if it is set
wrmsr
.0:
mov ecx, MSR_EFER
rdmsr
or ax, MSR_EFER_XD ; enable NXE
wrmsr
@StmXdDone:
push r8
; below step is needed, because STM does not run above code.
; we have to run below code to set IDT/CR0/CR4
mov rax, strict qword 0 ; mov rax, ASM_PFX(gStmSmiHandlerIdtr)
StmSmiHandlerIdtrAbsAddr:
lidt [rax]
mov rax, cr0
or eax, 0x80010023 ; enable paging + WP + NE + MP + PE
mov cr0, rax
mov rax, cr4
mov eax, 0x668 ; as cr4.PGE is not set here, refresh cr3
mov cr4, rax ; in PreModifyMtrrs() to flush TLB.
; STM init finish
jmp CommonHandler
ASM_PFX(gcStmSmiHandlerSize) : DW $ - _StmSmiEntryPoint
ASM_PFX(gcStmSmiHandlerOffset) : DW _StmSmiHandler - _StmSmiEntryPoint
global ASM_PFX(SmmCpuFeaturesLibStmSmiEntryFixupAddress)
ASM_PFX(SmmCpuFeaturesLibStmSmiEntryFixupAddress):
lea rax, [ASM_PFX(gStmSmiHandlerIdtr)]
lea rcx, [StmSmiEntrySmiHandlerIdtrAbsAddr]
mov qword [rcx - 8], rax
lea rcx, [StmSmiHandlerIdtrAbsAddr]
mov qword [rcx - 8], rax
lea rax, [CommonHandler]
lea rcx, [StmSmiEntryCommonHandlerAbsAddr]
mov qword [rcx - 8], rax
ret
|
; =============================================================================
; BareMetal -- a 64-bit OS written in Assembly for x86-64 systems
; Copyright (C) 2008-2016 Return Infinity -- see LICENSE.TXT
;
; Driver Includes
; =============================================================================
%include "drivers/pci.asm"
%include "drivers/pic.asm"
%include "drivers/storage/ahci.asm"
; %include "drivers/storage/ide.asm"
%include "drivers/net/i8254x.asm"
%include "drivers/net/rtl8169.asm"
%include "drivers/net/virtio.asm"
NIC_DeviceVendor_ID: ; The supported list of NICs
; The ID's are Device/Vendor
; Virtio
dd 0x1AF4FFFF
dd 0x10001AF4
; Realtek 816x/811x Gigabit Ethernet
dd 0x8169FFFF
dd 0x816710EC ; 8110SC/8169SC
dd 0x816810EC ; 8111/8168B
dd 0x816910EC ; 8169
; Intel 8254x Gigabit Ethernet
dd 0x8254FFFF
dd 0x10008086 ; 82542 (Fiber)
dd 0x10018086 ; 82543GC (Fiber)
dd 0x10048086 ; 82543GC (Copper)
dd 0x10088086 ; 82544EI (Copper)
dd 0x10098086 ; 82544EI (Fiber)
dd 0x100A8086 ; 82540EM
dd 0x100C8086 ; 82544GC (Copper)
dd 0x100D8086 ; 82544GC (LOM)
dd 0x100E8086 ; 82540EM
dd 0x100F8086 ; 82545EM (Copper)
dd 0x10108086 ; 82546EB (Copper)
dd 0x10118086 ; 82545EM (Fiber)
dd 0x10128086 ; 82546EB (Fiber)
dd 0x10138086 ; 82541EI
dd 0x10148086 ; 82541ER
dd 0x10158086 ; 82540EM (LOM)
dd 0x10168086 ; 82540EP (Mobile)
dd 0x10178086 ; 82540EP
dd 0x10188086 ; 82541EI
dd 0x10198086 ; 82547EI
dd 0x101a8086 ; 82547EI (Mobile)
dd 0x101d8086 ; 82546EB
dd 0x101e8086 ; 82540EP (Mobile)
dd 0x10268086 ; 82545GM
dd 0x10278086 ; 82545GM
dd 0x10288086 ; 82545GM
dd 0x105b8086 ; 82546GB (Copper)
dd 0x10758086 ; 82547GI
dd 0x10768086 ; 82541GI
dd 0x10778086 ; 82541GI
dd 0x10788086 ; 82541ER
dd 0x10798086 ; 82546GB
dd 0x107a8086 ; 82546GB
dd 0x107b8086 ; 82546GB
dd 0x107c8086 ; 82541PI
dd 0x10b58086 ; 82546GB (Copper)
dd 0x11078086 ; 82544EI
dd 0x11128086 ; 82544GC
dq 0x0000000000000000 ; End of list
; =============================================================================
; EOF
|
#include<cstdio>
#include<vector>
#include<algorithm>
std::vector<int> w,x;
int m;
void SumOfSub(int s,int k,int r)
{
x[k]=1;
if(s+w[k]==m)
{
for(int i = 0;i < k; i++)
{
if(x[i]==0)
continue;
printf("%3d,",w[i]);
}
printf("%3d.",w[k]);
printf("\n");
return;
}
else if(s+w[k]+w[k+1]<=m)
SumOfSub(s+w[k],k+1,r-w[k]);
if(s + r - w[k] >= m && s + w[k+1] <= m)
{
x[k]=0;
SumOfSub(s,k+1,r-w[k]);
}
return;
}
int main()
{
int cnt,sum=0,tmp;
printf("\nEnter Array size : ");
scanf("%d",&cnt);
printf("\nEnter %d elements : ",cnt);
for(int i = 0; i < cnt; i++)
{
scanf("%d",&tmp);
sum+=tmp;
w.push_back(tmp);
x.push_back(0);
}
std::sort(w.begin(),w.end());
for(int i = 0; i < cnt; i++)
{
printf("%5d",w[i]);
}
printf("\n Enter Sum of Subset : ");
scanf("%d",&m);
printf("\nAll Subsets with Sum %d : \n",m);
SumOfSub(0,0,sum);
}
|
#include "ComponentDirection.h"
ComponentDirection::~ComponentDirection()
{
}
//Keeps the component concurrency complient
void ComponentDirection::RenderSwap()
{
renderDirection = updateDirection;
}
|
clc
lda ({z1}),y
adc {m2}
pha
iny
lda ({z1}),y
adc {m2}
sta {z1}+1
pla
sta {z1}
|
; int vfscanf_unlocked(FILE *stream, const char *format, void *arg)
SECTION code_clib
SECTION code_stdio
PUBLIC _vfscanf_unlocked
EXTERN asm_vfscanf_unlocked
_vfscanf_unlocked:
pop af
pop ix
pop de
pop bc
push bc
push de
push hl
push af
jp asm_vfscanf_unlocked
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.